FrankeMING's picture
Upload folder using huggingface_hub
133fe23 verified
{"problem_id":"cwe-089#0-058d1db0e395","input":"def build_board(conn, game,size):\n # we'll build the empty board, and then fill in with the move list that\n # we get from the DB.\n board = []\n for i in range(size):\n board.append([\"\"]*size)\n\n\n # search for all moves that have happenend during this game.\n cursor = conn.cursor()\n cursor.execute(\"SELECT x,y,letter FROM moves WHERE gameID = %d;\" % game)\n\n counts = {\"X\":0, \"O\":0}\n for move in cursor.fetchall():\n (x,y,letter) = move\n\n x = int(x)\n y = int(y)\n assert x >= 0 and x < size\n assert y >= 0 and y < size\n\n assert letter in \"XO\"\n\n assert board[x][y] == \"\"\n board[x][y] = letter\n\n counts[letter] += 1\n\n cursor.close()\n\n assert counts[\"X\"] >= counts[\"O\"]\n assert counts[\"X\"] <= counts[\"O\"]+1\n\n if counts[\"X\"] == counts[\"O\"]:\n nextPlayer = 0\n else:\n nextPlayer = 1\n letter = \"XO\"[nextPlayer]\n\n return (board,nextPlayer,letter)","target":"def build_board(conn, game,size):\n # we'll build the empty board, and then fill in with the move list that\n # we get from the DB.\n board = []\n for i in range(size):\n board.append([\"\"]*size)\n\n\n # search for all moves that have happenend during this game.\n cursor = conn.cursor()\n cursor.execute(\"SELECT x,y,letter FROM moves WHERE gameID = %d;\", (game,))\n\n counts = {\"X\":0, \"O\":0}\n for move in cursor.fetchall():\n (x,y,letter) = move\n\n x = int(x)\n y = int(y)\n assert x >= 0 and x < size\n assert y >= 0 and y < size\n\n assert letter in \"XO\"\n\n assert board[x][y] == \"\"\n board[x][y] = letter\n\n counts[letter] += 1\n\n cursor.close()\n\n assert counts[\"X\"] >= counts[\"O\"]\n assert counts[\"X\"] <= counts[\"O\"]+1\n\n if counts[\"X\"] == counts[\"O\"]:\n nextPlayer = 0\n else:\n nextPlayer = 1\n letter = \"XO\"[nextPlayer]\n\n return (board,nextPlayer,letter)","lang":"python","vul_type":"cwe-089","target_token_count":271,"sven_meta":{"func_name":"build_board","file_name":"cgi/common.py","commit_link":"github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#8-24ab82d56e89","input":"@endpoints.route(\"/ranks\")\ndef ranks():\n if db == None:\n init()\n\n scene = request.args.get('scene', default='austin')\n date = request.args.get('date')\n \n # If no date was provided, pick the date of the latest tournament\n if date == None:\n sql = \"SELECT distinct date FROM ranks WHERE scene='{}' ORDER BY date DESC LIMIT 1;\".format(scene)\n res = db.exec(sql)\n date = res[0][0]\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{}' and date='{}'\".format(scene, date)\n res = db.exec(sql)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n cur_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n cur_ranks[tag] = rank\n\n # Now get the ranks from last month, so we know if these players went up or down\n y, m, d = date.split('-')\n prev_date = bracket_utils.get_previous_month(date)\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{}' and date='{}'\".format(scene, prev_date)\n res = db.exec(sql)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n prev_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n prev_ranks[tag] = rank\n\n return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)","target":"@endpoints.route(\"/ranks\")\ndef ranks():\n if db == None:\n init()\n\n scene = request.args.get('scene', default='austin')\n date = request.args.get('date')\n \n # If no date was provided, pick the date of the latest tournament\n if date == None:\n sql = \"SELECT distinct date FROM ranks WHERE scene='{scene}' ORDER BY date DESC LIMIT 1;\"\n args = {'scene': scene}\n res = db.exec(sql, args)\n date = res[0][0]\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'\"\n args = {'scene': scene, 'date': date}\n res = db.exec(sql, args)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n cur_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n cur_ranks[tag] = rank\n\n # Now get the ranks from last month, so we know if these players went up or down\n y, m, d = date.split('-')\n prev_date = bracket_utils.get_previous_month(date)\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'\"\n args = {'scene': scene, 'date': prev_date}\n res = db.exec(sql, args)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n prev_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n prev_ranks[tag] = rank\n\n return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)","lang":"python","vul_type":"cwe-089","target_token_count":417,"sven_meta":{"func_name":"ranks","file_name":"endpoints.py","commit_link":"github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#15-1eb68ef0e0d1","input":"@frappe.whitelist(allow_guest=True)\ndef send_message(subject=\"Website Query\", message=\"\", sender=\"\", status=\"Open\"):\n\tfrom frappe.www.contact import send_message as website_send_message\n\tlead = customer = None\n\n\twebsite_send_message(subject, message, sender)\n\n\tcustomer = frappe.db.sql(\"\"\"select distinct dl.link_name from `tabDynamic Link` dl\n\t\tleft join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'\n\t\tand c.email_id='{email_id}'\"\"\".format(email_id=sender))\n\n\tif not customer:\n\t\tlead = frappe.db.get_value('Lead', dict(email_id=sender))\n\t\tif not lead:\n\t\t\tnew_lead = frappe.get_doc(dict(\n\t\t\t\tdoctype='Lead',\n\t\t\t\temail_id = sender,\n\t\t\t\tlead_name = sender.split('@')[0].title()\n\t\t\t)).insert(ignore_permissions=True)\n\n\topportunity = frappe.get_doc(dict(\n\t\tdoctype ='Opportunity',\n\t\tenquiry_from = 'Customer' if customer else 'Lead',\n\t\tstatus = 'Open',\n\t\ttitle = subject,\n\t\tcontact_email = sender,\n\t\tto_discuss = message\n\t))\n\n\tif customer:\n\t\topportunity.customer = customer[0][0]\n\telif lead:\n\t\topportunity.lead = lead\n\telse:\n\t\topportunity.lead = new_lead.name\n\n\topportunity.insert(ignore_permissions=True)\n\n\tcomm = frappe.get_doc({\n\t\t\"doctype\":\"Communication\",\n\t\t\"subject\": subject,\n\t\t\"content\": message,\n\t\t\"sender\": sender,\n\t\t\"sent_or_received\": \"Received\",\n\t\t'reference_doctype': 'Opportunity',\n\t\t'reference_name': opportunity.name\n\t})\n\tcomm.insert(ignore_permissions=True)\n\n\treturn \"okay\"","target":"@frappe.whitelist(allow_guest=True)\ndef send_message(subject=\"Website Query\", message=\"\", sender=\"\", status=\"Open\"):\n\tfrom frappe.www.contact import send_message as website_send_message\n\tlead = customer = None\n\n\twebsite_send_message(subject, message, sender)\n\n\tcustomer = frappe.db.sql(\"\"\"select distinct dl.link_name from `tabDynamic Link` dl\n\t\tleft join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'\n\t\tand c.email_id = %s\"\"\", sender)\n\n\tif not customer:\n\t\tlead = frappe.db.get_value('Lead', dict(email_id=sender))\n\t\tif not lead:\n\t\t\tnew_lead = frappe.get_doc(dict(\n\t\t\t\tdoctype='Lead',\n\t\t\t\temail_id = sender,\n\t\t\t\tlead_name = sender.split('@')[0].title()\n\t\t\t)).insert(ignore_permissions=True)\n\n\topportunity = frappe.get_doc(dict(\n\t\tdoctype ='Opportunity',\n\t\tenquiry_from = 'Customer' if customer else 'Lead',\n\t\tstatus = 'Open',\n\t\ttitle = subject,\n\t\tcontact_email = sender,\n\t\tto_discuss = message\n\t))\n\n\tif customer:\n\t\topportunity.customer = customer[0][0]\n\telif lead:\n\t\topportunity.lead = lead\n\telse:\n\t\topportunity.lead = new_lead.name\n\n\topportunity.insert(ignore_permissions=True)\n\n\tcomm = frappe.get_doc({\n\t\t\"doctype\":\"Communication\",\n\t\t\"subject\": subject,\n\t\t\"content\": message,\n\t\t\"sender\": sender,\n\t\t\"sent_or_received\": \"Received\",\n\t\t'reference_doctype': 'Opportunity',\n\t\t'reference_name': opportunity.name\n\t})\n\tcomm.insert(ignore_permissions=True)\n\n\treturn \"okay\"","lang":"python","vul_type":"cwe-089","target_token_count":360,"sven_meta":{"func_name":"send_message","file_name":"erpnext/templates/utils.py","commit_link":"github.com/libracore/erpnext/commit/9acb885e60f77cd4e9ea8c98bdc39c18abcac731","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#21-0039b2cd868c","input":" def view_grocery_list():\n print(\"grocery== list\")\n groceryListFrame = Frame(self)\n groceryListFrame.rowconfigure(0, weight=1)\n groceryListFrame.columnconfigure(0, weight=1)\n groceryListFrame.rowconfigure(1, weight=3)\n groceryListFrame.columnconfigure(1, weight=3)\n groceryListFrame.pack()\n\n menu.pack_forget()\n groceryButton.pack_forget()\n label.configure(text=\"Grocery List\")\n\n i = 0\n database_file = \"meal_planner.db\"\n item_array = []\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n tableName = \"ingredients_\" + str(weekNumber)\n selection = cursor.execute(\"\"\"SELECT * FROM \"\"\" + tableName)\n for result in [selection]:\n for row in result.fetchall():\n print(row)\n for ingredient in row:\n print(ingredient)\n item_array.append(str(ingredient).split())\n i = i +1\n Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky=\"w\")\n \n\n j = 0\n for item in item_array:\n print(item)\n\n\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [groceryListFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)","target":" def view_grocery_list():\n print(\"grocery== list\")\n groceryListFrame = Frame(self)\n groceryListFrame.rowconfigure(0, weight=1)\n groceryListFrame.columnconfigure(0, weight=1)\n groceryListFrame.rowconfigure(1, weight=3)\n groceryListFrame.columnconfigure(1, weight=3)\n groceryListFrame.pack()\n\n menu.pack_forget()\n groceryButton.pack_forget()\n label.configure(text=\"Grocery List\")\n\n i = 0\n database_file = \"meal_planner.db\"\n item_array = []\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n tableName = \"ingredients_\" + str(weekNumber)\n selection = cursor.execute(\"\"\"SELECT * FROM ?;\"\"\", (tableName, ))\n for result in [selection]:\n for row in result.fetchall():\n print(row)\n for ingredient in row:\n print(ingredient)\n item_array.append(str(ingredient).split())\n i = i +1\n Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky=\"w\")\n \n\n j = 0\n for item in item_array:\n print(item)\n\n\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [groceryListFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)","lang":"python","vul_type":"cwe-089","target_token_count":340,"sven_meta":{"func_name":"__init__.view_grocery_list","file_name":"mealPlan.py","commit_link":"github.com/trishamoyer/RecipePlanner-Python/commit/44d2ce370715d9344fad34b3b749322ab095a925","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#36-5da1a990c61b","input":" def get_requested_day(self, date):\n\n data = dict()\n\n day_start, day_end = self.get_epoch_day(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}\n\n query = '''\n SELECT TimeStamp, SUM(Power) AS Power \n FROM DayData \n WHERE TimeStamp BETWEEN %s AND %s \n GROUP BY TimeStamp;\n '''\n\n data['data'] = list()\n for row in self.c.execute(query % (day_start, day_end)):\n data['data'].append({ 'time': row[0], 'power': row[1] })\n\n\n if self.get_datetime(date).date() == datetime.today().date():\n query = '''\n SELECT SUM(EToday) as EToday\n FROM Inverters;\n '''\n else:\n query = '''\n SELECT SUM(DayYield) AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN %s AND %s\n GROUP BY TimeStamp\n ''' % (day_start, day_end)\n self.c.execute(query)\n row = self.c.fetchone()\n if row and row[0]: data['total'] = row[0]\n else: data['total'] = 0\n\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );\n '''\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if (first_data): data['hasPrevious'] = (first_data < day_start)\n else: data['hasPrevious'] = False\n\n if (last_data): data['hasNext'] = (last_data > day_end)\n else: data['hasNext'] = False\n\n #print(json.dumps(data, indent=4))\n return data","target":" def get_requested_day(self, date):\n\n data = dict()\n\n day_start, day_end = self.get_epoch_day(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}\n\n query = '''\n SELECT TimeStamp, SUM(Power) AS Power \n FROM DayData \n WHERE TimeStamp BETWEEN ? AND ?\n GROUP BY TimeStamp;\n '''\n\n data['data'] = list()\n for row in self.c.execute(query, (day_start, day_end)):\n data['data'].append({ 'time': row[0], 'power': row[1] })\n\n\n if self.get_datetime(date).date() == datetime.today().date():\n query = '''\n SELECT SUM(EToday) as EToday\n FROM Inverters;\n '''\n self.c.execute(query)\n else:\n query = '''\n SELECT SUM(DayYield) AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN ? AND ?\n GROUP BY TimeStamp;\n '''\n self.c.execute(query, (day_start, day_end))\n\n row = self.c.fetchone()\n if row and row[0]: data['total'] = row[0]\n else: data['total'] = 0\n\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );\n '''\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if (first_data): data['hasPrevious'] = (first_data < day_start)\n else: data['hasPrevious'] = False\n\n if (last_data): data['hasNext'] = (last_data > day_end)\n else: data['hasNext'] = False\n\n #print(json.dumps(data, indent=4))\n return data","lang":"python","vul_type":"cwe-089","target_token_count":407,"sven_meta":{"func_name":"get_requested_day","file_name":"util/database.py","commit_link":"github.com/philipptrenz/sunportal/commit/7eef493a168ed4e6731ff800713bfb8aee99a506","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#46-8d6ffcb96c35","input":"def get_mod_taken_together_with(code):\n '''\n Retrieves the list of modules taken together with the specified\n module code in the same semester.\n\n Returns a table of lists (up to 10 top results). Each list contains\n (specified code, module code of mod taken together, aySem, number of students)\n\n e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students\n taking CS1010 and CS1231 together in AY 16/17 Sem 1.\n '''\n NUM_TOP_RESULTS_TO_RETURN = 10\n\n sql_command = \"SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) \" + \\\n \"FROM studentPlans sp1, studentPlans sp2 \" + \\\n \"WHERE sp1.moduleCode = '\" + code + \"' AND \" + \\\n \"sp2.moduleCode <> sp1.moduleCode AND \" + \\\n \"sp1.studentId = sp2.studentId AND \" + \\\n \"sp1.acadYearAndSem = sp2.acadYearAndSem \" + \\\n \"GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem \" + \\\n \"ORDER BY COUNT(*) DESC\"\n\n DB_CURSOR.execute(sql_command)\n\n return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)","target":"def get_mod_taken_together_with(code):\n '''\n Retrieves the list of modules taken together with the specified\n module code in the same semester.\n\n Returns a table of lists (up to 10 top results). Each list contains\n (specified code, module code of mod taken together, aySem, number of students)\n\n e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students\n taking CS1010 and CS1231 together in AY 16/17 Sem 1.\n '''\n NUM_TOP_RESULTS_TO_RETURN = 10\n\n sql_command = \"SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) \" + \\\n \"FROM studentPlans sp1, studentPlans sp2 \" + \\\n \"WHERE sp1.moduleCode = %s AND \" + \\\n \"sp2.moduleCode <> sp1.moduleCode AND \" + \\\n \"sp1.studentId = sp2.studentId AND \" + \\\n \"sp1.acadYearAndSem = sp2.acadYearAndSem \" + \\\n \"GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem \" + \\\n \"ORDER BY COUNT(*) DESC\"\n\n DB_CURSOR.execute(sql_command, (code,))\n\n return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)","lang":"python","vul_type":"cwe-089","target_token_count":311,"sven_meta":{"func_name":"get_mod_taken_together_with","file_name":"components/model.py","commit_link":"github.com/nus-mtp/cs-modify/commit/79b4b1dd7eba5445751808e4c50b49d2dd08366b","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#61-1df6e292d628","input":"@mod.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n error = None\n email = request.form['email'].strip()\n nickname = request.form['nickname'].strip()\n password = request.form['password'].strip()\n password2 = request.form['password2'].strip()\n\n email = email.lower()\n\n if email == \"\" or nickname == \"\" or password == \"\" or password2 == \"\":\n error = 'Please input all the information'\n elif password2 != password:\n error = 'The password is not repeated correctly'\n elif len(password) < 6:\n error = 'The password has at least 6 characters'\n elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +\n '[0-9a-zA-Z]{1,15}\\.[com,cn,net]', email):\n error = 'Please input the right email'\n\n sql = \"SELECT * FROM users where email = '%s';\" % (email)\n cursor.execute(sql)\n u = cursor.fetchone()\n\n if u is not None:\n error = 'The email has already exsit'\n\n if error is not None:\n return render_template('register.html', error=error)\n else:\n password = bcrypt.generate_password_hash(password)\n cursor.execute(\"INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);\", (email, nickname, password))\n conn.commit()\n flash('Register Success!')\n return redirect(url_for('users.login'))\n\n return render_template('register.html')","target":"@mod.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n error = None\n email = request.form['email'].strip()\n nickname = request.form['nickname'].strip()\n password = request.form['password'].strip()\n password2 = request.form['password2'].strip()\n\n email = email.lower()\n\n if email == \"\" or nickname == \"\" or password == \"\" or password2 == \"\":\n error = 'Please input all the information'\n elif password2 != password:\n error = 'The password is not repeated correctly'\n elif len(password) < 6:\n error = 'The password has at least 6 characters'\n elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +\n '[0-9a-zA-Z]{1,15}\\.[com,cn,net]', email):\n error = 'Please input the right email'\n\n cursor.execute(\"SELECT * FROM users where email = %s;\", (email,))\n u = cursor.fetchone()\n\n if u is not None:\n error = 'The email has already exsit'\n\n if error is not None:\n return render_template('register.html', error=error)\n else:\n password = bcrypt.generate_password_hash(password)\n cursor.execute(\"INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);\", (email, nickname, password))\n conn.commit()\n flash('Register Success!')\n return redirect(url_for('users.login'))\n\n return render_template('register.html')","lang":"python","vul_type":"cwe-089","target_token_count":327,"sven_meta":{"func_name":"register","file_name":"flaskr/flaskr/views/users.py","commit_link":"github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#70-eb5b60e88246","input":"def _get_degree_2(user_id, cnx):\n \"\"\"Get all users of degree 2 follow that are not currently followed.\n Example:\n this user (follows) user B (follows) user B\n AND user (does NOT follow) user B\n means that user B will be in the list\n Args:\n user_id (int): id of user\n cnx: DB connection\n Returns:\n list: list of user_ids\n \"\"\"\n sql = 'WITH tmp_suggest (followed_id) AS ' \\\n '(' \\\n 'SELECT b.followed_id AS followed_id ' \\\n 'FROM ' \\\n 'tbl_follow a INNER JOIN tbl_follow b ' \\\n 'ON a.followed_id = b.follower_id ' \\\n 'WHERE a.follower_id = %s ' \\\n 'AND b.followed_id NOT IN ' \\\n '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \\\n 'AND b.followed_id != %s ' \\\n ') ' \\\n 'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \\\n 'GROUP BY followed_id ' \\\n 'ORDER BY num_mutual DESC' % (user_id, user_id, user_id)\n with cnx.cursor() as cursor:\n cursor.execute(sql)\n res = cursor.fetchall()\n return list(map(lambda x: x[0], res))","target":"def _get_degree_2(user_id, cnx):\n \"\"\"Get all users of degree 2 follow that are not currently followed.\n Example:\n this user (follows) user B (follows) user B\n AND user (does NOT follow) user B\n means that user B will be in the list\n Args:\n user_id (int): id of user\n cnx: DB connection\n Returns:\n list: list of user_ids\n \"\"\"\n sql = 'WITH tmp_suggest (followed_id) AS ' \\\n '(' \\\n 'SELECT b.followed_id AS followed_id ' \\\n 'FROM ' \\\n 'tbl_follow a INNER JOIN tbl_follow b ' \\\n 'ON a.followed_id = b.follower_id ' \\\n 'WHERE a.follower_id = %s ' \\\n 'AND b.followed_id NOT IN ' \\\n '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \\\n 'AND b.followed_id != %s ' \\\n ') ' \\\n 'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \\\n 'GROUP BY followed_id ' \\\n 'ORDER BY num_mutual DESC'\n with cnx.cursor() as cursor:\n cursor.execute(sql, (user_id, user_id, user_id))\n res = cursor.fetchall()\n return list(map(lambda x: x[0], res))","lang":"python","vul_type":"cwe-089","target_token_count":298,"sven_meta":{"func_name":"_get_degree_2","file_name":"server/ygoons/modules/user/follow_suggest.py","commit_link":"github.com/young-goons/rifflo-server/commit/fb311df76713b638c9486250f9badb288ffb2189","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#76-5aee3ebacea6","input":" @staticmethod\n def compare_and_update(user, message):\n \"\"\"\n This method compare a user object from the bot and his info from\n the Telegram message to check whether a user has changed his bio\n or not. If yes, the user object that represents him in the bot will\n be updated accordingly. Now this function is called only when a user\n asks the bot for showing the most popular cams\n\n :param user: user object that represents a Telegram user in this bot\n :param message: object from Telegram that contains info about user's\n message and about himself\n :return: None\n \"\"\"\n\n log.info('Checking whether user have changed his info or not...')\n msg = message.from_user\n usr_from_message = User(message.chat.id, msg.first_name, msg.username,\n msg.last_name)\n\n if user.chat_id != usr_from_message.chat_id:\n log.error(\"Wrong user to compare!\")\n return\n\n if user.first_name != usr_from_message.first_name:\n user.first_name = usr_from_message.first_name\n\n elif user.nickname != usr_from_message.nickname:\n user.nickname = usr_from_message.nickname\n\n elif user.last_name != usr_from_message.last_name:\n user.last_name = usr_from_message.last_name\n\n else:\n log.debug(\"User's info hasn't changed\")\n return\n\n log.info(\"User has changed his info\")\n log.debug(\"Updating user's info in the database...\")\n query = (f\"UPDATE users \"\n f\"SET first_name='{user.first_name}', \"\n f\"nickname='{user.nickname}', \"\n f\"last_name='{user.last_name}' \"\n f\"WHERE chat_id={user.chat_id}\")\n\n try:\n db.add(query)\n except DatabaseError:\n log.error(\"Could not update info about %s in the database\",\n user)\n else:\n log.debug(\"User's info has been updated\")","target":" @staticmethod\n def compare_and_update(user, message):\n \"\"\"\n This method compare a user object from the bot and his info from\n the Telegram message to check whether a user has changed his bio\n or not. If yes, the user object that represents him in the bot will\n be updated accordingly. Now this function is called only when a user\n asks the bot for showing the most popular cams\n\n :param user: user object that represents a Telegram user in this bot\n :param message: object from Telegram that contains info about user's\n message and about himself\n :return: None\n \"\"\"\n\n log.info('Checking whether user have changed his info or not...')\n msg = message.from_user\n usr_from_message = User(message.chat.id, msg.first_name, msg.username,\n msg.last_name)\n\n if user.chat_id != usr_from_message.chat_id:\n log.error(\"Wrong user to compare!\")\n return\n\n if user.first_name != usr_from_message.first_name:\n user.first_name = usr_from_message.first_name\n\n elif user.nickname != usr_from_message.nickname:\n user.nickname = usr_from_message.nickname\n\n elif user.last_name != usr_from_message.last_name:\n user.last_name = usr_from_message.last_name\n\n else:\n log.debug(\"User's info hasn't changed\")\n return\n\n log.info(\"User has changed his info\")\n log.debug(\"Updating user's info in the database...\")\n query = (f\"UPDATE users \"\n f\"SET first_name=%s, \"\n f\"nickname=%s, \"\n f\"last_name=%s \"\n f\"WHERE chat_id=%s\")\n\n parameters = (user.first_name, user.nickname, user.last_name,\n user.chat_id)\n\n try:\n db.add(query, parameters)\n except DatabaseError:\n log.error(\"Could not update info about %s in the database\",\n user)\n else:\n log.debug(\"User's info has been updated\")","lang":"python","vul_type":"cwe-089","target_token_count":415,"sven_meta":{"func_name":"compare_and_update","file_name":"photogpsbot/users.py","commit_link":"github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#82-c90b0b529431","input":" def get_requested_month_for_inverter(self, inverter_serial, date):\n data = dict()\n\n month_start, month_end = self.get_epoch_month(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}\n month_total = 0\n\n query = '''\n SELECT TimeStamp, DayYield AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN %s AND %s AND Serial = %s\n '''\n\n data['data'] = list()\n for row in self.c.execute(query % (month_start, month_end, inverter_serial)):\n data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})\n month_total += row[1]\n\n data['total'] = month_total\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM MonthData \n WHERE Serial = %s;\n ''' % inverter_serial\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if first_data: data['hasPrevious'] = (first_data < month_start)\n else: data['hasPrevious'] = False\n if last_data: data['hasNext'] = (last_data > month_end)\n else: data['hasNext'] = False\n\n return data","target":" def get_requested_month_for_inverter(self, inverter_serial, date):\n data = dict()\n\n month_start, month_end = self.get_epoch_month(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}\n month_total = 0\n\n query = '''\n SELECT TimeStamp, DayYield AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN ? AND ? AND Serial=?;\n '''\n\n data['data'] = list()\n for row in self.c.execute(query, (month_start, month_end, inverter_serial)):\n data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})\n month_total += row[1]\n\n data['total'] = month_total\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM MonthData \n WHERE Serial=?;\n '''\n\n self.c.execute(query, (inverter_serial,))\n first_data, last_data = self.c.fetchone()\n\n if first_data: data['hasPrevious'] = (first_data < month_start)\n else: data['hasPrevious'] = False\n if last_data: data['hasNext'] = (last_data > month_end)\n else: data['hasNext'] = False\n\n return data","lang":"python","vul_type":"cwe-089","target_token_count":303,"sven_meta":{"func_name":"get_requested_month_for_inverter","file_name":"util/database.py","commit_link":"github.com/philipptrenz/sunportal/commit/7eef493a168ed4e6731ff800713bfb8aee99a506","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#93-c9d2dedc1961","input":"@app.route('/<page_name>/save', methods=['POST'])\ndef save_page_edit(page_name):\n # grab the new content from the user\n content = request.form.get('content')\n # check if 'page_name' exists in the database\n query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1\" % page_name)\n result = query.namedresult()\n # if it doesn't exist, create a new page in the database\n if len(result) < 1:\n db.insert(\n 'page', {\n 'page_name': page_name\n }\n )\n else:\n pass\n # now that we're certain that the page exists in the database, we again grab the query\n # and insert new content in the database\n query = db.query(\"select id from page where page_name = '%s'\" % page_name)\n page_id = query.namedresult()[0].id\n db.insert(\n 'page_content', {\n 'page_id': page_id,\n 'content': content,\n 'timestamp': time.strftime(\"%Y-%m-%d %H:%M:%S\", localtime())\n }\n )\n return redirect(\"/%s\" % page_name)","target":"@app.route('/<page_name>/save', methods=['POST'])\ndef save_page_edit(page_name):\n # grab the new content from the user\n content = request.form.get('content')\n # check if 'page_name' exists in the database\n query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1\", page_name)\n result = query.namedresult()\n # if it doesn't exist, create a new page in the database\n if len(result) < 1:\n db.insert(\n 'page', {\n 'page_name': page_name\n }\n )\n else:\n pass\n # now that we're certain that the page exists in the database, we again grab the query\n # and insert new content in the database\n query = db.query(\"select id from page where page_name = '%s'\" % page_name)\n page_id = query.namedresult()[0].id\n db.insert(\n 'page_content', {\n 'page_id': page_id,\n 'content': content,\n 'timestamp': time.strftime(\"%Y-%m-%d %H:%M:%S\", localtime())\n }\n )\n return redirect(\"/%s\" % page_name)","lang":"python","vul_type":"cwe-089","target_token_count":291,"sven_meta":{"func_name":"save_page_edit","file_name":"server.py","commit_link":"github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#107-bbb3b629e11d","input":"def process_form():\n # see https://docs.python.org/3.4/library/cgi.html for the basic usage\n # here.\n form = cgi.FieldStorage()\n\n\n if \"player1\" not in form or \"player2\" not in form or \"size\" not in form:\n raise FormError(\"Invalid parameters.\")\n\n player1 = form[\"player1\"].value\n player2 = form[\"player2\"].value\n for c in player1+player2:\n if c not in \"_-\" and not c.isdigit() and not c.isalpha():\n raise FormError(\"Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens\")\n return\n\n try:\n size = int(form[\"size\"].value)\n except:\n raise FormError(\"Invalid parameters: 'size' is not an integer.\")\n return\n\n if size < 2 or size > 9:\n raise FormError(\"The 'size' must be in the range 2-9, inclusive.\")\n\n\n # connect to the database\n conn = MySQLdb.connect(host = pnsdp.SQL_HOST,\n user = pnsdp.SQL_USER,\n passwd = pnsdp.SQL_PASSWD,\n db = pnsdp.SQL_DB)\n cursor = conn.cursor()\n\n # insert the new row\n cursor.execute(\"\"\"INSERT INTO games(player1,player2,size) VALUES(\"%s\",\"%s\",%d);\"\"\" % (player1,player2,size))\n\n gameID = cursor.lastrowid\n\n\n # MySQLdb has been building a transaction as we run. Commit them now, and\n # also clean up the other resources we've allocated.\n conn.commit()\n cursor.close()\n conn.close()\n\n return gameID","target":"def process_form():\n # see https://docs.python.org/3.4/library/cgi.html for the basic usage\n # here.\n form = cgi.FieldStorage()\n\n\n if \"player1\" not in form or \"player2\" not in form or \"size\" not in form:\n raise FormError(\"Invalid parameters.\")\n\n player1 = form[\"player1\"].value\n player2 = form[\"player2\"].value\n for c in player1+player2:\n if c not in \"_-\" and not c.isdigit() and not c.isalpha():\n raise FormError(\"Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens\")\n return\n\n try:\n size = int(form[\"size\"].value)\n except:\n raise FormError(\"Invalid parameters: 'size' is not an integer.\")\n return\n\n if size < 2 or size > 9:\n raise FormError(\"The 'size' must be in the range 2-9, inclusive.\")\n\n\n # connect to the database\n conn = MySQLdb.connect(host = pnsdp.SQL_HOST,\n user = pnsdp.SQL_USER,\n passwd = pnsdp.SQL_PASSWD,\n db = pnsdp.SQL_DB)\n cursor = conn.cursor()\n\n # insert the new row\n cursor.execute(\"\"\"INSERT INTO games(player1,player2,size) VALUES(\"%s\",\"%s\",%d);\"\"\", (player1,player2,size))\n\n gameID = cursor.lastrowid\n\n\n # MySQLdb has been building a transaction as we run. Commit them now, and\n # also clean up the other resources we've allocated.\n conn.commit()\n cursor.close()\n conn.close()\n\n return gameID","lang":"python","vul_type":"cwe-089","target_token_count":373,"sven_meta":{"func_name":"process_form","file_name":"cgi/create_game.py","commit_link":"github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#108-2253646ce3a1","input":" def clean_cache(self, limit):\n \"\"\"\n Method that remove several User objects from cache - the least \n active users\n :param limit: number of the users that the method should remove\n from cache\n :return: None\n \"\"\"\n\n log.info('Figuring out the least active users...')\n # Select users that the least active recently\n user_ids = tuple(self.users.keys())\n query = ('SELECT chat_id '\n 'FROM photo_queries_table2 '\n f'WHERE chat_id in {user_ids} '\n 'GROUP BY chat_id '\n 'ORDER BY MAX(time) '\n f'LIMIT {limit}')\n\n try:\n cursor = db.execute_query(query)\n except DatabaseConnectionError:\n log.error(\"Can't figure out the least active users...\")\n return\n\n if not cursor.rowcount:\n log.warning(\"There are no users in the db\")\n return\n\n # Make list out of tuple of tuples that is returned by MySQL\n least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]\n log.info('Removing %d least active users from cache...', limit)\n num_deleted_entries = 0\n for entry in least_active_users:\n log.debug('Deleting %s...', entry)\n deleted_entry = self.users.pop(entry, None)\n if deleted_entry:\n num_deleted_entries += 1\n log.debug(\"%d users were removed from cache.\", num_deleted_entries)","target":" def clean_cache(self, limit):\n \"\"\"\n Method that remove several User objects from cache - the least \n active users\n :param limit: number of the users that the method should remove\n from cache\n :return: None\n \"\"\"\n\n log.info('Figuring out the least active users...')\n # Select users that the least active recently\n user_ids = tuple(self.users.keys())\n query = ('SELECT chat_id '\n 'FROM photo_queries_table2 '\n f'WHERE chat_id in {user_ids} '\n 'GROUP BY chat_id '\n 'ORDER BY MAX(time) '\n f'LIMIT %s')\n\n parameters = limit,\n\n try:\n cursor = db.execute_query(query, parameters)\n except DatabaseConnectionError:\n log.error(\"Can't figure out the least active users...\")\n return\n\n if not cursor.rowcount:\n log.warning(\"There are no users in the db\")\n return\n\n # Make list out of tuple of tuples that is returned by MySQL\n least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]\n log.info('Removing %d least active users from cache...', limit)\n num_deleted_entries = 0\n for entry in least_active_users:\n log.debug('Deleting %s...', entry)\n deleted_entry = self.users.pop(entry, None)\n if deleted_entry:\n num_deleted_entries += 1\n log.debug(\"%d users were removed from cache.\", num_deleted_entries)","lang":"python","vul_type":"cwe-089","target_token_count":310,"sven_meta":{"func_name":"clean_cache","file_name":"photogpsbot/users.py","commit_link":"github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#120-a79c4d358af0","input":"@app.route('/movies/add', methods=['GET', 'POST'])\ndef add_movie():\n form = MovieForm()\n if not form.validate_on_submit():\n return render_template('new_movie.html', title='Add New Movie', form=form)\n lang_id = add_language(form.data['language'])\n movie = {\n 'title': '',\n 'description': '',\n 'release_year': 0,\n 'rental_duration': 0,\n 'rental_rate': 0.00,\n 'length': 0,\n 'replacement_cost': 0.00\n }\n for k, v in movie.items():\n movie[k] = form.data[k]\n movie['language_id'] = movie.get('language_id', lang_id)\n cur.execute(\n \"\"\"\n INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost)\n VALUES ('{}', '{}', {}, {}, {}, {}, {}, {})\n \"\"\".format(*[v for k, v in movie.items()])\n )\n try:\n cur.execute(f\"SELECT * FROM film where fulltext @@ to_tsquery('Dark Knight')\")\n res = cur.fetchall()\n conn.commit()\n return redirect(url_for('movies'))\n except Exception as e:\n return redirect(url_for('index'))","target":"@app.route('/movies/add', methods=['GET', 'POST'])\ndef add_movie():\n form = MovieForm()\n if not form.validate_on_submit():\n return render_template('new_movie.html', title='Add New Movie', form=form)\n lang_id = add_language(form.data['language'])\n movie = {\n 'title': '',\n 'description': '',\n 'release_year': 0,\n 'rental_duration': 0,\n 'rental_rate': 0.00,\n 'length': 0,\n 'replacement_cost': 0.00\n }\n for k, v in movie.items():\n movie[k] = form.data[k]\n movie['language_id'] = movie.get('language_id', lang_id)\n cur.execute(\n \"\"\"\n INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\", [(v, ) for k, v in movie.items()]\n )\n try:\n cur.execute(\"SELECT * FROM film where fulltext @@ to_tsquery(%s)\", (movie['title'], ))\n res = cur.fetchall()\n conn.commit()\n return redirect(url_for('movies'))\n except Exception as e:\n return redirect(url_for('index'))","lang":"python","vul_type":"cwe-089","target_token_count":291,"sven_meta":{"func_name":"add_movie","file_name":"app.py","commit_link":"github.com/Elbertbiggs360/dvdrental/commit/ad144ae2a08a332498d0831bc255170d57ba754b","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#134-6815b513f87c","input":" def fetch_resultSet(self, session, id):\n self._openContainer(session)\n\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = (\"SELECT class, data FROM %s WHERE identifier = '%s';\" %\n (self.table, sid)\n )\n res = self._query(query)\n try:\n rdict = res.dictresult()[0]\n except IndexError:\n raise ObjectDoesNotExistException('%s/%s' % (self.id, sid))\n\n data = rdict['data']\n try:\n ndata = pg.unescape_bytea(data)\n except:\n # Insufficient PyGreSQL version\n ndata = data.replace(\"\\\\'\", \"'\")\n\n ndata = ndata.replace('\\\\000', '\\x00')\n ndata = ndata.replace('\\\\012', '\\n')\n # data is res.dictresult()\n cl = rdict['class']\n rset = dynamic.buildObject(session, cl, [[]])\n rset.deserialize(session, ndata)\n rset.id = id\n\n # Update expires\n now = time.time()\n nowStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(now))\n expires = now + self.get_default(session, 'expires', 600)\n rset.timeExpires = expires\n expiresStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(expires))\n\n query = (\"UPDATE %s SET timeAccessed = '%s', expires = '%s' \"\n \"WHERE identifier = '%s';\" %\n (self.table, nowStr, expiresStr, sid)\n )\n self._query(query)\n return rset","target":" def fetch_resultSet(self, session, id):\n self._openContainer(session)\n\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = (\"SELECT class, data FROM %s WHERE identifier = $1;\" %\n (self.table)\n )\n res = self._query(query, sid)\n try:\n rdict = res.dictresult()[0]\n except IndexError:\n raise ObjectDoesNotExistException('%s/%s' % (self.id, sid))\n\n data = rdict['data']\n try:\n ndata = pg.unescape_bytea(data)\n except:\n # Insufficient PyGreSQL version\n ndata = data.replace(\"\\\\'\", \"'\")\n\n ndata = ndata.replace('\\\\000', '\\x00')\n ndata = ndata.replace('\\\\012', '\\n')\n # data is res.dictresult()\n cl = rdict['class']\n rset = dynamic.buildObject(session, cl, [[]])\n rset.deserialize(session, ndata)\n rset.id = id\n\n # Update expires\n now = time.time()\n nowStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(now))\n expires = now + self.get_default(session, 'expires', 600)\n rset.timeExpires = expires\n expiresStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(expires))\n\n query = (\"UPDATE %s SET timeAccessed = $1, expires = $2 \"\n \"WHERE identifier = $3;\" % (self.table)\n )\n self._query(query, nowStr, expiresStr, sid)\n return rset","lang":"python","vul_type":"cwe-089","target_token_count":378,"sven_meta":{"func_name":"fetch_resultSet","file_name":"cheshire3/sql/resultSetStore.py","commit_link":"github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#151-8bfb8968ccf5","input":"def create_cf_base():\n url = 'http://codeforces.com/problemset/'\n r = requests.get(url)\n max_page = 0\n soup = BeautifulSoup(r.text, \"lxml\")\n base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\cf.db\")\n conn = base.cursor()\n conn.execute(\"create table problems (problem INTEGER, diff CHAR)\")\n for i in available_tags:\n conn.execute(\"create table \" + i + \" (problems INTEGER, diff CHAR)\")\n\n for link in soup.find_all(attrs={\"class\" : \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[3]))\n\n a = 0\n b = 0\n f = False\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n old = ''\n for link in soup.find_all('a'):\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5 and old != s[3] + s[4]:\n a = s[3]\n b = s[4]\n old = s[3] + s[4]\n if not f:\n f = True\n last_update = old\n conn.execute(\"insert into problems values (?, ?)\", (a, b))\n if len(s) == 4 and s[3] in available_tags:\n conn.execute(\"insert into \" + s[3] + \" values (?, ?)\", (a, b))\n\n base.commit()\n base.close()\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)\")\n conn.execute(\"create table last_update_problemset (problem STRING)\")\n conn.execute(\"insert into last_update_problemset values (?)\", (last_update, ))\n settings.commit()\n settings.close()","target":"def create_cf_base():\n url = 'http://codeforces.com/problemset/'\n r = requests.get(url)\n max_page = 0\n soup = BeautifulSoup(r.text, \"lxml\")\n base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\cf.db\")\n conn = base.cursor()\n conn.execute(\"create table problems (problem INTEGER, diff CHAR)\")\n for i in available_tags:\n conn.execute(\"create table ? (problems INTEGER, diff CHAR)\", (i,))\n\n for link in soup.find_all(attrs={\"class\" : \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[3]))\n\n a = 0\n b = 0\n f = False\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n old = ''\n for link in soup.find_all('a'):\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5 and old != s[3] + s[4]:\n a = s[3]\n b = s[4]\n old = s[3] + s[4]\n if not f:\n f = True\n last_update = old\n conn.execute(\"insert into problems values (?, ?)\", (a, b))\n if len(s) == 4 and s[3] in available_tags:\n conn.execute(\"insert into ? values (?, ?)\", (s[3], a, b))\n\n base.commit()\n base.close()\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)\")\n conn.execute(\"create table last_update_problemset (problem STRING)\")\n conn.execute(\"insert into last_update_problemset values (?)\", (last_update, ))\n settings.commit()\n settings.close()","lang":"python","vul_type":"cwe-089","target_token_count":480,"sven_meta":{"func_name":"create_cf_base","file_name":"bases/createcfbase.py","commit_link":"github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#156-62894e526f8a","input":" def callback(recipeName):\n menu.pack_forget()\n viewRecipeFrame.pack(expand=True, fill='both')\n groceryButton.pack_forget()\n database_file = \"meal_planner.db\"\n print(recipeName)\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n selection = cursor.execute(\"\"\"SELECT * FROM recipe WHERE name = \"\"\" + \"\\\"\" + recipeName + \"\\\"\")\n for result in [selection]:\n for row in result.fetchall():\n name = row[0]\n time = row[1]\n servings = row[2]\n ingredients = row[4]\n directions = row[5]\n\n string = (\"Name: {} \\n Cook time: {} \\n Number of Servings: {} \\n \".format(name, time, servings))\n secondString = (\"Ingredients: {}\".format(ingredients))\n thirdString = (\"Directions: {}\".format(directions))\n Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [viewRecipeFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)","target":" def callback(recipeName):\n menu.pack_forget()\n viewRecipeFrame.pack(expand=True, fill='both')\n groceryButton.pack_forget()\n database_file = \"meal_planner.db\"\n print(recipeName)\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n selection = cursor.execute(\"\"\"SELECT * FROM recipe WHERE name = ?;\"\"\", (recipeName, ))\n for result in [selection]:\n for row in result.fetchall():\n name = row[0]\n time = row[1]\n servings = row[2]\n ingredients = row[4]\n directions = row[5]\n\n string = (\"Name: {} \\n Cook time: {} \\n Number of Servings: {} \\n \".format(name, time, servings))\n secondString = (\"Ingredients: {}\".format(ingredients))\n thirdString = (\"Directions: {}\".format(directions))\n Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [viewRecipeFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)","lang":"python","vul_type":"cwe-089","target_token_count":377,"sven_meta":{"func_name":"__init__.callback","file_name":"mealPlan.py","commit_link":"github.com/trishamoyer/RecipePlanner-Python/commit/44d2ce370715d9344fad34b3b749322ab095a925","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#167-f3778c74e1dc","input":"@app.route('/top_proxies')\ndef top_proxies():\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT sum(amount) FROM holders\"\n cur.execute(query)\n total = cur.fetchone()\n total_votes = total[0]\n\n query = \"SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as\"\n cur.execute(query)\n results = cur.fetchall()\n #con.close()\n\n proxies = []\n\n for p in range(0, len(results)):\n\n proxy_line = [0] * 5\n\n proxy_id = results[p][0]\n proxy_line[0] = proxy_id\n\n query = \"SELECT account_name, amount FROM holders WHERE account_id='\"+proxy_id+\"' LIMIT 1\"\n cur.execute(query)\n proxy = cur.fetchone()\n\n try:\n proxy_name = proxy[0]\n proxy_amount = proxy[1]\n except:\n proxy_name = \"unknown\"\n proxy_amount = 0\n\n\n proxy_line[1] = proxy_name\n\n query = \"SELECT amount, account_id FROM holders WHERE voting_as='\"+proxy_id+\"'\"\n cur.execute(query)\n results2 = cur.fetchall()\n\n proxy_line[2] = int(proxy_amount)\n\n for p2 in range(0, len(results2)):\n amount = results2[p2][0]\n account_id = results2[p2][1]\n proxy_line[2] = proxy_line[2] + int(amount) # total proxy votes\n proxy_line[3] = proxy_line[3] + 1 # followers\n\n if proxy_line[3] > 2:\n percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes))\n proxy_line[4] = percentage\n proxies.append(proxy_line)\n\n con.close()\n\n proxies = sorted(proxies, key=lambda k: int(k[2]))\n r_proxies = proxies[::-1]\n\n return jsonify(filter(None, r_proxies))","target":"@app.route('/top_proxies')\ndef top_proxies():\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT sum(amount) FROM holders\"\n cur.execute(query)\n total = cur.fetchone()\n total_votes = total[0]\n\n query = \"SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as\"\n cur.execute(query)\n results = cur.fetchall()\n #con.close()\n\n proxies = []\n\n for p in range(0, len(results)):\n\n proxy_line = [0] * 5\n\n proxy_id = results[p][0]\n proxy_line[0] = proxy_id\n\n query = \"SELECT account_name, amount FROM holders WHERE account_id=%s LIMIT 1\"\n cur.execute(query, (proxy_id,))\n proxy = cur.fetchone()\n\n try:\n proxy_name = proxy[0]\n proxy_amount = proxy[1]\n except:\n proxy_name = \"unknown\"\n proxy_amount = 0\n\n\n proxy_line[1] = proxy_name\n\n query = \"SELECT amount, account_id FROM holders WHERE voting_as=%s\"\n cur.execute(query, (proxy_id,))\n results2 = cur.fetchall()\n\n proxy_line[2] = int(proxy_amount)\n\n for p2 in range(0, len(results2)):\n amount = results2[p2][0]\n account_id = results2[p2][1]\n proxy_line[2] = proxy_line[2] + int(amount) # total proxy votes\n proxy_line[3] = proxy_line[3] + 1 # followers\n\n if proxy_line[3] > 2:\n percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes))\n proxy_line[4] = percentage\n proxies.append(proxy_line)\n\n con.close()\n\n proxies = sorted(proxies, key=lambda k: int(k[2]))\n r_proxies = proxies[::-1]\n\n return jsonify(filter(None, r_proxies))","lang":"python","vul_type":"cwe-089","target_token_count":433,"sven_meta":{"func_name":"top_proxies","file_name":"api.py","commit_link":"github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#176-66927d1ecd10","input":" @staticmethod\n def get_last_active_users(limit):\n \"\"\"\n Get from the database a tuple of users who have been recently using\n the bot\n :param limit: integer that specifies how much users to get\n :return: tuple of tuples with users info\n \"\"\"\n log.info('Evaluating last active users with date of '\n 'last time when they used bot...')\n\n # From photo_queries_table2 we take chat_id of the last\n # active users and from 'users' table we take info about these\n # users by chat_id which is a foreign key\n query = ('SELECT p.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'FROM photo_queries_table2 p '\n 'INNER JOIN users u '\n 'ON p.chat_id = u.chat_id '\n 'GROUP BY u.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'ORDER BY MAX(time)'\n f'DESC LIMIT {limit}')\n\n try:\n cursor = db.execute_query(query)\n except DatabaseConnectionError:\n log.error(\"Cannot get the last active users because of some \"\n \"problems with the database\")\n raise\n\n last_active_users = cursor.fetchall()\n return last_active_users","target":" @staticmethod\n def get_last_active_users(limit):\n \"\"\"\n Get from the database a tuple of users who have been recently using\n the bot\n :param limit: integer that specifies how much users to get\n :return: tuple of tuples with users info\n \"\"\"\n log.info('Evaluating last active users with date of '\n 'last time when they used bot...')\n\n # From photo_queries_table2 we take chat_id of the last\n # active users and from 'users' table we take info about these\n # users by chat_id which is a foreign key\n query = ('SELECT p.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'FROM photo_queries_table2 p '\n 'INNER JOIN users u '\n 'ON p.chat_id = u.chat_id '\n 'GROUP BY u.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'ORDER BY MAX(time)'\n f'DESC LIMIT %s')\n\n parameters = limit,\n\n try:\n cursor = db.execute_query(query, parameters)\n except DatabaseConnectionError:\n log.error(\"Cannot get the last active users because of some \"\n \"problems with the database\")\n raise\n\n last_active_users = cursor.fetchall()\n return last_active_users","lang":"python","vul_type":"cwe-089","target_token_count":281,"sven_meta":{"func_name":"get_last_active_users","file_name":"photogpsbot/users.py","commit_link":"github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#178-1a1f148dbb25","input":"def update_institutions(conn, sqlite, k10plus, ai):\n \"\"\"\n Update the institution table.\n \"\"\"\n current_institutions = get_all_current_institutions(k10plus, ai)\n old_institutions = get_all_old_institutions(conn, sqlite)\n\n # Check if the institution table is allready filled and this is not the first checkup\n institution_table_is_filled = len(old_institutions) > 10\n\n for old_institution in old_institutions:\n if institution_table_is_filled and old_institution not in current_institutions:\n message = \"Die ISIL %s ist im aktuellen Import nicht mehr vorhanden.\\nWenn dies beabsichtigt ist, bitte die Institution aus der Datenbank loeschen.\" % old_institution\n send_message(message)\n\n for current_institution in current_institutions:\n if current_institution == \" \" or '\"' in current_institution:\n continue\n if current_institution not in old_institutions:\n message = \"The institution %s is new in Solr.\" % current_institution\n if institution_table_is_filled:\n send_message(message)\n else:\n logging.info(message)\n sql = \"INSERT INTO institution (institution) VALUES ('%s')\" % current_institution\n sqlite.execute(sql)\n conn.commit()","target":"def update_institutions(conn, sqlite, k10plus, ai):\n \"\"\"\n Update the institution table.\n \"\"\"\n current_institutions = get_all_current_institutions(k10plus, ai)\n old_institutions = get_all_old_institutions(conn, sqlite)\n\n # Check if the institution table is allready filled and this is not the first checkup\n institution_table_is_filled = len(old_institutions) > 10\n\n for old_institution in old_institutions:\n if institution_table_is_filled and old_institution not in current_institutions:\n message = \"Die ISIL %s ist im aktuellen Import nicht mehr vorhanden.\\nWenn dies beabsichtigt ist, bitte die Institution aus der Datenbank loeschen.\" % old_institution\n send_message(message)\n\n for current_institution in current_institutions:\n if current_institution == \" \" or '\"' in current_institution:\n continue\n if current_institution not in old_institutions:\n message = \"The institution %s is new in Solr.\" % current_institution\n if institution_table_is_filled:\n send_message(message)\n else:\n logging.info(message)\n sql = \"INSERT INTO institution (institution) VALUES (?)\"\n sqlite.execute(sql, (current_institution,))\n conn.commit()","lang":"python","vul_type":"cwe-089","target_token_count":270,"sven_meta":{"func_name":"update_institutions","file_name":"bin/solrcheckup.py","commit_link":"github.com/miku/siskin/commit/7fa398d2fea72bf2e8b4808f75df4b3d35ae959a","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-089#181-05b7cb5ad097","input":"@app.route('/sloka')\ndef sloka():\n\n sloka_number = request.args.get('sloka_number')\n\n sloka_number_parts = sloka_number.split('.')\n\n sloka_number_previous = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])-1)\n sloka_number_next = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])+1)\n\n try:\n with sql.connect('amara.db') as con:\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"select * from mula where sloka_number = '%s' order by sloka_line;\" % sloka_number)\n mula = cur.fetchall();\n\n cur.execute(\"select * from pada where sloka_number = '%s' order by id;\" % sloka_number)\n pada = cur.fetchall();\n\n varga = \"\"\n if len(pada) > 0:\n varga = pada[0][\"varga\"]\n\n return render_template('sloka.html', mula=mula, pada=pada, varga=varga, sloka_number=sloka_number, sloka_number_previous=sloka_number_previous, sloka_number_next=sloka_number_next)\n finally:\n con.close()","target":"@app.route('/sloka')\ndef sloka():\n\n sloka_number = request.args.get('sloka_number')\n\n sloka_number_parts = sloka_number.split('.')\n\n sloka_number_previous = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])-1)\n sloka_number_next = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])+1)\n\n try:\n with sql.connect('amara.db') as con:\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"select * from mula where sloka_number = ? order by sloka_line;\", [sloka_number])\n mula = cur.fetchall();\n\n cur.execute(\"select * from pada where sloka_number = ? order by id;\", [sloka_number])\n pada = cur.fetchall();\n\n varga = \"\"\n if len(pada) > 0:\n varga = pada[0][\"varga\"]\n\n return render_template('sloka.html', mula=mula, pada=pada, varga=varga, sloka_number=sloka_number, sloka_number_previous=sloka_number_previous, sloka_number_next=sloka_number_next)\n finally:\n con.close()","lang":"python","vul_type":"cwe-089","target_token_count":297,"sven_meta":{"func_name":"sloka","file_name":"docker/app.py","commit_link":"github.com/aupasana/amara-quiz/commit/6ceb5dc8ec38b4a3f1399e578ab970f7e3354922","source_cwe_file":"cwe-089.jsonl"}}
{"problem_id":"cwe-125#2-35e661c51311","input":"static int ng_pkt(git_pkt **out, const char *line, size_t len)\n{\n\tgit_pkt_ng *pkt;\n\tconst char *ptr;\n\tsize_t alloclen;\n\n\tpkt = git__malloc(sizeof(*pkt));\n\tGITERR_CHECK_ALLOC(pkt);\n\n\tpkt->ref = NULL;\n\tpkt->type = GIT_PKT_NG;\n\n\tline += 3; /* skip \"ng \" */\n\tif (!(ptr = strchr(line, ' ')))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->ref = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->ref);\n\n\tmemcpy(pkt->ref, line, len);\n\tpkt->ref[len] = '\\0';\n\n\tline = ptr + 1;\n\tif (!(ptr = strchr(line, '\\n')))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->msg = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->msg);\n\n\tmemcpy(pkt->msg, line, len);\n\tpkt->msg[len] = '\\0';\n\n\t*out = (git_pkt *)pkt;\n\treturn 0;\n\nout_err:\n\tgiterr_set(GITERR_NET, \"invalid packet line\");\n\tgit__free(pkt->ref);\n\tgit__free(pkt);\n\treturn -1;\n}","target":"static int ng_pkt(git_pkt **out, const char *line, size_t len)\n{\n\tgit_pkt_ng *pkt;\n\tconst char *ptr;\n\tsize_t alloclen;\n\n\tpkt = git__malloc(sizeof(*pkt));\n\tGITERR_CHECK_ALLOC(pkt);\n\n\tpkt->ref = NULL;\n\tpkt->type = GIT_PKT_NG;\n\n\tif (len < 3)\n\t\tgoto out_err;\n\tline += 3; /* skip \"ng \" */\n\tlen -= 3;\n\tif (!(ptr = memchr(line, ' ', len)))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->ref = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->ref);\n\n\tmemcpy(pkt->ref, line, len);\n\tpkt->ref[len] = '\\0';\n\n\tif (len < 1)\n\t\tgoto out_err;\n\tline = ptr + 1;\n\tlen -= 1;\n\tif (!(ptr = memchr(line, '\\n', len)))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->msg = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->msg);\n\n\tmemcpy(pkt->msg, line, len);\n\tpkt->msg[len] = '\\0';\n\n\t*out = (git_pkt *)pkt;\n\treturn 0;\n\nout_err:\n\tgiterr_set(GITERR_NET, \"invalid packet line\");\n\tgit__free(pkt->ref);\n\tgit__free(pkt);\n\treturn -1;\n}","lang":"c","vul_type":"cwe-125","target_token_count":330,"sven_meta":{"func_name":"ng_pkt","file_name":"src/transports/smart_pkt.c","commit_link":"github.com/libgit2/libgit2/commit/1f9a8510e1d2f20ed7334eeeddb92c4dd8e7c649","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#11-52c63e4eb17a","input":"static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {\n\t// Skip whitespace\n\twhile (begin && isspace ((ut8)str[*begin])) {\n\t\t++(*begin);\n\t}\n\n\tif (!str[*begin]) { // null byte\n\t\t*end = *begin;\n\t\treturn TT_EOF;\n\t} else if (isalpha ((ut8)str[*begin])) { // word token\n\t\t*end = *begin;\n\t\twhile (end && isalnum ((ut8)str[*end])) {\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_WORD;\n\t} else if (isdigit ((ut8)str[*begin])) { // number token\n\t\t*end = *begin;\n\t\twhile (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_NUMBER;\n\t} else { // special character: [, ], +, *, ...\n\t\t*end = *begin + 1;\n\t\treturn TT_SPECIAL;\n\t}\n}","target":"static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {\n\tif (*begin > strlen (str)) {\n\t\treturn TT_EOF;\n\t}\n\t// Skip whitespace\n\twhile (begin && str[*begin] && isspace ((ut8)str[*begin])) {\n\t\t++(*begin);\n\t}\n\n\tif (!str[*begin]) { // null byte\n\t\t*end = *begin;\n\t\treturn TT_EOF;\n\t}\n\tif (isalpha ((ut8)str[*begin])) { // word token\n\t\t*end = *begin;\n\t\twhile (end && str[*end] && isalnum ((ut8)str[*end])) {\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_WORD;\n\t}\n\tif (isdigit ((ut8)str[*begin])) { // number token\n\t\t*end = *begin;\n\t\twhile (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_NUMBER;\n\t} else { // special character: [, ], +, *, ...\n\t\t*end = *begin + 1;\n\t\treturn TT_SPECIAL;\n\t}\n}","lang":"c","vul_type":"cwe-125","target_token_count":260,"sven_meta":{"func_name":"getToken","file_name":"libr/asm/p/asm_x86_nz.c","commit_link":"github.com/radare/radare2/commit/66191f780863ea8c66ace4040d0d04a8842e8432","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#12-f4464d5af6a0","input":"fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)\n{\n struct mrb_context *c = fiber_check(mrb, self);\n struct mrb_context *old_c = mrb->c;\n mrb_value value;\n\n fiber_check_cfunc(mrb, c);\n if (resume && c->status == MRB_FIBER_TRANSFERRED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n }\n if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"double resume (fib)\");\n }\n if (c->status == MRB_FIBER_TERMINATED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n }\n mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n if (c->status == MRB_FIBER_CREATED) {\n mrb_value *b, *e;\n\n if (len >= c->stend - c->stack) {\n mrb_raise(mrb, E_FIBER_ERROR, \"too many arguments to fiber\");\n }\n b = c->stack+1;\n e = b + len;\n while (b<e) {\n *b++ = *a++;\n }\n c->cibase->argc = (int)len;\n value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];\n }\n else {\n value = fiber_result(mrb, a, len);\n }\n fiber_switch_context(mrb, c);\n\n if (vmexec) {\n c->vmexec = TRUE;\n value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);\n mrb->c = old_c;\n }\n else {\n MARK_CONTEXT_MODIFY(c);\n }\n return value;\n}","target":"fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)\n{\n struct mrb_context *c = fiber_check(mrb, self);\n struct mrb_context *old_c = mrb->c;\n enum mrb_fiber_state status;\n mrb_value value;\n\n fiber_check_cfunc(mrb, c);\n status = c->status;\n if (resume && status == MRB_FIBER_TRANSFERRED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n }\n if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"double resume (fib)\");\n }\n if (status == MRB_FIBER_TERMINATED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n }\n old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n fiber_switch_context(mrb, c);\n if (status == MRB_FIBER_CREATED) {\n mrb_value *b, *e;\n\n mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */\n b = c->stack+1;\n e = b + len;\n while (b<e) {\n *b++ = *a++;\n }\n c->cibase->argc = (int)len;\n value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];\n }\n else {\n value = fiber_result(mrb, a, len);\n }\n\n if (vmexec) {\n c->vmexec = TRUE;\n value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);\n mrb->c = old_c;\n }\n else {\n MARK_CONTEXT_MODIFY(c);\n }\n return value;\n}","lang":"c","vul_type":"cwe-125","target_token_count":459,"sven_meta":{"func_name":"fiber_switch","file_name":"mrbgems/mruby-fiber/src/fiber.c","commit_link":"github.com/mruby/mruby/commit/778500563a9f7ceba996937dc886bd8cde29b42b","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#26-bb743c820ecd","input":"PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast<SgxParams *>(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast<void *>(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast<void *>(sgx_params->input));\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}","target":"PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast<SgxParams *>(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast<void *>(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast<void *>(sgx_params->input));\n }\n if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n sgx_params->output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}","lang":"cpp","vul_type":"cwe-125","target_token_count":410,"sven_meta":{"func_name":"asylo::primitives::TrustedPrimitives::UntrustedCall","file_name":"asylo/platform/primitives/sgx/trusted_sgx.cc","commit_link":"github.com/google/asylo/commit/83036fd841d33baa7e039f842d131aa7881fdcc2","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#29-45f421d471b1","input":"rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)\n{\n\tint i;\n\trdpBitmapCache* bitmapCache;\n\tbitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));\n\n\tif (!bitmapCache)\n\t\treturn NULL;\n\n\tbitmapCache->settings = settings;\n\tbitmapCache->update = ((freerdp*)settings->instance)->update;\n\tbitmapCache->context = bitmapCache->update->context;\n\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n\tbitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));\n\n\tif (!bitmapCache->cells)\n\t\tgoto fail;\n\n\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t{\n\t\tbitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;\n\t\t/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */\n\t\tbitmapCache->cells[i].entries =\n\t\t (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));\n\n\t\tif (!bitmapCache->cells[i].entries)\n\t\t\tgoto fail;\n\t}\n\n\treturn bitmapCache;\nfail:\n\n\tif (bitmapCache->cells)\n\t{\n\t\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t\t\tfree(bitmapCache->cells[i].entries);\n\t}\n\n\tfree(bitmapCache);\n\treturn NULL;\n}","target":"rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)\n{\n\tint i;\n\trdpBitmapCache* bitmapCache;\n\tbitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));\n\n\tif (!bitmapCache)\n\t\treturn NULL;\n\n\tbitmapCache->settings = settings;\n\tbitmapCache->update = ((freerdp*)settings->instance)->update;\n\tbitmapCache->context = bitmapCache->update->context;\n\tbitmapCache->cells =\n\t (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL));\n\n\tif (!bitmapCache->cells)\n\t\tgoto fail;\n\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n\n\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t{\n\t\tbitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;\n\t\t/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */\n\t\tbitmapCache->cells[i].entries =\n\t\t (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));\n\n\t\tif (!bitmapCache->cells[i].entries)\n\t\t\tgoto fail;\n\t}\n\n\treturn bitmapCache;\nfail:\n\n\tif (bitmapCache->cells)\n\t{\n\t\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t\t\tfree(bitmapCache->cells[i].entries);\n\t}\n\n\tfree(bitmapCache);\n\treturn NULL;\n}","lang":"c","vul_type":"cwe-125","target_token_count":321,"sven_meta":{"func_name":"bitmap_cache_new","file_name":"libfreerdp/cache/bitmap.c","commit_link":"github.com/FreeRDP/FreeRDP/commit/58dc36b3c883fd460199cedb6d30e58eba58298c","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#30-d8cc4cd71435","input":"ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 n;\n UINT8* ptr;\n\n if ((state->xsize * state->bits + 7) / 8 > state->bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n ptr = buf;\n\n for (;;) {\n\n\tif (bytes < 1)\n\t return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t /* Run */\n\t if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t n = ptr[0] & 0x3F;\n\n\t while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t }\n\n\t ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t /* Literal */\n\t state->buffer[state->x++] = ptr[0];\n\t ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n if (state->bytes % state->xsize && state->bytes > state->xsize) {\n int bands = state->bytes / state->xsize;\n int stride = state->bytes / bands;\n int i;\n for (i=1; i< bands; i++) { // note -- skipping first band\n memmove(&state->buffer[i*state->xsize],\n &state->buffer[i*stride],\n state->xsize);\n }\n }\n\t /* Got a full line, unpack it */\n\t state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t state->xoff * im->pixelsize, state->buffer,\n\t\t\t state->xsize);\n\n\t state->x = 0;\n\n\t if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t }\n\t}\n\n }\n}","target":"ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 n;\n UINT8* ptr;\n\n if ((state->xsize * state->bits + 7) / 8 > state->bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n ptr = buf;\n\n for (;;) {\n\n\tif (bytes < 1)\n\t return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t /* Run */\n\t if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t n = ptr[0] & 0x3F;\n\n\t while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t }\n\n\t ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t /* Literal */\n\t state->buffer[state->x++] = ptr[0];\n\t ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n if (state->bytes % state->xsize && state->bytes > state->xsize) {\n int bands = state->bytes / state->xsize;\n int stride = state->bytes / bands;\n int i;\n for (i=1; i< bands; i++) { // note -- skipping first band\n memmove(&state->buffer[i*state->xsize],\n &state->buffer[i*stride],\n state->xsize);\n }\n }\n\t /* Got a full line, unpack it */\n\t state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t state->xoff * im->pixelsize, state->buffer,\n\t\t\t state->xsize);\n\n\t state->x = 0;\n\n\t if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t }\n\t}\n\n }\n}","lang":"c","vul_type":"cwe-125","target_token_count":462,"sven_meta":{"func_name":"ImagingPcxDecode","file_name":"src/libImaging/PcxDecode.c","commit_link":"github.com/python-pillow/Pillow/commit/6a83e4324738bb0452fbe8074a995b1c73f08de7#diff-9478f2787e3ae9668a15123b165c23ac","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#45-1caa0ec74d5c","input":"static const struct usb_cdc_union_desc *\nims_pcu_get_cdc_union_desc(struct usb_interface *intf)\n{\n\tconst void *buf = intf->altsetting->extra;\n\tsize_t buflen = intf->altsetting->extralen;\n\tstruct usb_cdc_union_desc *union_desc;\n\n\tif (!buf) {\n\t\tdev_err(&intf->dev, \"Missing descriptor data\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (!buflen) {\n\t\tdev_err(&intf->dev, \"Zero length descriptor\\n\");\n\t\treturn NULL;\n\t}\n\n\twhile (buflen > 0) {\n\t\tunion_desc = (struct usb_cdc_union_desc *)buf;\n\n\t\tif (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&\n\t\t union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {\n\t\t\tdev_dbg(&intf->dev, \"Found union header\\n\");\n\t\t\treturn union_desc;\n\t\t}\n\n\t\tbuflen -= union_desc->bLength;\n\t\tbuf += union_desc->bLength;\n\t}\n\n\tdev_err(&intf->dev, \"Missing CDC union descriptor\\n\");\n\treturn NULL;","target":"static const struct usb_cdc_union_desc *\nims_pcu_get_cdc_union_desc(struct usb_interface *intf)\n{\n\tconst void *buf = intf->altsetting->extra;\n\tsize_t buflen = intf->altsetting->extralen;\n\tstruct usb_cdc_union_desc *union_desc;\n\n\tif (!buf) {\n\t\tdev_err(&intf->dev, \"Missing descriptor data\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (!buflen) {\n\t\tdev_err(&intf->dev, \"Zero length descriptor\\n\");\n\t\treturn NULL;\n\t}\n\n\twhile (buflen >= sizeof(*union_desc)) {\n\t\tunion_desc = (struct usb_cdc_union_desc *)buf;\n\n\t\tif (union_desc->bLength > buflen) {\n\t\t\tdev_err(&intf->dev, \"Too large descriptor\\n\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&\n\t\t union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {\n\t\t\tdev_dbg(&intf->dev, \"Found union header\\n\");\n\n\t\t\tif (union_desc->bLength >= sizeof(*union_desc))\n\t\t\t\treturn union_desc;\n\n\t\t\tdev_err(&intf->dev,\n\t\t\t\t\"Union descriptor to short (%d vs %zd\\n)\",\n\t\t\t\tunion_desc->bLength, sizeof(*union_desc));\n\t\t\treturn NULL;\n\t\t}\n\n\t\tbuflen -= union_desc->bLength;\n\t\tbuf += union_desc->bLength;\n\t}\n\n\tdev_err(&intf->dev, \"Missing CDC union descriptor\\n\");\n\treturn NULL;","lang":"c","vul_type":"cwe-125","target_token_count":319,"sven_meta":{"func_name":"ims_pcu_get_cdc_union_desc","file_name":"drivers/input/misc/ims-pcu.c","commit_link":"github.com/torvalds/linux/commit/ea04efee7635c9120d015dcdeeeb6988130cb67a","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#48-c874577075bf","input":"int enc_untrusted_inet_pton(int af, const char *src, void *dst) {\n if (!src || !dst) {\n return 0;\n }\n\n MessageWriter input;\n input.Push<int>(TokLinuxAfFamily(af));\n input.PushByReference(Extent{\n src, std::min(strlen(src) + 1, static_cast<size_t>(INET6_ADDRSTRLEN))});\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetPtonHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_pton\", 3);\n\n int result = output.next<int>();\n int klinux_errno = output.next<int>();\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return -1;\n }\n\n auto klinux_addr_buffer = output.next();\n size_t max_size = 0;\n if (af == AF_INET) {\n max_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n max_size = sizeof(struct in6_addr);\n }\n memcpy(dst, klinux_addr_buffer.data(),\n std::min(klinux_addr_buffer.size(), max_size));\n return result;\n}","target":"int enc_untrusted_inet_pton(int af, const char *src, void *dst) {\n if (!src || !dst) {\n return 0;\n }\n\n MessageWriter input;\n input.Push<int>(TokLinuxAfFamily(af));\n input.PushByReference(Extent{\n src, std::min(strlen(src) + 1, static_cast<size_t>(INET6_ADDRSTRLEN))});\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetPtonHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_pton\", 3);\n\n int result = output.next<int>();\n int klinux_errno = output.next<int>();\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return -1;\n }\n\n auto klinux_addr_buffer = output.next();\n size_t max_size = 0;\n if (af == AF_INET) {\n if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_inet_pton: unexpected output size\");\n }\n max_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_inet_pton: unexpected output size\");\n }\n max_size = sizeof(struct in6_addr);\n }\n memcpy(dst, klinux_addr_buffer.data(),\n std::min(klinux_addr_buffer.size(), max_size));\n return result;\n}","lang":"cpp","vul_type":"cwe-125","target_token_count":383,"sven_meta":{"func_name":"enc_untrusted_inet_pton","file_name":"asylo/platform/host_call/trusted/host_calls.cc","commit_link":"github.com/google/asylo/commit/8fed5e334131abaf9c5e17307642fbf6ce4a57ec","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#54-fe942f41e450","input":"static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}","target":"static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut + 1;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}","lang":"c","vul_type":"cwe-125","target_token_count":270,"sven_meta":{"func_name":"voutf","file_name":"src/tool_msgs.c","commit_link":"github.com/curl/curl/commit/d530e92f59ae9bb2d47066c3c460b25d2ffeb211","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#56-39bb903aabe7","input":"static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n{\n int i, j, v;\n\n if (get_bits1(gb)) {\n /* intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->intra_matrix[j] = v;\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n /* non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n if (get_bits1(gb)) {\n /* chroma_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n /* chroma_non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n next_start_code_studio(gb);\n}","target":"static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n{\n int i, j, v;\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->intra_matrix[j] = v;\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* chroma_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* chroma_non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n next_start_code_studio(gb);\n return 0;\n}","lang":"c","vul_type":"cwe-125","target_token_count":412,"sven_meta":{"func_name":"read_quant_matrix_ext","file_name":"libavcodec/mpeg4videodec.c","commit_link":"github.com/FFmpeg/FFmpeg/commit/5aba5b89d0b1d73164d3b81764828bb8b20ff32a","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#57-cd960df54aa0","input":"QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)\n{\n QCA::Initializer init;\n QByteArray temp = cipherText;\n\n //do padding ourselves\n if (direction)\n {\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n else\n {\n temp = b64ToByte(temp);\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n\n QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;\n QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);\n QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();\n temp2 += cipher.final().toByteArray();\n\n if (!cipher.ok())\n return cipherText;\n\n if (direction)\n temp2 = byteToB64(temp2);\n\n return temp2;\n}","target":"QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)\n{\n QCA::Initializer init;\n QByteArray temp = cipherText;\n\n //do padding ourselves\n if (direction)\n {\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n else\n {\n // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input\n if ((temp.length() % 12) != 0)\n return cipherText;\n\n temp = b64ToByte(temp);\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n\n QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;\n QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);\n QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();\n temp2 += cipher.final().toByteArray();\n\n if (!cipher.ok())\n return cipherText;\n\n if (direction) {\n // Sanity check\n if ((temp2.length() % 8) != 0)\n return cipherText;\n\n temp2 = byteToB64(temp2);\n }\n\n return temp2;\n}","lang":"cpp","vul_type":"cwe-125","target_token_count":284,"sven_meta":{"func_name":"Cipher::blowfishECB","file_name":"src/core/cipher.cpp","commit_link":"github.com/quassel/quassel/commit/8b5ecd226f9208af3074b33d3b7cf5e14f55b138","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#58-591b27adce5e","input":"static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {\n\tut8 op_byte = data[0];\n\tut64 offset = addr - java_get_method_start ();\n\tut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;\n\n\tif (op_byte == 0xaa) {\n\t\t// handle a table switch condition\n\t\tif (pos + 8 > len) {\n\t\t\treturn op->size;\n\t\t}\n\t\tint min_val = (ut32)(UINT (data, pos + 4)),\n\t\t\tmax_val = (ut32)(UINT (data, pos + 8));\n\n\t\tut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;\n\t\top->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);\n\t\tRAnalCaseOp *caseop = NULL;\n\t\tpos += 12;\n\t\tif (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {\n\t\t\t//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);\n\t\t\tfor (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {\n\t\t\t\t//ut32 value = (ut32)(UINT (data, pos));\n\t\t\t\tif (pos + 4 >= len) {\n\t\t\t\t\t// switch is too big cant read further\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tint offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));\n\t\t\t\tcaseop = r_anal_switch_op_add_case (op->switch_op,\n\t\t\t\t\taddr + pos, cur_case + min_val, addr + offset);\n\t\t\t\tif (caseop) {\n\t\t\t\t\tcaseop->bb_ref_to = addr+offset;\n\t\t\t\t\tcaseop->bb_ref_from = addr; // TODO figure this one out\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Invalid switch boundaries at 0x%\"PFMT64x\"\\n\", addr);\n\t\t}\n\t}\n\top->size = pos;\n\treturn op->size;\n}","target":"static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {\n\tut8 op_byte = data[0];\n\tut64 offset = addr - java_get_method_start ();\n\tut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;\n\n\tif (op_byte == 0xaa) {\n\t\t// handle a table switch condition\n\t\tif (pos + 8 + 8 > len) {\n\t\t\treturn op->size;\n\t\t}\n\t\tconst int min_val = (ut32)(UINT (data, pos + 4));\n\t\tconst int max_val = (ut32)(UINT (data, pos + 8));\n\n\t\tut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;\n\t\top->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);\n\t\tRAnalCaseOp *caseop = NULL;\n\t\tpos += 12;\n\t\tif (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {\n\t\t\t//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);\n\t\t\tfor (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {\n\t\t\t\t//ut32 value = (ut32)(UINT (data, pos));\n\t\t\t\tif (pos + 4 >= len) {\n\t\t\t\t\t// switch is too big cant read further\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tint offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));\n\t\t\t\tcaseop = r_anal_switch_op_add_case (op->switch_op,\n\t\t\t\t\taddr + pos, cur_case + min_val, addr + offset);\n\t\t\t\tif (caseop) {\n\t\t\t\t\tcaseop->bb_ref_to = addr+offset;\n\t\t\t\t\tcaseop->bb_ref_from = addr; // TODO figure this one out\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Invalid switch boundaries at 0x%\"PFMT64x\"\\n\", addr);\n\t\t}\n\t}\n\top->size = pos;\n\treturn op->size;\n}","lang":"c","vul_type":"cwe-125","target_token_count":495,"sven_meta":{"func_name":"java_switch_op","file_name":"libr/anal/p/anal_java.c","commit_link":"github.com/radare/radare2/commit/224e6bc13fa353dd3b7f7a2334588f1c4229e58d","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#60-42414a109884","input":"const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,\n socklen_t size) {\n if (!src || !dst) {\n errno = EFAULT;\n return nullptr;\n }\n size_t src_size = 0;\n if (af == AF_INET) {\n src_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n src_size = sizeof(struct in6_addr);\n } else {\n errno = EAFNOSUPPORT;\n return nullptr;\n }\n\n MessageWriter input;\n input.Push<int>(TokLinuxAfFamily(af));\n input.PushByReference(Extent{reinterpret_cast<const char *>(src), src_size});\n input.Push(size);\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetNtopHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_ntop\", 2);\n\n auto result = output.next();\n int klinux_errno = output.next<int>();\n if (result.empty()) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return nullptr;\n }\n\n memcpy(dst, result.data(),\n std::min(static_cast<size_t>(size),\n static_cast<size_t>(INET6_ADDRSTRLEN)));\n return dst;\n}","target":"const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,\n socklen_t size) {\n if (!src || !dst) {\n errno = EFAULT;\n return nullptr;\n }\n size_t src_size = 0;\n if (af == AF_INET) {\n src_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n src_size = sizeof(struct in6_addr);\n } else {\n errno = EAFNOSUPPORT;\n return nullptr;\n }\n\n MessageWriter input;\n input.Push<int>(TokLinuxAfFamily(af));\n input.PushByReference(Extent{reinterpret_cast<const char *>(src), src_size});\n input.Push(size);\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetNtopHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_ntop\", 2);\n\n auto result = output.next();\n int klinux_errno = output.next<int>();\n if (result.empty()) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return nullptr;\n }\n\n memcpy(\n dst, result.data(),\n std::min({static_cast<size_t>(size), static_cast<size_t>(result.size()),\n static_cast<size_t>(INET6_ADDRSTRLEN)}));\n return dst;\n}","lang":"cpp","vul_type":"cwe-125","target_token_count":305,"sven_meta":{"func_name":"enc_untrusted_inet_ntop","file_name":"asylo/platform/host_call/trusted/host_calls.cc","commit_link":"github.com/google/asylo/commit/6ff3b77ffe110a33a2f93848a6333f33616f02c4","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#61-a01cb3f981b3","input":"void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search ORACLE\\n\");\n\n if(packet->tcp != NULL) {\n sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculating ORACLE over tcp\\n\");\n /* Oracle Database 9g,10g,11g */\n if ((dport == 1521 || sport == 1521)\n\t&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n\t || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) \n\t && (packet->payload[1] != 0x00)\n\t && (packet->payload[2] == 0x00)\n\t\t && (packet->payload[3] == 0x00)))) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&\n packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&\n packet->payload[3] == 0x00 ) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n }\n } else {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n}","target":"void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search ORACLE\\n\");\n\n if(packet->tcp != NULL) {\n sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculating ORACLE over tcp\\n\");\n /* Oracle Database 9g,10g,11g */\n if ((dport == 1521 || sport == 1521)\n\t&& (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n\t || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) \n\t && (packet->payload[1] != 0x00)\n\t && (packet->payload[2] == 0x00)\n\t\t && (packet->payload[3] == 0x00)))) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&\n packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&\n packet->payload[3] == 0x00 ) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n }\n } else {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n}","lang":"c","vul_type":"cwe-125","target_token_count":451,"sven_meta":{"func_name":"ndpi_search_oracle","file_name":"src/lib/protocols/oracle.c","commit_link":"github.com/ntop/nDPI/commit/b69177be2fbe01c2442239a61832c44e40136c05","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#80-4a53ea1bee34","input":"static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)\n{\n\tWINPR_UNUSED(update);\n\tif (Stream_GetRemainingLength(s) < 18)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, bitmapData->destLeft);\n\tStream_Read_UINT16(s, bitmapData->destTop);\n\tStream_Read_UINT16(s, bitmapData->destRight);\n\tStream_Read_UINT16(s, bitmapData->destBottom);\n\tStream_Read_UINT16(s, bitmapData->width);\n\tStream_Read_UINT16(s, bitmapData->height);\n\tStream_Read_UINT16(s, bitmapData->bitsPerPixel);\n\tStream_Read_UINT16(s, bitmapData->flags);\n\tStream_Read_UINT16(s, bitmapData->bitmapLength);\n\n\tif (bitmapData->flags & BITMAP_COMPRESSION)\n\t{\n\t\tif (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tbitmapData->bitmapLength = bitmapData->cbCompMainBodySize;\n\t\t}\n\n\t\tbitmapData->compressed = TRUE;\n\t}\n\telse\n\t\tbitmapData->compressed = FALSE;\n\n\tif (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)\n\t\treturn FALSE;\n\n\tif (bitmapData->bitmapLength > 0)\n\t{\n\t\tbitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);\n\n\t\tif (!bitmapData->bitmapDataStream)\n\t\t\treturn FALSE;\n\n\t\tmemcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);\n\t\tStream_Seek(s, bitmapData->bitmapLength);\n\t}\n\n\treturn TRUE;\n}","target":"static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)\n{\n\tWINPR_UNUSED(update);\n\tif (Stream_GetRemainingLength(s) < 18)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, bitmapData->destLeft);\n\tStream_Read_UINT16(s, bitmapData->destTop);\n\tStream_Read_UINT16(s, bitmapData->destRight);\n\tStream_Read_UINT16(s, bitmapData->destBottom);\n\tStream_Read_UINT16(s, bitmapData->width);\n\tStream_Read_UINT16(s, bitmapData->height);\n\tStream_Read_UINT16(s, bitmapData->bitsPerPixel);\n\tStream_Read_UINT16(s, bitmapData->flags);\n\tStream_Read_UINT16(s, bitmapData->bitmapLength);\n\n\tif (bitmapData->flags & BITMAP_COMPRESSION)\n\t{\n\t\tif (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\treturn FALSE;\n\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tbitmapData->bitmapLength = bitmapData->cbCompMainBodySize;\n\t\t}\n\n\t\tbitmapData->compressed = TRUE;\n\t}\n\telse\n\t\tbitmapData->compressed = FALSE;\n\n\tif (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)\n\t\treturn FALSE;\n\n\tif (bitmapData->bitmapLength > 0)\n\t{\n\t\tbitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);\n\n\t\tif (!bitmapData->bitmapDataStream)\n\t\t\treturn FALSE;\n\n\t\tmemcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);\n\t\tStream_Seek(s, bitmapData->bitmapLength);\n\t}\n\n\treturn TRUE;\n}","lang":"c","vul_type":"cwe-125","target_token_count":476,"sven_meta":{"func_name":"update_read_bitmap_data","file_name":"libfreerdp/core/update.c","commit_link":"github.com/FreeRDP/FreeRDP/commit/f8890a645c221823ac133dbf991f8a65ae50d637","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#81-29bb54d2ec12","input":"static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,\n AUTODETECT_RSP_PDU* autodetectRspPdu)\n{\n\tBOOL success = TRUE;\n\n\tif (autodetectRspPdu->headerLength != 0x0E)\n\t\treturn FALSE;\n\n\tWLog_VRB(AUTODETECT_TAG, \"received Bandwidth Measure Results PDU\");\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */\n\n\tif (rdp->autodetect->bandwidthMeasureTimeDelta > 0)\n\t\trdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /\n\t\t rdp->autodetect->bandwidthMeasureTimeDelta;\n\telse\n\t\trdp->autodetect->netCharBandwidth = 0;\n\n\tIFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,\n\t autodetectRspPdu->sequenceNumber);\n\treturn success;\n}","target":"static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,\n AUTODETECT_RSP_PDU* autodetectRspPdu)\n{\n\tBOOL success = TRUE;\n\n\tif (autodetectRspPdu->headerLength != 0x0E)\n\t\treturn FALSE;\n\n\tWLog_VRB(AUTODETECT_TAG, \"received Bandwidth Measure Results PDU\");\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn -1;\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */\n\n\tif (rdp->autodetect->bandwidthMeasureTimeDelta > 0)\n\t\trdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /\n\t\t rdp->autodetect->bandwidthMeasureTimeDelta;\n\telse\n\t\trdp->autodetect->netCharBandwidth = 0;\n\n\tIFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,\n\t autodetectRspPdu->sequenceNumber);\n\treturn success;\n}","lang":"c","vul_type":"cwe-125","target_token_count":281,"sven_meta":{"func_name":"autodetect_recv_bandwidth_measure_results","file_name":"libfreerdp/core/autodetect.c","commit_link":"github.com/FreeRDP/FreeRDP/commit/f5e73cc7c9cd973b516a618da877c87b80950b65","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#82-74f4e8de4f9e","input":"static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,\n unsigned char **p,\n unsigned char *end )\n{\n int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n size_t len;\n ((void) ssl);\n\n /*\n * PSK parameters:\n *\n * opaque psk_identity_hint<0..2^16-1>;\n */\n if( (*p) > end - 2 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n len = (*p)[0] << 8 | (*p)[1];\n *p += 2;\n\n if( (*p) + len > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n\n /*\n * Note: we currently ignore the PKS identity hint, as we only allow one\n * PSK to be provisionned on the client. This could be changed later if\n * someone needs that feature.\n */\n *p += len;\n ret = 0;\n\n return( ret );\n}","target":"static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,\n unsigned char **p,\n unsigned char *end )\n{\n int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n size_t len;\n ((void) ssl);\n\n /*\n * PSK parameters:\n *\n * opaque psk_identity_hint<0..2^16-1>;\n */\n if( (*p) > end - 2 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n len = (*p)[0] << 8 | (*p)[1];\n *p += 2;\n\n if( (*p) > end - len )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n\n /*\n * Note: we currently ignore the PKS identity hint, as we only allow one\n * PSK to be provisionned on the client. This could be changed later if\n * someone needs that feature.\n */\n *p += len;\n ret = 0;\n\n return( ret );\n}","lang":"c","vul_type":"cwe-125","target_token_count":292,"sven_meta":{"func_name":"ssl_parse_server_psk_hint","file_name":"library/ssl_cli.c","commit_link":"github.com/ARMmbed/mbedtls/commit/5224a7544c95552553e2e6be0b4a789956a6464e","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#83-262f6cccc156","input":"static void youngcollection (lua_State *L, global_State *g) {\n GCObject **psurvival; /* to point to first non-dead survival object */\n lua_assert(g->gcstate == GCSpropagate);\n markold(g, g->survival, g->reallyold);\n markold(g, g->finobj, g->finobjrold);\n atomic(L);\n\n /* sweep nursery and get a pointer to its last live element */\n psurvival = sweepgen(L, g, &g->allgc, g->survival);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->reallyold);\n g->reallyold = g->old;\n g->old = *psurvival; /* 'survival' survivals are old now */\n g->survival = g->allgc; /* all news are survivals */\n\n /* repeat for 'finobj' lists */\n psurvival = sweepgen(L, g, &g->finobj, g->finobjsur);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->finobjrold);\n g->finobjrold = g->finobjold;\n g->finobjold = *psurvival; /* 'survival' survivals are old now */\n g->finobjsur = g->finobj; /* all news are survivals */\n\n sweepgen(L, g, &g->tobefnz, NULL);\n\n finishgencycle(L, g);\n}","target":"static void youngcollection (lua_State *L, global_State *g) {\n GCObject **psurvival; /* to point to first non-dead survival object */\n lua_assert(g->gcstate == GCSpropagate);\n markold(g, g->allgc, g->reallyold);\n markold(g, g->finobj, g->finobjrold);\n atomic(L);\n\n /* sweep nursery and get a pointer to its last live element */\n psurvival = sweepgen(L, g, &g->allgc, g->survival);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->reallyold);\n g->reallyold = g->old;\n g->old = *psurvival; /* 'survival' survivals are old now */\n g->survival = g->allgc; /* all news are survivals */\n\n /* repeat for 'finobj' lists */\n psurvival = sweepgen(L, g, &g->finobj, g->finobjsur);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->finobjrold);\n g->finobjrold = g->finobjold;\n g->finobjold = *psurvival; /* 'survival' survivals are old now */\n g->finobjsur = g->finobj; /* all news are survivals */\n\n sweepgen(L, g, &g->tobefnz, NULL);\n\n finishgencycle(L, g);\n}","lang":"c","vul_type":"cwe-125","target_token_count":353,"sven_meta":{"func_name":"youngcollection","file_name":"lgc.c","commit_link":"github.com/lua/lua/commit/127e7a6c8942b362aa3c6627f44d660a4fb75312","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#89-1c8704e60590","input":"static void hid_input_field(struct hid_device *hid, struct hid_field *field,\n\t\t\t __u8 *data, int interrupt)\n{\n\tunsigned n;\n\tunsigned count = field->report_count;\n\tunsigned offset = field->report_offset;\n\tunsigned size = field->report_size;\n\t__s32 min = field->logical_minimum;\n\t__s32 max = field->logical_maximum;\n\t__s32 *value;\n\n\tvalue = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);\n\tif (!value)\n\t\treturn;\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tvalue[n] = min < 0 ?\n\t\t\tsnto32(hid_field_extract(hid, data, offset + n * size,\n\t\t\t size), size) :\n\t\t\thid_field_extract(hid, data, offset + n * size, size);\n\n\t\t/* Ignore report if ErrorRollOver */\n\t\tif (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&\n\t\t value[n] >= min && value[n] <= max &&\n\t\t field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)\n\t\t\tgoto exit;\n\t}\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tif (HID_MAIN_ITEM_VARIABLE & field->flags) {\n\t\t\thid_process_event(hid, field, &field->usage[n], value[n], interrupt);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field->value[n] >= min && field->value[n] <= max\n\t\t\t&& field->usage[field->value[n] - min].hid\n\t\t\t&& search(value, field->value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);\n\n\t\tif (value[n] >= min && value[n] <= max\n\t\t\t&& field->usage[value[n] - min].hid\n\t\t\t&& search(field->value, value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);\n\t}\n\n\tmemcpy(field->value, value, count * sizeof(__s32));\nexit:\n\tkfree(value);\n}","target":"static void hid_input_field(struct hid_device *hid, struct hid_field *field,\n\t\t\t __u8 *data, int interrupt)\n{\n\tunsigned n;\n\tunsigned count = field->report_count;\n\tunsigned offset = field->report_offset;\n\tunsigned size = field->report_size;\n\t__s32 min = field->logical_minimum;\n\t__s32 max = field->logical_maximum;\n\t__s32 *value;\n\n\tvalue = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);\n\tif (!value)\n\t\treturn;\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tvalue[n] = min < 0 ?\n\t\t\tsnto32(hid_field_extract(hid, data, offset + n * size,\n\t\t\t size), size) :\n\t\t\thid_field_extract(hid, data, offset + n * size, size);\n\n\t\t/* Ignore report if ErrorRollOver */\n\t\tif (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&\n\t\t value[n] >= min && value[n] <= max &&\n\t\t value[n] - min < field->maxusage &&\n\t\t field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)\n\t\t\tgoto exit;\n\t}\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tif (HID_MAIN_ITEM_VARIABLE & field->flags) {\n\t\t\thid_process_event(hid, field, &field->usage[n], value[n], interrupt);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field->value[n] >= min && field->value[n] <= max\n\t\t\t&& field->value[n] - min < field->maxusage\n\t\t\t&& field->usage[field->value[n] - min].hid\n\t\t\t&& search(value, field->value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);\n\n\t\tif (value[n] >= min && value[n] <= max\n\t\t\t&& value[n] - min < field->maxusage\n\t\t\t&& field->usage[value[n] - min].hid\n\t\t\t&& search(field->value, value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);\n\t}\n\n\tmemcpy(field->value, value, count * sizeof(__s32));\nexit:\n\tkfree(value);\n}","lang":"c","vul_type":"cwe-125","target_token_count":502,"sven_meta":{"func_name":"hid_input_field","file_name":"drivers/hid/hid-core.c","commit_link":"github.com/torvalds/linux/commit/50220dead1650609206efe91f0cc116132d59b3f","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#94-9cd693faa994","input":"static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tUINT32 PathLength;\n\tStream_Seek(irp->input, 28);\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tStream_Read_UINT32(irp->input, PathLength);\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,\n\t &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}","target":"static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tWCHAR* ptr;\n\tUINT32 PathLength;\n\tif (!Stream_SafeSeek(irp->input, 28))\n\t\treturn ERROR_INVALID_DATA;\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;\n\tStream_Read_UINT32(irp->input, PathLength);\n\tptr = (WCHAR*)Stream_Pointer(irp->input);\n\tif (!Stream_SafeSeek(irp->input, PathLength))\n\t\treturn ERROR_INVALID_DATA;\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}","lang":"c","vul_type":"cwe-125","target_token_count":391,"sven_meta":{"func_name":"parallel_process_irp_create","file_name":"channels/parallel/client/parallel_main.c","commit_link":"github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#101-9d01383de1a6","input":"static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)\n{\n\tdouble width_d;\n\tdouble scale_f_d = 1.0;\n\tconst double filter_width_d = DEFAULT_BOX_RADIUS;\n\tint windows_size;\n\tunsigned int u;\n\tLineContribType *res;\n\n\tif (scale_d < 1.0) {\n\t\twidth_d = filter_width_d / scale_d;\n\t\tscale_f_d = scale_d;\n\t} else {\n\t\twidth_d= filter_width_d;\n\t}\n\n\twindows_size = 2 * (int)ceil(width_d) + 1;\n\tres = _gdContributionsAlloc(line_size, windows_size);\n\n\tfor (u = 0; u < line_size; u++) {\n\t\tconst double dCenter = (double)u / scale_d;\n\t\t/* get the significant edge points affecting the pixel */\n\t\tregister int iLeft = MAX(0, (int)floor (dCenter - width_d));\n\t\tint iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);\n\t\tdouble dTotalWeight = 0.0;\n\t\tint iSrc;\n\n\t\tres->ContribRow[u].Left = iLeft;\n\t\tres->ContribRow[u].Right = iRight;\n\n\t\t/* Cut edge points to fit in filter window in case of spill-off */\n\t\tif (iRight - iLeft + 1 > windows_size) {\n\t\t\tif (iLeft < ((int)src_size - 1 / 2)) {\n\t\t\t\tiLeft++;\n\t\t\t} else {\n\t\t\t\tiRight--;\n\t\t\t}\n\t\t}\n\n\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\tdTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));\n\t\t}\n\n\t\tif (dTotalWeight < 0.0) {\n\t\t\t_gdContributionsFree(res);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (dTotalWeight > 0.0) {\n\t\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\t\tres->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}","target":"static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)\n{\n\tdouble width_d;\n\tdouble scale_f_d = 1.0;\n\tconst double filter_width_d = DEFAULT_BOX_RADIUS;\n\tint windows_size;\n\tunsigned int u;\n\tLineContribType *res;\n\n\tif (scale_d < 1.0) {\n\t\twidth_d = filter_width_d / scale_d;\n\t\tscale_f_d = scale_d;\n\t} else {\n\t\twidth_d= filter_width_d;\n\t}\n\n\twindows_size = 2 * (int)ceil(width_d) + 1;\n\tres = _gdContributionsAlloc(line_size, windows_size);\n\n\tfor (u = 0; u < line_size; u++) {\n\t\tconst double dCenter = (double)u / scale_d;\n\t\t/* get the significant edge points affecting the pixel */\n\t\tregister int iLeft = MAX(0, (int)floor (dCenter - width_d));\n\t\tint iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);\n\t\tdouble dTotalWeight = 0.0;\n\t\tint iSrc;\n\n\t\t/* Cut edge points to fit in filter window in case of spill-off */\n\t\tif (iRight - iLeft + 1 > windows_size) {\n\t\t\tif (iLeft < ((int)src_size - 1 / 2)) {\n\t\t\t\tiLeft++;\n\t\t\t} else {\n\t\t\t\tiRight--;\n\t\t\t}\n\t\t}\n\n\t\tres->ContribRow[u].Left = iLeft;\n\t\tres->ContribRow[u].Right = iRight;\n\n\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\tdTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));\n\t\t}\n\n\t\tif (dTotalWeight < 0.0) {\n\t\t\t_gdContributionsFree(res);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (dTotalWeight > 0.0) {\n\t\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\t\tres->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}","lang":"c","vul_type":"cwe-125","target_token_count":501,"sven_meta":{"func_name":"_gdContributionsCalc","file_name":"src/gd_interpolation.c","commit_link":"github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#105-5c68af241977","input":"get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,\n size_t minimum)\n{\n\tstruct _7zip *zip = (struct _7zip *)a->format->data;\n\tssize_t bytes_avail;\n\n\tif (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {\n\t\t/* Copy mode. */\n\n\t\t/*\n\t\t * Note: '1' here is a performance optimization.\n\t\t * Recall that the decompression layer returns a count of\n\t\t * available bytes; asking for more than that forces the\n\t\t * decompressor to combine reads by copying data.\n\t\t */\n\t\t*buff = __archive_read_ahead(a, 1, &bytes_avail);\n\t\tif (bytes_avail <= 0) {\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Truncated 7-Zip file data\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif ((size_t)bytes_avail >\n\t\t zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\tif ((size_t)bytes_avail > size)\n\t\t\tbytes_avail = (ssize_t)size;\n\n\t\tzip->pack_stream_bytes_unconsumed = bytes_avail;\n\t} else if (zip->uncompressed_buffer_pointer == NULL) {\n\t\t/* Decompression has failed. */\n\t\tarchive_set_error(&(a->archive),\n\t\t ARCHIVE_ERRNO_MISC, \"Damaged 7-Zip archive\");\n\t\treturn (ARCHIVE_FATAL);\n\t} else {\n\t\t/* Packed mode. */\n\t\tif (minimum > zip->uncompressed_buffer_bytes_remaining) {\n\t\t\t/*\n\t\t\t * If remaining uncompressed data size is less than\n\t\t\t * the minimum size, fill the buffer up to the\n\t\t\t * minimum size.\n\t\t\t */\n\t\t\tif (extract_pack_stream(a, minimum) < 0)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif (size > zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\telse\n\t\t\tbytes_avail = (ssize_t)size;\n\t\t*buff = zip->uncompressed_buffer_pointer;\n\t\tzip->uncompressed_buffer_pointer += bytes_avail;\n\t}\n\tzip->uncompressed_buffer_bytes_remaining -= bytes_avail;\n\treturn (bytes_avail);\n}","target":"get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,\n size_t minimum)\n{\n\tstruct _7zip *zip = (struct _7zip *)a->format->data;\n\tssize_t bytes_avail;\n\n\tif (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {\n\t\t/* Copy mode. */\n\n\t\t*buff = __archive_read_ahead(a, minimum, &bytes_avail);\n\t\tif (bytes_avail <= 0) {\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Truncated 7-Zip file data\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif ((size_t)bytes_avail >\n\t\t zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\tif ((size_t)bytes_avail > size)\n\t\t\tbytes_avail = (ssize_t)size;\n\n\t\tzip->pack_stream_bytes_unconsumed = bytes_avail;\n\t} else if (zip->uncompressed_buffer_pointer == NULL) {\n\t\t/* Decompression has failed. */\n\t\tarchive_set_error(&(a->archive),\n\t\t ARCHIVE_ERRNO_MISC, \"Damaged 7-Zip archive\");\n\t\treturn (ARCHIVE_FATAL);\n\t} else {\n\t\t/* Packed mode. */\n\t\tif (minimum > zip->uncompressed_buffer_bytes_remaining) {\n\t\t\t/*\n\t\t\t * If remaining uncompressed data size is less than\n\t\t\t * the minimum size, fill the buffer up to the\n\t\t\t * minimum size.\n\t\t\t */\n\t\t\tif (extract_pack_stream(a, minimum) < 0)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif (size > zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\telse\n\t\t\tbytes_avail = (ssize_t)size;\n\t\t*buff = zip->uncompressed_buffer_pointer;\n\t\tzip->uncompressed_buffer_pointer += bytes_avail;\n\t}\n\tzip->uncompressed_buffer_bytes_remaining -= bytes_avail;\n\treturn (bytes_avail);\n}","lang":"c","vul_type":"cwe-125","target_token_count":443,"sven_meta":{"func_name":"get_uncompressed_data","file_name":"libarchive/archive_read_support_format_7zip.c","commit_link":"github.com/libarchive/libarchive/commit/65a23f5dbee4497064e9bb467f81138a62b0dae1","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#114-b8fcefc1e15c","input":"next_line(struct archive_read *a,\n const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)\n{\n\tssize_t len;\n\tint quit;\n\t\n\tquit = 0;\n\tif (*avail == 0) {\n\t\t*nl = 0;\n\t\tlen = 0;\n\t} else\n\t\tlen = get_line_size(*b, *avail, nl);\n\t/*\n\t * Read bytes more while it does not reach the end of line.\n\t */\n\twhile (*nl == 0 && len == *avail && !quit) {\n\t\tssize_t diff = *ravail - *avail;\n\t\tsize_t nbytes_req = (*ravail+1023) & ~1023U;\n\t\tssize_t tested;\n\n\t\t/* Increase reading bytes if it is not enough to at least\n\t\t * new two lines. */\n\t\tif (nbytes_req < (size_t)*ravail + 160)\n\t\t\tnbytes_req <<= 1;\n\n\t\t*b = __archive_read_ahead(a, nbytes_req, avail);\n\t\tif (*b == NULL) {\n\t\t\tif (*ravail >= *avail)\n\t\t\t\treturn (0);\n\t\t\t/* Reading bytes reaches the end of file. */\n\t\t\t*b = __archive_read_ahead(a, *avail, avail);\n\t\t\tquit = 1;\n\t\t}\n\t\t*ravail = *avail;\n\t\t*b += diff;\n\t\t*avail -= diff;\n\t\ttested = len;/* Skip some bytes we already determinated. */\n\t\tlen = get_line_size(*b, *avail, nl);\n\t\tif (len >= 0)\n\t\t\tlen += tested;\n\t}\n\treturn (len);\n}","target":"next_line(struct archive_read *a,\n const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)\n{\n\tssize_t len;\n\tint quit;\n\t\n\tquit = 0;\n\tif (*avail == 0) {\n\t\t*nl = 0;\n\t\tlen = 0;\n\t} else\n\t\tlen = get_line_size(*b, *avail, nl);\n\t/*\n\t * Read bytes more while it does not reach the end of line.\n\t */\n\twhile (*nl == 0 && len == *avail && !quit) {\n\t\tssize_t diff = *ravail - *avail;\n\t\tsize_t nbytes_req = (*ravail+1023) & ~1023U;\n\t\tssize_t tested;\n\n\t\t/* Increase reading bytes if it is not enough to at least\n\t\t * new two lines. */\n\t\tif (nbytes_req < (size_t)*ravail + 160)\n\t\t\tnbytes_req <<= 1;\n\n\t\t*b = __archive_read_ahead(a, nbytes_req, avail);\n\t\tif (*b == NULL) {\n\t\t\tif (*ravail >= *avail)\n\t\t\t\treturn (0);\n\t\t\t/* Reading bytes reaches the end of file. */\n\t\t\t*b = __archive_read_ahead(a, *avail, avail);\n\t\t\tquit = 1;\n\t\t}\n\t\t*ravail = *avail;\n\t\t*b += diff;\n\t\t*avail -= diff;\n\t\ttested = len;/* Skip some bytes we already determinated. */\n\t\tlen = get_line_size(*b + len, *avail - len, nl);\n\t\tif (len >= 0)\n\t\t\tlen += tested;\n\t}\n\treturn (len);\n}","lang":"c","vul_type":"cwe-125","target_token_count":362,"sven_meta":{"func_name":"next_line","file_name":"libarchive/archive_read_support_format_mtree.c","commit_link":"github.com/libarchive/libarchive/commit/eec077f52bfa2d3f7103b4b74d52572ba8a15aca","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#115-fbdc1c9cafc4","input":"x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)\n{\n\tunsigned int first = 0;\n\tunsigned int last = ARR_SIZE(insn_regs_intel) - 1;\n\tunsigned int mid = ARR_SIZE(insn_regs_intel) / 2;\n\n\tif (!intel_regs_sorted) {\n\t\tmemcpy(insn_regs_intel_sorted, insn_regs_intel,\n\t\t\t\tsizeof(insn_regs_intel_sorted));\n\t\tqsort(insn_regs_intel_sorted,\n\t\t\t\tARR_SIZE(insn_regs_intel_sorted),\n\t\t\t\tsizeof(struct insn_reg), regs_cmp);\n\t\tintel_regs_sorted = true;\n\t}\n\n\twhile (first <= last) {\n\t\tif (insn_regs_intel_sorted[mid].insn < id) {\n\t\t\tfirst = mid + 1;\n\t\t} else if (insn_regs_intel_sorted[mid].insn == id) {\n\t\t\tif (access) {\n\t\t\t\t*access = insn_regs_intel_sorted[mid].access;\n\t\t\t}\n\t\t\treturn insn_regs_intel_sorted[mid].reg;\n\t\t} else {\n\t\t\tif (mid == 0)\n\t\t\t\tbreak;\n\t\t\tlast = mid - 1;\n\t\t}\n\t\tmid = (first + last) / 2;\n\t}\n\n\t// not found\n\treturn 0;\n}","target":"x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)\n{\n\tstatic bool intel_regs_sorted = false;\n\tunsigned int first = 0;\n\tunsigned int last = ARR_SIZE(insn_regs_intel) - 1;\n\tunsigned int mid;\n\n\tif (!intel_regs_sorted) {\n\t\tmemcpy(insn_regs_intel_sorted, insn_regs_intel,\n\t\t\t\tsizeof(insn_regs_intel_sorted));\n\t\tqsort(insn_regs_intel_sorted,\n\t\t\t\tARR_SIZE(insn_regs_intel_sorted),\n\t\t\t\tsizeof(struct insn_reg), regs_cmp);\n\t\tintel_regs_sorted = true;\n\t}\n\n\tif (insn_regs_intel_sorted[0].insn > id ||\n\t\t\tinsn_regs_intel_sorted[last].insn < id) {\n\t\treturn 0;\n\t}\n\n\twhile (first <= last) {\n\t\tmid = (first + last) / 2;\n\t\tif (insn_regs_intel_sorted[mid].insn < id) {\n\t\t\tfirst = mid + 1;\n\t\t} else if (insn_regs_intel_sorted[mid].insn == id) {\n\t\t\tif (access) {\n\t\t\t\t*access = insn_regs_intel_sorted[mid].access;\n\t\t\t}\n\t\t\treturn insn_regs_intel_sorted[mid].reg;\n\t\t} else {\n\t\t\tif (mid == 0)\n\t\t\t\tbreak;\n\t\t\tlast = mid - 1;\n\t\t}\n\t}\n\n\t// not found\n\treturn 0;\n}","lang":"c","vul_type":"cwe-125","target_token_count":297,"sven_meta":{"func_name":"X86_insn_reg_intel","file_name":"arch/X86/X86Mapping.c","commit_link":"github.com/aquynh/capstone/commit/87a25bb543c8e4c09b48d4b4a6c7db31ce58df06","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#116-19a129d340d3","input":"R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 curpos, offset = 0;\n\tRBinJavaLineNumberAttribute *lnattr;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;\n\tattr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.line_number_table_attr.line_number_table = r_list_newf (free);\n\n\tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n\tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n\tif (linenum_len > sz) {\n\t\tfree (attr);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < linenum_len; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\t// printf (\"%llx %llx \\n\", curpos, sz);\n\t\t// XXX if (curpos + 8 >= sz) break;\n\t\tlnattr = R_NEW0 (RBinJavaLineNumberAttribute);\n\t\tif (!lnattr) {\n\t\t\tbreak;\n\t\t}\n\t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->file_offset = curpos;\n\t\tlnattr->size = 4;\n\t\tr_list_append (linenum_list, lnattr);\n\t}\n\tattr->size = offset;\n\treturn attr;\n}","target":"R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 curpos, offset = 0;\n\tRBinJavaLineNumberAttribute *lnattr;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;\n\tattr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.line_number_table_attr.line_number_table = r_list_newf (free);\n\n\tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n\tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n\tif (linenum_len > sz) {\n\t\tfree (attr);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < linenum_len; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\t// printf (\"%llx %llx \\n\", curpos, sz);\n\t\t// XXX if (curpos + 8 >= sz) break;\n\t\tlnattr = R_NEW0 (RBinJavaLineNumberAttribute);\n\t\tif (!lnattr) {\n\t\t\tbreak;\n\t\t}\n\t\tif (offset + 8 >= sz) {\n\t\t\tbreak;\n\t\t}\n\t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->file_offset = curpos;\n\t\tlnattr->size = 4;\n\t\tr_list_append (linenum_list, lnattr);\n\t}\n\tattr->size = offset;\n\treturn attr;\n}","lang":"c","vul_type":"cwe-125","target_token_count":418,"sven_meta":{"func_name":"r_bin_java_line_number_table_attr_new","file_name":"shlr/java/class.c","commit_link":"github.com/radare/radare2/commit/eb0fb72b3c5307ec8e33effb6bf947e38cfdffe8","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#119-be4fdb641998","input":" bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n auto const ch2 = *p++;\n auto const dch3 = dehexchar(*p++);\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n return false;\n }\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }","target":" bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n if (UNLIKELY(ch1 != '0')) return false;\n auto const ch2 = *p++;\n if (UNLIKELY(ch2 != '0')) return false;\n auto const dch3 = dehexchar(*p++);\n if (UNLIKELY(dch3 < 0)) return false;\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(dch4 < 0)) return false;\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }","lang":"cpp","vul_type":"cwe-125","target_token_count":407,"sven_meta":{"func_name":"HPHP::SimpleParser::handleBackslash","file_name":"hphp/runtime/ext/json/JSON_parser.cpp","commit_link":"github.com/facebook/hhvm/commit/b3679121bb3c7017ff04b4c08402ffff5cf59b13","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-125#128-212b82bfb12a","input":"ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags,\n struct sockaddr *src_addr, socklen_t *addrlen) {\n int klinux_flags = TokLinuxRecvSendFlag(flags);\n if (klinux_flags == 0 && flags != 0) {\n errno = EINVAL;\n return -1;\n }\n\n MessageWriter input;\n input.Push<int>(sockfd);\n input.Push<uint64_t>(len);\n input.Push<int>(klinux_flags);\n MessageReader output;\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kRecvFromHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_recvfrom\", 4);\n\n int result = output.next<int>();\n int klinux_errno = output.next<int>();\n // recvfrom() returns -1 on failure, with errno set to indicate the cause\n // of the error.\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return result;\n }\n\n auto buffer_received = output.next();\n memcpy(buf, buffer_received.data(), std::min(len, buffer_received.size()));\n\n // If |src_addr| is not NULL, and the underlying protocol provides the source\n // address, this source address is filled in. When |src_addr| is NULL, nothing\n // is filled in; in this case, |addrlen| is not used, and should also be NULL.\n if (src_addr != nullptr && addrlen != nullptr) {\n auto klinux_sockaddr_buf = output.next();\n const struct klinux_sockaddr *klinux_addr =\n klinux_sockaddr_buf.As<struct klinux_sockaddr>();\n FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr,\n addrlen, TrustedPrimitives::BestEffortAbort);\n }\n\n return result;\n}","target":"ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags,\n struct sockaddr *src_addr, socklen_t *addrlen) {\n int klinux_flags = TokLinuxRecvSendFlag(flags);\n if (klinux_flags == 0 && flags != 0) {\n errno = EINVAL;\n return -1;\n }\n\n MessageWriter input;\n input.Push<int>(sockfd);\n input.Push<uint64_t>(len);\n input.Push<int>(klinux_flags);\n MessageReader output;\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kRecvFromHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_recvfrom\", 4);\n\n int result = output.next<int>();\n int klinux_errno = output.next<int>();\n // recvfrom() returns -1 on failure, with errno set to indicate the cause\n // of the error.\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return result;\n }\n\n if (result > len) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_recvfrom: result exceeds requested\");\n }\n\n auto buffer_received = output.next();\n memcpy(buf, buffer_received.data(), std::min(len, buffer_received.size()));\n\n // If |src_addr| is not NULL, and the underlying protocol provides the source\n // address, this source address is filled in. When |src_addr| is NULL, nothing\n // is filled in; in this case, |addrlen| is not used, and should also be NULL.\n if (src_addr != nullptr && addrlen != nullptr) {\n auto klinux_sockaddr_buf = output.next();\n const struct klinux_sockaddr *klinux_addr =\n klinux_sockaddr_buf.As<struct klinux_sockaddr>();\n FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr,\n addrlen, TrustedPrimitives::BestEffortAbort);\n }\n\n return result;\n}","lang":"cpp","vul_type":"cwe-125","target_token_count":453,"sven_meta":{"func_name":"enc_untrusted_recvfrom","file_name":"asylo/platform/host_call/trusted/host_calls.cc","commit_link":"github.com/google/asylo/commit/6e158d558abd3c29a0208e30c97c9a8c5bd4230f","source_cwe_file":"cwe-125.jsonl"}}
{"problem_id":"cwe-078#0-a9aaae203e4b","input":"def start():\n print(\"[*] Starting backdoor process\")\n print(\"[*] Decompressing target to tmp directory...\")\n #subprocess.call(\"jar -x %s\" % target, shell=True)\n with zipfile.ZipFile(target, 'r') as zip:\n zip.extractall(\"tmp\")\n print(\"[*] Target dumped to tmp directory\")\n\n print(\"[*] Modifying manifest file...\")\n oldmain=\"\"\n man = open(\"tmp/META-INF/MANIFEST.MF\",\"r\").read()\n with open(\"tmp/META-INF/MANIFEST.MF\",\"w\") as f:\n for l in man.split(\"\\n\"):\n if \"Main-Class\" in l:\n oldmain=l[12:]\n f.write(\"Main-Class: %s\\n\" % \"Backdoor\")\n else:\n f.write(\"%s\\n\" % l)\n print(\"[*] Manifest file modified\")\n \n print(\"[*] Modifying provided backdoor...\")\n inmain=False\n level=0\n bd=open(backdoor, \"r\").read()\n with open(\"tmp/%s\" % backdoor,'w') as f:\n for l in bd.split(\"\\n\"):\n if \"main(\" in l:\n inmain=True\n f.write(l)\n elif \"}\" in l and level<2 and inmain:\n f.write(\"%s.main(args);}\" % oldmain)\n inmain=False\n elif \"}\" in l and level>1 and inmain:\n level-=1\n f.write(l)\n elif \"{\" in l and inmain:\n level+=1\n f.write(l)\n else:\n f.write(l)\n print(\"[*] Provided backdoor successfully modified\")\n\n print(\"[*] Compiling modified backdoor...\")\n if subprocess.call(\"javac -cp tmp/ tmp/%s\" % backdoor, shell=True) != 0:\n print(\"[!] Error compiling %s\" % backdoor)\n print(\"[*] Compiled modified backdoor\")\n \n if(len(oldmain)<1):\n print(\"[!] Main-Class manifest attribute not found\")\n else:\n print(\"[*] Repackaging target jar file...\")\n createZip(\"tmp\",outfile)\n print(\"[*] Target jar successfully repackaged\")\n shutil.rmtree('tmp/')","target":"def start():\n print(\"[*] Starting backdoor process\")\n print(\"[*] Decompressing target to tmp directory...\")\n #subprocess.call(\"jar -x %s\" % target, shell=True)\n with zipfile.ZipFile(target, 'r') as zip:\n zip.extractall(\"tmp\")\n print(\"[*] Target dumped to tmp directory\")\n\n print(\"[*] Modifying manifest file...\")\n oldmain=\"\"\n man = open(\"tmp/META-INF/MANIFEST.MF\",\"r\").read()\n with open(\"tmp/META-INF/MANIFEST.MF\",\"w\") as f:\n for l in man.split(\"\\n\"):\n if \"Main-Class\" in l:\n oldmain=l[12:]\n f.write(\"Main-Class: %s\\n\" % \"Backdoor\")\n else:\n f.write(\"%s\\n\" % l)\n print(\"[*] Manifest file modified\")\n \n print(\"[*] Modifying provided backdoor...\")\n inmain=False\n level=0\n bd=open(backdoor, \"r\").read()\n with open(\"tmp/%s\" % backdoor,'w') as f:\n for l in bd.split(\"\\n\"):\n if \"main(\" in l:\n inmain=True\n f.write(l)\n elif \"}\" in l and level<2 and inmain:\n f.write(\"%s.main(args);}\" % oldmain)\n inmain=False\n elif \"}\" in l and level>1 and inmain:\n level-=1\n f.write(l)\n elif \"{\" in l and inmain:\n level+=1\n f.write(l)\n else:\n f.write(l)\n print(\"[*] Provided backdoor successfully modified\")\n\n print(\"[*] Compiling modified backdoor...\")\n #if subprocess.call(\"javac -cp tmp/ tmp/%s\" % backdoor, shell=True) != 0:\n if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=False) != 0:\n print(\"[!] Error compiling %s\" % backdoor)\n print(\"[*] Compiled modified backdoor\")\n \n if(len(oldmain)<1):\n print(\"[!] Main-Class manifest attribute not found\")\n else:\n print(\"[*] Repackaging target jar file...\")\n createZip(\"tmp\",outfile)\n print(\"[*] Target jar successfully repackaged\")\n shutil.rmtree('tmp/')","lang":"python","vul_type":"cwe-078","target_token_count":511,"sven_meta":{"func_name":"start","file_name":"ajar.py","commit_link":"github.com/Atticuss/ajar/commit/5ed8aba271ad20e6168f2e3bd6c25ba89b84484f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#2-c82af2e5b379","input":" def _delete_vdisk(self, name, force):\n \"\"\"Deletes existing vdisks.\n\n It is very important to properly take care of mappings before deleting\n the disk:\n 1. If no mappings, then it was a vdisk, and can be deleted\n 2. If it is the source of a flashcopy mapping and copy_rate is 0, then\n it is a vdisk that has a snapshot. If the force flag is set,\n delete the mapping and the vdisk, otherwise set the mapping to\n copy and wait (this will allow users to delete vdisks that have\n snapshots if/when the upper layers allow it).\n 3. If it is the target of a mapping and copy_rate is 0, it is a\n snapshot, and we should properly stop the mapping and delete.\n 4. If it is the source/target of a mapping and copy_rate is not 0, it\n is a clone or vdisk created from a snapshot. We wait for the copy\n to complete (the mapping will be autodeleted) and then delete the\n vdisk.\n\n \"\"\"\n\n LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name)\n\n # Try to delete volume only if found on the storage\n vdisk_defined = self._is_vdisk_defined(name)\n if not vdisk_defined:\n LOG.info(_('warning: Tried to delete vdisk %s but it does not '\n 'exist.') % name)\n return\n\n self._ensure_vdisk_no_fc_mappings(name)\n\n forceflag = '-force' if force else ''\n cmd_params = {'frc': forceflag, 'name': name}\n ssh_cmd = 'svctask rmvdisk %(frc)s %(name)s' % cmd_params\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmvdisk\n self._assert_ssh_return(len(out.strip()) == 0,\n ('_delete_vdisk %(name)s')\n % {'name': name},\n ssh_cmd, out, err)\n LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)","target":" def _delete_vdisk(self, name, force):\n \"\"\"Deletes existing vdisks.\n\n It is very important to properly take care of mappings before deleting\n the disk:\n 1. If no mappings, then it was a vdisk, and can be deleted\n 2. If it is the source of a flashcopy mapping and copy_rate is 0, then\n it is a vdisk that has a snapshot. If the force flag is set,\n delete the mapping and the vdisk, otherwise set the mapping to\n copy and wait (this will allow users to delete vdisks that have\n snapshots if/when the upper layers allow it).\n 3. If it is the target of a mapping and copy_rate is 0, it is a\n snapshot, and we should properly stop the mapping and delete.\n 4. If it is the source/target of a mapping and copy_rate is not 0, it\n is a clone or vdisk created from a snapshot. We wait for the copy\n to complete (the mapping will be autodeleted) and then delete the\n vdisk.\n\n \"\"\"\n\n LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name)\n\n # Try to delete volume only if found on the storage\n vdisk_defined = self._is_vdisk_defined(name)\n if not vdisk_defined:\n LOG.info(_('warning: Tried to delete vdisk %s but it does not '\n 'exist.') % name)\n return\n\n self._ensure_vdisk_no_fc_mappings(name)\n\n ssh_cmd = ['svctask', 'rmvdisk', '-force', name]\n if not force:\n ssh_cmd.remove('-force')\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmvdisk\n self._assert_ssh_return(len(out.strip()) == 0,\n ('_delete_vdisk %(name)s')\n % {'name': name},\n ssh_cmd, out, err)\n LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)","lang":"python","vul_type":"cwe-078","target_token_count":449,"sven_meta":{"func_name":"_delete_vdisk","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#7-d026c91f8556","input":"@contextmanager\ndef run_interactive_shell_command(command, **kwargs):\n \"\"\"\n Runs a command in shell and provides stdout, stderr and stdin streams.\n\n This function creates a context manager that sets up the process, returns\n to caller, closes streams and waits for process to exit on leaving.\n\n The process is opened in `universal_newlines` mode.\n\n :param command: The command to run on shell.\n :param kwargs: Additional keyword arguments to pass to `subprocess.Popen`\n that is used to spawn the process (except `shell`,\n `stdout`, `stderr`, `stdin` and `universal_newlines`, a\n `TypeError` is raised then).\n :return: A context manager yielding the process started from the\n command.\n \"\"\"\n process = Popen(command,\n shell=True,\n stdout=PIPE,\n stderr=PIPE,\n stdin=PIPE,\n universal_newlines=True,\n **kwargs)\n try:\n yield process\n finally:\n process.stdout.close()\n process.stderr.close()\n process.stdin.close()\n process.wait()","target":"@contextmanager\ndef run_interactive_shell_command(command, **kwargs):\n \"\"\"\n Runs a single command in shell and provides stdout, stderr and stdin\n streams.\n\n This function creates a context manager that sets up the process (using\n `subprocess.Popen()`), returns to caller, closes streams and waits for\n process to exit on leaving.\n\n Shell execution is disabled by default (so no shell expansion takes place).\n If you want to turn shell execution on, you can pass `shell=True` like you\n would do for `subprocess.Popen()`.\n\n The process is opened in `universal_newlines` mode by default.\n\n :param command: The command to run on shell. This parameter can either\n be a sequence of arguments that are directly passed to\n the process or a string. A string gets splitted beforehand\n using `shlex.split()`.\n :param kwargs: Additional keyword arguments to pass to `subprocess.Popen`\n that is used to spawn the process (except `stdout`,\n `stderr`, `stdin` and `universal_newlines`, a `TypeError`\n is raised then).\n :return: A context manager yielding the process started from the\n command.\n \"\"\"\n if isinstance(command, str):\n command = shlex.split(command)\n\n process = Popen(command,\n stdout=PIPE,\n stderr=PIPE,\n stdin=PIPE,\n universal_newlines=True,\n **kwargs)\n try:\n yield process\n finally:\n process.stdout.close()\n process.stderr.close()\n process.stdin.close()\n process.wait()","lang":"python","vul_type":"cwe-078","target_token_count":332,"sven_meta":{"func_name":"run_interactive_shell_command","file_name":"coalib/misc/Shell.py","commit_link":"github.com/coala/coala/commit/adc94c745e4d9f792fd9c9791c7b4cd8790d0d2f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#10-44c736f7de43","input":" def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n 'fakehost 123456789012345 123456789054321')\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)","target":" def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost', '123456789012345',\n '123456789054321'])\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)","lang":"python","vul_type":"cwe-078","target_token_count":304,"sven_meta":{"func_name":"test_create_host","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#12-67776a32016e","input":" def _execute_command_and_parse_attributes(self, ssh_cmd):\n \"\"\"Execute command on the Storwize/SVC and parse attributes.\n\n Exception is raised if the information from the system\n can not be obtained.\n\n \"\"\"\n\n LOG.debug(_('enter: _execute_command_and_parse_attributes: '\n ' command %s') % ssh_cmd)\n\n try:\n out, err = self._run_ssh(ssh_cmd)\n except exception.ProcessExecutionError as e:\n # Didn't get details from the storage, return None\n LOG.error(_('CLI Exception output:\\n command: %(cmd)s\\n '\n 'stdout: %(out)s\\n stderr: %(err)s') %\n {'cmd': ssh_cmd,\n 'out': e.stdout,\n 'err': e.stderr})\n return None\n\n self._assert_ssh_return(len(out),\n '_execute_command_and_parse_attributes',\n ssh_cmd, out, err)\n attributes = {}\n for attrib_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attrib_name, foo, attrib_value = attrib_line.partition('!')\n if attrib_name is not None and len(attrib_name.strip()):\n attributes[attrib_name] = attrib_value\n\n LOG.debug(_('leave: _execute_command_and_parse_attributes:\\n'\n 'command: %(cmd)s\\n'\n 'attributes: %(attr)s')\n % {'cmd': ssh_cmd,\n 'attr': str(attributes)})\n\n return attributes","target":" def _execute_command_and_parse_attributes(self, ssh_cmd):\n \"\"\"Execute command on the Storwize/SVC and parse attributes.\n\n Exception is raised if the information from the system\n can not be obtained.\n\n \"\"\"\n\n LOG.debug(_('enter: _execute_command_and_parse_attributes: '\n ' command %s') % str(ssh_cmd))\n\n try:\n out, err = self._run_ssh(ssh_cmd)\n except exception.ProcessExecutionError as e:\n # Didn't get details from the storage, return None\n LOG.error(_('CLI Exception output:\\n command: %(cmd)s\\n '\n 'stdout: %(out)s\\n stderr: %(err)s') %\n {'cmd': ssh_cmd,\n 'out': e.stdout,\n 'err': e.stderr})\n return None\n\n self._assert_ssh_return(len(out),\n '_execute_command_and_parse_attributes',\n ssh_cmd, out, err)\n attributes = {}\n for attrib_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attrib_name, foo, attrib_value = attrib_line.partition('!')\n if attrib_name is not None and len(attrib_name.strip()):\n attributes[attrib_name] = attrib_value\n\n LOG.debug(_('leave: _execute_command_and_parse_attributes:\\n'\n 'command: %(cmd)s\\n'\n 'attributes: %(attr)s')\n % {'cmd': str(ssh_cmd),\n 'attr': str(attributes)})\n\n return attributes","lang":"python","vul_type":"cwe-078","target_token_count":314,"sven_meta":{"func_name":"_execute_command_and_parse_attributes","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#13-c9d59ea8af43","input":" def test_get_iscsi_ip_active(self):\n self.flags(lock_path=self.tempdir)\n\n #record set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = 'showport'\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = 'showport -iscsi'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = 'showport -iscsiname'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = 'showvlun -a -host fakehost'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), ''])\n\n self.mox.ReplayAll()\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.253')","target":" def test_get_iscsi_ip_active(self):\n self.flags(lock_path=self.tempdir)\n\n #record set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = ['showport']\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = ['showport', '-iscsi']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = ['showport', '-iscsiname']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), ''])\n\n self.mox.ReplayAll()\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.253')","lang":"python","vul_type":"cwe-078","target_token_count":399,"sven_meta":{"func_name":"test_get_iscsi_ip_active","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#14-6ede8efac84b","input":" def _find_host_from_wwpn(self, connector):\n for wwpn in connector['wwpns']:\n ssh_cmd = 'svcinfo lsfabric -wwpn %s -delim !' % wwpn\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n # This WWPN is not in use\n continue\n\n host_lines = out.strip().split('\\n')\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('remote_wwpn' in header and\n 'name' in header,\n '_find_host_from_wwpn',\n ssh_cmd, out, err)\n rmt_wwpn_idx = header.index('remote_wwpn')\n name_idx = header.index('name')\n\n wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines)\n\n if wwpn in wwpns:\n # All the wwpns will be the mapping for the same\n # host from this WWPN-based query. Just pick\n # the name from first line.\n hostname = host_lines[0].split('!')[name_idx]\n return hostname\n\n # Didn't find a host\n return None","target":" def _find_host_from_wwpn(self, connector):\n for wwpn in connector['wwpns']:\n ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n # This WWPN is not in use\n continue\n\n host_lines = out.strip().split('\\n')\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('remote_wwpn' in header and\n 'name' in header,\n '_find_host_from_wwpn',\n ssh_cmd, out, err)\n rmt_wwpn_idx = header.index('remote_wwpn')\n name_idx = header.index('name')\n\n wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines)\n\n if wwpn in wwpns:\n # All the wwpns will be the mapping for the same\n # host from this WWPN-based query. Just pick\n # the name from first line.\n hostname = host_lines[0].split('!')[name_idx]\n return hostname\n\n # Didn't find a host\n return None","lang":"python","vul_type":"cwe-078","target_token_count":272,"sven_meta":{"func_name":"_find_host_from_wwpn","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#16-3601019c9a9b","input":" def _get_host_from_connector(self, connector):\n \"\"\"List the hosts defined in the storage.\n\n Return the host name with the given connection info, or None if there\n is no host fitting that information.\n\n \"\"\"\n\n prefix = self._connector_to_hostname_prefix(connector)\n LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix)\n\n # Get list of host in the storage\n ssh_cmd = 'svcinfo lshost -delim !'\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n # If we have FC information, we have a faster lookup option\n hostname = None\n if 'wwpns' in connector:\n hostname = self._find_host_from_wwpn(connector)\n\n # If we don't have a hostname yet, try the long way\n if not hostname:\n host_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(host_lines),\n '_get_host_from_connector',\n ssh_cmd, out, err)\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header,\n '_get_host_from_connector',\n ssh_cmd, out, err)\n name_index = header.index('name')\n hosts = map(lambda x: x.split('!')[name_index], host_lines)\n hostname = self._find_host_exhaustive(connector, hosts)\n\n LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname)\n\n return hostname","target":" def _get_host_from_connector(self, connector):\n \"\"\"List the hosts defined in the storage.\n\n Return the host name with the given connection info, or None if there\n is no host fitting that information.\n\n \"\"\"\n\n prefix = self._connector_to_hostname_prefix(connector)\n LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix)\n\n # Get list of host in the storage\n ssh_cmd = ['svcinfo', 'lshost', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n # If we have FC information, we have a faster lookup option\n hostname = None\n if 'wwpns' in connector:\n hostname = self._find_host_from_wwpn(connector)\n\n # If we don't have a hostname yet, try the long way\n if not hostname:\n host_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(host_lines),\n '_get_host_from_connector',\n ssh_cmd, out, err)\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header,\n '_get_host_from_connector',\n ssh_cmd, out, err)\n name_index = header.index('name')\n hosts = map(lambda x: x.split('!')[name_index], host_lines)\n hostname = self._find_host_exhaustive(connector, hosts)\n\n LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname)\n\n return hostname","lang":"python","vul_type":"cwe-078","target_token_count":335,"sven_meta":{"func_name":"_get_host_from_connector","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#18-4a612d4393e8","input":"def main():\n global word\n print(\"Starting script... press 'ctrl+c' in terminal to turn off\")\n while True:\n if pyperclip.paste() != word and len(pyperclip.paste().split())<5:\n word = pyperclip.paste()\n wordChc=False\n req = requests.get(\"https://api-portal.dictionary.com/dcom/pageData/%s\" % word)\n wordChcURB = False\n reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word)\n try: \n data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions']\n except TypeError:\n os.system('notify-send \"Cant find |%s| on dictionary.com!\"' % word)\n wordChc = True\n except KeyError:\n os.system('notify-send \"Cant find |%s| on dictionary.com!\"' % word)\n wordChc = True\n\n if not wordChc:\n definitions = []\n try:\n for definition in data[:3]:\n definitions.append(cleanhtml(definition['definition']))\n definitions.append(\"------------\")\n os.system('notify-send \"definitions from dictionary.com:[{}\\n{}\"'\\\n .format(word+\"]\\n------------\",'\\n'.join(definitions)))\n except KeyError:\n os.system('notify-send \"no results in dictionary.com\"')\n try: \n dataURB = json.loads(reqURB.text)['list']\n except TypeError:\n os.system('notify-send \"Cant find |%s| on urbandictionary.com!\"' % word)\n wordChcURB = True\n except KeyError:\n os.system('notify-send \"Cant find |%s| on urbandictionary.com!\"' % word)\n wordChcURB = True\n\n if not wordChcURB: \n definitionsURB = []\n for definition in dataURB[:3]:\n definitionsURB.append(definition['definition'])\n definitionsURB.append(\"------------\")\n os.system('notify-send \"definitions from urbandictionary.com:[{}\\n{}\"'\\\n .format(word+\"]\\n------------\",'\\n'.join(definitionsURB)))\n os.system('notify-send \"Thank you for using define.py made by kelj0\"')","target":"def main():\n global word\n print(\"Starting script... press 'ctrl+c' in terminal to turn off\")\n while True:\n if pyperclip.paste() != word and len(pyperclip.paste().split())<5:\n word = pyperclip.paste()\n wordChc=False\n req = requests.get(\"https://api-portal.dictionary.com/dcom/pageData/%s\" % word)\n wordChcURB = False\n reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word)\n try: \n data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions']\n except TypeError:\n os.system('notify-send \"Cant find that word on dictionary.com!\"')\n wordChc = True\n except KeyError:\n os.system('notify-send \"Cant find that word on dictionary.com!\"')\n wordChc = True\n\n if not wordChc:\n definitions = []\n try:\n for definition in data[:3]:\n definitions.append(cleanhtml(definition['definition']))\n definitions.append(\"------------\")\n os.system('notify-send \"definitions from dictionary.com:\\n{}\"'.format('\\n'.join(definitions)))\n except KeyError:\n os.system('notify-send \"no results in dictionary.com\"')\n try: \n dataURB = json.loads(reqURB.text)['list']\n except TypeError:\n os.system('notify-send \"Cant find that word on urbandictionary.com!\"' % word)\n wordChcURB = True\n except KeyError:\n os.system('notify-send \"Cant find that word on urbandictionary.com!\"' % word)\n wordChcURB = True\n\n if not wordChcURB: \n definitionsURB = []\n for definition in dataURB[:3]:\n definitionsURB.append(definition['definition'])\n definitionsURB.append(\"------------\")\n os.system('notify-send \"definitions from urbandictionary.com:\\n{}\"'.format('\\n'.join(definitionsURB)))\n os.system('notify-send \"Thank you for using define.py made by kelj0\"')","lang":"python","vul_type":"cwe-078","target_token_count":470,"sven_meta":{"func_name":"main","file_name":"SmallProjects/Define/define.py","commit_link":"github.com/kelj0/LearningPython/commit/2563088bf44f4d5e7f7d65f3c41f12fdaef4a1e4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#20-3a0c17bdb6c5","input":" def _get_flashcopy_mapping_attributes(self, fc_map_id):\n LOG.debug(_('enter: _get_flashcopy_mapping_attributes: mapping %s')\n % fc_map_id)\n\n fc_ls_map_cmd = 'svcinfo lsfcmap -filtervalue id=%s -delim !' % \\\n fc_map_id\n out, err = self._run_ssh(fc_ls_map_cmd)\n if not len(out.strip()):\n return None\n\n # Get list of FlashCopy mappings\n # We expect zero or one line if mapping does not exist,\n # two lines if it does exist, otherwise error\n lines = out.strip().split('\\n')\n self._assert_ssh_return(len(lines) <= 2,\n '_get_flashcopy_mapping_attributes',\n fc_ls_map_cmd, out, err)\n\n if len(lines) == 2:\n attributes = self._get_hdr_dic(lines[0], lines[1], '!')\n else: # 0 or 1 lines\n attributes = None\n\n LOG.debug(_('leave: _get_flashcopy_mapping_attributes: mapping '\n '%(fc_map_id)s, attributes %(attributes)s') %\n {'fc_map_id': fc_map_id, 'attributes': attributes})\n\n return attributes","target":" def _get_flashcopy_mapping_attributes(self, fc_map_id):\n LOG.debug(_('enter: _get_flashcopy_mapping_attributes: mapping %s')\n % fc_map_id)\n\n fc_ls_map_cmd = ['svcinfo', 'lsfcmap', '-filtervalue',\n 'id=%s' % fc_map_id, '-delim', '!']\n out, err = self._run_ssh(fc_ls_map_cmd)\n if not len(out.strip()):\n return None\n\n # Get list of FlashCopy mappings\n # We expect zero or one line if mapping does not exist,\n # two lines if it does exist, otherwise error\n lines = out.strip().split('\\n')\n self._assert_ssh_return(len(lines) <= 2,\n '_get_flashcopy_mapping_attributes',\n fc_ls_map_cmd, out, err)\n\n if len(lines) == 2:\n attributes = self._get_hdr_dic(lines[0], lines[1], '!')\n else: # 0 or 1 lines\n attributes = None\n\n LOG.debug(_('leave: _get_flashcopy_mapping_attributes: mapping '\n '%(fc_map_id)s, attributes %(attributes)s') %\n {'fc_map_id': fc_map_id, 'attributes': attributes})\n\n return attributes","lang":"python","vul_type":"cwe-078","target_token_count":265,"sven_meta":{"func_name":"_get_flashcopy_mapping_attributes","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#23-a63bbfd97879","input":" def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n 'fakehost 123456789012345 123456789054321')\n create_host_ret = pack(CLI_CR +\n 'already used by host fakehost.foo (19)')\n _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, ''])\n\n show_3par_cmd = 'showhost -verbose fakehost.foo'\n _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')","target":" def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost', '123456789012345',\n '123456789054321'])\n create_host_ret = pack(CLI_CR +\n 'already used by host fakehost.foo (19)')\n _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, ''])\n\n show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')","lang":"python","vul_type":"cwe-078","target_token_count":349,"sven_meta":{"func_name":"test_create_invalid_host","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#25-4244e117e96d","input":" def _make_fc_map(self, source, target, full_copy):\n copyflag = '' if full_copy else '-copyrate 0'\n fc_map_cli_cmd = ('svctask mkfcmap -source %(src)s -target %(tgt)s '\n '-autodelete %(copyflag)s' %\n {'src': source,\n 'tgt': target,\n 'copyflag': copyflag})\n out, err = self._run_ssh(fc_map_cli_cmd)\n self._driver_assert(\n len(out.strip()),\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n # Ensure that the output is as expected\n match_obj = re.search('FlashCopy Mapping, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n try:\n fc_map_id = match_obj.group(1)\n self._driver_assert(\n fc_map_id is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n except IndexError:\n self._driver_assert(\n False,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n return fc_map_id","target":" def _make_fc_map(self, source, target, full_copy):\n fc_map_cli_cmd = ['svctask', 'mkfcmap', '-source', source, '-target',\n target, '-autodelete']\n if not full_copy:\n fc_map_cli_cmd.extend(['-copyrate', '0'])\n out, err = self._run_ssh(fc_map_cli_cmd)\n self._driver_assert(\n len(out.strip()),\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n # Ensure that the output is as expected\n match_obj = re.search('FlashCopy Mapping, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n try:\n fc_map_id = match_obj.group(1)\n self._driver_assert(\n fc_map_id is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n except IndexError:\n self._driver_assert(\n False,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n return fc_map_id","lang":"python","vul_type":"cwe-078","target_token_count":489,"sven_meta":{"func_name":"_make_fc_map","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#26-460c5df17593","input":" def test_get_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = 'showport'\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = 'showport -iscsi'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = 'showport -iscsiname'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n #record\n show_vlun_cmd = 'showvlun -a -host fakehost'\n show_vlun_ret = 'no vluns listed\\r\\n'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), ''])\n show_vlun_cmd = 'showvlun -a -showcols Port'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.iscsi_ip_address = '10.10.10.10'\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.252')","target":" def test_get_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = ['showport']\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = ['showport', '-iscsi']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = ['showport', '-iscsiname']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n #record\n show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']\n show_vlun_ret = 'no vluns listed\\r\\n'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), ''])\n show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.iscsi_ip_address = '10.10.10.10'\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.252')","lang":"python","vul_type":"cwe-078","target_token_count":419,"sven_meta":{"func_name":"test_get_iscsi_ip","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#27-07746633810f","input":"def usage(args=None):\n '''\n Return usage information for volumes mounted on this minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' disk.usage\n '''\n if __grains__['kernel'] == 'Linux':\n cmd = 'df -P'\n elif __grains__['kernel'] == 'OpenBSD':\n cmd = 'df -kP'\n else:\n cmd = 'df'\n if args:\n cmd = cmd + ' -' + args\n ret = {}\n out = __salt__['cmd.run'](cmd).splitlines()\n for line in out:\n if not line:\n continue\n if line.startswith('Filesystem'):\n continue\n comps = line.split()\n while not comps[1].isdigit():\n comps[0] = '{0} {1}'.format(comps[0], comps[1])\n comps.pop(1)\n try:\n if __grains__['kernel'] == 'Darwin':\n ret[comps[8]] = {\n 'filesystem': comps[0],\n '512-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n 'iused': comps[5],\n 'ifree': comps[6],\n '%iused': comps[7],\n }\n else:\n ret[comps[5]] = {\n 'filesystem': comps[0],\n '1K-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n }\n except IndexError:\n log.warn(\"Problem parsing disk usage information\")\n ret = {}\n return ret","target":"def usage(args=None):\n '''\n Return usage information for volumes mounted on this minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' disk.usage\n '''\n flags = ''\n allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')\n for flag in args:\n if flag in allowed:\n flags += flag\n else:\n break\n if __grains__['kernel'] == 'Linux':\n cmd = 'df -P'\n elif __grains__['kernel'] == 'OpenBSD':\n cmd = 'df -kP'\n else:\n cmd = 'df'\n if args:\n cmd += ' -{0}'.format(flags)\n ret = {}\n out = __salt__['cmd.run'](cmd).splitlines()\n for line in out:\n if not line:\n continue\n if line.startswith('Filesystem'):\n continue\n comps = line.split()\n while not comps[1].isdigit():\n comps[0] = '{0} {1}'.format(comps[0], comps[1])\n comps.pop(1)\n try:\n if __grains__['kernel'] == 'Darwin':\n ret[comps[8]] = {\n 'filesystem': comps[0],\n '512-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n 'iused': comps[5],\n 'ifree': comps[6],\n '%iused': comps[7],\n }\n else:\n ret[comps[5]] = {\n 'filesystem': comps[0],\n '1K-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n }\n except IndexError:\n log.warn(\"Problem parsing disk usage information\")\n ret = {}\n return ret","lang":"python","vul_type":"cwe-078","target_token_count":437,"sven_meta":{"func_name":"usage","file_name":"salt/modules/disk.py","commit_link":"github.com/saltstack/salt/commit/ebdef37b7e5d2b95a01d34b211c61c61da67e46a","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#30-7c7940c704c2","input":" def _run_ssh(self, command, check_exit=True, attempts=1):\n if not self.sshpool:\n self.sshpool = utils.SSHPool(self.config.san_ip,\n self.config.san_ssh_port,\n self.config.ssh_conn_timeout,\n self.config.san_login,\n password=self.config.san_password,\n privatekey=\n self.config.san_private_key,\n min_size=\n self.config.ssh_min_pool_conn,\n max_size=\n self.config.ssh_max_pool_conn)\n try:\n total_attempts = attempts\n with self.sshpool.item() as ssh:\n while attempts > 0:\n attempts -= 1\n try:\n return self._ssh_execute(ssh, command,\n check_exit_code=check_exit)\n except Exception as e:\n LOG.error(e)\n greenthread.sleep(randint(20, 500) / 100.0)\n msg = (_(\"SSH Command failed after '%(total_attempts)r' \"\n \"attempts : '%(command)s'\") %\n {'total_attempts': total_attempts, 'command': command})\n raise paramiko.SSHException(msg)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error running ssh command: %s\") % command)","target":" def _run_ssh(self, cmd_list, check_exit=True, attempts=1):\n utils.check_ssh_injection(cmd_list)\n command = ' '. join(cmd_list)\n\n if not self.sshpool:\n self.sshpool = utils.SSHPool(self.config.san_ip,\n self.config.san_ssh_port,\n self.config.ssh_conn_timeout,\n self.config.san_login,\n password=self.config.san_password,\n privatekey=\n self.config.san_private_key,\n min_size=\n self.config.ssh_min_pool_conn,\n max_size=\n self.config.ssh_max_pool_conn)\n try:\n total_attempts = attempts\n with self.sshpool.item() as ssh:\n while attempts > 0:\n attempts -= 1\n try:\n return self._ssh_execute(ssh, command,\n check_exit_code=check_exit)\n except Exception as e:\n LOG.error(e)\n greenthread.sleep(randint(20, 500) / 100.0)\n msg = (_(\"SSH Command failed after '%(total_attempts)r' \"\n \"attempts : '%(command)s'\") %\n {'total_attempts': total_attempts, 'command': command})\n raise paramiko.SSHException(msg)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error running ssh command: %s\") % command)","lang":"python","vul_type":"cwe-078","target_token_count":300,"sven_meta":{"func_name":"_run_ssh","file_name":"cinder/volume/drivers/san/hp/hp_3par_common.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#34-c6fd76b935a4","input":" def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n '(\\'OpenStack\\',) '\n 'fakehost iqn.1993-08.org.debian:01:222')\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)","target":" def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost',\n 'iqn.1993-08.org.debian:01:222'])\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)","lang":"python","vul_type":"cwe-078","target_token_count":293,"sven_meta":{"func_name":"test_create_host","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#39-bb9352c88007","input":"def populate_custom_grains_and_pillar():\n '''\n Populate local salt-minion grains and pillar fields values as specified in\n config file.\n\n For example:\n\n custom_grains_pillar:\n grains:\n - selinux: selinux:enabled\n - release: osrelease\n pillar:\n - ntpserver: network_services:ntpserver\n\n Note that the core grains are already included in hubble grains -- this\n is only necessary for custom grains and pillar data.\n '''\n log.debug('Fetching custom grains and pillar details')\n grains = {}\n salt.modules.config.__opts__ = __opts__\n custom_grains = __salt__['config.get']('custom_grains_pillar:grains', [])\n for grain in custom_grains:\n for key in grain:\n if _valid_command(grain[key]):\n value = __salt__['cmd.run']('salt-call grains.get {0}'.format(grain[key])).split('\\n')[1].strip()\n grains[key] = value\n custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', [])\n for pillar in custom_pillar:\n for key in pillar:\n if _valid_command(pillar[key]):\n value = __salt__['cmd.run']('salt-call pillar.get {0}'.format(pillar[key])).split('\\n')[1].strip()\n grains[key] = value\n log.debug('Done with fetching custom grains and pillar details')\n return grains","target":"def populate_custom_grains_and_pillar():\n '''\n Populate local salt-minion grains and pillar fields values as specified in\n config file.\n\n For example:\n\n custom_grains_pillar:\n grains:\n - selinux: selinux:enabled\n - release: osrelease\n pillar:\n - ntpserver: network_services:ntpserver\n\n Note that the core grains are already included in hubble grains -- this\n is only necessary for custom grains and pillar data.\n '''\n log.debug('Fetching custom grains and pillar details')\n grains = {}\n salt.modules.config.__opts__ = __opts__\n custom_grains = __salt__['config.get']('custom_grains_pillar:grains', [])\n for grain in custom_grains:\n for key in grain:\n value = __salt__['cmd.run'](['salt-call', 'grains.get', grain[key]]).split('\\n')[1].strip()\n grains[key] = value\n custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', [])\n for pillar in custom_pillar:\n for key in pillar:\n value = __salt__['cmd.run'](['salt-call', 'pillar.get', pillar[key]]).split('\\n')[1].strip()\n grains[key] = value\n log.debug('Done with fetching custom grains and pillar details')\n return grains","lang":"python","vul_type":"cwe-078","target_token_count":302,"sven_meta":{"func_name":"populate_custom_grains_and_pillar","file_name":"hubblestack/extmods/grains/custom_grains_pillar.py","commit_link":"github.com/hubblestack/hubble/commit/d9ca4a93ea5aabb1298c5b3dbfb23e94203428b9","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#40-86bcfc95a9d4","input":" def copy(self, src_data, src_path, dst_data, dst_path, job_id=None):\n credentials = ''\n\n if src_data is None: # Local\n src = src_path\n else:\n credentials += self._formatCredentials(src_data, name='src')\n src = 'src:{}'.format(src_path)\n\n if dst_data is None: # Local\n dst = dst_path\n else:\n credentials += self._formatCredentials(dst_data, name='dst')\n dst = 'dst:{}'.format(dst_path)\n\n\n command = (\n '{credentials} '\n 'rclone copy {src} {dst} '\n '--progress '\n '--stats 2s '\n ).format(\n credentials=credentials,\n src=src,\n dst=dst,\n )\n\n logging.info(sanitize(command))\n\n if job_id is None:\n job_id = self._get_next_job_id()\n else:\n if self._job_id_exists(job_id):\n raise ValueError('rclone copy job with ID {} already exists'.fromat(job_id))\n\n self._stop_events[job_id] = threading.Event()\n\n try:\n self._execute_interactive(command, job_id)\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))\n\n return job_id","target":" def copy(self, src_data, src_path, dst_data, dst_path, job_id=None):\n credentials = {}\n\n if src_data is None: # Local\n src = src_path\n else:\n credentials.update(self._formatCredentials(src_data, name='src'))\n src = 'src:{}'.format(src_path)\n\n if dst_data is None: # Local\n dst = dst_path\n else:\n credentials.update(self._formatCredentials(dst_data, name='dst'))\n dst = 'dst:{}'.format(dst_path)\n\n command = [\n 'rclone',\n 'copy',\n src,\n dst,\n '--progress',\n '--stats', '2s',\n ]\n\n bash_command = \"{} {}\".format(\n ' '.join(\"{}='{}'\".format(key, value) for key, value in credentials.items()),\n ' '.join(command),\n )\n\n logging.info(sanitize(bash_command))\n\n if job_id is None:\n job_id = self._get_next_job_id()\n else:\n if self._job_id_exists(job_id):\n raise ValueError('rclone copy job with ID {} already exists'.fromat(job_id))\n\n self._stop_events[job_id] = threading.Event()\n\n try:\n self._execute_interactive(command, credentials, job_id)\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))\n\n return job_id","lang":"python","vul_type":"cwe-078","target_token_count":296,"sven_meta":{"func_name":"copy","file_name":"src/backend/api/utils/rclone_connection.py","commit_link":"github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#43-97660977fd9d","input":" def handle_message(self, ch, method, properties, body):\n \"\"\"\n this is a pika.basic_consumer callback\n handles client inputs, runs appropriate workflows and views\n\n Args:\n ch: amqp channel\n method: amqp method\n properties:\n body: message body\n \"\"\"\n input = {}\n try:\n self.sessid = method.routing_key\n\n input = json_decode(body)\n data = input['data']\n\n # since this comes as \"path\" we dont know if it's view or workflow yet\n #TODO: just a workaround till we modify ui to\n if 'path' in data:\n if data['path'] in settings.VIEW_URLS:\n data['view'] = data['path']\n else:\n data['wf'] = data['path']\n session = Session(self.sessid)\n\n headers = {'remote_ip': input['_zops_remote_ip']}\n\n if 'wf' in data:\n output = self._handle_workflow(session, data, headers)\n elif 'job' in data:\n\n self._handle_job(session, data, headers)\n return\n else:\n output = self._handle_view(session, data, headers)\n\n except HTTPError as e:\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), \"code\": e.code}\n log.exception(\"Http error occurred\")\n except:\n self.current = Current(session=session, input=data)\n self.current.headers = headers\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n err = traceback.format_exc()\n output = {'error': self._prepare_error_msg(err), \"code\": 500}\n log.exception(\"Worker error occurred with messsage body:\\n%s\" % body)\n if 'callbackID' in input:\n output['callbackID'] = input['callbackID']\n log.info(\"OUTPUT for %s: %s\" % (self.sessid, output))\n output['reply_timestamp'] = time()\n self.send_output(output)","target":" def handle_message(self, ch, method, properties, body):\n \"\"\"\n this is a pika.basic_consumer callback\n handles client inputs, runs appropriate workflows and views\n\n Args:\n ch: amqp channel\n method: amqp method\n properties:\n body: message body\n \"\"\"\n input = {}\n headers = {}\n try:\n self.sessid = method.routing_key\n\n input = json_decode(body)\n data = input['data']\n\n # since this comes as \"path\" we dont know if it's view or workflow yet\n # TODO: just a workaround till we modify ui to\n if 'path' in data:\n if data['path'] in settings.VIEW_URLS:\n data['view'] = data['path']\n else:\n data['wf'] = data['path']\n session = Session(self.sessid)\n\n headers = {'remote_ip': input['_zops_remote_ip'],\n 'source': input['_zops_source']}\n\n if 'wf' in data:\n output = self._handle_workflow(session, data, headers)\n elif 'job' in data:\n\n self._handle_job(session, data, headers)\n return\n else:\n output = self._handle_view(session, data, headers)\n\n except HTTPError as e:\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), \"code\": e.code}\n log.exception(\"Http error occurred\")\n except:\n self.current = Current(session=session, input=data)\n self.current.headers = headers\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n err = traceback.format_exc()\n output = {'error': self._prepare_error_msg(err), \"code\": 500}\n log.exception(\"Worker error occurred with messsage body:\\n%s\" % body)\n if 'callbackID' in input:\n output['callbackID'] = input['callbackID']\n log.info(\"OUTPUT for %s: %s\" % (self.sessid, output))\n output['reply_timestamp'] = time()\n self.send_output(output)","lang":"python","vul_type":"cwe-078","target_token_count":467,"sven_meta":{"func_name":"handle_message","file_name":"zengine/wf_daemon.py","commit_link":"github.com/zetaops/zengine/commit/52eafbee90f8ddf78be0c7452828d49423246851","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#50-0b3e8f1918f8","input":" def _create_vdisk(self, name, size, units, opts):\n \"\"\"Create a new vdisk.\"\"\"\n\n LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)\n\n model_update = None\n autoex = '-autoexpand' if opts['autoexpand'] else ''\n easytier = '-easytier on' if opts['easytier'] else '-easytier off'\n\n # Set space-efficient options\n if opts['rsize'] == -1:\n ssh_cmd_se_opt = ''\n else:\n ssh_cmd_se_opt = (\n '-rsize %(rsize)d%% %(autoex)s -warning %(warn)d%%' %\n {'rsize': opts['rsize'],\n 'autoex': autoex,\n 'warn': opts['warning']})\n if opts['compression']:\n ssh_cmd_se_opt = ssh_cmd_se_opt + ' -compressed'\n else:\n ssh_cmd_se_opt = ssh_cmd_se_opt + (\n ' -grainsize %d' % opts['grainsize'])\n\n ssh_cmd = ('svctask mkvdisk -name %(name)s -mdiskgrp %(mdiskgrp)s '\n '-iogrp 0 -size %(size)s -unit '\n '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'\n % {'name': name,\n 'mdiskgrp': self.configuration.storwize_svc_volpool_name,\n 'size': size, 'unit': units, 'easytier': easytier,\n 'ssh_cmd_se_opt': ssh_cmd_se_opt})\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), '_create_vdisk',\n ssh_cmd, out, err)\n\n # Ensure that the output is as expected\n match_obj = re.search('Virtual Disk, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('_create_vdisk %(name)s - did not find '\n 'success message in CLI output.\\n '\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'name': name, 'out': str(out), 'err': str(err)})\n\n LOG.debug(_('leave: _create_vdisk: volume %s ') % name)","target":" def _create_vdisk(self, name, size, units, opts):\n \"\"\"Create a new vdisk.\"\"\"\n\n LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)\n\n model_update = None\n easytier = 'on' if opts['easytier'] else 'off'\n\n # Set space-efficient options\n if opts['rsize'] == -1:\n ssh_cmd_se_opt = []\n else:\n ssh_cmd_se_opt = ['-rsize', '%s%%' % str(opts['rsize']),\n '-autoexpand', '-warning',\n '%s%%' % str(opts['warning'])]\n if not opts['autoexpand']:\n ssh_cmd_se_opt.remove('-autoexpand')\n\n if opts['compression']:\n ssh_cmd_se_opt.append('-compressed')\n else:\n ssh_cmd_se_opt.extend(['-grainsize', str(opts['grainsize'])])\n\n ssh_cmd = ['svctask', 'mkvdisk', '-name', name, '-mdiskgrp',\n self.configuration.storwize_svc_volpool_name,\n '-iogrp', '0', '-size', size, '-unit',\n units, '-easytier', easytier] + ssh_cmd_se_opt\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), '_create_vdisk',\n ssh_cmd, out, err)\n\n # Ensure that the output is as expected\n match_obj = re.search('Virtual Disk, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('_create_vdisk %(name)s - did not find '\n 'success message in CLI output.\\n '\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'name': name, 'out': str(out), 'err': str(err)})\n\n LOG.debug(_('leave: _create_vdisk: volume %s ') % name)","lang":"python","vul_type":"cwe-078","target_token_count":440,"sven_meta":{"func_name":"_create_vdisk","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#51-ff53f932fe8f","input":" def test_invalid_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = 'showport'\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = 'showport -iscsi'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = 'showport -iscsiname'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']\n config.iscsi_ip_address = '10.10.10.10'\n self.mox.ReplayAll()\n\n # no valid ip addr should be configured.\n self.assertRaises(exception.InvalidInput,\n self.setup_driver,\n config,\n set_up_fakes=False)","target":" def test_invalid_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = ['showport']\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = ['showport', '-iscsi']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = ['showport', '-iscsiname']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']\n config.iscsi_ip_address = '10.10.10.10'\n self.mox.ReplayAll()\n\n # no valid ip addr should be configured.\n self.assertRaises(exception.InvalidInput,\n self.setup_driver,\n config,\n set_up_fakes=False)","lang":"python","vul_type":"cwe-078","target_token_count":292,"sven_meta":{"func_name":"test_invalid_iscsi_ip","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#56-0f9c9f940fdd","input":" def _update_volume_stats(self):\n \"\"\"Retrieve stats info from volume group.\"\"\"\n\n LOG.debug(_(\"Updating volume stats\"))\n data = {}\n\n data['vendor_name'] = 'IBM'\n data['driver_version'] = '1.1'\n data['storage_protocol'] = list(self._enabled_protocols)\n\n data['total_capacity_gb'] = 0 # To be overwritten\n data['free_capacity_gb'] = 0 # To be overwritten\n data['reserved_percentage'] = 0\n data['QoS_support'] = False\n\n pool = self.configuration.storwize_svc_volpool_name\n #Get storage system name\n ssh_cmd = 'svcinfo lssystem -delim !'\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes or not attributes['name']:\n exception_message = (_('_update_volume_stats: '\n 'Could not get system name'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n backend_name = self.configuration.safe_get('volume_backend_name')\n if not backend_name:\n backend_name = '%s_%s' % (attributes['name'], pool)\n data['volume_backend_name'] = backend_name\n\n ssh_cmd = 'svcinfo lsmdiskgrp -bytes -delim ! %s' % pool\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes:\n LOG.error(_('Could not get pool data from the storage'))\n exception_message = (_('_update_volume_stats: '\n 'Could not get storage pool data'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n data['total_capacity_gb'] = (float(attributes['capacity']) /\n (1024 ** 3))\n data['free_capacity_gb'] = (float(attributes['free_capacity']) /\n (1024 ** 3))\n data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']\n data['compression_support'] = self._compression_enabled\n\n self._stats = data","target":" def _update_volume_stats(self):\n \"\"\"Retrieve stats info from volume group.\"\"\"\n\n LOG.debug(_(\"Updating volume stats\"))\n data = {}\n\n data['vendor_name'] = 'IBM'\n data['driver_version'] = '1.1'\n data['storage_protocol'] = list(self._enabled_protocols)\n\n data['total_capacity_gb'] = 0 # To be overwritten\n data['free_capacity_gb'] = 0 # To be overwritten\n data['reserved_percentage'] = 0\n data['QoS_support'] = False\n\n pool = self.configuration.storwize_svc_volpool_name\n #Get storage system name\n ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!']\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes or not attributes['name']:\n exception_message = (_('_update_volume_stats: '\n 'Could not get system name'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n backend_name = self.configuration.safe_get('volume_backend_name')\n if not backend_name:\n backend_name = '%s_%s' % (attributes['name'], pool)\n data['volume_backend_name'] = backend_name\n\n ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!', pool]\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes:\n LOG.error(_('Could not get pool data from the storage'))\n exception_message = (_('_update_volume_stats: '\n 'Could not get storage pool data'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n data['total_capacity_gb'] = (float(attributes['capacity']) /\n (1024 ** 3))\n data['free_capacity_gb'] = (float(attributes['free_capacity']) /\n (1024 ** 3))\n data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']\n data['compression_support'] = self._compression_enabled\n\n self._stats = data","lang":"python","vul_type":"cwe-078","target_token_count":438,"sven_meta":{"func_name":"_update_volume_stats","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#57-8035e4e0e399","input":" def test_create_modify_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])\n\n create_host_cmd = ('createhost -add fakehost '\n '123456789012345 123456789054321')\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)","target":" def test_create_modify_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])\n\n create_host_cmd = ['createhost', '-add', 'fakehost', '123456789012345',\n '123456789054321']\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)","lang":"python","vul_type":"cwe-078","target_token_count":306,"sven_meta":{"func_name":"test_create_modify_host","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#59-a64989f2b4c7","input":" def _get_least_used_nsp(self, nspss):\n \"\"\"\"Return the nsp that has the fewest active vluns.\"\"\"\n # return only the nsp (node:server:port)\n result = self.common._cli_run('showvlun -a -showcols Port', None)\n\n # count the number of nsps (there is 1 for each active vlun)\n nsp_counts = {}\n for nsp in nspss:\n # initialize counts to zero\n nsp_counts[nsp] = 0\n\n current_least_used_nsp = None\n if result:\n # first line is header\n result = result[1:]\n for line in result:\n nsp = line.strip()\n if nsp in nsp_counts:\n nsp_counts[nsp] = nsp_counts[nsp] + 1\n\n # identify key (nsp) of least used nsp\n current_smallest_count = sys.maxint\n for (nsp, count) in nsp_counts.iteritems():\n if count < current_smallest_count:\n current_least_used_nsp = nsp\n current_smallest_count = count\n\n return current_least_used_nsp","target":" def _get_least_used_nsp(self, nspss):\n \"\"\"\"Return the nsp that has the fewest active vluns.\"\"\"\n # return only the nsp (node:server:port)\n result = self.common._cli_run(['showvlun', '-a', '-showcols', 'Port'])\n\n # count the number of nsps (there is 1 for each active vlun)\n nsp_counts = {}\n for nsp in nspss:\n # initialize counts to zero\n nsp_counts[nsp] = 0\n\n current_least_used_nsp = None\n if result:\n # first line is header\n result = result[1:]\n for line in result:\n nsp = line.strip()\n if nsp in nsp_counts:\n nsp_counts[nsp] = nsp_counts[nsp] + 1\n\n # identify key (nsp) of least used nsp\n current_smallest_count = sys.maxint\n for (nsp, count) in nsp_counts.iteritems():\n if count < current_smallest_count:\n current_least_used_nsp = nsp\n current_smallest_count = count\n\n return current_least_used_nsp","lang":"python","vul_type":"cwe-078","target_token_count":258,"sven_meta":{"func_name":"_get_least_used_nsp","file_name":"cinder/volume/drivers/san/hp/hp_3par_iscsi.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#63-30c0e48002c5","input":"def test_settings_path_skip_issue_909(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'skip =\\n'\n ' file_to_be_skipped.py\\n'\n 'skip_glob =\\n'\n ' *glob_skip*\\n')\n\n base_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n base_dir.join('file_to_be_skipped.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors\n check_output(['isort', '--check-only'])\n results = check_output(['isort', '--check-only', '--settings-path=conf/.isort.cfg'])\n os.chdir(str(test_run_directory))\n\n assert b'skipped 2' in results.lower()","target":"def test_settings_path_skip_issue_909(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'skip =\\n'\n ' file_to_be_skipped.py\\n'\n 'skip_glob =\\n'\n ' *glob_skip*\\n')\n\n base_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n base_dir.join('file_to_be_skipped.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors\n subprocess.run(['isort', '--check-only'], check=True)\n result = subprocess.run(\n ['isort', '--check-only', '--settings-path=conf/.isort.cfg'],\n stdout=subprocess.PIPE,\n check=True\n )\n os.chdir(str(test_run_directory))\n\n assert b'skipped 2' in result.stdout.lower()","lang":"python","vul_type":"cwe-078","target_token_count":274,"sven_meta":{"func_name":"test_settings_path_skip_issue_909","file_name":"test_isort.py","commit_link":"github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#65-c6c5f37df5b7","input":" def take_bug_report(self, test_name, begin_time):\n \"\"\"Takes a bug report on the device and stores it in a file.\n\n Args:\n test_name: Name of the test case that triggered this bug report.\n begin_time: Logline format timestamp taken when the test started.\n \"\"\"\n new_br = True\n try:\n stdout = self.adb.shell('bugreportz -v').decode('utf-8')\n # This check is necessary for builds before N, where adb shell's ret\n # code and stderr are not propagated properly.\n if 'not found' in stdout:\n new_br = False\n except adb.AdbError:\n new_br = False\n br_path = os.path.join(self.log_path, 'BugReports')\n utils.create_dir(br_path)\n base_name = ',%s,%s.txt' % (begin_time, self.serial)\n if new_br:\n base_name = base_name.replace('.txt', '.zip')\n test_name_len = utils.MAX_FILENAME_LEN - len(base_name)\n out_name = test_name[:test_name_len] + base_name\n full_out_path = os.path.join(br_path, out_name.replace(' ', r'\\ '))\n # in case device restarted, wait for adb interface to return\n self.wait_for_boot_completion()\n self.log.info('Taking bugreport for %s.', test_name)\n if new_br:\n out = self.adb.shell('bugreportz').decode('utf-8')\n if not out.startswith('OK'):\n raise DeviceError(self, 'Failed to take bugreport: %s' % out)\n br_out_path = out.split(':')[1].strip()\n self.adb.pull('%s %s' % (br_out_path, full_out_path))\n else:\n self.adb.bugreport(' > %s' % full_out_path)\n self.log.info('Bugreport for %s taken at %s.', test_name,\n full_out_path)","target":" def take_bug_report(self, test_name, begin_time):\n \"\"\"Takes a bug report on the device and stores it in a file.\n\n Args:\n test_name: Name of the test case that triggered this bug report.\n begin_time: Logline format timestamp taken when the test started.\n \"\"\"\n new_br = True\n try:\n stdout = self.adb.shell('bugreportz -v').decode('utf-8')\n # This check is necessary for builds before N, where adb shell's ret\n # code and stderr are not propagated properly.\n if 'not found' in stdout:\n new_br = False\n except adb.AdbError:\n new_br = False\n br_path = os.path.join(self.log_path, 'BugReports')\n utils.create_dir(br_path)\n base_name = ',%s,%s.txt' % (begin_time, self.serial)\n if new_br:\n base_name = base_name.replace('.txt', '.zip')\n test_name_len = utils.MAX_FILENAME_LEN - len(base_name)\n out_name = test_name[:test_name_len] + base_name\n full_out_path = os.path.join(br_path, out_name.replace(' ', r'\\ '))\n # in case device restarted, wait for adb interface to return\n self.wait_for_boot_completion()\n self.log.info('Taking bugreport for %s.', test_name)\n if new_br:\n out = self.adb.shell('bugreportz').decode('utf-8')\n if not out.startswith('OK'):\n raise DeviceError(self, 'Failed to take bugreport: %s' % out)\n br_out_path = out.split(':')[1].strip()\n self.adb.pull([br_out_path, full_out_path])\n else:\n # shell=True as this command redirects the stdout to a local file\n # using shell redirection.\n self.adb.bugreport(' > %s' % full_out_path, shell=True)\n self.log.info('Bugreport for %s taken at %s.', test_name,\n full_out_path)","lang":"python","vul_type":"cwe-078","target_token_count":434,"sven_meta":{"func_name":"take_bug_report","file_name":"mobly/controllers/android_device.py","commit_link":"github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#66-a63bbfd97879","input":" def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n '(\\'OpenStack\\',) '\n 'fakehost iqn.1993-08.org.debian:01:222')\n in_use_ret = pack('\\r\\nalready used by host fakehost.foo ')\n _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])\n\n show_3par_cmd = 'showhost -verbose fakehost.foo'\n _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')","target":" def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost',\n 'iqn.1993-08.org.debian:01:222'])\n in_use_ret = pack('\\r\\nalready used by host fakehost.foo ')\n _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])\n\n show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')","lang":"python","vul_type":"cwe-078","target_token_count":335,"sven_meta":{"func_name":"test_create_invalid_host","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#68-cfef6e3f1ddb","input":"def test_skip_paths_issue_938(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'line_length = 88\\n'\n 'multi_line_output = 4\\n'\n 'lines_after_imports = 2\\n'\n 'skip_glob =\\n'\n ' migrations/**.py\\n')\n base_dir.join('dont_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n migrations_dir = base_dir.mkdir('migrations')\n migrations_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n results = check_output(['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n os.chdir(str(test_run_directory))\n\n assert b'skipped' not in results.lower()\n\n os.chdir(str(base_dir))\n results = check_output(['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n os.chdir(str(test_run_directory))\n\n assert b'skipped 1' in results.lower()","target":"def test_skip_paths_issue_938(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'line_length = 88\\n'\n 'multi_line_output = 4\\n'\n 'lines_after_imports = 2\\n'\n 'skip_glob =\\n'\n ' migrations/**.py\\n')\n base_dir.join('dont_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n migrations_dir = base_dir.mkdir('migrations')\n migrations_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n result = subprocess.run(\n ['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n stdout=subprocess.PIPE,\n check=True,\n )\n os.chdir(str(test_run_directory))\n\n assert b'skipped' not in result.stdout.lower()\n\n os.chdir(str(base_dir))\n result = subprocess.run(\n ['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n stdout=subprocess.PIPE,\n check=True,\n )\n os.chdir(str(test_run_directory))\n\n assert b'skipped 1' in result.stdout.lower()","lang":"python","vul_type":"cwe-078","target_token_count":333,"sven_meta":{"func_name":"test_skip_paths_issue_938","file_name":"test_isort.py","commit_link":"github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#69-4fda1d07f940","input":" def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):\n # Ensure vdisk has no FlashCopy mappings\n mapping_ids = self._get_vdisk_fc_mappings(name)\n while len(mapping_ids):\n wait_for_copy = False\n for map_id in mapping_ids:\n attrs = self._get_flashcopy_mapping_attributes(map_id)\n if not attrs:\n continue\n source = attrs['source_vdisk_name']\n target = attrs['target_vdisk_name']\n copy_rate = attrs['copy_rate']\n status = attrs['status']\n\n if copy_rate == '0':\n # Case #2: A vdisk that has snapshots\n if source == name:\n if not allow_snaps:\n return False\n ssh_cmd = ('svctask chfcmap -copyrate 50 '\n '-autodelete on %s' % map_id)\n out, err = self._run_ssh(ssh_cmd)\n wait_for_copy = True\n # Case #3: A snapshot\n else:\n msg = (_('Vdisk %(name)s not involved in '\n 'mapping %(src)s -> %(tgt)s') %\n {'name': name, 'src': source, 'tgt': target})\n self._driver_assert(target == name, msg)\n if status in ['copying', 'prepared']:\n self._run_ssh('svctask stopfcmap %s' % map_id)\n elif status in ['stopping', 'preparing']:\n wait_for_copy = True\n else:\n self._run_ssh('svctask rmfcmap -force %s' % map_id)\n # Case 4: Copy in progress - wait and will autodelete\n else:\n if status == 'prepared':\n self._run_ssh('svctask stopfcmap %s' % map_id)\n self._run_ssh('svctask rmfcmap -force %s' % map_id)\n elif status == 'idle_or_copied':\n # Prepare failed\n self._run_ssh('svctask rmfcmap -force %s' % map_id)\n else:\n wait_for_copy = True\n if wait_for_copy:\n time.sleep(5)\n mapping_ids = self._get_vdisk_fc_mappings(name)\n return True","target":" def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):\n # Ensure vdisk has no FlashCopy mappings\n mapping_ids = self._get_vdisk_fc_mappings(name)\n while len(mapping_ids):\n wait_for_copy = False\n for map_id in mapping_ids:\n attrs = self._get_flashcopy_mapping_attributes(map_id)\n if not attrs:\n continue\n source = attrs['source_vdisk_name']\n target = attrs['target_vdisk_name']\n copy_rate = attrs['copy_rate']\n status = attrs['status']\n\n if copy_rate == '0':\n # Case #2: A vdisk that has snapshots\n if source == name:\n if not allow_snaps:\n return False\n ssh_cmd = ['svctask', 'chfcmap', '-copyrate', '50',\n '-autodelete', 'on', map_id]\n out, err = self._run_ssh(ssh_cmd)\n wait_for_copy = True\n # Case #3: A snapshot\n else:\n msg = (_('Vdisk %(name)s not involved in '\n 'mapping %(src)s -> %(tgt)s') %\n {'name': name, 'src': source, 'tgt': target})\n self._driver_assert(target == name, msg)\n if status in ['copying', 'prepared']:\n self._run_ssh(['svctask', 'stopfcmap', map_id])\n elif status in ['stopping', 'preparing']:\n wait_for_copy = True\n else:\n self._run_ssh(['svctask', 'rmfcmap', '-force',\n map_id])\n # Case 4: Copy in progress - wait and will autodelete\n else:\n if status == 'prepared':\n self._run_ssh(['svctask', 'stopfcmap', map_id])\n self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n elif status == 'idle_or_copied':\n # Prepare failed\n self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n else:\n wait_for_copy = True\n if wait_for_copy:\n time.sleep(5)\n mapping_ids = self._get_vdisk_fc_mappings(name)\n return True","lang":"python","vul_type":"cwe-078","target_token_count":491,"sven_meta":{"func_name":"_ensure_vdisk_no_fc_mappings","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#71-40fbd4edf7d3","input":"def repack(host, targets, channel='stable'):\n url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'\n req = requests.get(url)\n req.raise_for_status()\n manifest = toml.loads(req.content)\n if manifest['manifest-version'] != '2':\n print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])\n return\n print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))\n rustc_version, rustc = package(manifest, 'rustc', host)\n if rustc['available']:\n print('rustc %s\\n %s\\n %s' % (rustc_version, rustc['url'], rustc['hash']))\n fetch(rustc['url'])\n cargo_version, cargo = package(manifest, 'cargo', host)\n if cargo['available']:\n print('cargo %s\\n %s\\n %s' % (cargo_version, cargo['url'], cargo['hash']))\n fetch(cargo['url'])\n stds = []\n for target in targets:\n version, info = package(manifest, 'rust-std', target)\n if info['available']:\n print('rust-std %s\\n %s\\n %s' % (version, info['url'], info['hash']))\n fetch(info['url'])\n stds.append(info)\n print('Installing packages...')\n tar_basename = 'rustc-%s-repack' % host\n install_dir = 'rustc'\n os.system('rm -rf %s' % install_dir)\n install(os.path.basename(rustc['url']), install_dir)\n install(os.path.basename(cargo['url']), install_dir)\n for std in stds:\n install(os.path.basename(std['url']), install_dir)\n print('Tarring %s...' % tar_basename)\n os.system('tar cjf %s.tar.bz2 %s/*' % (tar_basename, install_dir))\n os.system('rm -rf %s' % install_dir)","target":"def repack(host, targets, channel='stable'):\n print(\"Repacking rust for %s...\" % host)\n url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'\n req = requests.get(url)\n req.raise_for_status()\n manifest = toml.loads(req.content)\n if manifest['manifest-version'] != '2':\n print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])\n return\n print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))\n rustc_version, rustc = package(manifest, 'rustc', host)\n if rustc['available']:\n print('rustc %s\\n %s\\n %s' % (rustc_version, rustc['url'], rustc['hash']))\n fetch(rustc['url'])\n cargo_version, cargo = package(manifest, 'cargo', host)\n if cargo['available']:\n print('cargo %s\\n %s\\n %s' % (cargo_version, cargo['url'], cargo['hash']))\n fetch(cargo['url'])\n stds = []\n for target in targets:\n version, info = package(manifest, 'rust-std', target)\n if info['available']:\n print('rust-std %s\\n %s\\n %s' % (version, info['url'], info['hash']))\n fetch(info['url'])\n stds.append(info)\n print('Installing packages...')\n tar_basename = 'rustc-%s-repack' % host\n install_dir = 'rustc'\n subprocess.check_call(['rm', '-rf', install_dir])\n install(os.path.basename(rustc['url']), install_dir)\n install(os.path.basename(cargo['url']), install_dir)\n for std in stds:\n install(os.path.basename(std['url']), install_dir)\n print('Tarring %s...' % tar_basename)\n subprocess.check_call(['tar', 'cjf', tar_basename + '.tar.bz2', install_dir])\n subprocess.check_call(['rm', '-rf', install_dir])","lang":"python","vul_type":"cwe-078","target_token_count":452,"sven_meta":{"func_name":"repack","file_name":"repack_rust.py","commit_link":"github.com/rillian/rust-build/commit/b8af51e5811fcb35eff9e1e3e91c98490e7a7dcb","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#75-ee319f181670","input":" def get_ports(self):\n # First get the active FC ports\n out = self._cli_run('showport', None)\n\n # strip out header\n # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,\n # Protocol,Label,Partner,FailoverState\n out = out[1:len(out) - 2]\n\n ports = {'FC': [], 'iSCSI': {}}\n for line in out:\n tmp = line.split(',')\n\n if tmp:\n if tmp[1] == 'target' and tmp[2] == 'ready':\n if tmp[6] == 'FC':\n ports['FC'].append(tmp[4])\n\n # now get the active iSCSI ports\n out = self._cli_run('showport -iscsi', None)\n\n # strip out header\n # N:S:P,State,IPAddr,Netmask,Gateway,\n # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port\n out = out[1:len(out) - 2]\n for line in out:\n tmp = line.split(',')\n\n if tmp and len(tmp) > 2:\n if tmp[1] == 'ready':\n ports['iSCSI'][tmp[2]] = {}\n\n # now get the nsp and iqn\n result = self._cli_run('showport -iscsiname', None)\n if result:\n # first line is header\n # nsp, ip,iqn\n result = result[1:]\n for line in result:\n info = line.split(\",\")\n if info and len(info) > 2:\n if info[1] in ports['iSCSI']:\n nsp = info[0]\n ip_addr = info[1]\n iqn = info[2]\n ports['iSCSI'][ip_addr] = {'nsp': nsp,\n 'iqn': iqn\n }\n\n LOG.debug(\"PORTS = %s\" % pprint.pformat(ports))\n return ports","target":" def get_ports(self):\n # First get the active FC ports\n out = self._cli_run(['showport'])\n\n # strip out header\n # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,\n # Protocol,Label,Partner,FailoverState\n out = out[1:len(out) - 2]\n\n ports = {'FC': [], 'iSCSI': {}}\n for line in out:\n tmp = line.split(',')\n\n if tmp:\n if tmp[1] == 'target' and tmp[2] == 'ready':\n if tmp[6] == 'FC':\n ports['FC'].append(tmp[4])\n\n # now get the active iSCSI ports\n out = self._cli_run(['showport', '-iscsi'])\n\n # strip out header\n # N:S:P,State,IPAddr,Netmask,Gateway,\n # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port\n out = out[1:len(out) - 2]\n for line in out:\n tmp = line.split(',')\n\n if tmp and len(tmp) > 2:\n if tmp[1] == 'ready':\n ports['iSCSI'][tmp[2]] = {}\n\n # now get the nsp and iqn\n result = self._cli_run(['showport', '-iscsiname'])\n if result:\n # first line is header\n # nsp, ip,iqn\n result = result[1:]\n for line in result:\n info = line.split(\",\")\n if info and len(info) > 2:\n if info[1] in ports['iSCSI']:\n nsp = info[0]\n ip_addr = info[1]\n iqn = info[2]\n ports['iSCSI'][ip_addr] = {'nsp': nsp,\n 'iqn': iqn\n }\n\n LOG.debug(\"PORTS = %s\" % pprint.pformat(ports))\n return ports","lang":"python","vul_type":"cwe-078","target_token_count":446,"sven_meta":{"func_name":"get_ports","file_name":"cinder/volume/drivers/san/hp/hp_3par_common.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#76-bd3889ea8301","input":" def test_get_least_used_nsp(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = 'showvlun -a -showcols Port'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n # in use count 11 12\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])\n self.assertEqual(nsp, '0:2:1')\n\n # in use count 11 10\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])\n self.assertEqual(nsp, '1:2:1')\n\n # in use count 0 10\n nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])\n self.assertEqual(nsp, '1:1:1')","target":" def test_get_least_used_nsp(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n # in use count 11 12\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])\n self.assertEqual(nsp, '0:2:1')\n\n # in use count 11 10\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])\n self.assertEqual(nsp, '1:2:1')\n\n # in use count 0 10\n nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])\n self.assertEqual(nsp, '1:1:1')","lang":"python","vul_type":"cwe-078","target_token_count":340,"sven_meta":{"func_name":"test_get_least_used_nsp","file_name":"cinder/tests/test_hp3par.py","commit_link":"github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#77-2ae9f2223708","input":" def _cmd_to_dict(self, cmd):\n arg_list = cmd.split()\n no_param_args = [\n 'autodelete',\n 'autoexpand',\n 'bytes',\n 'compressed',\n 'force',\n 'nohdr',\n ]\n one_param_args = [\n 'chapsecret',\n 'cleanrate',\n 'copyrate',\n 'delim',\n 'filtervalue',\n 'grainsize',\n 'hbawwpn',\n 'host',\n 'iogrp',\n 'iscsiname',\n 'mdiskgrp',\n 'name',\n 'rsize',\n 'scsi',\n 'size',\n 'source',\n 'target',\n 'unit',\n 'easytier',\n 'warning',\n 'wwpn',\n ]\n\n # Handle the special case of lsnode which is a two-word command\n # Use the one word version of the command internally\n if arg_list[0] in ('svcinfo', 'svctask'):\n if arg_list[1] == 'lsnode':\n if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! <node id>\n ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}\n else:\n ret = {'cmd': 'lsnodecanister'}\n else:\n ret = {'cmd': arg_list[1]}\n arg_list.pop(0)\n else:\n ret = {'cmd': arg_list[0]}\n\n skip = False\n for i in range(1, len(arg_list)):\n if skip:\n skip = False\n continue\n if arg_list[i][0] == '-':\n if arg_list[i][1:] in no_param_args:\n ret[arg_list[i][1:]] = True\n elif arg_list[i][1:] in one_param_args:\n ret[arg_list[i][1:]] = arg_list[i + 1]\n skip = True\n else:\n raise exception.InvalidInput(\n reason=_('unrecognized argument %s') % arg_list[i])\n else:\n ret['obj'] = arg_list[i]\n return ret","target":" def _cmd_to_dict(self, arg_list):\n no_param_args = [\n 'autodelete',\n 'autoexpand',\n 'bytes',\n 'compressed',\n 'force',\n 'nohdr',\n ]\n one_param_args = [\n 'chapsecret',\n 'cleanrate',\n 'copyrate',\n 'delim',\n 'filtervalue',\n 'grainsize',\n 'hbawwpn',\n 'host',\n 'iogrp',\n 'iscsiname',\n 'mdiskgrp',\n 'name',\n 'rsize',\n 'scsi',\n 'size',\n 'source',\n 'target',\n 'unit',\n 'easytier',\n 'warning',\n 'wwpn',\n ]\n\n # Handle the special case of lsnode which is a two-word command\n # Use the one word version of the command internally\n if arg_list[0] in ('svcinfo', 'svctask'):\n if arg_list[1] == 'lsnode':\n if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! <node id>\n ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}\n else:\n ret = {'cmd': 'lsnodecanister'}\n else:\n ret = {'cmd': arg_list[1]}\n arg_list.pop(0)\n else:\n ret = {'cmd': arg_list[0]}\n\n skip = False\n for i in range(1, len(arg_list)):\n if skip:\n skip = False\n continue\n if arg_list[i][0] == '-':\n if arg_list[i][1:] in no_param_args:\n ret[arg_list[i][1:]] = True\n elif arg_list[i][1:] in one_param_args:\n ret[arg_list[i][1:]] = arg_list[i + 1]\n skip = True\n else:\n raise exception.InvalidInput(\n reason=_('unrecognized argument %s') % arg_list[i])\n else:\n ret['obj'] = arg_list[i]\n return ret","lang":"python","vul_type":"cwe-078","target_token_count":453,"sven_meta":{"func_name":"_cmd_to_dict","file_name":"cinder/tests/test_storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#80-1a5e15258113","input":" def _create_host(self, connector):\n \"\"\"Create a new host on the storage system.\n\n We create a host name and associate it with the given connection\n information.\n\n \"\"\"\n\n LOG.debug(_('enter: _create_host: host %s') % connector['host'])\n\n rand_id = str(random.randint(0, 99999999)).zfill(8)\n host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),\n rand_id)\n\n # Get all port information from the connector\n ports = []\n if 'initiator' in connector:\n ports.append('-iscsiname %s' % connector['initiator'])\n if 'wwpns' in connector:\n for wwpn in connector['wwpns']:\n ports.append('-hbawwpn %s' % wwpn)\n\n # When creating a host, we need one port\n self._driver_assert(len(ports), _('_create_host: No connector ports'))\n port1 = ports.pop(0)\n ssh_cmd = ('svctask mkhost -force %(port1)s -name \"%(host_name)s\"' %\n {'port1': port1, 'host_name': host_name})\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return('successfully created' in out,\n '_create_host', ssh_cmd, out, err)\n\n # Add any additional ports to the host\n for port in ports:\n ssh_cmd = ('svctask addhostport -force %s %s' % (port, host_name))\n out, err = self._run_ssh(ssh_cmd)\n\n LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %\n {'host': connector['host'], 'host_name': host_name})\n return host_name","target":" def _create_host(self, connector):\n \"\"\"Create a new host on the storage system.\n\n We create a host name and associate it with the given connection\n information.\n\n \"\"\"\n\n LOG.debug(_('enter: _create_host: host %s') % connector['host'])\n\n rand_id = str(random.randint(0, 99999999)).zfill(8)\n host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),\n rand_id)\n\n # Get all port information from the connector\n ports = []\n if 'initiator' in connector:\n ports.append('-iscsiname %s' % connector['initiator'])\n if 'wwpns' in connector:\n for wwpn in connector['wwpns']:\n ports.append('-hbawwpn %s' % wwpn)\n\n # When creating a host, we need one port\n self._driver_assert(len(ports), _('_create_host: No connector ports'))\n port1 = ports.pop(0)\n arg_name, arg_val = port1.split()\n ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name',\n '\"%s\"' % host_name]\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return('successfully created' in out,\n '_create_host', ssh_cmd, out, err)\n\n # Add any additional ports to the host\n for port in ports:\n arg_name, arg_val = port.split()\n ssh_cmd = ['svctask', 'addhostport', '-force', arg_name, arg_val,\n host_name]\n out, err = self._run_ssh(ssh_cmd)\n\n LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %\n {'host': connector['host'], 'host_name': host_name})\n return host_name","lang":"python","vul_type":"cwe-078","target_token_count":412,"sven_meta":{"func_name":"_create_host","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#92-813e30256cf6","input":" def poll(self, poll_input):\n username = poll_input.credentials.username\n password = poll_input.credentials.password\n domain = poll_input.credentials.domain\n \n if domain is None:\n opt_str = '--ignore-certificate --authonly -u {} -p {} {}:{}'\n options = opt_str.format(\n username, password,\n poll_input.server, poll_input.port)\n else:\n opt_str = '--ignore-certificate --authonly -d {} -u {} -p {} {}:{}'\n options = opt_str.format(\n domain.domain, username, password,\n poll_input.server, poll_input.port)\n\n try:\n output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)\n result = RdpPollResult(True)\n return result\n except Exception as e:\n if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):\n result = RdpPollResult(True)\n return result\n print(\"{{{{%s}}}}\" % e.output)\n result = RdpPollResult(False, e)\n return result","target":" def poll(self, poll_input):\n username = poll_input.credentials.username\n password = poll_input.credentials.password\n domain = poll_input.credentials.domain\n \n if domain is None:\n opt_str = '--ignore-certificate --authonly -u \\'{}\\' -p \\'{}\\' {}:{}'\n options = opt_str.format(\n username, password,\n poll_input.server, poll_input.port)\n else:\n opt_str = '--ignore-certificate --authonly -d {} -u \\'{}\\' -p \\'{}\\' {}:{}'\n options = opt_str.format(\n domain.domain, username, password,\n poll_input.server, poll_input.port)\n\n try:\n output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)\n result = RdpPollResult(True)\n return result\n except Exception as e:\n if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):\n result = RdpPollResult(True)\n return result\n print(\"{{{{%s}}}}\" % e.output)\n result = RdpPollResult(False, e)\n return result","lang":"python","vul_type":"cwe-078","target_token_count":273,"sven_meta":{"func_name":"poll","file_name":"polling/poll_rdp.py","commit_link":"github.com/DSU-DefSecClub/ScoringEngine/commit/010eefe1ad416c0bdaa16fd59eca0dc8e3086a13","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-078#93-79813f98fa39","input":" def terminate_connection(self, volume, connector, **kwargs):\n \"\"\"Cleanup after an iSCSI connection has been terminated.\n\n When we clean up a terminated connection between a given connector\n and volume, we:\n 1. Translate the given connector to a host name\n 2. Remove the volume-to-host mapping if it exists\n 3. Delete the host if it has no more mappings (hosts are created\n automatically by this driver when mappings are created)\n \"\"\"\n LOG.debug(_('enter: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})\n\n vol_name = volume['name']\n host_name = self._get_host_from_connector(connector)\n # Verify that _get_host_from_connector returned the host.\n # This should always succeed as we terminate an existing connection.\n self._driver_assert(\n host_name is not None,\n _('_get_host_from_connector failed to return the host name '\n 'for connector'))\n\n # Check if vdisk-host mapping exists, remove if it does\n mapping_data = self._get_hostvdisk_mappings(host_name)\n if vol_name in mapping_data:\n ssh_cmd = 'svctask rmvdiskhostmap -host %s %s' % \\\n (host_name, vol_name)\n out, err = self._run_ssh(ssh_cmd)\n # Verify CLI behaviour - no output is returned from\n # rmvdiskhostmap\n self._assert_ssh_return(len(out.strip()) == 0,\n 'terminate_connection', ssh_cmd, out, err)\n del mapping_data[vol_name]\n else:\n LOG.error(_('terminate_connection: No mapping of volume '\n '%(vol_name)s to host %(host_name)s found') %\n {'vol_name': vol_name, 'host_name': host_name})\n\n # If this host has no more mappings, delete it\n if not mapping_data:\n self._delete_host(host_name)\n\n LOG.debug(_('leave: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})","target":" def terminate_connection(self, volume, connector, **kwargs):\n \"\"\"Cleanup after an iSCSI connection has been terminated.\n\n When we clean up a terminated connection between a given connector\n and volume, we:\n 1. Translate the given connector to a host name\n 2. Remove the volume-to-host mapping if it exists\n 3. Delete the host if it has no more mappings (hosts are created\n automatically by this driver when mappings are created)\n \"\"\"\n LOG.debug(_('enter: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})\n\n vol_name = volume['name']\n host_name = self._get_host_from_connector(connector)\n # Verify that _get_host_from_connector returned the host.\n # This should always succeed as we terminate an existing connection.\n self._driver_assert(\n host_name is not None,\n _('_get_host_from_connector failed to return the host name '\n 'for connector'))\n\n # Check if vdisk-host mapping exists, remove if it does\n mapping_data = self._get_hostvdisk_mappings(host_name)\n if vol_name in mapping_data:\n ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name,\n vol_name]\n out, err = self._run_ssh(ssh_cmd)\n # Verify CLI behaviour - no output is returned from\n # rmvdiskhostmap\n self._assert_ssh_return(len(out.strip()) == 0,\n 'terminate_connection', ssh_cmd, out, err)\n del mapping_data[vol_name]\n else:\n LOG.error(_('terminate_connection: No mapping of volume '\n '%(vol_name)s to host %(host_name)s found') %\n {'vol_name': vol_name, 'host_name': host_name})\n\n # If this host has no more mappings, delete it\n if not mapping_data:\n self._delete_host(host_name)\n\n LOG.debug(_('leave: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})","lang":"python","vul_type":"cwe-078","target_token_count":458,"sven_meta":{"func_name":"terminate_connection","file_name":"cinder/volume/drivers/storwize_svc.py","commit_link":"github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4","source_cwe_file":"cwe-078.jsonl"}}
{"problem_id":"cwe-476#7-fdfc30cad0a1","input":"static ExprList *exprListAppendList(\n Parse *pParse, /* Parsing context */\n ExprList *pList, /* List to which to append. Might be NULL */\n ExprList *pAppend, /* List of values to append. Might be NULL */\n int bIntToNull\n){\n if( pAppend ){\n int i;\n int nInit = pList ? pList->nExpr : 0;\n for(i=0; i<pAppend->nExpr; i++){\n Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);\n if( bIntToNull && pDup && pDup->op==TK_INTEGER ){\n pDup->op = TK_NULL;\n pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);\n }\n pList = sqlite3ExprListAppend(pParse, pList, pDup);\n if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;\n }\n }\n return pList;\n}","target":"static ExprList *exprListAppendList(\n Parse *pParse, /* Parsing context */\n ExprList *pList, /* List to which to append. Might be NULL */\n ExprList *pAppend, /* List of values to append. Might be NULL */\n int bIntToNull\n){\n if( pAppend ){\n int i;\n int nInit = pList ? pList->nExpr : 0;\n for(i=0; i<pAppend->nExpr; i++){\n Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);\n assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );\n if( bIntToNull && pDup && pDup->op==TK_INTEGER ){\n pDup->op = TK_NULL;\n pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);\n pDup->u.zToken = 0;\n }\n pList = sqlite3ExprListAppend(pParse, pList, pDup);\n if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;\n }\n }\n return pList;\n}","lang":"c","vul_type":"cwe-476","target_token_count":270,"sven_meta":{"func_name":"exprListAppendList","file_name":"src/window.c","commit_link":"github.com/sqlite/sqlite/commit/75e95e1fcd52d3ec8282edb75ac8cd0814095d54","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#11-547124a10526","input":"static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)\n{\n\tstruct sockaddr_rc *sa = (struct sockaddr_rc *) addr;\n\tstruct sock *sk = sock->sk;\n\tint chan = sa->rc_channel;\n\tint err = 0;\n\n\tBT_DBG(\"sk %p %pMR\", sk, &sa->rc_bdaddr);\n\n\tif (!addr || addr->sa_family != AF_BLUETOOTH)\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != BT_OPEN) {\n\t\terr = -EBADFD;\n\t\tgoto done;\n\t}\n\n\tif (sk->sk_type != SOCK_STREAM) {\n\t\terr = -EINVAL;\n\t\tgoto done;\n\t}\n\n\twrite_lock(&rfcomm_sk_list.lock);\n\n\tif (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {\n\t\terr = -EADDRINUSE;\n\t} else {\n\t\t/* Save source address */\n\t\tbacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);\n\t\trfcomm_pi(sk)->channel = chan;\n\t\tsk->sk_state = BT_BOUND;\n\t}\n\n\twrite_unlock(&rfcomm_sk_list.lock);\n\ndone:\n\trelease_sock(sk);\n\treturn err;\n}","target":"static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)\n{\n\tstruct sockaddr_rc sa;\n\tstruct sock *sk = sock->sk;\n\tint len, err = 0;\n\n\tif (!addr || addr->sa_family != AF_BLUETOOTH)\n\t\treturn -EINVAL;\n\n\tmemset(&sa, 0, sizeof(sa));\n\tlen = min_t(unsigned int, sizeof(sa), addr_len);\n\tmemcpy(&sa, addr, len);\n\n\tBT_DBG(\"sk %p %pMR\", sk, &sa.rc_bdaddr);\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != BT_OPEN) {\n\t\terr = -EBADFD;\n\t\tgoto done;\n\t}\n\n\tif (sk->sk_type != SOCK_STREAM) {\n\t\terr = -EINVAL;\n\t\tgoto done;\n\t}\n\n\twrite_lock(&rfcomm_sk_list.lock);\n\n\tif (sa.rc_channel &&\n\t __rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {\n\t\terr = -EADDRINUSE;\n\t} else {\n\t\t/* Save source address */\n\t\tbacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);\n\t\trfcomm_pi(sk)->channel = sa.rc_channel;\n\t\tsk->sk_state = BT_BOUND;\n\t}\n\n\twrite_unlock(&rfcomm_sk_list.lock);\n\ndone:\n\trelease_sock(sk);\n\treturn err;\n}","lang":"c","vul_type":"cwe-476","target_token_count":283,"sven_meta":{"func_name":"rfcomm_sock_bind","file_name":"net/bluetooth/rfcomm/sock.c","commit_link":"github.com/torvalds/linux/commit/951b6a0717db97ce420547222647bcc40bf1eacd","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#12-61e61d4c1262","input":"AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, \n AP4_UI08 version,\n AP4_UI32 flags,\n AP4_ByteStream& stream) :\n AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)\n{\n AP4_UI32 predefined;\n stream.ReadUI32(predefined);\n stream.ReadUI32(m_HandlerType);\n stream.ReadUI32(m_Reserved[0]);\n stream.ReadUI32(m_Reserved[1]);\n stream.ReadUI32(m_Reserved[2]);\n \n // read the name unless it is empty\n int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n if (name_size == 0) return;\n char* name = new char[name_size+1];\n stream.Read(name, name_size);\n name[name_size] = '\\0'; // force a null termination\n // handle a special case: the Quicktime files have a pascal\n // string here, but ISO MP4 files have a C string.\n // we try to detect a pascal encoding and correct it.\n if (name[0] == name_size-1) {\n m_HandlerName = name+1;\n } else {\n m_HandlerName = name;\n }\n delete[] name;\n}","target":"AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, \n AP4_UI08 version,\n AP4_UI32 flags,\n AP4_ByteStream& stream) :\n AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)\n{\n AP4_UI32 predefined;\n stream.ReadUI32(predefined);\n stream.ReadUI32(m_HandlerType);\n stream.ReadUI32(m_Reserved[0]);\n stream.ReadUI32(m_Reserved[1]);\n stream.ReadUI32(m_Reserved[2]);\n \n // read the name unless it is empty\n if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;\n AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n char* name = new char[name_size+1];\n if (name == NULL) return;\n stream.Read(name, name_size);\n name[name_size] = '\\0'; // force a null termination\n // handle a special case: the Quicktime files have a pascal\n // string here, but ISO MP4 files have a C string.\n // we try to detect a pascal encoding and correct it.\n if (name[0] == name_size-1) {\n m_HandlerName = name+1;\n } else {\n m_HandlerName = name;\n }\n delete[] name;\n}","lang":"cpp","vul_type":"cwe-476","target_token_count":313,"sven_meta":{"func_name":"AP4_HdlrAtom::AP4_HdlrAtom","file_name":"Source/C++/Core/Ap4HdlrAtom.cpp","commit_link":"github.com/axiomatic-systems/Bento4/commit/22192de5367fa0cee985917f092be4060b7c00b0","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#13-22d39ffa165c","input":"generatePreview (const char inFileName[],\n\t\t float exposure,\n\t\t int previewWidth,\n\t\t int &previewHeight,\n\t\t Array2D <PreviewRgba> &previewPixels)\n{\n //\n // Read the input file\n //\n\n RgbaInputFile in (inFileName);\n\n Box2i dw = in.dataWindow();\n float a = in.pixelAspectRatio();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n\n Array2D <Rgba> pixels (h, w);\n in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);\n in.readPixels (dw.min.y, dw.max.y);\n\n //\n // Make a preview image\n //\n\n previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);\n previewPixels.resizeErase (previewHeight, previewWidth);\n\n float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1;\n float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1;\n float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));\n\n for (int y = 0; y < previewHeight; ++y)\n {\n\tfor (int x = 0; x < previewWidth; ++x)\n\t{\n\t PreviewRgba &preview = previewPixels[y][x];\n\t const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];\n\n\t preview.r = gamma (pixel.r, m);\n\t preview.g = gamma (pixel.g, m);\n\t preview.b = gamma (pixel.b, m);\n\t preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);\n\t}\n }\n}","target":"generatePreview (const char inFileName[],\n\t\t float exposure,\n\t\t int previewWidth,\n\t\t int &previewHeight,\n\t\t Array2D <PreviewRgba> &previewPixels)\n{\n //\n // Read the input file\n //\n\n RgbaInputFile in (inFileName);\n\n Box2i dw = in.dataWindow();\n float a = in.pixelAspectRatio();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n\n Array2D <Rgba> pixels (h, w);\n in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);\n in.readPixels (dw.min.y, dw.max.y);\n\n //\n // Make a preview image\n //\n\n previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);\n previewPixels.resizeErase (previewHeight, previewWidth);\n\n float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;\n float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;\n float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));\n\n for (int y = 0; y < previewHeight; ++y)\n {\n\tfor (int x = 0; x < previewWidth; ++x)\n\t{\n\t PreviewRgba &preview = previewPixels[y][x];\n\t const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];\n\n\t preview.r = gamma (pixel.r, m);\n\t preview.g = gamma (pixel.g, m);\n\t preview.b = gamma (pixel.b, m);\n\t preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);\n\t}\n }\n}","lang":"cpp","vul_type":"cwe-476","target_token_count":462,"sven_meta":{"func_name":"generatePreview","file_name":"OpenEXR/exrmakepreview/makePreview.cpp","commit_link":"github.com/AcademySoftwareFoundation/openexr/commit/74504503cff86e986bac441213c403b0ba28d58f","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#21-acf22b5978a8","input":"static int unimac_mdio_probe(struct platform_device *pdev)\n{\n\tstruct unimac_mdio_pdata *pdata = pdev->dev.platform_data;\n\tstruct unimac_mdio_priv *priv;\n\tstruct device_node *np;\n\tstruct mii_bus *bus;\n\tstruct resource *r;\n\tint ret;\n\n\tnp = pdev->dev.of_node;\n\n\tpriv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);\n\tif (!priv)\n\t\treturn -ENOMEM;\n\n\tr = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\n\t/* Just ioremap, as this MDIO block is usually integrated into an\n\t * Ethernet MAC controller register range\n\t */\n\tpriv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));\n\tif (!priv->base) {\n\t\tdev_err(&pdev->dev, \"failed to remap register\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tpriv->mii_bus = mdiobus_alloc();\n\tif (!priv->mii_bus)\n\t\treturn -ENOMEM;\n\n\tbus = priv->mii_bus;\n\tbus->priv = priv;\n\tif (pdata) {\n\t\tbus->name = pdata->bus_name;\n\t\tpriv->wait_func = pdata->wait_func;\n\t\tpriv->wait_func_data = pdata->wait_func_data;\n\t\tbus->phy_mask = ~pdata->phy_mask;\n\t} else {\n\t\tbus->name = \"unimac MII bus\";\n\t\tpriv->wait_func_data = priv;\n\t\tpriv->wait_func = unimac_mdio_poll;\n\t}\n\tbus->parent = &pdev->dev;\n\tbus->read = unimac_mdio_read;\n\tbus->write = unimac_mdio_write;\n\tbus->reset = unimac_mdio_reset;\n\tsnprintf(bus->id, MII_BUS_ID_SIZE, \"%s-%d\", pdev->name, pdev->id);\n\n\tret = of_mdiobus_register(bus, np);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"MDIO bus registration failed\\n\");\n\t\tgoto out_mdio_free;\n\t}\n\n\tplatform_set_drvdata(pdev, priv);\n\n\tdev_info(&pdev->dev, \"Broadcom UniMAC MDIO bus at 0x%p\\n\", priv->base);\n\n\treturn 0;\n\nout_mdio_free:\n\tmdiobus_free(bus);\n\treturn ret;\n}","target":"static int unimac_mdio_probe(struct platform_device *pdev)\n{\n\tstruct unimac_mdio_pdata *pdata = pdev->dev.platform_data;\n\tstruct unimac_mdio_priv *priv;\n\tstruct device_node *np;\n\tstruct mii_bus *bus;\n\tstruct resource *r;\n\tint ret;\n\n\tnp = pdev->dev.of_node;\n\n\tpriv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);\n\tif (!priv)\n\t\treturn -ENOMEM;\n\n\tr = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tif (!r)\n\t\treturn -EINVAL;\n\n\t/* Just ioremap, as this MDIO block is usually integrated into an\n\t * Ethernet MAC controller register range\n\t */\n\tpriv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));\n\tif (!priv->base) {\n\t\tdev_err(&pdev->dev, \"failed to remap register\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tpriv->mii_bus = mdiobus_alloc();\n\tif (!priv->mii_bus)\n\t\treturn -ENOMEM;\n\n\tbus = priv->mii_bus;\n\tbus->priv = priv;\n\tif (pdata) {\n\t\tbus->name = pdata->bus_name;\n\t\tpriv->wait_func = pdata->wait_func;\n\t\tpriv->wait_func_data = pdata->wait_func_data;\n\t\tbus->phy_mask = ~pdata->phy_mask;\n\t} else {\n\t\tbus->name = \"unimac MII bus\";\n\t\tpriv->wait_func_data = priv;\n\t\tpriv->wait_func = unimac_mdio_poll;\n\t}\n\tbus->parent = &pdev->dev;\n\tbus->read = unimac_mdio_read;\n\tbus->write = unimac_mdio_write;\n\tbus->reset = unimac_mdio_reset;\n\tsnprintf(bus->id, MII_BUS_ID_SIZE, \"%s-%d\", pdev->name, pdev->id);\n\n\tret = of_mdiobus_register(bus, np);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"MDIO bus registration failed\\n\");\n\t\tgoto out_mdio_free;\n\t}\n\n\tplatform_set_drvdata(pdev, priv);\n\n\tdev_info(&pdev->dev, \"Broadcom UniMAC MDIO bus at 0x%p\\n\", priv->base);\n\n\treturn 0;\n\nout_mdio_free:\n\tmdiobus_free(bus);\n\treturn ret;\n}","lang":"c","vul_type":"cwe-476","target_token_count":499,"sven_meta":{"func_name":"unimac_mdio_probe","file_name":"drivers/net/phy/mdio-bcm-unimac.c","commit_link":"github.com/torvalds/linux/commit/297a6961ffb8ff4dc66c9fbf53b924bd1dda05d5","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#22-65f43e486823","input":"static int hi3660_stub_clk_probe(struct platform_device *pdev)\n{\n\tstruct device *dev = &pdev->dev;\n\tstruct resource *res;\n\tunsigned int i;\n\tint ret;\n\n\t/* Use mailbox client without blocking */\n\tstub_clk_chan.cl.dev = dev;\n\tstub_clk_chan.cl.tx_done = NULL;\n\tstub_clk_chan.cl.tx_block = false;\n\tstub_clk_chan.cl.knows_txdone = false;\n\n\t/* Allocate mailbox channel */\n\tstub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);\n\tif (IS_ERR(stub_clk_chan.mbox))\n\t\treturn PTR_ERR(stub_clk_chan.mbox);\n\n\tres = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tfreq_reg = devm_ioremap(dev, res->start, resource_size(res));\n\tif (!freq_reg)\n\t\treturn -ENOMEM;\n\n\tfreq_reg += HI3660_STUB_CLOCK_DATA;\n\n\tfor (i = 0; i < HI3660_CLK_STUB_NUM; i++) {\n\t\tret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,\n\t\t\t\t\t hi3660_stub_clks);\n}","target":"static int hi3660_stub_clk_probe(struct platform_device *pdev)\n{\n\tstruct device *dev = &pdev->dev;\n\tstruct resource *res;\n\tunsigned int i;\n\tint ret;\n\n\t/* Use mailbox client without blocking */\n\tstub_clk_chan.cl.dev = dev;\n\tstub_clk_chan.cl.tx_done = NULL;\n\tstub_clk_chan.cl.tx_block = false;\n\tstub_clk_chan.cl.knows_txdone = false;\n\n\t/* Allocate mailbox channel */\n\tstub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);\n\tif (IS_ERR(stub_clk_chan.mbox))\n\t\treturn PTR_ERR(stub_clk_chan.mbox);\n\n\tres = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tif (!res)\n\t\treturn -EINVAL;\n\tfreq_reg = devm_ioremap(dev, res->start, resource_size(res));\n\tif (!freq_reg)\n\t\treturn -ENOMEM;\n\n\tfreq_reg += HI3660_STUB_CLOCK_DATA;\n\n\tfor (i = 0; i < HI3660_CLK_STUB_NUM; i++) {\n\t\tret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,\n\t\t\t\t\t hi3660_stub_clks);\n}","lang":"c","vul_type":"cwe-476","target_token_count":297,"sven_meta":{"func_name":"hi3660_stub_clk_probe","file_name":"drivers/clk/hisilicon/clk-hi3660-stub.c","commit_link":"github.com/torvalds/linux/commit/9903e41ae1f5d50c93f268ca3304d4d7c64b9311","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#24-3089607ddcee","input":"void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)\n{\n\tstruct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);\n\tbool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||\n\t\t ipv6_sk_rxinfo(sk);\n\n\tif (prepare && skb_rtable(skb)) {\n\t\t/* skb->cb is overloaded: prior to this point it is IP{6}CB\n\t\t * which has interface index (iif) as the first member of the\n\t\t * underlying inet{6}_skb_parm struct. This code then overlays\n\t\t * PKTINFO_SKB_CB and in_pktinfo also has iif as the first\n\t\t * element so the iif is picked up from the prior IPCB. If iif\n\t\t * is the loopback interface, then return the sending interface\n\t\t * (e.g., process binds socket to eth0 for Tx which is\n\t\t * redirected to loopback in the rtable/dst).\n\t\t */\n\t\tif (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)\n\t\t\tpktinfo->ipi_ifindex = inet_iif(skb);\n\n\t\tpktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);\n\t} else {\n\t\tpktinfo->ipi_ifindex = 0;\n\t\tpktinfo->ipi_spec_dst.s_addr = 0;\n\t}\n\tskb_dst_drop(skb);\n}","target":"void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)\n{\n\tstruct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);\n\tbool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||\n\t\t ipv6_sk_rxinfo(sk);\n\n\tif (prepare && skb_rtable(skb)) {\n\t\t/* skb->cb is overloaded: prior to this point it is IP{6}CB\n\t\t * which has interface index (iif) as the first member of the\n\t\t * underlying inet{6}_skb_parm struct. This code then overlays\n\t\t * PKTINFO_SKB_CB and in_pktinfo also has iif as the first\n\t\t * element so the iif is picked up from the prior IPCB. If iif\n\t\t * is the loopback interface, then return the sending interface\n\t\t * (e.g., process binds socket to eth0 for Tx which is\n\t\t * redirected to loopback in the rtable/dst).\n\t\t */\n\t\tif (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)\n\t\t\tpktinfo->ipi_ifindex = inet_iif(skb);\n\n\t\tpktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);\n\t} else {\n\t\tpktinfo->ipi_ifindex = 0;\n\t\tpktinfo->ipi_spec_dst.s_addr = 0;\n\t}\n\t/* We need to keep the dst for __ip_options_echo()\n\t * We could restrict the test to opt.ts_needtime || opt.srr,\n\t * but the following is good enough as IP options are not often used.\n\t */\n\tif (unlikely(IPCB(skb)->opt.optlen))\n\t\tskb_dst_force(skb);\n\telse\n\t\tskb_dst_drop(skb);\n}","lang":"c","vul_type":"cwe-476","target_token_count":367,"sven_meta":{"func_name":"ipv4_pktinfo_prepare","file_name":"net/ipv4/ip_sockglue.c","commit_link":"github.com/torvalds/linux/commit/34b2cef20f19c87999fff3da4071e66937db9644","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#29-fdedee012c88","input":"static int mpeg4video_probe(AVProbeData *probe_packet)\n{\n uint32_t temp_buffer = -1;\n int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;\n int i;\n\n for (i = 0; i < probe_packet->buf_size; i++) {\n temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];\n if ((temp_buffer & 0xffffff00) != 0x100)\n continue;\n\n if (temp_buffer == VOP_START_CODE)\n VOP++;\n else if (temp_buffer == VISUAL_OBJECT_START_CODE)\n VISO++;\n else if (temp_buffer < 0x120)\n VO++;\n else if (temp_buffer < 0x130)\n VOL++;\n else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&\n !(0x1B9 < temp_buffer && temp_buffer < 0x1C4))\n res++;\n }\n\n if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)\n return AVPROBE_SCORE_EXTENSION;\n return 0;\n}","target":"static int mpeg4video_probe(AVProbeData *probe_packet)\n{\n uint32_t temp_buffer = -1;\n int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;\n int i;\n\n for (i = 0; i < probe_packet->buf_size; i++) {\n temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];\n if (temp_buffer & 0xfffffe00)\n continue;\n if (temp_buffer < 2)\n continue;\n\n if (temp_buffer == VOP_START_CODE)\n VOP++;\n else if (temp_buffer == VISUAL_OBJECT_START_CODE)\n VISO++;\n else if (temp_buffer >= 0x100 && temp_buffer < 0x120)\n VO++;\n else if (temp_buffer >= 0x120 && temp_buffer < 0x130)\n VOL++;\n else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&\n !(0x1B9 < temp_buffer && temp_buffer < 0x1C4))\n res++;\n }\n\n if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)\n return AVPROBE_SCORE_EXTENSION;\n return 0;\n}","lang":"c","vul_type":"cwe-476","target_token_count":302,"sven_meta":{"func_name":"mpeg4video_probe","file_name":"libavformat/m4vdec.c","commit_link":"github.com/libav/libav/commit/e5b019725f53b79159931d3a7317107cbbfd0860","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#30-0faa609ba58a","input":"int megasas_alloc_cmds(struct megasas_instance *instance)\n{\n\tint i;\n\tint j;\n\tu16 max_cmd;\n\tstruct megasas_cmd *cmd;\n\n\tmax_cmd = instance->max_mfi_cmds;\n\n\t/*\n\t * instance->cmd_list is an array of struct megasas_cmd pointers.\n\t * Allocate the dynamic array first and then allocate individual\n\t * commands.\n\t */\n\tinstance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);\n\n\tif (!instance->cmd_list) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"out of memory\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tmemset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tinstance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),\n\t\t\t\t\t\tGFP_KERNEL);\n\n\t\tif (!instance->cmd_list[i]) {\n\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tkfree(instance->cmd_list[j]);\n\n\t\t\tkfree(instance->cmd_list);\n\t\t\tinstance->cmd_list = NULL;\n\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tcmd = instance->cmd_list[i];\n\t\tmemset(cmd, 0, sizeof(struct megasas_cmd));\n\t\tcmd->index = i;\n\t\tcmd->scmd = NULL;\n\t\tcmd->instance = instance;\n\n\t\tlist_add_tail(&cmd->list, &instance->cmd_pool);\n\t}\n\n\t/*\n\t * Create a frame pool and assign one frame to each cmd\n\t */\n\tif (megasas_create_frame_pool(instance)) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"Error creating frame DMA pool\\n\");\n\t\tmegasas_free_cmds(instance);\n\t}\n\n\treturn 0;\n}","target":"int megasas_alloc_cmds(struct megasas_instance *instance)\n{\n\tint i;\n\tint j;\n\tu16 max_cmd;\n\tstruct megasas_cmd *cmd;\n\n\tmax_cmd = instance->max_mfi_cmds;\n\n\t/*\n\t * instance->cmd_list is an array of struct megasas_cmd pointers.\n\t * Allocate the dynamic array first and then allocate individual\n\t * commands.\n\t */\n\tinstance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);\n\n\tif (!instance->cmd_list) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"out of memory\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tmemset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tinstance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),\n\t\t\t\t\t\tGFP_KERNEL);\n\n\t\tif (!instance->cmd_list[i]) {\n\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tkfree(instance->cmd_list[j]);\n\n\t\t\tkfree(instance->cmd_list);\n\t\t\tinstance->cmd_list = NULL;\n\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tcmd = instance->cmd_list[i];\n\t\tmemset(cmd, 0, sizeof(struct megasas_cmd));\n\t\tcmd->index = i;\n\t\tcmd->scmd = NULL;\n\t\tcmd->instance = instance;\n\n\t\tlist_add_tail(&cmd->list, &instance->cmd_pool);\n\t}\n\n\t/*\n\t * Create a frame pool and assign one frame to each cmd\n\t */\n\tif (megasas_create_frame_pool(instance)) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"Error creating frame DMA pool\\n\");\n\t\tmegasas_free_cmds(instance);\n\t\treturn -ENOMEM;\n\t}\n\n\treturn 0;\n}","lang":"c","vul_type":"cwe-476","target_token_count":400,"sven_meta":{"func_name":"megasas_alloc_cmds","file_name":"drivers/scsi/megaraid/megaraid_sas_base.c","commit_link":"github.com/torvalds/linux/commit/bcf3b67d16a4c8ffae0aa79de5853435e683945c","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#33-ca73e800b7fb","input":"lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)\n{\n struct lys_restr *result;\n int i;\n\n if (!size) {\n return NULL;\n }\n\n result = calloc(size, sizeof *result);\n LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);\n\n for (i = 0; i < size; i++) {\n result[i].ext_size = old[i].ext_size;\n lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);\n result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);\n result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);\n result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);\n result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);\n }\n\n return result;\n}","target":"lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)\n{\n struct lys_restr *result;\n int i;\n\n if (!size) {\n return NULL;\n }\n\n result = calloc(size, sizeof *result);\n LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);\n\n for (i = 0; i < size; i++) {\n /* copying unresolved extensions is not supported */\n if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) {\n result[i].ext_size = old[i].ext_size;\n lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n }\n result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);\n result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);\n result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);\n result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);\n result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);\n }\n\n return result;\n}","lang":"c","vul_type":"cwe-476","target_token_count":315,"sven_meta":{"func_name":"lys_restr_dup","file_name":"src/tree_schema.c","commit_link":"github.com/CESNET/libyang/commit/7852b272ef77f8098c35deea6c6f09cb78176f08","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#48-61c457b51706","input":"long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n{\n\tstruct key *key;\n\tkey_ref_t key_ref;\n\tlong ret;\n\n\t/* find the key first */\n\tkey_ref = lookup_user_key(keyid, 0, 0);\n\tif (IS_ERR(key_ref)) {\n\t\tret = -ENOKEY;\n\t\tgoto error;\n\t}\n\n\tkey = key_ref_to_ptr(key_ref);\n\n\t/* see if we can read it directly */\n\tret = key_permission(key_ref, KEY_NEED_READ);\n\tif (ret == 0)\n\t\tgoto can_read_key;\n\tif (ret != -EACCES)\n\t\tgoto error2;\n\n\t/* we can't; see if it's searchable from this process's keyrings\n\t * - we automatically take account of the fact that it may be\n\t * dangling off an instantiation key\n\t */\n\tif (!is_key_possessed(key_ref)) {\n\t\tret = -EACCES;\n\t\tgoto error2;\n\t}\n\n\t/* the key is probably readable - now try to read it */\ncan_read_key:\n\tret = -EOPNOTSUPP;\n\tif (key->type->read) {\n\t\t/* Read the data with the semaphore held (since we might sleep)\n\t\t * to protect against the key being updated or revoked.\n\t\t */\n\t\tdown_read(&key->sem);\n\t\tret = key_validate(key);\n\t\tif (ret == 0)\n\t\t\tret = key->type->read(key, buffer, buflen);\n\t\tup_read(&key->sem);\n\t}\n\nerror2:\n\tkey_put(key);\nerror:\n\treturn ret;\n}","target":"long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n{\n\tstruct key *key;\n\tkey_ref_t key_ref;\n\tlong ret;\n\n\t/* find the key first */\n\tkey_ref = lookup_user_key(keyid, 0, 0);\n\tif (IS_ERR(key_ref)) {\n\t\tret = -ENOKEY;\n\t\tgoto error;\n\t}\n\n\tkey = key_ref_to_ptr(key_ref);\n\n\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n\t\tret = -ENOKEY;\n\t\tgoto error2;\n\t}\n\n\t/* see if we can read it directly */\n\tret = key_permission(key_ref, KEY_NEED_READ);\n\tif (ret == 0)\n\t\tgoto can_read_key;\n\tif (ret != -EACCES)\n\t\tgoto error2;\n\n\t/* we can't; see if it's searchable from this process's keyrings\n\t * - we automatically take account of the fact that it may be\n\t * dangling off an instantiation key\n\t */\n\tif (!is_key_possessed(key_ref)) {\n\t\tret = -EACCES;\n\t\tgoto error2;\n\t}\n\n\t/* the key is probably readable - now try to read it */\ncan_read_key:\n\tret = -EOPNOTSUPP;\n\tif (key->type->read) {\n\t\t/* Read the data with the semaphore held (since we might sleep)\n\t\t * to protect against the key being updated or revoked.\n\t\t */\n\t\tdown_read(&key->sem);\n\t\tret = key_validate(key);\n\t\tif (ret == 0)\n\t\t\tret = key->type->read(key, buffer, buflen);\n\t\tup_read(&key->sem);\n\t}\n\nerror2:\n\tkey_put(key);\nerror:\n\treturn ret;\n}","lang":"c","vul_type":"cwe-476","target_token_count":363,"sven_meta":{"func_name":"keyctl_read_key","file_name":"security/keys/keyctl.c","commit_link":"github.com/torvalds/linux/commit/37863c43b2c6464f252862bf2e9768264e961678","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#49-d65a5d8c68df","input":"ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n const char **elem_rtrn, const char **field_rtrn,\n ExprDef **index_rtrn)\n{\n switch (expr->expr.op) {\n case EXPR_IDENT:\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n return (*field_rtrn != NULL);\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);\n *index_rtrn = NULL;\n return true;\n case EXPR_ARRAY_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);\n *index_rtrn = expr->array_ref.entry;\n return true;\n default:\n break;\n }\n log_wsgo(ctx, \"Unexpected operator %d in ResolveLhs\\n\", expr->expr.op);\n return false;\n}","target":"ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n const char **elem_rtrn, const char **field_rtrn,\n ExprDef **index_rtrn)\n{\n switch (expr->expr.op) {\n case EXPR_IDENT:\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n return (*field_rtrn != NULL);\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);\n *index_rtrn = NULL;\n return (*elem_rtrn != NULL && *field_rtrn != NULL);\n case EXPR_ARRAY_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);\n *index_rtrn = expr->array_ref.entry;\n\tif (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)\n\t\treturn false;\n\tif (*field_rtrn == NULL)\n\t\treturn false;\n return true;\n default:\n break;\n }\n log_wsgo(ctx, \"Unexpected operator %d in ResolveLhs\\n\", expr->expr.op);\n return false;\n}","lang":"c","vul_type":"cwe-476","target_token_count":313,"sven_meta":{"func_name":"ExprResolveLhs","file_name":"src/xkbcomp/expr.c","commit_link":"github.com/xkbcommon/libxkbcommon/commit/bb4909d2d8fa6b08155e449986a478101e2b2634","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#50-ff4ae20c385d","input":"tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)\n{\n\tconst char *s = name;\n\n\twhile (1) {\n\t\tconst char *s0 = s;\n\t\tchar *dirname;\n\n\t\t/* Find a directory component, if any. */\n\t\twhile (1) {\n\t\t\tif (*s == 0) {\n\t\t\t\tif (last && s != s0)\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\treturn dir;\n\t\t\t}\n\t\t\t/* This is deliberately slash-only. */\n\t\t\tif (*s == '/')\n\t\t\t\tbreak;\n\t\t\ts++;\n\t\t}\n\n\t\tdirname = g_strndup (s0, s - s0);\n\t\twhile (*s == '/')\n\t\t\ts++;\n\n\t\tif (strcmp (dirname, \".\") != 0) {\n\t\t\tGsfInput *subdir =\n\t\t\t\tgsf_infile_child_by_name (GSF_INFILE (dir),\n\t\t\t\t\t\t\t dirname);\n\t\t\tif (subdir) {\n\t\t\t\t/* Undo the ref. */\n\t\t\t\tg_object_unref (subdir);\n\t\t\t\tdir = GSF_INFILE_TAR (subdir);\n\t\t\t} else\n\t\t\t\tdir = tar_create_dir (dir, dirname);\n\t\t}\n\n\t\tg_free (dirname);\n\t}\n}","target":"tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)\n{\n\tconst char *s = name;\n\n\twhile (1) {\n\t\tconst char *s0 = s;\n\t\tchar *dirname;\n\n\t\t/* Find a directory component, if any. */\n\t\twhile (1) {\n\t\t\tif (*s == 0) {\n\t\t\t\tif (last && s != s0)\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\treturn dir;\n\t\t\t}\n\t\t\t/* This is deliberately slash-only. */\n\t\t\tif (*s == '/')\n\t\t\t\tbreak;\n\t\t\ts++;\n\t\t}\n\n\t\tdirname = g_strndup (s0, s - s0);\n\t\twhile (*s == '/')\n\t\t\ts++;\n\n\t\tif (strcmp (dirname, \".\") != 0) {\n\t\t\tGsfInput *subdir =\n\t\t\t\tgsf_infile_child_by_name (GSF_INFILE (dir),\n\t\t\t\t\t\t\t dirname);\n\t\t\tif (subdir) {\n\t\t\t\tdir = GSF_IS_INFILE_TAR (subdir)\n\t\t\t\t\t? GSF_INFILE_TAR (subdir)\n\t\t\t\t\t: dir;\n\t\t\t\t/* Undo the ref. */\n\t\t\t\tg_object_unref (subdir);\n\t\t\t} else\n\t\t\t\tdir = tar_create_dir (dir, dirname);\n\t\t}\n\n\t\tg_free (dirname);\n\t}\n}","lang":"c","vul_type":"cwe-476","target_token_count":275,"sven_meta":{"func_name":"tar_directory_for_file","file_name":"gsf/gsf-infile-tar.c","commit_link":"github.com/GNOME/libgsf/commit/95a8351a75758cf10b3bf6abae0b6b461f90d9e5","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#56-0bd5324e7689","input":"static int __init big_key_init(void)\n{\n\treturn register_key_type(&key_type_big_key);\n}","target":"static int __init big_key_init(void)\n{\n\tstruct crypto_skcipher *cipher;\n\tstruct crypto_rng *rng;\n\tint ret;\n\n\trng = crypto_alloc_rng(big_key_rng_name, 0, 0);\n\tif (IS_ERR(rng)) {\n\t\tpr_err(\"Can't alloc rng: %ld\\n\", PTR_ERR(rng));\n\t\treturn PTR_ERR(rng);\n\t}\n\n\tbig_key_rng = rng;\n\n\t/* seed RNG */\n\tret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng));\n\tif (ret) {\n\t\tpr_err(\"Can't reset rng: %d\\n\", ret);\n\t\tgoto error_rng;\n\t}\n\n\t/* init block cipher */\n\tcipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC);\n\tif (IS_ERR(cipher)) {\n\t\tret = PTR_ERR(cipher);\n\t\tpr_err(\"Can't alloc crypto: %d\\n\", ret);\n\t\tgoto error_rng;\n\t}\n\n\tbig_key_skcipher = cipher;\n\n\tret = register_key_type(&key_type_big_key);\n\tif (ret < 0) {\n\t\tpr_err(\"Can't register type: %d\\n\", ret);\n\t\tgoto error_cipher;\n\t}\n\n\treturn 0;\n\nerror_cipher:\n\tcrypto_free_skcipher(big_key_skcipher);\nerror_rng:\n\tcrypto_free_rng(big_key_rng);\n\treturn ret;\n}","lang":"c","vul_type":"cwe-476","target_token_count":280,"sven_meta":{"func_name":"big_key_init","file_name":"security/keys/big_key.c","commit_link":"github.com/torvalds/linux/commit/7df3e59c3d1df4f87fe874c7956ef7a3d2f4d5fb","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#58-b51548a923e2","input":"CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)\n{\n bool ok;\n XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };\n enum xkb_file_type type;\n struct xkb_context *ctx = keymap->ctx;\n\n /* Collect section files and check for duplicates. */\n for (file = (XkbFile *) file->defs; file;\n file = (XkbFile *) file->common.next) {\n if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||\n file->file_type > LAST_KEYMAP_FILE_TYPE) {\n log_err(ctx, \"Cannot define %s in a keymap file\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n if (files[file->file_type]) {\n log_err(ctx,\n \"More than one %s section in keymap file; \"\n \"All sections after the first ignored\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n files[file->file_type] = file;\n }\n\n /*\n * Check that all required section were provided.\n * Report everything before failing.\n */\n ok = true;\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n if (files[type] == NULL) {\n log_err(ctx, \"Required section %s missing from keymap\\n\",\n xkb_file_type_to_string(type));\n ok = false;\n }\n }\n if (!ok)\n return false;\n\n /* Compile sections. */\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n log_dbg(ctx, \"Compiling %s \\\"%s\\\"\\n\",\n xkb_file_type_to_string(type), files[type]->name);\n\n ok = compile_file_fns[type](files[type], keymap, merge);\n if (!ok) {\n log_err(ctx, \"Failed to compile %s\\n\",\n xkb_file_type_to_string(type));\n return false;\n }\n }\n\n return UpdateDerivedKeymapFields(keymap);\n}","target":"CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)\n{\n bool ok;\n XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };\n enum xkb_file_type type;\n struct xkb_context *ctx = keymap->ctx;\n\n /* Collect section files and check for duplicates. */\n for (file = (XkbFile *) file->defs; file;\n file = (XkbFile *) file->common.next) {\n if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||\n file->file_type > LAST_KEYMAP_FILE_TYPE) {\n if (file->file_type == FILE_TYPE_GEOMETRY) {\n log_vrb(ctx, 1,\n \"Geometry sections are not supported; ignoring\\n\");\n } else {\n log_err(ctx, \"Cannot define %s in a keymap file\\n\",\n xkb_file_type_to_string(file->file_type));\n }\n continue;\n }\n\n if (files[file->file_type]) {\n log_err(ctx,\n \"More than one %s section in keymap file; \"\n \"All sections after the first ignored\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n files[file->file_type] = file;\n }\n\n /*\n * Check that all required section were provided.\n * Report everything before failing.\n */\n ok = true;\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n if (files[type] == NULL) {\n log_err(ctx, \"Required section %s missing from keymap\\n\",\n xkb_file_type_to_string(type));\n ok = false;\n }\n }\n if (!ok)\n return false;\n\n /* Compile sections. */\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n log_dbg(ctx, \"Compiling %s \\\"%s\\\"\\n\",\n xkb_file_type_to_string(type), files[type]->name);\n\n ok = compile_file_fns[type](files[type], keymap, merge);\n if (!ok) {\n log_err(ctx, \"Failed to compile %s\\n\",\n xkb_file_type_to_string(type));\n return false;\n }\n }\n\n return UpdateDerivedKeymapFields(keymap);\n}","lang":"c","vul_type":"cwe-476","target_token_count":505,"sven_meta":{"func_name":"CompileKeymap","file_name":"src/xkbcomp/keymap.c","commit_link":"github.com/xkbcommon/libxkbcommon/commit/917636b1d0d70205a13f89062b95e3a0fc31d4ff","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#61-1e3644f547d7","input":"static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,\n\t\t\t\t struct srpt_recv_ioctx *recv_ioctx,\n\t\t\t\t struct srpt_send_ioctx *send_ioctx)\n{\n\tstruct srp_tsk_mgmt *srp_tsk;\n\tstruct se_cmd *cmd;\n\tstruct se_session *sess = ch->sess;\n\tuint64_t unpacked_lun;\n\tuint32_t tag = 0;\n\tint tcm_tmr;\n\tint rc;\n\n\tBUG_ON(!send_ioctx);\n\n\tsrp_tsk = recv_ioctx->ioctx.buf;\n\tcmd = &send_ioctx->cmd;\n\n\tpr_debug(\"recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld\"\n\t\t \" cm_id %p sess %p\\n\", srp_tsk->tsk_mgmt_func,\n\t\t srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);\n\n\tsrpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);\n\tsend_ioctx->cmd.tag = srp_tsk->tag;\n\ttcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);\n\tif (tcm_tmr < 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\tTMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;\n\t\tgoto fail;\n\t}\n\tunpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,\n\t\t\t\t sizeof(srp_tsk->lun));\n\n\tif (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {\n\t\trc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);\n\t\tif (rc < 0) {\n\t\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\t\t\tTMR_TASK_DOES_NOT_EXIST;\n\t\t\tgoto fail;\n\t\t}\n\t\ttag = srp_tsk->task_tag;\n\t}\n\trc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,\n\t\t\t\tsrp_tsk, tcm_tmr, GFP_KERNEL, tag,\n\t\t\t\tTARGET_SCF_ACK_KREF);\n\tif (rc != 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;\n\t\tgoto fail;\n\t}\n\treturn;\nfail:\n\ttransport_send_check_condition_and_sense(cmd, 0, 0); // XXX:\n}","target":"static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,\n\t\t\t\t struct srpt_recv_ioctx *recv_ioctx,\n\t\t\t\t struct srpt_send_ioctx *send_ioctx)\n{\n\tstruct srp_tsk_mgmt *srp_tsk;\n\tstruct se_cmd *cmd;\n\tstruct se_session *sess = ch->sess;\n\tuint64_t unpacked_lun;\n\tint tcm_tmr;\n\tint rc;\n\n\tBUG_ON(!send_ioctx);\n\n\tsrp_tsk = recv_ioctx->ioctx.buf;\n\tcmd = &send_ioctx->cmd;\n\n\tpr_debug(\"recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld\"\n\t\t \" cm_id %p sess %p\\n\", srp_tsk->tsk_mgmt_func,\n\t\t srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);\n\n\tsrpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);\n\tsend_ioctx->cmd.tag = srp_tsk->tag;\n\ttcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);\n\tunpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,\n\t\t\t\t sizeof(srp_tsk->lun));\n\trc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,\n\t\t\t\tsrp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag,\n\t\t\t\tTARGET_SCF_ACK_KREF);\n\tif (rc != 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;\n\t\tgoto fail;\n\t}\n\treturn;\nfail:\n\ttransport_send_check_condition_and_sense(cmd, 0, 0); // XXX:\n}","lang":"c","vul_type":"cwe-476","target_token_count":380,"sven_meta":{"func_name":"srpt_handle_tsk_mgmt","file_name":"drivers/infiniband/ulp/srpt/ib_srpt.c","commit_link":"github.com/torvalds/linux/commit/51093254bf879bc9ce96590400a87897c7498463","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#62-b93674cb7ca0","input":"ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,\n xkb_mod_mask_t *mods_rtrn, CompatInfo *info)\n{\n if (expr == NULL) {\n *pred_rtrn = MATCH_ANY_OR_NONE;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n\n *pred_rtrn = MATCH_EXACTLY;\n if (expr->expr.op == EXPR_ACTION_DECL) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);\n if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {\n log_err(info->ctx,\n \"Illegal modifier predicate \\\"%s\\\"; Ignored\\n\", pred_txt);\n return false;\n }\n expr = expr->action.args;\n }\n else if (expr->expr.op == EXPR_IDENT) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);\n if (pred_txt && istreq(pred_txt, \"any\")) {\n *pred_rtrn = MATCH_ANY;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n }\n\n return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,\n mods_rtrn);\n}","target":"ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,\n xkb_mod_mask_t *mods_rtrn, CompatInfo *info)\n{\n if (expr == NULL) {\n *pred_rtrn = MATCH_ANY_OR_NONE;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n\n *pred_rtrn = MATCH_EXACTLY;\n if (expr->expr.op == EXPR_ACTION_DECL) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);\n if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) ||\n !expr->action.args) {\n log_err(info->ctx,\n \"Illegal modifier predicate \\\"%s\\\"; Ignored\\n\", pred_txt);\n return false;\n }\n expr = expr->action.args;\n }\n else if (expr->expr.op == EXPR_IDENT) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);\n if (pred_txt && istreq(pred_txt, \"any\")) {\n *pred_rtrn = MATCH_ANY;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n }\n\n return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,\n mods_rtrn);\n}","lang":"c","vul_type":"cwe-476","target_token_count":298,"sven_meta":{"func_name":"ResolveStateAndPredicate","file_name":"src/xkbcomp/compat.c","commit_link":"github.com/xkbcommon/libxkbcommon/commit/96df3106d49438e442510c59acad306e94f3db4d","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-476#65-f8ef24f24430","input":"acc_ctx_cont(OM_uint32 *minstat,\n\t gss_buffer_t buf,\n\t gss_ctx_id_t *ctx,\n\t gss_buffer_t *responseToken,\n\t gss_buffer_t *mechListMIC,\n\t OM_uint32 *negState,\n\t send_token_flag *return_token)\n{\n\tOM_uint32 ret, tmpmin;\n\tgss_OID supportedMech;\n\tspnego_gss_ctx_id_t sc;\n\tunsigned int len;\n\tunsigned char *ptr, *bufstart;\n\n\tsc = (spnego_gss_ctx_id_t)*ctx;\n\tret = GSS_S_DEFECTIVE_TOKEN;\n\t*negState = REJECT;\n\t*minstat = 0;\n\tsupportedMech = GSS_C_NO_OID;\n\t*return_token = ERROR_TOKEN_SEND;\n\t*responseToken = *mechListMIC = GSS_C_NO_BUFFER;\n\n\tptr = bufstart = buf->value;\n#define REMAIN (buf->length - (ptr - bufstart))\n\tif (REMAIN > INT_MAX)\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\n\t/*\n\t * Attempt to work with old Sun SPNEGO.\n\t */\n\tif (*ptr == HEADER_ID) {\n\t\tret = g_verify_token_header(gss_mech_spnego,\n\t\t\t\t\t &len, &ptr, 0, REMAIN);\n\t\tif (ret) {\n\t\t\t*minstat = ret;\n\t\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t\t}\n\t}\n\tif (*ptr != (CONTEXT | 0x01)) {\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t}\n\tret = get_negTokenResp(minstat, ptr, REMAIN,\n\t\t\t negState, &supportedMech,\n\t\t\t responseToken, mechListMIC);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\tif (*responseToken == GSS_C_NO_BUFFER &&\n\t *mechListMIC == GSS_C_NO_BUFFER) {\n\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tsc->firstpass = 0;\n\t*negState = ACCEPT_INCOMPLETE;\n\t*return_token = CONT_TOKEN_SEND;\ncleanup:\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tgeneric_gss_release_oid(&tmpmin, &supportedMech);\n\t}\n\treturn ret;\n#undef REMAIN\n}","target":"acc_ctx_cont(OM_uint32 *minstat,\n\t gss_buffer_t buf,\n\t gss_ctx_id_t *ctx,\n\t gss_buffer_t *responseToken,\n\t gss_buffer_t *mechListMIC,\n\t OM_uint32 *negState,\n\t send_token_flag *return_token)\n{\n\tOM_uint32 ret, tmpmin;\n\tgss_OID supportedMech;\n\tspnego_gss_ctx_id_t sc;\n\tunsigned int len;\n\tunsigned char *ptr, *bufstart;\n\n\tsc = (spnego_gss_ctx_id_t)*ctx;\n\tret = GSS_S_DEFECTIVE_TOKEN;\n\t*negState = REJECT;\n\t*minstat = 0;\n\tsupportedMech = GSS_C_NO_OID;\n\t*return_token = ERROR_TOKEN_SEND;\n\t*responseToken = *mechListMIC = GSS_C_NO_BUFFER;\n\n\tptr = bufstart = buf->value;\n#define REMAIN (buf->length - (ptr - bufstart))\n\tif (REMAIN == 0 || REMAIN > INT_MAX)\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\n\t/*\n\t * Attempt to work with old Sun SPNEGO.\n\t */\n\tif (*ptr == HEADER_ID) {\n\t\tret = g_verify_token_header(gss_mech_spnego,\n\t\t\t\t\t &len, &ptr, 0, REMAIN);\n\t\tif (ret) {\n\t\t\t*minstat = ret;\n\t\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t\t}\n\t}\n\tif (*ptr != (CONTEXT | 0x01)) {\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t}\n\tret = get_negTokenResp(minstat, ptr, REMAIN,\n\t\t\t negState, &supportedMech,\n\t\t\t responseToken, mechListMIC);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\tif (*responseToken == GSS_C_NO_BUFFER &&\n\t *mechListMIC == GSS_C_NO_BUFFER) {\n\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tsc->firstpass = 0;\n\t*negState = ACCEPT_INCOMPLETE;\n\t*return_token = CONT_TOKEN_SEND;\ncleanup:\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tgeneric_gss_release_oid(&tmpmin, &supportedMech);\n\t}\n\treturn ret;\n#undef REMAIN\n}","lang":"c","vul_type":"cwe-476","target_token_count":512,"sven_meta":{"func_name":"acc_ctx_cont","file_name":"src/lib/gssapi/spnego/spnego_mech.c","commit_link":"github.com/krb5/krb5/commit/524688ce87a15fc75f87efc8c039ba4c7d5c197b","source_cwe_file":"cwe-476.jsonl"}}
{"problem_id":"cwe-416#3-f862b96faa78","input":"int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)\n{\n\tstruct sctp_association *asoc = sctp_id2assoc(sk, id);\n\tstruct sctp_sock *sp = sctp_sk(sk);\n\tstruct socket *sock;\n\tint err = 0;\n\n\tif (!asoc)\n\t\treturn -EINVAL;\n\n\t/* If there is a thread waiting on more sndbuf space for\n\t * sending on this asoc, it cannot be peeled.\n\t */\n\tif (waitqueue_active(&asoc->wait))\n\t\treturn -EBUSY;\n\n\t/* An association cannot be branched off from an already peeled-off\n\t * socket, nor is this supported for tcp style sockets.\n\t */\n\tif (!sctp_style(sk, UDP))\n\t\treturn -EINVAL;\n\n\t/* Create a new socket. */\n\terr = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);\n\tif (err < 0)\n\t\treturn err;\n\n\tsctp_copy_sock(sock->sk, sk, asoc);\n\n\t/* Make peeled-off sockets more like 1-1 accepted sockets.\n\t * Set the daddr and initialize id to something more random\n\t */\n\tsp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);\n\n\t/* Populate the fields of the newsk from the oldsk and migrate the\n\t * asoc to the newsk.\n\t */\n\tsctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);\n\n\t*sockp = sock;\n\n\treturn err;\n}","target":"int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)\n{\n\tstruct sctp_association *asoc = sctp_id2assoc(sk, id);\n\tstruct sctp_sock *sp = sctp_sk(sk);\n\tstruct socket *sock;\n\tint err = 0;\n\n\t/* Do not peel off from one netns to another one. */\n\tif (!net_eq(current->nsproxy->net_ns, sock_net(sk)))\n\t\treturn -EINVAL;\n\n\tif (!asoc)\n\t\treturn -EINVAL;\n\n\t/* If there is a thread waiting on more sndbuf space for\n\t * sending on this asoc, it cannot be peeled.\n\t */\n\tif (waitqueue_active(&asoc->wait))\n\t\treturn -EBUSY;\n\n\t/* An association cannot be branched off from an already peeled-off\n\t * socket, nor is this supported for tcp style sockets.\n\t */\n\tif (!sctp_style(sk, UDP))\n\t\treturn -EINVAL;\n\n\t/* Create a new socket. */\n\terr = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);\n\tif (err < 0)\n\t\treturn err;\n\n\tsctp_copy_sock(sock->sk, sk, asoc);\n\n\t/* Make peeled-off sockets more like 1-1 accepted sockets.\n\t * Set the daddr and initialize id to something more random\n\t */\n\tsp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);\n\n\t/* Populate the fields of the newsk from the oldsk and migrate the\n\t * asoc to the newsk.\n\t */\n\tsctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);\n\n\t*sockp = sock;\n\n\treturn err;\n}","lang":"c","vul_type":"cwe-416","target_token_count":369,"sven_meta":{"func_name":"sctp_do_peeloff","file_name":"net/sctp/socket.c","commit_link":"github.com/torvalds/linux/commit/df80cd9b28b9ebaa284a41df611dbf3a2d05ca74","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#6-1ad71a59d50d","input":"static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg)\n{\n\tstruct xc2028_data *priv = fe->tuner_priv;\n\tstruct xc2028_ctrl *p = priv_cfg;\n\tint rc = 0;\n\n\ttuner_dbg(\"%s called\\n\", __func__);\n\n\tmutex_lock(&priv->lock);\n\n\t/*\n\t * Copy the config data.\n\t * For the firmware name, keep a local copy of the string,\n\t * in order to avoid troubles during device release.\n\t */\n\tkfree(priv->ctrl.fname);\n\tmemcpy(&priv->ctrl, p, sizeof(priv->ctrl));\n\tif (p->fname) {\n\t\tpriv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL);\n\t\tif (priv->ctrl.fname == NULL)\n\t\t\trc = -ENOMEM;\n\t}\n\n\t/*\n\t * If firmware name changed, frees firmware. As free_firmware will\n\t * reset the status to NO_FIRMWARE, this forces a new request_firmware\n\t */\n\tif (!firmware_name[0] && p->fname &&\n\t priv->fname && strcmp(p->fname, priv->fname))\n\t\tfree_firmware(priv);\n\n\tif (priv->ctrl.max_len < 9)\n\t\tpriv->ctrl.max_len = 13;\n\n\tif (priv->state == XC2028_NO_FIRMWARE) {\n\t\tif (!firmware_name[0])\n\t\t\tpriv->fname = priv->ctrl.fname;\n\t\telse\n\t\t\tpriv->fname = firmware_name;\n\n\t\trc = request_firmware_nowait(THIS_MODULE, 1,\n\t\t\t\t\t priv->fname,\n\t\t\t\t\t priv->i2c_props.adap->dev.parent,\n\t\t\t\t\t GFP_KERNEL,\n\t\t\t\t\t fe, load_firmware_cb);\n\t\tif (rc < 0) {\n\t\t\ttuner_err(\"Failed to request firmware %s\\n\",\n\t\t\t\t priv->fname);\n\t\t\tpriv->state = XC2028_NODEV;\n\t\t} else\n\t\t\tpriv->state = XC2028_WAITING_FIRMWARE;\n\t}\n\tmutex_unlock(&priv->lock);\n\n\treturn rc;\n}","target":"static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg)\n{\n\tstruct xc2028_data *priv = fe->tuner_priv;\n\tstruct xc2028_ctrl *p = priv_cfg;\n\tint rc = 0;\n\n\ttuner_dbg(\"%s called\\n\", __func__);\n\n\tmutex_lock(&priv->lock);\n\n\t/*\n\t * Copy the config data.\n\t * For the firmware name, keep a local copy of the string,\n\t * in order to avoid troubles during device release.\n\t */\n\tkfree(priv->ctrl.fname);\n\tpriv->ctrl.fname = NULL;\n\tmemcpy(&priv->ctrl, p, sizeof(priv->ctrl));\n\tif (p->fname) {\n\t\tpriv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL);\n\t\tif (priv->ctrl.fname == NULL)\n\t\t\treturn -ENOMEM;\n\t}\n\n\t/*\n\t * If firmware name changed, frees firmware. As free_firmware will\n\t * reset the status to NO_FIRMWARE, this forces a new request_firmware\n\t */\n\tif (!firmware_name[0] && p->fname &&\n\t priv->fname && strcmp(p->fname, priv->fname))\n\t\tfree_firmware(priv);\n\n\tif (priv->ctrl.max_len < 9)\n\t\tpriv->ctrl.max_len = 13;\n\n\tif (priv->state == XC2028_NO_FIRMWARE) {\n\t\tif (!firmware_name[0])\n\t\t\tpriv->fname = priv->ctrl.fname;\n\t\telse\n\t\t\tpriv->fname = firmware_name;\n\n\t\trc = request_firmware_nowait(THIS_MODULE, 1,\n\t\t\t\t\t priv->fname,\n\t\t\t\t\t priv->i2c_props.adap->dev.parent,\n\t\t\t\t\t GFP_KERNEL,\n\t\t\t\t\t fe, load_firmware_cb);\n\t\tif (rc < 0) {\n\t\t\ttuner_err(\"Failed to request firmware %s\\n\",\n\t\t\t\t priv->fname);\n\t\t\tpriv->state = XC2028_NODEV;\n\t\t} else\n\t\t\tpriv->state = XC2028_WAITING_FIRMWARE;\n\t}\n\tmutex_unlock(&priv->lock);\n\n\treturn rc;\n}","lang":"c","vul_type":"cwe-416","target_token_count":438,"sven_meta":{"func_name":"xc2028_set_config","file_name":"drivers/media/tuners/tuner-xc2028.c","commit_link":"github.com/torvalds/linux/commit/8dfbcc4351a0b6d2f2d77f367552f48ffefafe18","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#10-daef89c72ecd","input":"int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,\n\t\t\tstruct rq_map_data *map_data,\n\t\t\tconst struct iov_iter *iter, gfp_t gfp_mask)\n{\n\tbool copy = false;\n\tunsigned long align = q->dma_pad_mask | queue_dma_alignment(q);\n\tstruct bio *bio = NULL;\n\tstruct iov_iter i;\n\tint ret;\n\n\tif (map_data)\n\t\tcopy = true;\n\telse if (iov_iter_alignment(iter) & align)\n\t\tcopy = true;\n\telse if (queue_virt_boundary(q))\n\t\tcopy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);\n\n\ti = *iter;\n\tdo {\n\t\tret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);\n\t\tif (ret)\n\t\t\tgoto unmap_rq;\n\t\tif (!bio)\n\t\t\tbio = rq->bio;\n\t} while (iov_iter_count(&i));\n\n\tif (!bio_flagged(bio, BIO_USER_MAPPED))\n\t\trq->cmd_flags |= REQ_COPY_USER;\n\treturn 0;\n\nunmap_rq:\n\t__blk_rq_unmap_user(bio);\n\trq->bio = NULL;\n\treturn -EINVAL;\n}","target":"int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,\n\t\t\tstruct rq_map_data *map_data,\n\t\t\tconst struct iov_iter *iter, gfp_t gfp_mask)\n{\n\tbool copy = false;\n\tunsigned long align = q->dma_pad_mask | queue_dma_alignment(q);\n\tstruct bio *bio = NULL;\n\tstruct iov_iter i;\n\tint ret;\n\n\tif (!iter_is_iovec(iter))\n\t\tgoto fail;\n\n\tif (map_data)\n\t\tcopy = true;\n\telse if (iov_iter_alignment(iter) & align)\n\t\tcopy = true;\n\telse if (queue_virt_boundary(q))\n\t\tcopy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);\n\n\ti = *iter;\n\tdo {\n\t\tret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);\n\t\tif (ret)\n\t\t\tgoto unmap_rq;\n\t\tif (!bio)\n\t\t\tbio = rq->bio;\n\t} while (iov_iter_count(&i));\n\n\tif (!bio_flagged(bio, BIO_USER_MAPPED))\n\t\trq->cmd_flags |= REQ_COPY_USER;\n\treturn 0;\n\nunmap_rq:\n\t__blk_rq_unmap_user(bio);\nfail:\n\trq->bio = NULL;\n\treturn -EINVAL;\n}","lang":"c","vul_type":"cwe-416","target_token_count":263,"sven_meta":{"func_name":"blk_rq_map_user_iov","file_name":"block/blk-map.c","commit_link":"github.com/torvalds/linux/commit/a0ac402cfcdc904f9772e1762b3fda112dcc56a0","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#12-9291b4857ded","input":"onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,\n OnigCompileInfo* ci, OnigErrorInfo* einfo)\n{\n int r;\n UChar *cpat, *cpat_end;\n\n if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;\n\n if (ci->pattern_enc != ci->target_enc) {\n r = conv_encoding(ci->pattern_enc, ci->target_enc, pattern, pattern_end,\n &cpat, &cpat_end);\n if (r != 0) return r;\n }\n else {\n cpat = (UChar* )pattern;\n cpat_end = (UChar* )pattern_end;\n }\n\n *reg = (regex_t* )xmalloc(sizeof(regex_t));\n if (IS_NULL(*reg)) {\n r = ONIGERR_MEMORY;\n goto err2;\n }\n\n r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,\n ci->syntax);\n if (r != 0) goto err;\n\n r = onig_compile(*reg, cpat, cpat_end, einfo);\n if (r != 0) {\n err:\n onig_free(*reg);\n *reg = NULL;\n }\n\n err2:\n if (cpat != pattern) xfree(cpat);\n\n return r;\n}","target":"onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,\n OnigCompileInfo* ci, OnigErrorInfo* einfo)\n{\n int r;\n UChar *cpat, *cpat_end;\n\n if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;\n\n if (ci->pattern_enc != ci->target_enc) {\n return ONIGERR_NOT_SUPPORTED_ENCODING_COMBINATION;\n }\n else {\n cpat = (UChar* )pattern;\n cpat_end = (UChar* )pattern_end;\n }\n\n *reg = (regex_t* )xmalloc(sizeof(regex_t));\n if (IS_NULL(*reg)) {\n r = ONIGERR_MEMORY;\n goto err2;\n }\n\n r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,\n ci->syntax);\n if (r != 0) goto err;\n\n r = onig_compile(*reg, cpat, cpat_end, einfo);\n if (r != 0) {\n err:\n onig_free(*reg);\n *reg = NULL;\n }\n\n err2:\n if (cpat != pattern) xfree(cpat);\n\n return r;\n}","lang":"c","vul_type":"cwe-416","target_token_count":282,"sven_meta":{"func_name":"onig_new_deluxe","file_name":"src/regext.c","commit_link":"github.com/kkos/oniguruma/commit/0f7f61ed1b7b697e283e37bd2d731d0bd57adb55","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#16-a82a08b96d69","input":"int shadow_server_start(rdpShadowServer* server)\n{\n\tBOOL ipc;\n\tBOOL status;\n\tWSADATA wsaData;\n\n\tif (!server)\n\t\treturn -1;\n\n\tif (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)\n\t\treturn -1;\n\n#ifndef _WIN32\n\tsignal(SIGPIPE, SIG_IGN);\n#endif\n\tserver->screen = shadow_screen_new(server);\n\n\tif (!server->screen)\n\t{\n\t\tWLog_ERR(TAG, \"screen_new failed\");\n\t\treturn -1;\n\t}\n\n\tserver->capture = shadow_capture_new(server);\n\n\tif (!server->capture)\n\t{\n\t\tWLog_ERR(TAG, \"capture_new failed\");\n\t\treturn -1;\n\t}\n\n\t/* Bind magic:\n\t *\n\t * emtpy ... bind TCP all\n\t * <local path> ... bind local (IPC)\n\t * bind-socket,<address> ... bind TCP to specified interface\n\t */\n\tipc = server->ipcSocket && (strncmp(bind_address, server->ipcSocket,\n\t strnlen(bind_address, sizeof(bind_address))) != 0);\n\tif (!ipc)\n\t{\n\t\tsize_t x, count;\n\t\tchar** list = CommandLineParseCommaSeparatedValuesEx(NULL, server->ipcSocket, &count);\n\t\tif (!list || (count <= 1))\n\t\t{\n\t\t\tfree(list);\n\t\t\tif (server->ipcSocket == NULL)\n\t\t\t{\n\t\t\t\tif (!open_port(server, NULL))\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn -1;\n\t\t}\n\n\t\tfor (x = 1; x < count; x++)\n\t\t{\n\t\t\tBOOL success = open_port(server, list[x]);\n\t\t\tif (!success)\n\t\t\t{\n\t\t\t\tfree(list);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tfree(list);\n\t}\n\telse\n\t{\n\t\tstatus = server->listener->OpenLocal(server->listener, server->ipcSocket);\n\t\tif (!status)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Problem creating local socket listener. (Port already used or \"\n\t\t\t \"insufficient permissions?)\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (!(server->thread = CreateThread(NULL, 0, shadow_server_thread, (void*)server, 0, NULL)))\n\t{\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}","target":"int shadow_server_start(rdpShadowServer* server)\n{\n\tBOOL ipc;\n\tBOOL status;\n\tWSADATA wsaData;\n\n\tif (!server)\n\t\treturn -1;\n\n\tif (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)\n\t\treturn -1;\n\n#ifndef _WIN32\n\tsignal(SIGPIPE, SIG_IGN);\n#endif\n\tserver->screen = shadow_screen_new(server);\n\n\tif (!server->screen)\n\t{\n\t\tWLog_ERR(TAG, \"screen_new failed\");\n\t\treturn -1;\n\t}\n\n\tserver->capture = shadow_capture_new(server);\n\n\tif (!server->capture)\n\t{\n\t\tWLog_ERR(TAG, \"capture_new failed\");\n\t\treturn -1;\n\t}\n\n\t/* Bind magic:\n\t *\n\t * emtpy ... bind TCP all\n\t * <local path> ... bind local (IPC)\n\t * bind-socket,<address> ... bind TCP to specified interface\n\t */\n\tipc = server->ipcSocket && (strncmp(bind_address, server->ipcSocket,\n\t strnlen(bind_address, sizeof(bind_address))) != 0);\n\tif (!ipc)\n\t{\n\t\tsize_t x, count;\n\t\tchar** list = CommandLineParseCommaSeparatedValuesEx(NULL, server->ipcSocket, &count);\n\t\tif (!list || (count <= 1))\n\t\t{\n\t\t\tif (server->ipcSocket == NULL)\n\t\t\t{\n\t\t\t\tif (!open_port(server, NULL))\n\t\t\t\t{\n\t\t\t\t\tfree(list);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfree(list);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tfor (x = 1; x < count; x++)\n\t\t{\n\t\t\tBOOL success = open_port(server, list[x]);\n\t\t\tif (!success)\n\t\t\t{\n\t\t\t\tfree(list);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tfree(list);\n\t}\n\telse\n\t{\n\t\tstatus = server->listener->OpenLocal(server->listener, server->ipcSocket);\n\t\tif (!status)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Problem creating local socket listener. (Port already used or \"\n\t\t\t \"insufficient permissions?)\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (!(server->thread = CreateThread(NULL, 0, shadow_server_thread, (void*)server, 0, NULL)))\n\t{\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}","lang":"c","vul_type":"cwe-416","target_token_count":504,"sven_meta":{"func_name":"shadow_server_start","file_name":"server/shadow/shadow_server.c","commit_link":"github.com/FreeRDP/FreeRDP/commit/6d86e20e1e7caaab4f0c7f89e36d32914dbccc52","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#19-1f066d22ef08","input":"static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,\n\tstruct user_namespace *user_ns)\n{\n\tmm->mmap = NULL;\n\tmm->mm_rb = RB_ROOT;\n\tmm->vmacache_seqnum = 0;\n\tatomic_set(&mm->mm_users, 1);\n\tatomic_set(&mm->mm_count, 1);\n\tinit_rwsem(&mm->mmap_sem);\n\tINIT_LIST_HEAD(&mm->mmlist);\n\tmm->core_state = NULL;\n\tatomic_long_set(&mm->nr_ptes, 0);\n\tmm_nr_pmds_init(mm);\n\tmm->map_count = 0;\n\tmm->locked_vm = 0;\n\tmm->pinned_vm = 0;\n\tmemset(&mm->rss_stat, 0, sizeof(mm->rss_stat));\n\tspin_lock_init(&mm->page_table_lock);\n\tmm_init_cpumask(mm);\n\tmm_init_aio(mm);\n\tmm_init_owner(mm, p);\n\tmmu_notifier_mm_init(mm);\n\tinit_tlb_flush_pending(mm);\n#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS\n\tmm->pmd_huge_pte = NULL;\n#endif\n\n\tif (current->mm) {\n\t\tmm->flags = current->mm->flags & MMF_INIT_MASK;\n\t\tmm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;\n\t} else {\n\t\tmm->flags = default_dump_filter;\n\t\tmm->def_flags = 0;\n\t}\n\n\tif (mm_alloc_pgd(mm))\n\t\tgoto fail_nopgd;\n\n\tif (init_new_context(p, mm))\n\t\tgoto fail_nocontext;\n\n\tmm->user_ns = get_user_ns(user_ns);\n\treturn mm;\n\nfail_nocontext:\n\tmm_free_pgd(mm);\nfail_nopgd:\n\tfree_mm(mm);\n\treturn NULL;\n}","target":"static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,\n\tstruct user_namespace *user_ns)\n{\n\tmm->mmap = NULL;\n\tmm->mm_rb = RB_ROOT;\n\tmm->vmacache_seqnum = 0;\n\tatomic_set(&mm->mm_users, 1);\n\tatomic_set(&mm->mm_count, 1);\n\tinit_rwsem(&mm->mmap_sem);\n\tINIT_LIST_HEAD(&mm->mmlist);\n\tmm->core_state = NULL;\n\tatomic_long_set(&mm->nr_ptes, 0);\n\tmm_nr_pmds_init(mm);\n\tmm->map_count = 0;\n\tmm->locked_vm = 0;\n\tmm->pinned_vm = 0;\n\tmemset(&mm->rss_stat, 0, sizeof(mm->rss_stat));\n\tspin_lock_init(&mm->page_table_lock);\n\tmm_init_cpumask(mm);\n\tmm_init_aio(mm);\n\tmm_init_owner(mm, p);\n\tRCU_INIT_POINTER(mm->exe_file, NULL);\n\tmmu_notifier_mm_init(mm);\n\tinit_tlb_flush_pending(mm);\n#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS\n\tmm->pmd_huge_pte = NULL;\n#endif\n\n\tif (current->mm) {\n\t\tmm->flags = current->mm->flags & MMF_INIT_MASK;\n\t\tmm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;\n\t} else {\n\t\tmm->flags = default_dump_filter;\n\t\tmm->def_flags = 0;\n\t}\n\n\tif (mm_alloc_pgd(mm))\n\t\tgoto fail_nopgd;\n\n\tif (init_new_context(p, mm))\n\t\tgoto fail_nocontext;\n\n\tmm->user_ns = get_user_ns(user_ns);\n\treturn mm;\n\nfail_nocontext:\n\tmm_free_pgd(mm);\nfail_nopgd:\n\tfree_mm(mm);\n\treturn NULL;\n}","lang":"c","vul_type":"cwe-416","target_token_count":403,"sven_meta":{"func_name":"mm_init","file_name":"kernel/fork.c","commit_link":"github.com/torvalds/linux/commit/2b7e8665b4ff51c034c55df3cff76518d1a9ee3a","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#30-1190aec5743f","input":"static int kvm_ioctl_create_device(struct kvm *kvm,\n\t\t\t\t struct kvm_create_device *cd)\n{\n\tstruct kvm_device_ops *ops = NULL;\n\tstruct kvm_device *dev;\n\tbool test = cd->flags & KVM_CREATE_DEVICE_TEST;\n\tint ret;\n\n\tif (cd->type >= ARRAY_SIZE(kvm_device_ops_table))\n\t\treturn -ENODEV;\n\n\tops = kvm_device_ops_table[cd->type];\n\tif (ops == NULL)\n\t\treturn -ENODEV;\n\n\tif (test)\n\t\treturn 0;\n\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tdev->ops = ops;\n\tdev->kvm = kvm;\n\n\tmutex_lock(&kvm->lock);\n\tret = ops->create(dev, cd->type);\n\tif (ret < 0) {\n\t\tmutex_unlock(&kvm->lock);\n\t\tkfree(dev);\n\t\treturn ret;\n\t}\n\tlist_add(&dev->vm_node, &kvm->devices);\n\tmutex_unlock(&kvm->lock);\n\n\tif (ops->init)\n\t\tops->init(dev);\n\n\tret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);\n\tif (ret < 0) {\n\t\tops->destroy(dev);\n\t\tmutex_lock(&kvm->lock);\n\t\tlist_del(&dev->vm_node);\n\t\tmutex_unlock(&kvm->lock);\n\t\treturn ret;\n\t}\n\n\tkvm_get_kvm(kvm);\n\tcd->fd = ret;\n\treturn 0;\n}","target":"static int kvm_ioctl_create_device(struct kvm *kvm,\n\t\t\t\t struct kvm_create_device *cd)\n{\n\tstruct kvm_device_ops *ops = NULL;\n\tstruct kvm_device *dev;\n\tbool test = cd->flags & KVM_CREATE_DEVICE_TEST;\n\tint ret;\n\n\tif (cd->type >= ARRAY_SIZE(kvm_device_ops_table))\n\t\treturn -ENODEV;\n\n\tops = kvm_device_ops_table[cd->type];\n\tif (ops == NULL)\n\t\treturn -ENODEV;\n\n\tif (test)\n\t\treturn 0;\n\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tdev->ops = ops;\n\tdev->kvm = kvm;\n\n\tmutex_lock(&kvm->lock);\n\tret = ops->create(dev, cd->type);\n\tif (ret < 0) {\n\t\tmutex_unlock(&kvm->lock);\n\t\tkfree(dev);\n\t\treturn ret;\n\t}\n\tlist_add(&dev->vm_node, &kvm->devices);\n\tmutex_unlock(&kvm->lock);\n\n\tif (ops->init)\n\t\tops->init(dev);\n\n\tret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);\n\tif (ret < 0) {\n\t\tmutex_lock(&kvm->lock);\n\t\tlist_del(&dev->vm_node);\n\t\tmutex_unlock(&kvm->lock);\n\t\tops->destroy(dev);\n\t\treturn ret;\n\t}\n\n\tkvm_get_kvm(kvm);\n\tcd->fd = ret;\n\treturn 0;\n}","lang":"c","vul_type":"cwe-416","target_token_count":314,"sven_meta":{"func_name":"kvm_ioctl_create_device","file_name":"virt/kvm/kvm_main.c","commit_link":"github.com/torvalds/linux/commit/a0f1d21c1ccb1da66629627a74059dd7f5ac9c61","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#32-7944a99ad014","input":"archive_read_format_rar_read_data(struct archive_read *a, const void **buff,\n size_t *size, int64_t *offset)\n{\n struct rar *rar = (struct rar *)(a->format->data);\n int ret;\n\n if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {\n\t rar->has_encrypted_entries = 0;\n }\n\n if (rar->bytes_unconsumed > 0) {\n /* Consume as much as the decompressor actually used. */\n __archive_read_consume(a, rar->bytes_unconsumed);\n rar->bytes_unconsumed = 0;\n }\n\n *buff = NULL;\n if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {\n *size = 0;\n *offset = rar->offset;\n if (*offset < rar->unp_size)\n *offset = rar->unp_size;\n return (ARCHIVE_EOF);\n }\n\n switch (rar->compression_method)\n {\n case COMPRESS_METHOD_STORE:\n ret = read_data_stored(a, buff, size, offset);\n break;\n\n case COMPRESS_METHOD_FASTEST:\n case COMPRESS_METHOD_FAST:\n case COMPRESS_METHOD_NORMAL:\n case COMPRESS_METHOD_GOOD:\n case COMPRESS_METHOD_BEST:\n ret = read_data_compressed(a, buff, size, offset);\n if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN)\n __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);\n break;\n\n default:\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Unsupported compression method for RAR file.\");\n ret = ARCHIVE_FATAL;\n break;\n }\n return (ret);\n}","target":"archive_read_format_rar_read_data(struct archive_read *a, const void **buff,\n size_t *size, int64_t *offset)\n{\n struct rar *rar = (struct rar *)(a->format->data);\n int ret;\n\n if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {\n\t rar->has_encrypted_entries = 0;\n }\n\n if (rar->bytes_unconsumed > 0) {\n /* Consume as much as the decompressor actually used. */\n __archive_read_consume(a, rar->bytes_unconsumed);\n rar->bytes_unconsumed = 0;\n }\n\n *buff = NULL;\n if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {\n *size = 0;\n *offset = rar->offset;\n if (*offset < rar->unp_size)\n *offset = rar->unp_size;\n return (ARCHIVE_EOF);\n }\n\n switch (rar->compression_method)\n {\n case COMPRESS_METHOD_STORE:\n ret = read_data_stored(a, buff, size, offset);\n break;\n\n case COMPRESS_METHOD_FASTEST:\n case COMPRESS_METHOD_FAST:\n case COMPRESS_METHOD_NORMAL:\n case COMPRESS_METHOD_GOOD:\n case COMPRESS_METHOD_BEST:\n ret = read_data_compressed(a, buff, size, offset);\n if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) {\n __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);\n rar->start_new_table = 1;\n }\n break;\n\n default:\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Unsupported compression method for RAR file.\");\n ret = ARCHIVE_FATAL;\n break;\n }\n return (ret);\n}","lang":"c","vul_type":"cwe-416","target_token_count":400,"sven_meta":{"func_name":"archive_read_format_rar_read_data","file_name":"libarchive/archive_read_support_format_rar.c","commit_link":"github.com/libarchive/libarchive/commit/b8592ecba2f9e451e1f5cb7ab6dcee8b8e7b3f60","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#33-81e260d134cb","input":"R_API void r_anal_bb_free(RAnalBlock *bb) {\n\tif (!bb) {\n\t\treturn;\n\t}\n\tr_anal_cond_free (bb->cond);\n\tR_FREE (bb->fingerprint);\n\tr_anal_diff_free (bb->diff);\n\tbb->diff = NULL;\n\tR_FREE (bb->op_bytes);\n\tr_anal_switch_op_free (bb->switch_op);\n\tbb->switch_op = NULL;\n\tbb->fingerprint = NULL;\n\tbb->cond = NULL;\n\tR_FREE (bb->label);\n\tR_FREE (bb->op_pos);\n\tR_FREE (bb->parent_reg_arena);\n\tif (bb->prev) {\n\t\tif (bb->prev->jumpbb == bb) {\n\t\t\tbb->prev->jumpbb = NULL;\n\t\t}\n\t\tif (bb->prev->failbb == bb) {\n\t\t\tbb->prev->failbb = NULL;\n\t\t}\n\t\tbb->prev = NULL;\n\t}\n\tif (bb->jumpbb) {\n\t\tbb->jumpbb->prev = NULL;\n\t\tbb->jumpbb = NULL;\n\t}\n\tif (bb->failbb) {\n\t\tbb->failbb->prev = NULL;\n\t\tbb->failbb = NULL;\n\t}\n\tR_FREE (bb);\n}","target":"R_API void r_anal_bb_free(RAnalBlock *bb) {\n\tif (!bb) {\n\t\treturn;\n\t}\n\tr_anal_cond_free (bb->cond);\n\tR_FREE (bb->fingerprint);\n\tr_anal_diff_free (bb->diff);\n\tbb->diff = NULL;\n\tR_FREE (bb->op_bytes);\n\tr_anal_switch_op_free (bb->switch_op);\n\tbb->switch_op = NULL;\n\tbb->fingerprint = NULL;\n\tbb->cond = NULL;\n\tR_FREE (bb->label);\n\tR_FREE (bb->op_pos);\n\tR_FREE (bb->parent_reg_arena);\n\tif (bb->prev) {\n\t\tif (bb->prev->jumpbb == bb) {\n\t\t\tbb->prev->jumpbb = NULL;\n\t\t}\n\t\tif (bb->prev->failbb == bb) {\n\t\t\tbb->prev->failbb = NULL;\n\t\t}\n\t\tbb->prev = NULL;\n\t}\n\tif (bb->jumpbb) {\n\t\tbb->jumpbb->prev = NULL;\n\t\tbb->jumpbb = NULL;\n\t}\n\tif (bb->failbb) {\n\t\tbb->failbb->prev = NULL;\n\t\tbb->failbb = NULL;\n\t}\n\tif (bb->next) {\n\t\t// avoid double free\n\t\tbb->next->prev = NULL;\n\t}\n\tR_FREE (bb); // double free\n}","lang":"c","vul_type":"cwe-416","target_token_count":295,"sven_meta":{"func_name":"r_anal_bb_free","file_name":"libr/anal/bb.c","commit_link":"github.com/radare/radare2/commit/90b71c017a7fa9732fe45fd21b245ee051b1f548","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#35-e668b1c21939","input":"static int rm_read_multi(AVFormatContext *s, AVIOContext *pb,\n AVStream *st, char *mime)\n{\n int number_of_streams = avio_rb16(pb);\n int number_of_mdpr;\n int i, ret;\n unsigned size2;\n for (i = 0; i<number_of_streams; i++)\n avio_rb16(pb);\n number_of_mdpr = avio_rb16(pb);\n if (number_of_mdpr != 1) {\n avpriv_request_sample(s, \"MLTI with multiple (%d) MDPR\", number_of_mdpr);\n }\n for (i = 0; i < number_of_mdpr; i++) {\n AVStream *st2;\n if (i > 0) {\n st2 = avformat_new_stream(s, NULL);\n if (!st2) {\n ret = AVERROR(ENOMEM);\n return ret;\n }\n st2->id = st->id + (i<<16);\n st2->codecpar->bit_rate = st->codecpar->bit_rate;\n st2->start_time = st->start_time;\n st2->duration = st->duration;\n st2->codecpar->codec_type = AVMEDIA_TYPE_DATA;\n st2->priv_data = ff_rm_alloc_rmstream();\n if (!st2->priv_data)\n return AVERROR(ENOMEM);\n } else\n st2 = st;\n\n size2 = avio_rb32(pb);\n ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data,\n size2, mime);\n if (ret < 0)\n return ret;\n }\n return 0;\n}","target":"static int rm_read_multi(AVFormatContext *s, AVIOContext *pb,\n AVStream *st, char *mime)\n{\n int number_of_streams = avio_rb16(pb);\n int number_of_mdpr;\n int i, ret;\n unsigned size2;\n for (i = 0; i<number_of_streams; i++)\n avio_rb16(pb);\n number_of_mdpr = avio_rb16(pb);\n if (number_of_mdpr != 1) {\n avpriv_request_sample(s, \"MLTI with multiple (%d) MDPR\", number_of_mdpr);\n }\n for (i = 0; i < number_of_mdpr; i++) {\n AVStream *st2;\n if (i > 0) {\n st2 = avformat_new_stream(s, NULL);\n if (!st2) {\n ret = AVERROR(ENOMEM);\n return ret;\n }\n st2->id = st->id + (i<<16);\n st2->codecpar->bit_rate = st->codecpar->bit_rate;\n st2->start_time = st->start_time;\n st2->duration = st->duration;\n st2->codecpar->codec_type = AVMEDIA_TYPE_DATA;\n st2->priv_data = ff_rm_alloc_rmstream();\n if (!st2->priv_data)\n return AVERROR(ENOMEM);\n } else\n st2 = st;\n\n size2 = avio_rb32(pb);\n ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data,\n size2, NULL);\n if (ret < 0)\n return ret;\n }\n return 0;\n}","lang":"c","vul_type":"cwe-416","target_token_count":374,"sven_meta":{"func_name":"rm_read_multi","file_name":"libavformat/rmdec.c","commit_link":"github.com/FFmpeg/FFmpeg/commit/a7e032a277452366771951e29fd0bf2bd5c029f0","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#38-285a1a2f364b","input":"vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) \n{\n\tVipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );\n\tGifFileType *file = gif->file;\n\tColorMapObject *map = file->Image.ColorMap ?\n\t\tfile->Image.ColorMap : file->SColorMap;\n\n\tGifByteType *extension;\n\n\tif( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {\n\t\tvips_foreign_load_gif_error( gif ); \n\t\treturn( -1 );\n\t}\n\n\t/* Check that the frame looks sane. Perhaps giflib checks\n\t * this for us.\n\t */\n\tif( file->Image.Left < 0 ||\n\t\tfile->Image.Width < 1 ||\n\t\tfile->Image.Width > 10000 ||\n\t\tfile->Image.Left + file->Image.Width > file->SWidth ||\n\t\tfile->Image.Top < 0 ||\n\t\tfile->Image.Height < 1 ||\n\t\tfile->Image.Height > 10000 ||\n\t\tfile->Image.Top + file->Image.Height > file->SHeight ) {\n\t\tvips_error( class->nickname, \"%s\", _( \"bad frame size\" ) ); \n\t\treturn( -1 ); \n\t}\n\n\t/* Test for a non-greyscale colourmap for this frame.\n\t */\n\tif( !gif->has_colour &&\n\t\tmap ) {\n\t\tint i;\n\n\t\tfor( i = 0; i < map->ColorCount; i++ ) \n\t\t\tif( map->Colors[i].Red != map->Colors[i].Green ||\n\t\t\t\tmap->Colors[i].Green != map->Colors[i].Blue ) {\n\t\t\t\tgif->has_colour = TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\t/* Step over compressed image data.\n\t */\n\tdo {\n\t\tif( vips_foreign_load_gif_code_next( gif, &extension ) ) \n\t\t\treturn( -1 );\n\t} while( extension != NULL );\n\n\treturn( 0 );\n}","target":"vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) \n{\n\tVipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );\n\tGifFileType *file = gif->file;\n\n\tColorMapObject *map;\n\tGifByteType *extension;\n\n\tif( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {\n\t\tvips_foreign_load_gif_error( gif ); \n\t\treturn( -1 );\n\t}\n\n\t/* Check that the frame looks sane. Perhaps giflib checks\n\t * this for us.\n\t */\n\tif( file->Image.Left < 0 ||\n\t\tfile->Image.Width < 1 ||\n\t\tfile->Image.Width > 10000 ||\n\t\tfile->Image.Left + file->Image.Width > file->SWidth ||\n\t\tfile->Image.Top < 0 ||\n\t\tfile->Image.Height < 1 ||\n\t\tfile->Image.Height > 10000 ||\n\t\tfile->Image.Top + file->Image.Height > file->SHeight ) {\n\t\tvips_error( class->nickname, \"%s\", _( \"bad frame size\" ) ); \n\t\treturn( -1 ); \n\t}\n\n\t/* Test for a non-greyscale colourmap for this frame.\n\t */\n\tmap = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap;\n\tif( !gif->has_colour &&\n\t\tmap ) {\n\t\tint i;\n\n\t\tfor( i = 0; i < map->ColorCount; i++ ) \n\t\t\tif( map->Colors[i].Red != map->Colors[i].Green ||\n\t\t\t\tmap->Colors[i].Green != map->Colors[i].Blue ) {\n\t\t\t\tgif->has_colour = TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\t/* Step over compressed image data.\n\t */\n\tdo {\n\t\tif( vips_foreign_load_gif_code_next( gif, &extension ) ) \n\t\t\treturn( -1 );\n\t} while( extension != NULL );\n\n\treturn( 0 );\n}","lang":"c","vul_type":"cwe-416","target_token_count":416,"sven_meta":{"func_name":"vips_foreign_load_gif_scan_image","file_name":"libvips/foreign/gifload.c","commit_link":"github.com/libvips/libvips/commit/ce684dd008532ea0bf9d4a1d89bacb35f4a83f4d","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#44-8d0abf8ced87","input":"static void *__ns_get_path(struct path *path, struct ns_common *ns)\n{\n\tstruct vfsmount *mnt = nsfs_mnt;\n\tstruct qstr qname = { .name = \"\", };\n\tstruct dentry *dentry;\n\tstruct inode *inode;\n\tunsigned long d;\n\n\trcu_read_lock();\n\td = atomic_long_read(&ns->stashed);\n\tif (!d)\n\t\tgoto slow;\n\tdentry = (struct dentry *)d;\n\tif (!lockref_get_not_dead(&dentry->d_lockref))\n\t\tgoto slow;\n\trcu_read_unlock();\n\tns->ops->put(ns);\ngot_it:\n\tpath->mnt = mntget(mnt);\n\tpath->dentry = dentry;\n\treturn NULL;\nslow:\n\trcu_read_unlock();\n\tinode = new_inode_pseudo(mnt->mnt_sb);\n\tif (!inode) {\n\t\tns->ops->put(ns);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\tinode->i_ino = ns->inum;\n\tinode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);\n\tinode->i_flags |= S_IMMUTABLE;\n\tinode->i_mode = S_IFREG | S_IRUGO;\n\tinode->i_fop = &ns_file_operations;\n\tinode->i_private = ns;\n\n\tdentry = d_alloc_pseudo(mnt->mnt_sb, &qname);\n\tif (!dentry) {\n\t\tiput(inode);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\td_instantiate(dentry, inode);\n\tdentry->d_fsdata = (void *)ns->ops;\n\td = atomic_long_cmpxchg(&ns->stashed, 0, (unsigned long)dentry);\n\tif (d) {\n\t\td_delete(dentry);\t/* make sure ->d_prune() does nothing */\n\t\tdput(dentry);\n\t\tcpu_relax();\n\t\treturn ERR_PTR(-EAGAIN);\n\t}\n\tgoto got_it;\n}","target":"static void *__ns_get_path(struct path *path, struct ns_common *ns)\n{\n\tstruct vfsmount *mnt = nsfs_mnt;\n\tstruct qstr qname = { .name = \"\", };\n\tstruct dentry *dentry;\n\tstruct inode *inode;\n\tunsigned long d;\n\n\trcu_read_lock();\n\td = atomic_long_read(&ns->stashed);\n\tif (!d)\n\t\tgoto slow;\n\tdentry = (struct dentry *)d;\n\tif (!lockref_get_not_dead(&dentry->d_lockref))\n\t\tgoto slow;\n\trcu_read_unlock();\n\tns->ops->put(ns);\ngot_it:\n\tpath->mnt = mntget(mnt);\n\tpath->dentry = dentry;\n\treturn NULL;\nslow:\n\trcu_read_unlock();\n\tinode = new_inode_pseudo(mnt->mnt_sb);\n\tif (!inode) {\n\t\tns->ops->put(ns);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\tinode->i_ino = ns->inum;\n\tinode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);\n\tinode->i_flags |= S_IMMUTABLE;\n\tinode->i_mode = S_IFREG | S_IRUGO;\n\tinode->i_fop = &ns_file_operations;\n\tinode->i_private = ns;\n\n\tdentry = d_alloc_pseudo(mnt->mnt_sb, &qname);\n\tif (!dentry) {\n\t\tiput(inode);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\td_instantiate(dentry, inode);\n\tdentry->d_flags |= DCACHE_RCUACCESS;\n\tdentry->d_fsdata = (void *)ns->ops;\n\td = atomic_long_cmpxchg(&ns->stashed, 0, (unsigned long)dentry);\n\tif (d) {\n\t\td_delete(dentry);\t/* make sure ->d_prune() does nothing */\n\t\tdput(dentry);\n\t\tcpu_relax();\n\t\treturn ERR_PTR(-EAGAIN);\n\t}\n\tgoto got_it;\n}","lang":"c","vul_type":"cwe-416","target_token_count":411,"sven_meta":{"func_name":"__ns_get_path","file_name":"fs/nsfs.c","commit_link":"github.com/torvalds/linux/commit/073c516ff73557a8f7315066856c04b50383ac34","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#45-e7f448494cd5","input":"PHP_FUNCTION(unserialize)\n{\n\tchar *buf = NULL;\n\tsize_t buf_len;\n\tconst unsigned char *p;\n\tphp_unserialize_data_t var_hash;\n\tzval *options = NULL, *classes = NULL;\n\tHashTable *class_hash = NULL;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|a\", &buf, &buf_len, &options) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (buf_len == 0) {\n\t\tRETURN_FALSE;\n\t}\n\n\tp = (const unsigned char*) buf;\n\tPHP_VAR_UNSERIALIZE_INIT(var_hash);\n\tif(options != NULL) {\n\t\tclasses = zend_hash_str_find(Z_ARRVAL_P(options), \"allowed_classes\", sizeof(\"allowed_classes\")-1);\n\t\tif(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {\n\t\t\tALLOC_HASHTABLE(class_hash);\n\t\t\tzend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);\n\t\t}\n\t\tif(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {\n\t\t\tzval *entry;\n\t\t\tzend_string *lcname;\n\n\t\t\tZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {\n\t\t\t\tconvert_to_string_ex(entry);\n\t\t\t\tlcname = zend_string_tolower(Z_STR_P(entry));\n\t\t\t\tzend_hash_add_empty_element(class_hash, lcname);\n\t\t zend_string_release(lcname);\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t}\n\t}\n\n\tif (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) {\n\t\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\t\tif (class_hash) {\n\t\t\tzend_hash_destroy(class_hash);\n\t\t\tFREE_HASHTABLE(class_hash);\n\t\t}\n\t\tzval_ptr_dtor(return_value);\n\t\tif (!EG(exception)) {\n\t\t\tphp_error_docref(NULL, E_NOTICE, \"Error at offset \" ZEND_LONG_FMT \" of %zd bytes\",\n\t\t\t\t(zend_long)((char*)p - buf), buf_len);\n\t\t}\n\t\tRETURN_FALSE;\n\t}\n\t/* We should keep an reference to return_value to prevent it from being dtor\n\t in case nesting calls to unserialize */\n\tvar_push_dtor(&var_hash, return_value);\n\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\tif (class_hash) {\n\t\tzend_hash_destroy(class_hash);\n\t\tFREE_HASHTABLE(class_hash);\n\t}\n}","target":"PHP_FUNCTION(unserialize)\n{\n\tchar *buf = NULL;\n\tsize_t buf_len;\n\tconst unsigned char *p;\n\tphp_unserialize_data_t var_hash;\n\tzval *options = NULL, *classes = NULL;\n\tzval *retval;\n\tHashTable *class_hash = NULL;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|a\", &buf, &buf_len, &options) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (buf_len == 0) {\n\t\tRETURN_FALSE;\n\t}\n\n\tp = (const unsigned char*) buf;\n\tPHP_VAR_UNSERIALIZE_INIT(var_hash);\n\tif(options != NULL) {\n\t\tclasses = zend_hash_str_find(Z_ARRVAL_P(options), \"allowed_classes\", sizeof(\"allowed_classes\")-1);\n\t\tif(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {\n\t\t\tALLOC_HASHTABLE(class_hash);\n\t\t\tzend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);\n\t\t}\n\t\tif(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {\n\t\t\tzval *entry;\n\t\t\tzend_string *lcname;\n\n\t\t\tZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {\n\t\t\t\tconvert_to_string_ex(entry);\n\t\t\t\tlcname = zend_string_tolower(Z_STR_P(entry));\n\t\t\t\tzend_hash_add_empty_element(class_hash, lcname);\n\t\t zend_string_release(lcname);\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t}\n\t}\n\n\tretval = var_tmp_var(&var_hash);\n\tif (!php_var_unserialize_ex(retval, &p, p + buf_len, &var_hash, class_hash)) {\n\t\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\t\tif (class_hash) {\n\t\t\tzend_hash_destroy(class_hash);\n\t\t\tFREE_HASHTABLE(class_hash);\n\t\t}\n\t\tif (!EG(exception)) {\n\t\t\tphp_error_docref(NULL, E_NOTICE, \"Error at offset \" ZEND_LONG_FMT \" of %zd bytes\",\n\t\t\t\t(zend_long)((char*)p - buf), buf_len);\n\t\t}\n\t\tRETURN_FALSE;\n\t}\n\n\tZVAL_COPY(return_value, retval);\n\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\tif (class_hash) {\n\t\tzend_hash_destroy(class_hash);\n\t\tFREE_HASHTABLE(class_hash);\n\t}\n}","lang":"c","vul_type":"cwe-416","target_token_count":501,"sven_meta":{"func_name":"PHP_FUNCTION","file_name":"ext/standard/var.c","commit_link":"github.com/php/php-src/commit/b2af4e8868726a040234de113436c6e4f6372d17","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#52-a4ddb36a5478","input":"static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}","target":"static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL,\n packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}","lang":"c","vul_type":"cwe-416","target_token_count":345,"sven_meta":{"func_name":"ndpi_reset_packet_line_info","file_name":"src/lib/ndpi_main.c","commit_link":"github.com/ntop/nDPI/commit/6a9f5e4f7c3fd5ddab3e6727b071904d76773952","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-416#55-c1d2c18f1f94","input":"mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy)\n{\n mrb_value orig;\n mrb_value buf;\n struct mrb_io *fptr_copy;\n struct mrb_io *fptr_orig;\n mrb_bool failed = TRUE;\n\n mrb_get_args(mrb, \"o\", &orig);\n fptr_copy = (struct mrb_io *)DATA_PTR(copy);\n if (fptr_copy != NULL) {\n fptr_finalize(mrb, fptr_copy, FALSE);\n mrb_free(mrb, fptr_copy);\n }\n fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb);\n fptr_orig = io_get_open_fptr(mrb, orig);\n\n DATA_TYPE(copy) = &mrb_io_type;\n DATA_PTR(copy) = fptr_copy;\n\n buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, \"@buf\"));\n mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, \"@buf\"), buf);\n\n fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed);\n if (failed) {\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd);\n\n if (fptr_orig->fd2 != -1) {\n fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed);\n if (failed) {\n close(fptr_copy->fd);\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd2);\n }\n\n fptr_copy->pid = fptr_orig->pid;\n fptr_copy->readable = fptr_orig->readable;\n fptr_copy->writable = fptr_orig->writable;\n fptr_copy->sync = fptr_orig->sync;\n fptr_copy->is_socket = fptr_orig->is_socket;\n\n return copy;\n}","target":"mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy)\n{\n mrb_value orig;\n mrb_value buf;\n struct mrb_io *fptr_copy;\n struct mrb_io *fptr_orig;\n mrb_bool failed = TRUE;\n\n mrb_get_args(mrb, \"o\", &orig);\n fptr_orig = io_get_open_fptr(mrb, orig);\n fptr_copy = (struct mrb_io *)DATA_PTR(copy);\n if (fptr_copy != NULL) {\n fptr_finalize(mrb, fptr_copy, FALSE);\n mrb_free(mrb, fptr_copy);\n }\n fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb);\n\n DATA_TYPE(copy) = &mrb_io_type;\n DATA_PTR(copy) = fptr_copy;\n\n buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, \"@buf\"));\n mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, \"@buf\"), buf);\n\n fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed);\n if (failed) {\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd);\n\n if (fptr_orig->fd2 != -1) {\n fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed);\n if (failed) {\n close(fptr_copy->fd);\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd2);\n }\n\n fptr_copy->pid = fptr_orig->pid;\n fptr_copy->readable = fptr_orig->readable;\n fptr_copy->writable = fptr_orig->writable;\n fptr_copy->sync = fptr_orig->sync;\n fptr_copy->is_socket = fptr_orig->is_socket;\n\n return copy;\n}","lang":"c","vul_type":"cwe-416","target_token_count":423,"sven_meta":{"func_name":"mrb_io_initialize_copy","file_name":"mrbgems/mruby-io/src/io.c","commit_link":"github.com/mruby/mruby/commit/b51b21fc63c9805862322551387d9036f2b63433","source_cwe_file":"cwe-416.jsonl"}}
{"problem_id":"cwe-022#1-a631ff381000","input":" def zmi_page_request(self, *args, **kwargs):\r\n request = self.REQUEST\r\n RESPONSE = request.RESPONSE\r\n SESSION = request.SESSION\r\n self._zmi_page_request()\r\n RESPONSE.setHeader('Expires',DateTime(request['ZMI_TIME']-10000).toZone('GMT+1').rfc822())\r\n RESPONSE.setHeader('Cache-Control', 'no-cache')\r\n RESPONSE.setHeader('Pragma', 'no-cache')\r\n RESPONSE.setHeader('Content-Type', 'text/html;charset=%s'%request['ZMS_CHARSET'])\r\n if not request.get( 'preview'):\r\n request.set( 'preview','preview')\r\n langs = self.getLanguages(request)\r\n if request.get('lang') not in langs:\r\n request.set('lang',langs[0])\r\n if request.get('manage_lang') not in self.getLocale().get_manage_langs():\r\n request.set('manage_lang',self.get_manage_lang())\r\n if not request.get('manage_tabs_message'):\r\n request.set( 'manage_tabs_message',self.getConfProperty('ZMS.manage_tabs_message',''))\r\n # manage_system\r\n if request.form.has_key('zmi-manage-system'):\r\n request.SESSION.set('zmi-manage-system',int(request.get('zmi-manage-system')))\r\n # avoid declarative urls\r\n physical_path = self.getPhysicalPath()\r\n path_to_handle = request['URL0'][len(request['BASE0']):].split('/')\r\n path = path_to_handle[:-1]\r\n if len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0:\r\n for i in range(len(path)):\r\n if path[:-(i+1)] != physical_path[:-(i+1)]:\r\n path[:-(i+1)] = physical_path[:-(i+1)]\r\n new_path = path+[path_to_handle[-1]]\r\n if path_to_handle != new_path:\r\n request.RESPONSE.redirect('/'.join(new_path))","target":" def zmi_page_request(self, *args, **kwargs):\r\n request = self.REQUEST\r\n RESPONSE = request.RESPONSE\r\n SESSION = request.SESSION\r\n self._zmi_page_request()\r\n RESPONSE.setHeader('Expires',DateTime(request['ZMI_TIME']-10000).toZone('GMT+1').rfc822())\r\n RESPONSE.setHeader('Cache-Control', 'no-cache')\r\n RESPONSE.setHeader('Pragma', 'no-cache')\r\n RESPONSE.setHeader('Content-Type', 'text/html;charset=%s'%request['ZMS_CHARSET'])\r\n if not request.get( 'preview'):\r\n request.set( 'preview','preview')\r\n langs = self.getLanguages(request)\r\n if request.get('lang') not in langs:\r\n request.set('lang',langs[0])\r\n if request.get('manage_lang') not in self.getLocale().get_manage_langs():\r\n request.set('manage_lang',self.get_manage_lang())\r\n if not request.get('manage_tabs_message'):\r\n request.set( 'manage_tabs_message',self.getConfProperty('ZMS.manage_tabs_message',''))\r\n # manage_system\r\n if request.form.has_key('zmi-manage-system'):\r\n request.SESSION.set('zmi-manage-system',int(request.get('zmi-manage-system')))\r\n # avoid declarative urls\r\n physical_path = self.getPhysicalPath()\r\n path_to_handle = request['URL0'][len(request['BASE0']):].split('/')\r\n path = path_to_handle[:-1]\r\n if self.getDocumentElement().id in path and len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0:\r\n for i in range(len(path)):\r\n if path[:-(i+1)] != physical_path[:-(i+1)]:\r\n path[:-(i+1)] = physical_path[:-(i+1)]\r\n new_path = path+[path_to_handle[-1]]\r\n if path_to_handle != new_path:\r\n request.RESPONSE.redirect('/'.join(new_path))","lang":"python","vul_type":"cwe-022","target_token_count":419,"sven_meta":{"func_name":"zmi_page_request","file_name":"ZMSItem.py","commit_link":"github.com/zms-publishing/zms4/commit/3f28620d475220dfdb06f79787158ac50727c61a","source_cwe_file":"cwe-022.jsonl"}}
{"problem_id":"cwe-022#15-76bee86ce6de","input":" def get_files(self, submit_id, password=None, astree=False):\n \"\"\"\n Returns files from a submitted analysis.\n @param password: The password to unlock container archives with\n @param astree: sflock option; determines the format in which the files are returned\n @return: A tree of files\n \"\"\"\n submit = Database().view_submit(submit_id)\n files, duplicates = [], []\n\n for data in submit.data[\"data\"]:\n if data[\"type\"] == \"file\":\n filename = Storage.get_filename_from_path(data[\"data\"])\n filepath = os.path.join(submit.tmp_path, data[\"data\"])\n filedata = open(filepath, \"rb\").read()\n\n unpacked = sflock.unpack(\n filepath=filename, contents=filedata,\n password=password, duplicates=duplicates\n )\n\n if astree:\n unpacked = unpacked.astree()\n\n files.append(unpacked)\n elif data[\"type\"] == \"url\":\n files.append({\n \"filename\": data[\"data\"],\n \"filepath\": \"\",\n \"relapath\": \"\",\n \"selected\": True,\n \"size\": 0,\n \"type\": \"url\",\n \"package\": \"ie\",\n \"extrpath\": [],\n \"duplicate\": False,\n \"children\": [],\n \"mime\": \"text/html\",\n \"finger\": {\n \"magic_human\": \"url\",\n \"magic\": \"url\"\n }\n })\n else:\n raise RuntimeError(\n \"Unknown data entry type: %s\" % data[\"type\"]\n )\n\n return {\n \"files\": files,\n \"path\": submit.tmp_path,\n }","target":" def get_files(self, submit_id, password=None, astree=False):\n \"\"\"\n Returns files from a submitted analysis.\n @param password: The password to unlock container archives with\n @param astree: sflock option; determines the format in which the files are returned\n @return: A tree of files\n \"\"\"\n submit = Database().view_submit(submit_id)\n files, duplicates = [], []\n\n for data in submit.data[\"data\"]:\n if data[\"type\"] == \"file\":\n filename = Storage.get_filename_from_path(data[\"data\"])\n filepath = os.path.join(submit.tmp_path, filename)\n\n unpacked = sflock.unpack(\n filepath=filepath, password=password, duplicates=duplicates\n )\n\n if astree:\n unpacked = unpacked.astree(sanitize=True)\n\n files.append(unpacked)\n elif data[\"type\"] == \"url\":\n files.append({\n \"filename\": data[\"data\"],\n \"filepath\": \"\",\n \"relapath\": \"\",\n \"selected\": True,\n \"size\": 0,\n \"type\": \"url\",\n \"package\": \"ie\",\n \"extrpath\": [],\n \"duplicate\": False,\n \"children\": [],\n \"mime\": \"text/html\",\n \"finger\": {\n \"magic_human\": \"url\",\n \"magic\": \"url\"\n }\n })\n else:\n raise RuntimeError(\n \"Unknown data entry type: %s\" % data[\"type\"]\n )\n\n return files","lang":"python","vul_type":"cwe-022","target_token_count":314,"sven_meta":{"func_name":"get_files","file_name":"cuckoo/core/submit.py","commit_link":"github.com/cuckoosandbox/cuckoo/commit/168cabf86730d56b7fa319278bf0f0034052666a","source_cwe_file":"cwe-022.jsonl"}}
{"problem_id":"cwe-022#31-cc0c10d323d2","input":"header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)\n{\n struct ImapMbox mx;\n struct Url url;\n char cachepath[PATH_MAX];\n char mbox[PATH_MAX];\n\n if (path)\n imap_cachepath(idata, path, mbox, sizeof(mbox));\n else\n {\n if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)\n return NULL;\n\n imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));\n FREE(&mx.mbox);\n }\n\n mutt_account_tourl(&idata->conn->account, &url);\n url.path = mbox;\n url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);\n\n return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);\n}","target":"header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)\n{\n struct ImapMbox mx;\n struct Url url;\n char cachepath[PATH_MAX];\n char mbox[PATH_MAX];\n\n if (path)\n imap_cachepath(idata, path, mbox, sizeof(mbox));\n else\n {\n if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)\n return NULL;\n\n imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));\n FREE(&mx.mbox);\n }\n\n if (strstr(mbox, \"/../\") || (strcmp(mbox, \"..\") == 0) || (strncmp(mbox, \"../\", 3) == 0))\n return NULL;\n size_t len = strlen(mbox);\n if ((len > 3) && (strcmp(mbox + len - 3, \"/..\") == 0))\n return NULL;\n\n mutt_account_tourl(&idata->conn->account, &url);\n url.path = mbox;\n url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);\n\n return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);\n}","lang":"c","vul_type":"cwe-022","target_token_count":278,"sven_meta":{"func_name":"imap_hcache_open","file_name":"imap/util.c","commit_link":"github.com/neomutt/neomutt/commit/57971dba06346b2d7179294f4528b8d4427a7c5d","source_cwe_file":"cwe-022.jsonl"}}
{"problem_id":"cwe-022#36-cfa530b836e2","input":"async def save(request):\n # TODO csrf\n data = await request.post()\n item = Item(data['src'])\n\n # Update name\n new_src = data.get('new_src')\n if new_src and new_src != data['src']:\n # don't need to worry about html unquote\n shutil.move(item.abspath, settings.STORAGE_DIR + new_src)\n old_backup_abspath = item.backup_abspath\n item = Item(new_src)\n if os.path.isfile(old_backup_abspath):\n shutil.move(old_backup_abspath, item.backup_abspath)\n\n # Update meta\n for field in item.FORM:\n # TODO handle .repeatable (keywords)\n item.meta[field] = [data.get(field, '')]\n\n if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath):\n shutil.copyfile(item.abspath, item.backup_abspath)\n\n # WISHLIST don't write() if nothing changed\n item.meta.write()\n\n return web.Response(\n status=200,\n body=json.dumps(item.get_form_fields()).encode('utf8'),\n content_type='application/json',\n )","target":"async def save(request):\n # TODO csrf\n data = await request.post()\n item = Item(data['src'])\n\n # Update name\n new_src = data.get('new_src')\n if new_src:\n new_abspath = os.path.abspath(settings.STORAGE_DIR + new_src)\n if not new_abspath.startswith(settings.STORAGE_DIR):\n return web.Response(status=400, body=b'Invalid Request')\n\n if new_abspath != item.abspath:\n shutil.move(item.abspath, new_abspath)\n old_backup_abspath = item.backup_abspath\n item = Item(new_src)\n if os.path.isfile(old_backup_abspath):\n shutil.move(old_backup_abspath, item.backup_abspath)\n\n # Update meta\n for field in item.FORM:\n # TODO handle .repeatable (keywords)\n item.meta[field] = [data.get(field, '')]\n\n if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath):\n shutil.copyfile(item.abspath, item.backup_abspath)\n\n # WISHLIST don't write() if nothing changed\n item.meta.write()\n\n return web.Response(\n status=200,\n body=json.dumps(item.get_form_fields()).encode('utf8'),\n content_type='application/json',\n )","lang":"python","vul_type":"cwe-022","target_token_count":269,"sven_meta":{"func_name":"save","file_name":"gallery/gallery.py","commit_link":"github.com/crccheck/gallery-cms/commit/60dec5c580a779ae27824ed54cb113eca25afdc0","source_cwe_file":"cwe-022.jsonl"}}
{"problem_id":"cwe-022#40-4f5ccce9780b","input":"def new_goal():\n \"\"\"\n new goal\n \"\"\"\n\n goals_dir_check()\n\n click.echo(chalk.blue('Input a single-word name of the goal:'))\n goal_name = input().strip()\n\n if goal_name_exists(goal_name):\n click.echo(chalk.red(\n 'A goal with this name already exists. Please type \"yoda goals view\" to see a list of existing goals'))\n else:\n click.echo(chalk.blue('Input description of the goal:'))\n text = input().strip()\n\n click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):'))\n deadline = input().strip()\n\n if os.path.isfile(GOALS_CONFIG_FILE_PATH):\n setup_data = dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH)\n else:\n setup_data = dict(\n entries=[\n dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n ]\n )\n input_data(setup_data, GOALS_CONFIG_FILE_PATH)\n\n input_data(dict(entries=[]), get_goal_file_path(goal_name))","target":"def new_goal():\n \"\"\"\n new goal\n \"\"\"\n\n goals_dir_check()\n\n goal_name_not_ok = True\n\n click.echo(chalk.blue('Input a single-word name of the goal:'))\n while goal_name_not_ok:\n goal_name = input().strip()\n if goal_name.isalnum():\n goal_name_not_ok = False\n else:\n click.echo(chalk.red('Only alphanumeric characters can be used! Please input the goal name:'))\n\n if goal_name_exists(goal_name):\n click.echo(chalk.red(\n 'A goal with this name already exists. Please type \"yoda goals view\" to see a list of existing goals'))\n else:\n click.echo(chalk.blue('Input description of the goal:'))\n text = input().strip()\n\n click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):'))\n incorrect_date_format = True\n while incorrect_date_format:\n deadline = input().strip()\n try:\n date_str = datetime.datetime.strptime(deadline, '%Y-%m-%d').strftime('%Y-%m-%d')\n if date_str != deadline:\n raise ValueError\n incorrect_date_format = False\n except ValueError:\n click.echo(chalk.red(\"Incorrect data format, should be YYYY-MM-DD. Please repeat:\"))\n\n if os.path.isfile(GOALS_CONFIG_FILE_PATH):\n setup_data = dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH)\n else:\n setup_data = dict(\n entries=[\n dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n ]\n )\n input_data(setup_data, GOALS_CONFIG_FILE_PATH)\n\n input_data(dict(entries=[]), get_goal_file_path(goal_name))","lang":"python","vul_type":"cwe-022","target_token_count":388,"sven_meta":{"func_name":"new_goal","file_name":"modules/goals.py","commit_link":"github.com/yoda-pa/yoda/commit/263946316041601de75638ee303a892f2652cf40","source_cwe_file":"cwe-022.jsonl"}}
{"problem_id":"cwe-022#41-1868f634d06d","input":"def _inject_admin_password_into_fs(admin_passwd, fs, execute=None):\n \"\"\"Set the root password to admin_passwd\n\n admin_password is a root password\n fs is the path to the base of the filesystem into which to inject\n the key.\n\n This method modifies the instance filesystem directly,\n and does not require a guest agent running in the instance.\n\n \"\"\"\n # The approach used here is to copy the password and shadow\n # files from the instance filesystem to local files, make any\n # necessary changes, and then copy them back.\n\n admin_user = 'root'\n\n fd, tmp_passwd = tempfile.mkstemp()\n os.close(fd)\n fd, tmp_shadow = tempfile.mkstemp()\n os.close(fd)\n\n utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd,\n run_as_root=True)\n utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow,\n run_as_root=True)\n _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)\n utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'),\n run_as_root=True)\n os.unlink(tmp_passwd)\n utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'),\n run_as_root=True)\n os.unlink(tmp_shadow)","target":"def _inject_admin_password_into_fs(admin_passwd, fs, execute=None):\n \"\"\"Set the root password to admin_passwd\n\n admin_password is a root password\n fs is the path to the base of the filesystem into which to inject\n the key.\n\n This method modifies the instance filesystem directly,\n and does not require a guest agent running in the instance.\n\n \"\"\"\n # The approach used here is to copy the password and shadow\n # files from the instance filesystem to local files, make any\n # necessary changes, and then copy them back.\n\n admin_user = 'root'\n\n fd, tmp_passwd = tempfile.mkstemp()\n os.close(fd)\n fd, tmp_shadow = tempfile.mkstemp()\n os.close(fd)\n\n passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd')\n shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow')\n\n utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True)\n utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True)\n _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)\n utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True)\n os.unlink(tmp_passwd)\n utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True)\n os.unlink(tmp_shadow)","lang":"python","vul_type":"cwe-022","target_token_count":289,"sven_meta":{"func_name":"_inject_admin_password_into_fs","file_name":"nova/virt/disk/api.py","commit_link":"github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7","source_cwe_file":"cwe-022.jsonl"}}
{"problem_id":"cwe-787#9-836517feae17","input":"idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)\n{\n uint32_t *input_u32;\n uint8_t *input_u8, *output_u8;\n size_t length;\n int rc;\n\n if (!input)\n {\n if (output)\n\t*output = 0;\n return IDN2_OK;\n }\n\n input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));\n if (!input_u32)\n return IDN2_MALLOC;\n\n u32_cpy (input_u32, input, inlen);\n input_u32[inlen] = 0;\n\n input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);\n free (input_u32);\n if (!input_u8)\n {\n if (errno == ENOMEM)\n\treturn IDN2_MALLOC;\n return IDN2_ENCODING_ERROR;\n }\n\n rc = idn2_lookup_u8 (input_u8, &output_u8, flags);\n free (input_u8);\n\n if (rc == IDN2_OK)\n {\n /* wow, this is ugly, but libidn manpage states:\n * char * out output zero terminated string that must have room for at\n * least 63 characters plus the terminating zero.\n */\n if (output)\n\tstrcpy (output, (const char *) output_u8);\n\n free(output_u8);\n }\n\n return rc;\n}","target":"idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)\n{\n uint32_t *input_u32;\n uint8_t *input_u8, *output_u8;\n size_t length;\n int rc;\n\n if (!input)\n {\n if (output)\n\t*output = 0;\n return IDN2_OK;\n }\n\n input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));\n if (!input_u32)\n return IDN2_MALLOC;\n\n u32_cpy (input_u32, input, inlen);\n input_u32[inlen] = 0;\n\n input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);\n free (input_u32);\n if (!input_u8)\n {\n if (errno == ENOMEM)\n\treturn IDN2_MALLOC;\n return IDN2_ENCODING_ERROR;\n }\n\n rc = idn2_lookup_u8 (input_u8, &output_u8, flags);\n free (input_u8);\n\n if (rc == IDN2_OK)\n {\n /* wow, this is ugly, but libidn manpage states:\n * char * out output zero terminated string that must have room for at\n * least 63 characters plus the terminating zero.\n */\n size_t len = strlen ((char *) output_u8);\n\n if (len > 63)\n {\n\t free (output_u8);\n\t return IDN2_TOO_BIG_DOMAIN;\n }\n\n if (output)\n\tstrcpy (output, (char *) output_u8);\n\n free (output_u8);\n }\n\n return rc;\n}","lang":"c","vul_type":"cwe-787","target_token_count":391,"sven_meta":{"func_name":"idn2_to_ascii_4i","file_name":"lib/lookup.c","commit_link":"github.com/libidn/libidn2/commit/e4d1558aa2c1c04a05066ee8600f37603890ba8c","source_cwe_file":"cwe-787.jsonl"}}
{"problem_id":"cwe-787#21-7d71d71a0a22","input":"TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n int max_index = -1;\n const int segment_id_size = segment_ids->dims->data[0];\n if (segment_id_size > 0) {\n max_index = segment_ids->data.i32[segment_id_size - 1];\n }\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;\n for (int i = 1; i < data_rank; ++i) {\n output_shape->data[i] = data->dims->data[i];\n }\n return context->ResizeTensor(context, output, output_shape);\n}","target":"TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n // Segment ids should be of same cardinality as first input dimension and they\n // should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid)\n const int segment_id_size = segment_ids->dims->data[0];\n TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);\n int previous_segment_id = -1;\n for (int i = 0; i < segment_id_size; i++) {\n const int current_segment_id = GetTensorData<int32_t>(segment_ids)[i];\n if (i == 0) {\n TF_LITE_ENSURE_EQ(context, current_segment_id, 0);\n } else {\n int delta = current_segment_id - previous_segment_id;\n TF_LITE_ENSURE(context, delta == 0 || delta == 1);\n }\n previous_segment_id = current_segment_id;\n }\n\n const int max_index = previous_segment_id;\n\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;\n for (int i = 1; i < data_rank; ++i) {\n output_shape->data[i] = data->dims->data[i];\n }\n return context->ResizeTensor(context, output, output_shape);\n}","lang":"cpp","vul_type":"cwe-787","target_token_count":346,"sven_meta":{"func_name":"tflite::ops::builtin::segment_sum::ResizeOutputTensor","file_name":"tensorflow/lite/kernels/segment_sum.cc","commit_link":"github.com/tensorflow/tensorflow/commit/204945b19e44b57906c9344c0d00120eeeae178a","source_cwe_file":"cwe-787.jsonl"}}
{"problem_id":"cwe-787#31-fc99fe3f0b38","input":"static void handle_PORT(ctrl_t *ctrl, char *str)\n{\n\tint a, b, c, d, e, f;\n\tchar addr[INET_ADDRSTRLEN];\n\tstruct sockaddr_in sin;\n\n\tif (ctrl->data_sd > 0) {\n\t\tuev_io_stop(&ctrl->data_watcher);\n\t\tclose(ctrl->data_sd);\n\t\tctrl->data_sd = -1;\n\t}\n\n\t/* Convert PORT command's argument to IP address + port */\n\tsscanf(str, \"%d,%d,%d,%d,%d,%d\", &a, &b, &c, &d, &e, &f);\n\tsprintf(addr, \"%d.%d.%d.%d\", a, b, c, d);\n\n\t/* Check IPv4 address using inet_aton(), throw away converted result */\n\tif (!inet_aton(addr, &(sin.sin_addr))) {\n\t\tERR(0, \"Invalid address '%s' given to PORT command\", addr);\n\t\tsend_msg(ctrl->sd, \"500 Illegal PORT command.\\r\\n\");\n\t\treturn;\n\t}\n\n\tstrlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address));\n\tctrl->data_port = e * 256 + f;\n\n\tDBG(\"Client PORT command accepted for %s:%d\", ctrl->data_address, ctrl->data_port);\n\tsend_msg(ctrl->sd, \"200 PORT command successful.\\r\\n\");\n}","target":"static void handle_PORT(ctrl_t *ctrl, char *str)\n{\n\tint a, b, c, d, e, f;\n\tchar addr[INET_ADDRSTRLEN];\n\tstruct sockaddr_in sin;\n\n\tif (ctrl->data_sd > 0) {\n\t\tuev_io_stop(&ctrl->data_watcher);\n\t\tclose(ctrl->data_sd);\n\t\tctrl->data_sd = -1;\n\t}\n\n\t/* Convert PORT command's argument to IP address + port */\n\tsscanf(str, \"%d,%d,%d,%d,%d,%d\", &a, &b, &c, &d, &e, &f);\n\tsnprintf(addr, sizeof(addr), \"%d.%d.%d.%d\", a, b, c, d);\n\n\t/* Check IPv4 address using inet_aton(), throw away converted result */\n\tif (!inet_aton(addr, &(sin.sin_addr))) {\n\t\tERR(0, \"Invalid address '%s' given to PORT command\", addr);\n\t\tsend_msg(ctrl->sd, \"500 Illegal PORT command.\\r\\n\");\n\t\treturn;\n\t}\n\n\tstrlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address));\n\tctrl->data_port = e * 256 + f;\n\n\tDBG(\"Client PORT command accepted for %s:%d\", ctrl->data_address, ctrl->data_port);\n\tsend_msg(ctrl->sd, \"200 PORT command successful.\\r\\n\");\n}","lang":"c","vul_type":"cwe-787","target_token_count":293,"sven_meta":{"func_name":"handle_PORT","file_name":"src/ftpcmd.c","commit_link":"github.com/troglobit/uftpd/commit/0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd","source_cwe_file":"cwe-787.jsonl"}}
{"problem_id":"cwe-787#32-36a832e48755","input":"int rom_copy(uint8_t *dest, hwaddr addr, size_t size)\n{\n hwaddr end = addr + size;\n uint8_t *s, *d = dest;\n size_t l = 0;\n Rom *rom;\n\n QTAILQ_FOREACH(rom, &roms, next) {\n if (rom->fw_file) {\n continue;\n }\n if (rom->mr) {\n continue;\n }\n if (rom->addr + rom->romsize < addr) {\n continue;\n }\n if (rom->addr > end) {\n break;\n }\n\n d = dest + (rom->addr - addr);\n s = rom->data;\n l = rom->datasize;\n\n if ((d + l) > (dest + size)) {\n l = dest - d;\n }\n\n if (l > 0) {\n memcpy(d, s, l);\n }\n\n if (rom->romsize > rom->datasize) {\n /* If datasize is less than romsize, it means that we didn't\n * allocate all the ROM because the trailing data are only zeros.\n */\n\n d += l;\n l = rom->romsize - rom->datasize;\n\n if ((d + l) > (dest + size)) {\n /* Rom size doesn't fit in the destination area. Adjust to avoid\n * overflow.\n */\n l = dest - d;\n }\n\n if (l > 0) {\n memset(d, 0x0, l);\n }\n }\n }\n\n return (d + l) - dest;\n}","target":"int rom_copy(uint8_t *dest, hwaddr addr, size_t size)\n{\n hwaddr end = addr + size;\n uint8_t *s, *d = dest;\n size_t l = 0;\n Rom *rom;\n\n QTAILQ_FOREACH(rom, &roms, next) {\n if (rom->fw_file) {\n continue;\n }\n if (rom->mr) {\n continue;\n }\n if (rom->addr + rom->romsize < addr) {\n continue;\n }\n if (rom->addr > end || rom->addr < addr) {\n break;\n }\n\n d = dest + (rom->addr - addr);\n s = rom->data;\n l = rom->datasize;\n\n if ((d + l) > (dest + size)) {\n l = dest - d;\n }\n\n if (l > 0) {\n memcpy(d, s, l);\n }\n\n if (rom->romsize > rom->datasize) {\n /* If datasize is less than romsize, it means that we didn't\n * allocate all the ROM because the trailing data are only zeros.\n */\n\n d += l;\n l = rom->romsize - rom->datasize;\n\n if ((d + l) > (dest + size)) {\n /* Rom size doesn't fit in the destination area. Adjust to avoid\n * overflow.\n */\n l = dest - d;\n }\n\n if (l > 0) {\n memset(d, 0x0, l);\n }\n }\n }\n\n return (d + l) - dest;\n}","lang":"c","vul_type":"cwe-787","target_token_count":352,"sven_meta":{"func_name":"rom_copy","file_name":"hw/core/loader.c","commit_link":"github.com/qemu/qemu/commit/4f1c6cb2f9afafda05eab150fd2bd284edce6676","source_cwe_file":"cwe-787.jsonl"}}
{"problem_id":"cwe-787#34-3eda953a2788","input":"TiledInputFile::rawTileData (int &dx, int &dy,\n\t\t\t int &lx, int &ly,\n const char *&pixelData,\n\t\t\t int &pixelDataSize)\n{\n try\n {\n Lock lock (*_data->_streamData);\n\n if (!isValidTile (dx, dy, lx, ly))\n throw IEX_NAMESPACE::ArgExc (\"Tried to read a tile outside \"\n\t\t\t \"the image file's data window.\");\n\n TileBuffer *tileBuffer = _data->getTileBuffer (0);\n\n //\n // if file is a multipart file, we have to seek to the required tile\n // since we don't know where the file pointer is\n //\n int old_dx=dx;\n int old_dy=dy;\n int old_lx=lx;\n int old_ly=ly;\n if(isMultiPart(version()))\n {\n _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly));\n }\n readNextTileData (_data->_streamData, _data, dx, dy, lx, ly,\n\t\t\t tileBuffer->buffer,\n pixelDataSize);\n if(isMultiPart(version()))\n {\n if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly)\n {\n throw IEX_NAMESPACE::ArgExc (\"rawTileData read the wrong tile\");\n }\n }\n pixelData = tileBuffer->buffer;\n }\n catch (IEX_NAMESPACE::BaseExc &e)\n {\n REPLACE_EXC (e, \"Error reading pixel data from image \"\n \"file \\\"\" << fileName() << \"\\\". \" << e.what());\n throw;\n }\n}","target":"TiledInputFile::rawTileData (int &dx, int &dy,\n\t\t\t int &lx, int &ly,\n const char *&pixelData,\n\t\t\t int &pixelDataSize)\n{\n try\n {\n Lock lock (*_data->_streamData);\n\n if (!isValidTile (dx, dy, lx, ly))\n throw IEX_NAMESPACE::ArgExc (\"Tried to read a tile outside \"\n\t\t\t \"the image file's data window.\");\n\n TileBuffer *tileBuffer = _data->getTileBuffer (0);\n\n //\n // if file is a multipart file, we have to seek to the required tile\n // since we don't know where the file pointer is\n //\n int old_dx=dx;\n int old_dy=dy;\n int old_lx=lx;\n int old_ly=ly;\n if(isMultiPart(version()))\n {\n _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly));\n }\n readNextTileData (_data->_streamData, _data, dx, dy, lx, ly,\n\t\t\t tileBuffer->buffer,\n pixelDataSize);\n if(isMultiPart(version()))\n {\n if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly)\n {\n throw IEX_NAMESPACE::ArgExc (\"rawTileData read the wrong tile\");\n }\n }\n else\n {\n if(!isValidTile (dx, dy, lx, ly) )\n {\n throw IEX_NAMESPACE::IoExc (\"rawTileData read an invalid tile\");\n }\n }\n pixelData = tileBuffer->buffer;\n }\n catch (IEX_NAMESPACE::BaseExc &e)\n {\n REPLACE_EXC (e, \"Error reading pixel data from image \"\n \"file \\\"\" << fileName() << \"\\\". \" << e.what());\n throw;\n }\n}","lang":"cpp","vul_type":"cwe-787","target_token_count":404,"sven_meta":{"func_name":"TiledInputFile::rawTileData","file_name":"OpenEXR/IlmImf/ImfTiledInputFile.cpp","commit_link":"github.com/AcademySoftwareFoundation/openexr/commit/6bb36714528a9563dd3b92720c5063a1284b86f8","source_cwe_file":"cwe-787.jsonl"}}
{"problem_id":"cwe-787#36-c2a7543d01b7","input":"static int decode_zbuf(AVBPrint *bp, const uint8_t *data,\n const uint8_t *data_end)\n{\n z_stream zstream;\n unsigned char *buf;\n unsigned buf_size;\n int ret;\n\n zstream.zalloc = ff_png_zalloc;\n zstream.zfree = ff_png_zfree;\n zstream.opaque = NULL;\n if (inflateInit(&zstream) != Z_OK)\n return AVERROR_EXTERNAL;\n zstream.next_in = (unsigned char *)data;\n zstream.avail_in = data_end - data;\n av_bprint_init(bp, 0, -1);\n\n while (zstream.avail_in > 0) {\n av_bprint_get_buffer(bp, 1, &buf, &buf_size);\n if (!buf_size) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n zstream.next_out = buf;\n zstream.avail_out = buf_size;\n ret = inflate(&zstream, Z_PARTIAL_FLUSH);\n if (ret != Z_OK && ret != Z_STREAM_END) {\n ret = AVERROR_EXTERNAL;\n goto fail;\n }\n bp->len += zstream.next_out - buf;\n if (ret == Z_STREAM_END)\n break;\n }\n inflateEnd(&zstream);\n bp->str[bp->len] = 0;\n return 0;\n\nfail:\n inflateEnd(&zstream);\n av_bprint_finalize(bp, NULL);\n return ret;\n}","target":"static int decode_zbuf(AVBPrint *bp, const uint8_t *data,\n const uint8_t *data_end)\n{\n z_stream zstream;\n unsigned char *buf;\n unsigned buf_size;\n int ret;\n\n zstream.zalloc = ff_png_zalloc;\n zstream.zfree = ff_png_zfree;\n zstream.opaque = NULL;\n if (inflateInit(&zstream) != Z_OK)\n return AVERROR_EXTERNAL;\n zstream.next_in = (unsigned char *)data;\n zstream.avail_in = data_end - data;\n av_bprint_init(bp, 0, -1);\n\n while (zstream.avail_in > 0) {\n av_bprint_get_buffer(bp, 2, &buf, &buf_size);\n if (buf_size < 2) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n zstream.next_out = buf;\n zstream.avail_out = buf_size - 1;\n ret = inflate(&zstream, Z_PARTIAL_FLUSH);\n if (ret != Z_OK && ret != Z_STREAM_END) {\n ret = AVERROR_EXTERNAL;\n goto fail;\n }\n bp->len += zstream.next_out - buf;\n if (ret == Z_STREAM_END)\n break;\n }\n inflateEnd(&zstream);\n bp->str[bp->len] = 0;\n return 0;\n\nfail:\n inflateEnd(&zstream);\n av_bprint_finalize(bp, NULL);\n return ret;\n}","lang":"c","vul_type":"cwe-787","target_token_count":329,"sven_meta":{"func_name":"decode_zbuf","file_name":"libavcodec/pngdec.c","commit_link":"github.com/FFmpeg/FFmpeg/commit/e371f031b942d73e02c090170975561fabd5c264","source_cwe_file":"cwe-787.jsonl"}}
{"problem_id":"cwe-787#43-37e1405ec1f6","input":"char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)\n{\n char *buffer=NULL;\n int n=0;\n\n FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(\"\", cl, NULL);\n /*\n rfbLog(\"rfbProcessFileTransferReadBuffer(%dlen)\\n\", length);\n */\n if (length>0) {\n buffer=malloc((uint64_t)length+1);\n if (buffer!=NULL) {\n if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {\n if (n != 0)\n rfbLogPerror(\"rfbProcessFileTransferReadBuffer: read\");\n rfbCloseClient(cl);\n /* NOTE: don't forget to free(buffer) if you return early! */\n if (buffer!=NULL) free(buffer);\n return NULL;\n }\n /* Null Terminate */\n buffer[length]=0;\n }\n }\n return buffer;\n}","target":"char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)\n{\n char *buffer=NULL;\n int n=0;\n\n FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(\"\", cl, NULL);\n\n /*\n We later alloc length+1, which might wrap around on 32-bit systems if length equals\n 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF\n will safely be allocated since this check will never trigger and malloc() can digest length+1\n without problems as length is a uint32_t.\n */\n if(length == SIZE_MAX) {\n\trfbErr(\"rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u\", (unsigned int)length);\n\trfbCloseClient(cl);\n\treturn NULL;\n }\n\n if (length>0) {\n buffer=malloc((size_t)length+1);\n if (buffer!=NULL) {\n if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {\n if (n != 0)\n rfbLogPerror(\"rfbProcessFileTransferReadBuffer: read\");\n rfbCloseClient(cl);\n /* NOTE: don't forget to free(buffer) if you return early! */\n if (buffer!=NULL) free(buffer);\n return NULL;\n }\n /* Null Terminate */\n buffer[length]=0;\n }\n }\n return buffer;\n}","lang":"c","vul_type":"cwe-787","target_token_count":324,"sven_meta":{"func_name":"rfbProcessFileTransferReadBuffer","file_name":"libvncserver/rfbserver.c","commit_link":"github.com/LibVNC/libvncserver/commit/15bb719c03cc70f14c36a843dcb16ed69b405707","source_cwe_file":"cwe-787.jsonl"}}
{"problem_id":"cwe-079#1-fdc5cca261bb","input":" DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) {\n setupUi(this);\n if (size == 1)\n label->setText(tr(\"Are you sure you want to delete '%1' from the transfer list?\", \"Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?\").arg(name));\n else\n label->setText(tr(\"Are you sure you want to delete these %1 torrents from the transfer list?\", \"Are you sure you want to delete these 5 torrents from the transfer list?\").arg(QString::number(size)));\n // Icons\n lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon(\"dialog-warning\").pixmap(lbl_warn->height()));\n lbl_warn->setFixedWidth(lbl_warn->height());\n rememberBtn->setIcon(GuiIconProvider::instance()->getIcon(\"object-locked\"));\n\n move(Utils::Misc::screenCenter(this));\n checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault());\n connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));\n buttonBox->button(QDialogButtonBox::Cancel)->setFocus();\n }","target":" DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) {\n setupUi(this);\n if (size == 1)\n label->setText(tr(\"Are you sure you want to delete '%1' from the transfer list?\", \"Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?\").arg(Utils::String::toHtmlEscaped(name)));\n else\n label->setText(tr(\"Are you sure you want to delete these %1 torrents from the transfer list?\", \"Are you sure you want to delete these 5 torrents from the transfer list?\").arg(QString::number(size)));\n // Icons\n lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon(\"dialog-warning\").pixmap(lbl_warn->height()));\n lbl_warn->setFixedWidth(lbl_warn->height());\n rememberBtn->setIcon(GuiIconProvider::instance()->getIcon(\"object-locked\"));\n\n move(Utils::Misc::screenCenter(this));\n checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault());\n connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));\n buttonBox->button(QDialogButtonBox::Cancel)->setFocus();\n }","lang":"c","vul_type":"cwe-079","target_token_count":267,"sven_meta":{"func_name":"DeletionConfirmationDlg::DeletionConfirmationDlg","file_name":"src/gui/deletionconfirmationdlg.h","commit_link":"github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#3-4412e8937473","input":"def index(request, is_mobile=False):\n hue_collections = DashboardController(request.user).get_search_collections()\n collection_id = request.GET.get('collection')\n\n if not hue_collections or not collection_id:\n return admin_collections(request, True, is_mobile)\n\n try:\n collection_doc = Document2.objects.get(id=collection_id)\n if USE_NEW_EDITOR.get():\n collection_doc.can_read_or_exception(request.user)\n else:\n collection_doc.doc.get().can_read_or_exception(request.user)\n collection = Collection2(request.user, document=collection_doc)\n except Exception, e:\n raise PopupException(e, title=_(\"Dashboard does not exist or you don't have the permission to access it.\"))\n\n query = {'qs': [{'q': ''}], 'fqs': [], 'start': 0}\n\n if request.method == 'GET':\n if 'q' in request.GET:\n query['qs'][0]['q'] = request.GET.get('q')\n if 'qd' in request.GET:\n query['qd'] = request.GET.get('qd')\n\n template = 'search.mako'\n if is_mobile:\n template = 'search_m.mako'\n\n return render(template, request, {\n 'collection': collection,\n 'query': json.dumps(query),\n 'initial': json.dumps({\n 'collections': [],\n 'layout': DEFAULT_LAYOUT,\n 'is_latest': LATEST.get(),\n 'engines': get_engines(request.user)\n }),\n 'is_owner': collection_doc.doc.get().can_write(request.user),\n 'can_edit_index': can_edit_index(request.user),\n 'is_embeddable': request.GET.get('is_embeddable', False),\n 'mobile': is_mobile,\n })","target":"def index(request, is_mobile=False):\n hue_collections = DashboardController(request.user).get_search_collections()\n collection_id = request.GET.get('collection')\n\n if not hue_collections or not collection_id:\n return admin_collections(request, True, is_mobile)\n\n try:\n collection_doc = Document2.objects.get(id=collection_id)\n if USE_NEW_EDITOR.get():\n collection_doc.can_read_or_exception(request.user)\n else:\n collection_doc.doc.get().can_read_or_exception(request.user)\n collection = Collection2(request.user, document=collection_doc)\n except Exception, e:\n raise PopupException(e, title=_(\"Dashboard does not exist or you don't have the permission to access it.\"))\n\n query = {'qs': [{'q': ''}], 'fqs': [], 'start': 0}\n\n if request.method == 'GET':\n if 'q' in request.GET:\n query['qs'][0]['q'] = antixss(request.GET.get('q', ''))\n if 'qd' in request.GET:\n query['qd'] = antixss(request.GET.get('qd', ''))\n\n template = 'search.mako'\n if is_mobile:\n template = 'search_m.mako'\n\n return render(template, request, {\n 'collection': collection,\n 'query': json.dumps(query),\n 'initial': json.dumps({\n 'collections': [],\n 'layout': DEFAULT_LAYOUT,\n 'is_latest': LATEST.get(),\n 'engines': get_engines(request.user)\n }),\n 'is_owner': collection_doc.can_write(request.user) if USE_NEW_EDITOR.get() else collection_doc.doc.get().can_write(request.user),\n 'can_edit_index': can_edit_index(request.user),\n 'is_embeddable': request.GET.get('is_embeddable', False),\n 'mobile': is_mobile,\n })","lang":"python","vul_type":"cwe-079","target_token_count":383,"sven_meta":{"func_name":"index","file_name":"desktop/libs/dashboard/src/dashboard/views.py","commit_link":"github.com/gethue/hue/commit/37b529b1f9aeb5d746599a9ed4e2288cf3ad3e1d","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#13-803f93e40115","input":"@check_document_access_permission()\ndef edit_workflow(request):\n workflow_id = request.GET.get('workflow')\n \n if workflow_id:\n wid = {}\n if workflow_id.isdigit():\n wid['id'] = workflow_id\n else:\n wid['uuid'] = workflow_id\n doc = Document2.objects.get(type='oozie-workflow2', **wid)\n workflow = Workflow(document=doc)\n else:\n doc = None\n workflow = Workflow()\n workflow.set_workspace(request.user)\n workflow.check_workspace(request.fs, request.user)\n \n workflow_data = workflow.get_data()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n return render('editor/workflow_editor.mako', request, {\n 'layout_json': json.dumps(workflow_data['layout']),\n 'workflow_json': json.dumps(workflow_data['workflow']),\n 'credentials_json': json.dumps(credentials.credentials.keys()),\n 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'subworkflows_json': json.dumps(_get_workflows(request.user)),\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })","target":"@check_document_access_permission()\ndef edit_workflow(request):\n workflow_id = request.GET.get('workflow')\n \n if workflow_id:\n wid = {}\n if workflow_id.isdigit():\n wid['id'] = workflow_id\n else:\n wid['uuid'] = workflow_id\n doc = Document2.objects.get(type='oozie-workflow2', **wid)\n workflow = Workflow(document=doc)\n else:\n doc = None\n workflow = Workflow()\n workflow.set_workspace(request.user)\n workflow.check_workspace(request.fs, request.user)\n \n workflow_data = workflow.get_data()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n return render('editor/workflow_editor.mako', request, {\n 'layout_json': json.dumps(workflow_data['layout'], cls=JSONEncoderForHTML),\n 'workflow_json': json.dumps(workflow_data['workflow'], cls=JSONEncoderForHTML),\n 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES, cls=JSONEncoderForHTML),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'subworkflows_json': json.dumps(_get_workflows(request.user), cls=JSONEncoderForHTML),\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })","lang":"python","vul_type":"cwe-079","target_token_count":319,"sven_meta":{"func_name":"edit_workflow","file_name":"apps/oozie/src/oozie/views/editor2.py","commit_link":"github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#17-1a1121e69073","input":"@check_document_access_permission()\ndef edit_coordinator(request):\n coordinator_id = request.GET.get('coordinator')\n doc = None\n \n if coordinator_id:\n doc = Document2.objects.get(id=coordinator_id)\n coordinator = Coordinator(document=doc)\n else:\n coordinator = Coordinator()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])\n for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]\n\n if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows):\n raise PopupException(_('You don\\'t have access to the workflow of this coordinator.'))\n\n return render('editor/coordinator_editor.mako', request, {\n 'coordinator_json': coordinator.json,\n 'credentials_json': json.dumps(credentials.credentials.keys()),\n 'workflows_json': json.dumps(workflows),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })","target":"@check_document_access_permission()\ndef edit_coordinator(request):\n coordinator_id = request.GET.get('coordinator')\n doc = None\n \n if coordinator_id:\n doc = Document2.objects.get(id=coordinator_id)\n coordinator = Coordinator(document=doc)\n else:\n coordinator = Coordinator()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])\n for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]\n\n if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows):\n raise PopupException(_('You don\\'t have access to the workflow of this coordinator.'))\n\n return render('editor/coordinator_editor.mako', request, {\n 'coordinator_json': coordinator.json_for_html(),\n 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })","lang":"python","vul_type":"cwe-079","target_token_count":287,"sven_meta":{"func_name":"edit_coordinator","file_name":"apps/oozie/src/oozie/views/editor2.py","commit_link":"github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#23-dcbe3bb95c17","input":"@csrf.csrf_protect\ndef subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (<a href=\"%(url)s\">undo</a>).'\n ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())","target":"@csrf.csrf_protect\ndef subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (<a href=\"%(url)s\">undo</a>).'\n ) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())","lang":"python","vul_type":"cwe-079","target_token_count":307,"sven_meta":{"func_name":"subscribe_for_tags","file_name":"askbot/views/commands.py","commit_link":"github.com/ASKBOT/askbot-devel/commit/a676a86b6b7a5737d4da4f59f71e037406f88d29","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#24-966e998331fa","input":"def nav_path(request):\n \"\"\"Return current path as list of items with \"name\" and \"href\" members\n\n The href members are view_directory links for directories and view_log\n links for files, but are set to None when the link would point to\n the current view\"\"\"\n\n if not request.repos:\n return []\n\n is_dir = request.pathtype == vclib.DIR\n\n # add root item\n items = []\n root_item = _item(name=request.server.escape(request.repos.name), href=None)\n if request.path_parts or request.view_func is not view_directory:\n root_item.href = request.get_url(view_func=view_directory,\n where='', pathtype=vclib.DIR,\n params={}, escape=1)\n items.append(root_item)\n\n # add path part items\n path_parts = []\n for part in request.path_parts:\n path_parts.append(part)\n is_last = len(path_parts) == len(request.path_parts)\n\n item = _item(name=part, href=None)\n\n if not is_last or (is_dir and request.view_func is not view_directory):\n item.href = request.get_url(view_func=view_directory,\n where=_path_join(path_parts),\n pathtype=vclib.DIR,\n params={}, escape=1)\n elif not is_dir and request.view_func is not view_log:\n item.href = request.get_url(view_func=view_log,\n where=_path_join(path_parts),\n pathtype=vclib.FILE,\n params={}, escape=1)\n items.append(item)\n\n return items","target":"def nav_path(request):\n \"\"\"Return current path as list of items with \"name\" and \"href\" members\n\n The href members are view_directory links for directories and view_log\n links for files, but are set to None when the link would point to\n the current view\"\"\"\n\n if not request.repos:\n return []\n\n is_dir = request.pathtype == vclib.DIR\n\n # add root item\n items = []\n root_item = _item(name=request.server.escape(request.repos.name), href=None)\n if request.path_parts or request.view_func is not view_directory:\n root_item.href = request.get_url(view_func=view_directory,\n where='', pathtype=vclib.DIR,\n params={}, escape=1)\n items.append(root_item)\n\n # add path part items\n path_parts = []\n for part in request.path_parts:\n path_parts.append(part)\n is_last = len(path_parts) == len(request.path_parts)\n\n item = _item(name=request.server.escape(part), href=None)\n\n if not is_last or (is_dir and request.view_func is not view_directory):\n item.href = request.get_url(view_func=view_directory,\n where=_path_join(path_parts),\n pathtype=vclib.DIR,\n params={}, escape=1)\n elif not is_dir and request.view_func is not view_log:\n item.href = request.get_url(view_func=view_log,\n where=_path_join(path_parts),\n pathtype=vclib.FILE,\n params={}, escape=1)\n items.append(item)\n\n return items","lang":"python","vul_type":"cwe-079","target_token_count":332,"sven_meta":{"func_name":"nav_path","file_name":"lib/viewvc.py","commit_link":"github.com/viewvc/viewvc/commit/9dcfc7daa4c940992920d3b2fbd317da20e44aad","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#29-02244c7fdbeb","input":"void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent)\n{\n clear();\n m_torrent = torrent;\n downloaded_pieces->setTorrent(m_torrent);\n pieces_availability->setTorrent(m_torrent);\n if (!m_torrent) return;\n\n // Save path\n updateSavePath(m_torrent);\n // Hash\n hash_lbl->setText(m_torrent->hash());\n PropListModel->model()->clear();\n if (m_torrent->hasMetadata()) {\n // Creation date\n lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate));\n\n label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize()));\n\n // Comment\n comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment()));\n\n // URL seeds\n loadUrlSeeds();\n\n label_created_by_val->setText(m_torrent->creator());\n\n // List files in torrent\n PropListModel->model()->setupModelData(m_torrent->info());\n filesList->setExpanded(PropListModel->index(0, 0), true);\n\n // Load file priorities\n PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities());\n }\n // Load dynamic data\n loadDynamicData();\n}","target":"void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent)\n{\n clear();\n m_torrent = torrent;\n downloaded_pieces->setTorrent(m_torrent);\n pieces_availability->setTorrent(m_torrent);\n if (!m_torrent) return;\n\n // Save path\n updateSavePath(m_torrent);\n // Hash\n hash_lbl->setText(m_torrent->hash());\n PropListModel->model()->clear();\n if (m_torrent->hasMetadata()) {\n // Creation date\n lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate));\n\n label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize()));\n\n // Comment\n comment_text->setText(Utils::Misc::parseHtmlLinks(Utils::String::toHtmlEscaped(m_torrent->comment())));\n\n // URL seeds\n loadUrlSeeds();\n\n label_created_by_val->setText(Utils::String::toHtmlEscaped(m_torrent->creator()));\n\n // List files in torrent\n PropListModel->model()->setupModelData(m_torrent->info());\n filesList->setExpanded(PropListModel->index(0, 0), true);\n\n // Load file priorities\n PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities());\n }\n // Load dynamic data\n loadDynamicData();\n}","lang":"cpp","vul_type":"cwe-079","target_token_count":292,"sven_meta":{"func_name":"PropertiesWidget::loadTorrentInfos","file_name":"src/gui/properties/propertieswidget.cpp","commit_link":"github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#32-94da25c4c470","input":"@register.tag\n@basictag(takes_context=True)\ndef screenshotcommentcounts(context, screenshot):\n \"\"\"\n Returns a JSON array of current comments for a screenshot.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n text The text of the comment\n localdraft True if this is the current user's draft comment\n x The X location of the comment's region\n y The Y location of the comment's region\n w The width of the comment's region\n h The height of the comment's region\n =========== ==================================================\n \"\"\"\n comments = {}\n user = context.get('user', None)\n\n for comment in screenshot.comments.all():\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n position = '%dx%d+%d+%d' % (comment.w, comment.h, \\\n comment.x, comment.y)\n\n comments.setdefault(position, []).append({\n 'id': comment.id,\n 'text': comment.text,\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n 'url': comment.get_review_url(),\n 'localdraft' : review.user == user and \\\n not review.public,\n 'x' : comment.x,\n 'y' : comment.y,\n 'w' : comment.w,\n 'h' : comment.h,\n })\n\n return simplejson.dumps(comments)","target":"@register.tag\n@basictag(takes_context=True)\ndef screenshotcommentcounts(context, screenshot):\n \"\"\"\n Returns a JSON array of current comments for a screenshot.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n text The text of the comment\n localdraft True if this is the current user's draft comment\n x The X location of the comment's region\n y The Y location of the comment's region\n w The width of the comment's region\n h The height of the comment's region\n =========== ==================================================\n \"\"\"\n comments = {}\n user = context.get('user', None)\n\n for comment in screenshot.comments.all():\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n position = '%dx%d+%d+%d' % (comment.w, comment.h, \\\n comment.x, comment.y)\n\n comments.setdefault(position, []).append({\n 'id': comment.id,\n 'text': escape(comment.text),\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n 'url': comment.get_review_url(),\n 'localdraft' : review.user == user and \\\n not review.public,\n 'x' : comment.x,\n 'y' : comment.y,\n 'w' : comment.w,\n 'h' : comment.h,\n })\n\n return simplejson.dumps(comments)","lang":"python","vul_type":"cwe-079","target_token_count":333,"sven_meta":{"func_name":"screenshotcommentcounts","file_name":"reviewboard/reviews/templatetags/reviewtags.py","commit_link":"github.com/reviewboard/reviewboard/commit/7a0a9d94555502278534dedcf2d75e9fccce8c3d","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#34-ad88dc49ed96","input":"def get_list_context(context=None):\n\tlist_context = frappe._dict(\n\t\ttemplate = \"templates/includes/blog/blog.html\",\n\t\tget_list = get_blog_list,\n\t\thide_filters = True,\n\t\tchildren = get_children(),\n\t\t# show_search = True,\n\t\ttitle = _('Blog')\n\t)\n\n\tcategory = frappe.local.form_dict.blog_category or frappe.local.form_dict.category\n\tif category:\n\t\tcategory_title = get_blog_category(category)\n\t\tlist_context.sub_title = _(\"Posts filed under {0}\").format(category_title)\n\t\tlist_context.title = category_title\n\n\telif frappe.local.form_dict.blogger:\n\t\tblogger = frappe.db.get_value(\"Blogger\", {\"name\": frappe.local.form_dict.blogger}, \"full_name\")\n\t\tlist_context.sub_title = _(\"Posts by {0}\").format(blogger)\n\t\tlist_context.title = blogger\n\n\telif frappe.local.form_dict.txt:\n\t\tlist_context.sub_title = _('Filtered by \"{0}\"').format(frappe.local.form_dict.txt)\n\n\tif list_context.sub_title:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"},\n\t\t\t\t\t\t\t\t{\"name\": \"Blog\", \"route\": \"/blog\"}]\n\telse:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"}]\n\n\tlist_context.update(frappe.get_doc(\"Blog Settings\", \"Blog Settings\").as_dict(no_default_fields=True))\n\treturn list_context","target":"def get_list_context(context=None):\n\tlist_context = frappe._dict(\n\t\ttemplate = \"templates/includes/blog/blog.html\",\n\t\tget_list = get_blog_list,\n\t\thide_filters = True,\n\t\tchildren = get_children(),\n\t\t# show_search = True,\n\t\ttitle = _('Blog')\n\t)\n\n\tcategory = sanitize_html(frappe.local.form_dict.blog_category or frappe.local.form_dict.category)\n\tif category:\n\t\tcategory_title = get_blog_category(category)\n\t\tlist_context.sub_title = _(\"Posts filed under {0}\").format(category_title)\n\t\tlist_context.title = category_title\n\n\telif frappe.local.form_dict.blogger:\n\t\tblogger = frappe.db.get_value(\"Blogger\", {\"name\": frappe.local.form_dict.blogger}, \"full_name\")\n\t\tlist_context.sub_title = _(\"Posts by {0}\").format(blogger)\n\t\tlist_context.title = blogger\n\n\telif frappe.local.form_dict.txt:\n\t\tlist_context.sub_title = _('Filtered by \"{0}\"').format(sanitize_html(frappe.local.form_dict.txt))\n\n\tif list_context.sub_title:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"},\n\t\t\t\t\t\t\t\t{\"name\": \"Blog\", \"route\": \"/blog\"}]\n\telse:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"}]\n\n\tlist_context.update(frappe.get_doc(\"Blog Settings\", \"Blog Settings\").as_dict(no_default_fields=True))\n\treturn list_context","lang":"python","vul_type":"cwe-079","target_token_count":296,"sven_meta":{"func_name":"get_list_context","file_name":"frappe/website/doctype/blog_post/blog_post.py","commit_link":"github.com/omirajkar/bench_frappe/commit/2fa19c25066ed17478d683666895e3266936aee6","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#35-83e51d3d3dc7","input":" def mode_init(self, request):\n \"\"\"\n This is called by render_POST when the client requests an init\n mode operation (at startup)\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = request.args.get('csessid')[0]\n\n remote_addr = request.getClientIP()\n host_string = \"%s (%s:%s)\" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port)\n\n sess = AjaxWebClientSession()\n sess.client = self\n sess.init_session(\"ajax/comet\", remote_addr, self.sessionhandler)\n\n sess.csessid = csessid\n csession = _CLIENT_SESSIONS(session_key=sess.csessid)\n uid = csession and csession.get(\"webclient_authenticated_uid\", False)\n if uid:\n # the client session is already logged in\n sess.uid = uid\n sess.logged_in = True\n\n sess.sessionhandler.connect(sess)\n\n self.last_alive[csessid] = (time.time(), False)\n if not self.keep_alive:\n # the keepalive is not running; start it.\n self.keep_alive = LoopingCall(self._keepalive)\n self.keep_alive.start(_KEEPALIVE, now=False)\n\n return jsonify({'msg': host_string, 'csessid': csessid})","target":" def mode_init(self, request):\n \"\"\"\n This is called by render_POST when the client requests an init\n mode operation (at startup)\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = cgi.escape(request.args['csessid'][0])\n\n remote_addr = request.getClientIP()\n host_string = \"%s (%s:%s)\" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port)\n\n sess = AjaxWebClientSession()\n sess.client = self\n sess.init_session(\"ajax/comet\", remote_addr, self.sessionhandler)\n\n sess.csessid = csessid\n csession = _CLIENT_SESSIONS(session_key=sess.csessid)\n uid = csession and csession.get(\"webclient_authenticated_uid\", False)\n if uid:\n # the client session is already logged in\n sess.uid = uid\n sess.logged_in = True\n\n sess.sessionhandler.connect(sess)\n\n self.last_alive[csessid] = (time.time(), False)\n if not self.keep_alive:\n # the keepalive is not running; start it.\n self.keep_alive = LoopingCall(self._keepalive)\n self.keep_alive.start(_KEEPALIVE, now=False)\n\n return jsonify({'msg': host_string, 'csessid': csessid})","lang":"python","vul_type":"cwe-079","target_token_count":279,"sven_meta":{"func_name":"mode_init","file_name":"evennia/server/portal/webclient_ajax.py","commit_link":"github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#36-cc81169c84c4","input":"def handle_file(u: Profile, headline: str, category: str, text: str, file):\n m: Media = Media()\n upload_base_path: str = 'uploads/' + str(date.today().year)\n high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path):\n os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path)\n with open(high_res_file_name, 'wb+') as destination:\n for chunk in file.chunks():\n destination.write(chunk)\n # TODO crop image\n original = Image.open(high_res_file_name)\n width, height = original.size\n diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2))\n width /= diameter\n height /= diameter\n width *= IMAGE_SCALE\n height *= IMAGE_SCALE\n cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS)\n cropped.save(low_res_file_name)\n m.text = text\n m.cachedText = compile_markdown(text)\n m.category = category\n m.highResFile = \"/\" + high_res_file_name\n m.lowResFile = \"/\" + low_res_file_name\n m.headline = headline\n m.save()\n mu: MediaUpload = MediaUpload()\n mu.UID = u\n mu.MID = m\n mu.save()\n logging.info(\"Uploaded file '\" + str(file.name) + \"' and cropped it. The resulting PK is \" + str(m.pk))","target":"def handle_file(u: Profile, headline: str, category: str, text: str, file):\n m: Media = Media()\n upload_base_path: str = 'uploads/' + str(date.today().year)\n high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path):\n os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path)\n with open(high_res_file_name, 'wb+') as destination:\n for chunk in file.chunks():\n destination.write(chunk)\n # TODO crop image\n original = Image.open(high_res_file_name)\n width, height = original.size\n diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2))\n width /= diameter\n height /= diameter\n width *= IMAGE_SCALE\n height *= IMAGE_SCALE\n cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS)\n cropped.save(low_res_file_name)\n m.text = escape(text)\n m.cachedText = compile_markdown(escape(text))\n m.category = escape(category)\n m.highResFile = \"/\" + high_res_file_name\n m.lowResFile = \"/\" + low_res_file_name\n m.headline = escape(headline)\n m.save()\n mu: MediaUpload = MediaUpload()\n mu.UID = u\n mu.MID = m\n mu.save()\n logging.info(\"Uploaded file '\" + str(file.name) + \"' and cropped it. The resulting PK is \" + str(m.pk))","lang":"python","vul_type":"cwe-079","target_token_count":369,"sven_meta":{"func_name":"handle_file","file_name":"c3shop/frontpage/management/mediatools/media_actions.py","commit_link":"github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#37-b4fe315c51a8","input":"@register.tag\n@basictag(takes_context=True)\ndef commentcounts(context, filediff, interfilediff=None):\n \"\"\"\n Returns a JSON array of current comments for a filediff, sorted by\n line number.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n comment_id The ID of the comment\n text The text of the comment\n line The first line number\n num_lines The number of lines this comment spans\n user A dictionary containing \"username\" and \"name\" keys\n for the user\n url The URL to the comment\n localdraft True if this is the current user's draft comment\n =========== ==================================================\n \"\"\"\n comment_dict = {}\n user = context.get('user', None)\n\n if interfilediff:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff=interfilediff)\n else:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff__isnull=True)\n\n for comment in query:\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n key = (comment.first_line, comment.num_lines)\n\n comment_dict.setdefault(key, []).append({\n 'comment_id': comment.id,\n 'text': comment.text,\n 'line': comment.first_line,\n 'num_lines': comment.num_lines,\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n #'timestamp': comment.timestamp,\n 'url': comment.get_review_url(),\n 'localdraft': review.user == user and \\\n not review.public,\n })\n\n comments_array = []\n\n for key, value in comment_dict.iteritems():\n comments_array.append({\n 'linenum': key[0],\n 'num_lines': key[1],\n 'comments': value,\n })\n\n comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or\n cmp(x['num_lines'], y['num_lines'])))\n\n return simplejson.dumps(comments_array)","target":"@register.tag\n@basictag(takes_context=True)\ndef commentcounts(context, filediff, interfilediff=None):\n \"\"\"\n Returns a JSON array of current comments for a filediff, sorted by\n line number.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n comment_id The ID of the comment\n text The text of the comment\n line The first line number\n num_lines The number of lines this comment spans\n user A dictionary containing \"username\" and \"name\" keys\n for the user\n url The URL to the comment\n localdraft True if this is the current user's draft comment\n =========== ==================================================\n \"\"\"\n comment_dict = {}\n user = context.get('user', None)\n\n if interfilediff:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff=interfilediff)\n else:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff__isnull=True)\n\n for comment in query:\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n key = (comment.first_line, comment.num_lines)\n\n comment_dict.setdefault(key, []).append({\n 'comment_id': comment.id,\n 'text': escape(comment.text),\n 'line': comment.first_line,\n 'num_lines': comment.num_lines,\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n #'timestamp': comment.timestamp,\n 'url': comment.get_review_url(),\n 'localdraft': review.user == user and \\\n not review.public,\n })\n\n comments_array = []\n\n for key, value in comment_dict.iteritems():\n comments_array.append({\n 'linenum': key[0],\n 'num_lines': key[1],\n 'comments': value,\n })\n\n comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or\n cmp(x['num_lines'], y['num_lines'])))\n\n return simplejson.dumps(comments_array)","lang":"python","vul_type":"cwe-079","target_token_count":470,"sven_meta":{"func_name":"commentcounts","file_name":"reviewboard/reviews/templatetags/reviewtags.py","commit_link":"github.com/reviewboard/reviewboard/commit/7a0a9d94555502278534dedcf2d75e9fccce8c3d","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-079#41-a1231ab75c3a","input":"def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):\n \"\"\"\n This function is used to alter the reservation beeing build inside\n a cookie. This function automatically crafts the required response.\n \"\"\"\n js_string: str = \"\"\n r: GroupReservation = None\n u: Profile = get_current_user(request)\n forward_url: str = default_foreward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n if \"srid\" in request.GET:\n if not request.GET.get(\"rid\"):\n return HttpResponseRedirect(\"/admin?error=missing%20primary%20reservation%20id\")\n srid: int = int(request.GET[\"srid\"])\n sr: SubReservation = None\n if srid == 0:\n sr = SubReservation()\n else:\n sr = SubReservation.objects.get(id=srid)\n if request.POST.get(\"notes\"):\n sr.notes = request.POST[\"notes\"]\n else:\n sr.notes = \" \"\n sr.primary_reservation = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n sr.save()\n print(request.POST)\n print(sr.notes)\n return HttpResponseRedirect(\"/admin/reservations/edit?rid=\" + str(int(request.GET[\"rid\"])) + \"&srid=\" + str(sr.id))\n if \"rid\" in request.GET:\n # update reservation\n r = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n elif u.number_of_allowed_reservations > GroupReservation.objects.all().filter(createdByUser=u).count():\n r = GroupReservation()\n r.createdByUser = u\n r.ready = False\n r.open = True\n r.pickupDate = datetime.datetime.now()\n else:\n return HttpResponseRedirect(\"/admin?error=Too%20Many%20reservations\")\n if request.POST.get(\"notes\"):\n r.notes = request.POST[\"notes\"]\n if request.POST.get(\"contact\"):\n r.responsiblePerson = str(request.POST[\"contact\"])\n if (r.createdByUser == u or o.rights > 1) and not r.submitted:\n r.save()\n else:\n return HttpResponseRedirect(\"/admin?error=noyb\")\n response: HttpResponseRedirect = HttpResponseRedirect(forward_url + \"?rid=\" + str(r.id))\n return response","target":"def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):\n \"\"\"\n This function is used to alter the reservation beeing build inside\n a cookie. This function automatically crafts the required response.\n \"\"\"\n js_string: str = \"\"\n r: GroupReservation = None\n u: Profile = get_current_user(request)\n forward_url: str = default_foreward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n if \"srid\" in request.GET:\n if not request.GET.get(\"rid\"):\n return HttpResponseRedirect(\"/admin?error=missing%20primary%20reservation%20id\")\n srid: int = int(request.GET[\"srid\"])\n sr: SubReservation = None\n if srid == 0:\n sr = SubReservation()\n else:\n sr = SubReservation.objects.get(id=srid)\n if request.POST.get(\"notes\"):\n sr.notes = escape(request.POST[\"notes\"])\n else:\n sr.notes = \" \"\n sr.primary_reservation = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n sr.save()\n print(request.POST)\n print(sr.notes)\n return HttpResponseRedirect(\"/admin/reservations/edit?rid=\" + str(int(request.GET[\"rid\"])) + \"&srid=\" + str(sr.id))\n if \"rid\" in request.GET:\n # update reservation\n r = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n elif u.number_of_allowed_reservations > GroupReservation.objects.all().filter(createdByUser=u).count():\n r = GroupReservation()\n r.createdByUser = u\n r.ready = False\n r.open = True\n r.pickupDate = datetime.datetime.now()\n else:\n return HttpResponseRedirect(\"/admin?error=Too%20Many%20reservations\")\n if request.POST.get(\"notes\"):\n r.notes = escape(request.POST[\"notes\"])\n if request.POST.get(\"contact\"):\n r.responsiblePerson = escape(str(request.POST[\"contact\"]))\n if (r.createdByUser == u or o.rights > 1) and not r.submitted:\n r.save()\n else:\n return HttpResponseRedirect(\"/admin?error=noyb\")\n response: HttpResponseRedirect = HttpResponseRedirect(forward_url + \"?rid=\" + str(r.id))\n return response","lang":"python","vul_type":"cwe-079","target_token_count":482,"sven_meta":{"func_name":"manipulate_reservation_action","file_name":"c3shop/frontpage/management/reservation_actions.py","commit_link":"github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600","source_cwe_file":"cwe-079.jsonl"}}
{"problem_id":"cwe-190#8-106070f03b78","input":"UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) {\n if(!isWritable() || srcLength == 0 || srcChars == NULL) {\n return *this;\n }\n\n // Perform all remaining operations relative to srcChars + srcStart.\n // From this point forward, do not use srcStart.\n srcChars += srcStart;\n\n if(srcLength < 0) {\n // get the srcLength if necessary\n if((srcLength = u_strlen(srcChars)) == 0) {\n return *this;\n }\n }\n\n int32_t oldLength = length();\n int32_t newLength = oldLength + srcLength;\n\n // Check for append onto ourself\n const UChar* oldArray = getArrayStart();\n if (isBufferWritable() &&\n oldArray < srcChars + srcLength &&\n srcChars < oldArray + oldLength) {\n // Copy into a new UnicodeString and start over\n UnicodeString copy(srcChars, srcLength);\n if (copy.isBogus()) {\n setToBogus();\n return *this;\n }\n return doAppend(copy.getArrayStart(), 0, srcLength);\n }\n\n // optimize append() onto a large-enough, owned string\n if((newLength <= getCapacity() && isBufferWritable()) ||\n cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {\n UChar *newArray = getArrayStart();\n // Do not copy characters when\n // UChar *buffer=str.getAppendBuffer(...);\n // is followed by\n // str.append(buffer, length);\n // or\n // str.appendString(buffer, length)\n // or similar.\n if(srcChars != newArray + oldLength) {\n us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);\n }\n setLength(newLength);\n }\n return *this;\n}","target":"UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) {\n if(!isWritable() || srcLength == 0 || srcChars == NULL) {\n return *this;\n }\n\n // Perform all remaining operations relative to srcChars + srcStart.\n // From this point forward, do not use srcStart.\n srcChars += srcStart;\n\n if(srcLength < 0) {\n // get the srcLength if necessary\n if((srcLength = u_strlen(srcChars)) == 0) {\n return *this;\n }\n }\n\n int32_t oldLength = length();\n int32_t newLength;\n if (uprv_add32_overflow(oldLength, srcLength, &newLength)) {\n setToBogus();\n return *this;\n }\n\n // Check for append onto ourself\n const UChar* oldArray = getArrayStart();\n if (isBufferWritable() &&\n oldArray < srcChars + srcLength &&\n srcChars < oldArray + oldLength) {\n // Copy into a new UnicodeString and start over\n UnicodeString copy(srcChars, srcLength);\n if (copy.isBogus()) {\n setToBogus();\n return *this;\n }\n return doAppend(copy.getArrayStart(), 0, srcLength);\n }\n\n // optimize append() onto a large-enough, owned string\n if((newLength <= getCapacity() && isBufferWritable()) ||\n cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {\n UChar *newArray = getArrayStart();\n // Do not copy characters when\n // UChar *buffer=str.getAppendBuffer(...);\n // is followed by\n // str.append(buffer, length);\n // or\n // str.appendString(buffer, length)\n // or similar.\n if(srcChars != newArray + oldLength) {\n us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);\n }\n setLength(newLength);\n }\n return *this;\n}","lang":"cpp","vul_type":"cwe-190","target_token_count":449,"sven_meta":{"func_name":"UnicodeString::doAppend","file_name":"icu4c/source/common/unistr.cpp","commit_link":"github.com/unicode-org/icu/commit/b7d08bc04a4296982fcef8b6b8a354a9e4e7afca","source_cwe_file":"cwe-190.jsonl"}}
{"problem_id":"cwe-190#15-67865420feee","input":"static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)\n{\n\tstruct uvesafb_pal_entry *entries;\n\tint shift = 16 - dac_width;\n\tint i, err = 0;\n\n\tif (info->var.bits_per_pixel == 8) {\n\t\tif (cmap->start + cmap->len > info->cmap.start +\n\t\t info->cmap.len || cmap->start < info->cmap.start)\n\t\t\treturn -EINVAL;\n\n\t\tentries = kmalloc(sizeof(*entries) * cmap->len, GFP_KERNEL);\n\t\tif (!entries)\n\t\t\treturn -ENOMEM;\n\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\tentries[i].red = cmap->red[i] >> shift;\n\t\t\tentries[i].green = cmap->green[i] >> shift;\n\t\t\tentries[i].blue = cmap->blue[i] >> shift;\n\t\t\tentries[i].pad = 0;\n\t\t}\n\t\terr = uvesafb_setpalette(entries, cmap->len, cmap->start, info);\n\t\tkfree(entries);\n\t} else {\n\t\t/*\n\t\t * For modes with bpp > 8, we only set the pseudo palette in\n\t\t * the fb_info struct. We rely on uvesafb_setcolreg to do all\n\t\t * sanity checking.\n\t\t */\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\terr |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],\n\t\t\t\t\t\tcmap->green[i], cmap->blue[i],\n\t\t\t\t\t\t0, info);\n\t\t}\n\t}\n\treturn err;\n}","target":"static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)\n{\n\tstruct uvesafb_pal_entry *entries;\n\tint shift = 16 - dac_width;\n\tint i, err = 0;\n\n\tif (info->var.bits_per_pixel == 8) {\n\t\tif (cmap->start + cmap->len > info->cmap.start +\n\t\t info->cmap.len || cmap->start < info->cmap.start)\n\t\t\treturn -EINVAL;\n\n\t\tentries = kmalloc_array(cmap->len, sizeof(*entries),\n\t\t\t\t\tGFP_KERNEL);\n\t\tif (!entries)\n\t\t\treturn -ENOMEM;\n\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\tentries[i].red = cmap->red[i] >> shift;\n\t\t\tentries[i].green = cmap->green[i] >> shift;\n\t\t\tentries[i].blue = cmap->blue[i] >> shift;\n\t\t\tentries[i].pad = 0;\n\t\t}\n\t\terr = uvesafb_setpalette(entries, cmap->len, cmap->start, info);\n\t\tkfree(entries);\n\t} else {\n\t\t/*\n\t\t * For modes with bpp > 8, we only set the pseudo palette in\n\t\t * the fb_info struct. We rely on uvesafb_setcolreg to do all\n\t\t * sanity checking.\n\t\t */\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\terr |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],\n\t\t\t\t\t\tcmap->green[i], cmap->blue[i],\n\t\t\t\t\t\t0, info);\n\t\t}\n\t}\n\treturn err;\n}","lang":"c","vul_type":"cwe-190","target_token_count":355,"sven_meta":{"func_name":"uvesafb_setcmap","file_name":"drivers/video/fbdev/uvesafb.c","commit_link":"github.com/torvalds/linux/commit/9f645bcc566a1e9f921bdae7528a01ced5bc3713","source_cwe_file":"cwe-190.jsonl"}}
{"problem_id":"cwe-190#17-d189ca95612d","input":"bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid)\n{\n\tint frameSize = afGetVirtualFrameSize(infile, trackid, 1);\n\n\tconst int kBufferFrameCount = 65536;\n\tvoid *buffer = malloc(kBufferFrameCount * frameSize);\n\n\tAFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK);\n\tAFframecount totalFramesWritten = 0;\n\n\tbool success = true;\n\n\twhile (totalFramesWritten < totalFrames)\n\t{\n\t\tAFframecount framesToRead = totalFrames - totalFramesWritten;\n\t\tif (framesToRead > kBufferFrameCount)\n\t\t\tframesToRead = kBufferFrameCount;\n\n\t\tAFframecount framesRead = afReadFrames(infile, trackid, buffer,\n\t\t\tframesToRead);\n\n\t\tif (framesRead < framesToRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad read of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tAFframecount framesWritten = afWriteFrames(outfile, trackid, buffer,\n\t\t\tframesRead);\n\n\t\tif (framesWritten < framesRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad write of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\ttotalFramesWritten += framesWritten;\n\t}\n\n\tfree(buffer);\n\n\treturn success;\n}","target":"bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid)\n{\n\tint frameSize = afGetVirtualFrameSize(infile, trackid, 1);\n\n\tint kBufferFrameCount = 65536;\n\tint bufferSize;\n\twhile (multiplyCheckOverflow(kBufferFrameCount, frameSize, &bufferSize))\n\t\tkBufferFrameCount /= 2;\n\tvoid *buffer = malloc(bufferSize);\n\n\tAFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK);\n\tAFframecount totalFramesWritten = 0;\n\n\tbool success = true;\n\n\twhile (totalFramesWritten < totalFrames)\n\t{\n\t\tAFframecount framesToRead = totalFrames - totalFramesWritten;\n\t\tif (framesToRead > kBufferFrameCount)\n\t\t\tframesToRead = kBufferFrameCount;\n\n\t\tAFframecount framesRead = afReadFrames(infile, trackid, buffer,\n\t\t\tframesToRead);\n\n\t\tif (framesRead < framesToRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad read of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tAFframecount framesWritten = afWriteFrames(outfile, trackid, buffer,\n\t\t\tframesRead);\n\n\t\tif (framesWritten < framesRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad write of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\ttotalFramesWritten += framesWritten;\n\t}\n\n\tfree(buffer);\n\n\treturn success;\n}","lang":"c","vul_type":"cwe-190","target_token_count":310,"sven_meta":{"func_name":"copyaudiodata","file_name":"sfcommands/sfconvert.c","commit_link":"github.com/antlarr/audiofile/commit/7d65f89defb092b63bcbc5d98349fb222ca73b3c","source_cwe_file":"cwe-190.jsonl"}}
{"problem_id":"cwe-190#23-d91a1a46f304","input":"String StringUtil::Implode(const Variant& items, const String& delim,\n const bool checkIsContainer /* = true */) {\n if (checkIsContainer && !isContainer(items)) {\n throw_param_is_not_container();\n }\n int size = getContainerSize(items);\n if (size == 0) return empty_string();\n\n req::vector<String> sitems;\n sitems.reserve(size);\n int len = 0;\n int lenDelim = delim.size();\n for (ArrayIter iter(items); iter; ++iter) {\n sitems.emplace_back(iter.second().toString());\n len += sitems.back().size() + lenDelim;\n }\n len -= lenDelim; // always one delimiter less than count of items\n assert(sitems.size() == size);\n\n String s = String(len, ReserveString);\n char *buffer = s.mutableData();\n const char *sdelim = delim.data();\n char *p = buffer;\n String &init_str = sitems[0];\n int init_len = init_str.size();\n memcpy(p, init_str.data(), init_len);\n p += init_len;\n for (int i = 1; i < size; i++) {\n String &item = sitems[i];\n memcpy(p, sdelim, lenDelim);\n p += lenDelim;\n int lenItem = item.size();\n memcpy(p, item.data(), lenItem);\n p += lenItem;\n }\n assert(p - buffer == len);\n s.setSize(len);\n return s;\n}","target":"String StringUtil::Implode(const Variant& items, const String& delim,\n const bool checkIsContainer /* = true */) {\n if (checkIsContainer && !isContainer(items)) {\n throw_param_is_not_container();\n }\n int size = getContainerSize(items);\n if (size == 0) return empty_string();\n\n req::vector<String> sitems;\n sitems.reserve(size);\n size_t len = 0;\n size_t lenDelim = delim.size();\n for (ArrayIter iter(items); iter; ++iter) {\n sitems.emplace_back(iter.second().toString());\n len += sitems.back().size() + lenDelim;\n }\n len -= lenDelim; // always one delimiter less than count of items\n assert(sitems.size() == size);\n\n String s = String(len, ReserveString);\n char *buffer = s.mutableData();\n const char *sdelim = delim.data();\n char *p = buffer;\n String &init_str = sitems[0];\n int init_len = init_str.size();\n memcpy(p, init_str.data(), init_len);\n p += init_len;\n for (int i = 1; i < size; i++) {\n String &item = sitems[i];\n memcpy(p, sdelim, lenDelim);\n p += lenDelim;\n int lenItem = item.size();\n memcpy(p, item.data(), lenItem);\n p += lenItem;\n }\n assert(p - buffer == len);\n s.setSize(len);\n return s;\n}","lang":"cpp","vul_type":"cwe-190","target_token_count":330,"sven_meta":{"func_name":"HPHP::StringUtil::Implode","file_name":"hphp/runtime/base/string-util.cpp","commit_link":"github.com/facebook/hhvm/commit/2c9a8fcc73a151608634d3e712973d192027c271","source_cwe_file":"cwe-190.jsonl"}}