cwe,func_name,func_src_before,func_src_after,line_changes,char_changes,commit_link,file_name,vul_type,num_tokens cwe-089,analyze_scene," def analyze_scene(self, scene): base_urls = scene.get_base_urls() users = scene.get_users() name = scene.get_name() LOG.info('found the following users for scene {}: {}'.format(name, users)) # This scene might have one user who always posts the brackets on their challonge account for user in users: # Have we analyzed this user before? sql = ""SELECT * FROM user_analyzed WHERE user='{}';"".format(user) results = self.db.exec(sql) # Did we have any matches in the database? if len(results) > 0: # We have analyzed this user before. Just grab one page of brackets to see if there have been any new tournaments # eg, just look at /users/christmasmike?page=1 instead of all the pages that exist most_recent_page = bracket_utils.get_brackets_from_user(user, pages=1) for bracket in most_recent_page: LOG.info('here are the brackets from the most recent page of user {}: {}'.format(user, most_recent_page)) # This user has already been analyzed, there's a good chance this bracket has been analyzed also sql = ""SELECT * FROM user_analyzed WHERE url='{}' AND user='{}';"".format(bracket, user) results = self.db.exec(sql) if len(results) == 0: # This is a new bracket that must have been published in the last hour or so LOG.info('found this url from a user: {} {}'.format(bracket, user)) display_name = bracket_utils.get_display_base(bracket) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(bracket, name, display_name) # mark this bracket as analyzed sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES ('{}', '{}', '{}');"".format(bracket, user, name) self.db.exec(sql) # Tweet that we found a new bracket msg = ""Found new {} bracket: {}"".format(name, bracket) tweet(msg) else: LOG.info('url {} is not new for user {}'.format(bracket, user)) else: # This is a new user, analyze all brackets user_urls = bracket_utils.get_brackets_from_user(user) for url in user_urls: LOG.info('found this url from a user: {} {}'.format(url, user)) display_name = bracket_utils.get_display_base(url) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(url, name, display_name) # mark this bracket as analyzed sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES ('{}', '{}', '{}');"".format(url, user, name) self.db.exec(sql) LOG.info('done with user {}'.format(user)) # This scene might always call their brackets the same thing, eg weekly1, weekly2, weekly3 etc for base_url in base_urls: # attempt to load this data from the database LOG.info('About to start this analysis thread for scene {}'.format(scene.get_name())) sql = ""SELECT first,last FROM valids WHERE base_url = '"" + str(base_url) + ""';"" result = self.db.exec(sql) has_results = len(result) > 0 # Did we find a match in the database? if has_results: LOG.info(""validURLs found values in the database"" + str(result)) first = result[0][0] last = result[0][1] # Check for a new valid URL new_last = bracket_utils._get_last_valid_url(base_url, last-1) if not new_last == last: if new_last - last > 5: with open(""DEBUGOUTPUT.txt"", 'a') as f: f.write(""[validURLs.py:55]: found a SHIT TON of new tournaments for bracket: {}"".format(base_url)) else: bracket = base_url.replace('###', str(new_last)) LOG.info('Found new bracket: {}'.format(bracket)) msg = ""Found new bracket: {}"".format(bracket) tweet(msg) # If there's been a new last, update the database sql = ""UPDATE valids SET last="" + str(new_last) + "" where base_url = '""+str(base_url)+""';"" self.db.exec(sql) # Analyze each of these new brackets for i in range(last+1, new_last+1): # Since this URL is new, we have to process the data bracket = base_url.replace('###', str(i)) # Create the display name for this bracket # Eg challonge.com/NP9ATX54 -> NP9 54 display_name = bracket_utils.get_display_base(bracket, counter=i) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(bracket, name, display_name, new_bracket=True) else: # We need to create first and last from scratch first = bracket_utils._get_first_valid_url(base_url) last = bracket_utils._get_last_valid_url(base_url, first) # This is new data, we need to put it into the db sql = ""INSERT INTO valids (base_url, first, last, scene) VALUES ("" sql += ""'""+str(base_url)+""', ""+str(first)+ "", ""+str(last)+"", '""+str(name)+""');"" self.db.exec(sql) for i in range(first, last+1): bracket = base_url.replace('###', str(i)) # Create the display name for this bracket # Eg challonge.com/NP9ATX54 -> NP9 54 display_name = bracket_utils.get_display_base(bracket, counter=i) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(bracket, name, display_name) # Calculate ranks after each tournament so we can see how players are progressing if not analyzed_scenes and should_tweet: tweet('About to start ranking for scene {}'.format(name)) self.data_processor.check_and_update_ranks(name)"," def analyze_scene(self, scene): base_urls = scene.get_base_urls() users = scene.get_users() name = scene.get_name() LOG.info('found the following users for scene {}: {}'.format(name, users)) # This scene might have one user who always posts the brackets on their challonge account for user in users: # Have we analyzed this user before? sql = ""SELECT * FROM user_analyzed WHERE user='{user}';"" args = {'user': user} results = self.db.exec(sql, args) # Did we have any matches in the database? if len(results) > 0: # We have analyzed this user before. Just grab one page of brackets to see if there have been any new tournaments # eg, just look at /users/christmasmike?page=1 instead of all the pages that exist most_recent_page = bracket_utils.get_brackets_from_user(user, pages=1) for bracket in most_recent_page: LOG.info('here are the brackets from the most recent page of user {}: {}'.format(user, most_recent_page)) # This user has already been analyzed, there's a good chance this bracket has been analyzed also sql = ""SELECT * FROM user_analyzed WHERE url='{bracket}' AND user='{user}';"" args = {'bracket': bracket, 'user': user} results = self.db.exec(sql, args) if len(results) == 0: # This is a new bracket that must have been published in the last hour or so LOG.info('found this url from a user: {} {}'.format(bracket, user)) display_name = bracket_utils.get_display_base(bracket) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(bracket, name, display_name) # mark this bracket as analyzed sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES ('{bracket}', '{user}', '{name}');"" args = {'bracket': bracket, 'user':user, 'name':name} self.db.exec(sql, args) # Tweet that we found a new bracket msg = ""Found new {} bracket: {}"".format(name, bracket) tweet(msg) else: LOG.info('url {} is not new for user {}'.format(bracket, user)) else: # This is a new user, analyze all brackets user_urls = bracket_utils.get_brackets_from_user(user) for url in user_urls: LOG.info('found this url from a user: {} {}'.format(url, user)) display_name = bracket_utils.get_display_base(url) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(url, name, display_name) # mark this bracket as analyzed sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES ('{url}', '{user}', '{name}');"" args = {'url': url, 'user':user, 'name':name} self.db.exec(sql, args) LOG.info('done with user {}'.format(user)) # This scene might always call their brackets the same thing, eg weekly1, weekly2, weekly3 etc for base_url in base_urls: # attempt to load this data from the database LOG.info('About to start this analysis thread for scene {}'.format(scene.get_name())) sql = ""SELECT first,last FROM valids WHERE base_url = '{base_url}';"" args = {'base_url': base_url} result = self.db.exec(sql, args) has_results = len(result) > 0 # Did we find a match in the database? if has_results: LOG.info(""validURLs found values in the database"" + str(result)) first = result[0][0] last = result[0][1] # Check for a new valid URL new_last = bracket_utils._get_last_valid_url(base_url, last-1) if not new_last == last: if new_last - last > 5: with open(""DEBUGOUTPUT.txt"", 'a') as f: f.write(""[validURLs.py:55]: found a SHIT TON of new tournaments for bracket: {}"".format(base_url)) else: bracket = base_url.replace('###', str(new_last)) LOG.info('Found new bracket: {}'.format(bracket)) msg = ""Found new bracket: {}"".format(bracket) tweet(msg) # If there's been a new last, update the database sql = ""UPDATE valids SET last={new_last} where base_url='{base_url}';"" args = {'new_last': new_last, 'base_url': base_url} self.db.exec(sql, args) # Analyze each of these new brackets for i in range(last+1, new_last+1): # Since this URL is new, we have to process the data bracket = base_url.replace('###', str(i)) # Create the display name for this bracket # Eg challonge.com/NP9ATX54 -> NP9 54 display_name = bracket_utils.get_display_base(bracket, counter=i) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(bracket, name, display_name, new_bracket=True) else: # We need to create first and last from scratch first = bracket_utils._get_first_valid_url(base_url) last = bracket_utils._get_last_valid_url(base_url, first) # This is new data, we need to put it into the db sql = ""INSERT INTO valids (base_url, first, last, scene) VALUES ('{base_url}', '{first}', '{last}', '{name}');"" args = {'base_url': base_url, 'first': first, 'last': last, 'name': name} self.db.exec(sql, args) for i in range(first, last+1): bracket = base_url.replace('###', str(i)) # Create the display name for this bracket # Eg challonge.com/NP9ATX54 -> NP9 54 display_name = bracket_utils.get_display_base(bracket, counter=i) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue self.data_processor.process(bracket, name, display_name) # Calculate ranks after each tournament so we can see how players are progressing if not analyzed_scenes and should_tweet: tweet('About to start ranking for scene {}'.format(name)) self.data_processor.check_and_update_ranks(name)","{'deleted': [{'line_no': 10, 'char_start': 402, 'char_end': 480, 'line': ' sql = ""SELECT * FROM user_analyzed WHERE user=\'{}\';"".format(user)\n'}, {'line_no': 11, 'char_start': 480, 'char_end': 520, 'line': ' results = self.db.exec(sql)\n'}, {'line_no': 21, 'char_start': 1217, 'char_end': 1325, 'line': ' sql = ""SELECT * FROM user_analyzed WHERE url=\'{}\' AND user=\'{}\';"".format(bracket, user)\n'}, {'line_no': 22, 'char_start': 1325, 'char_end': 1373, 'line': ' results = self.db.exec(sql)\n'}, {'line_no': 36, 'char_start': 2156, 'char_end': 2288, 'line': ' sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES (\'{}\', \'{}\', \'{}\');"".format(bracket, user, name)\n'}, {'line_no': 37, 'char_start': 2288, 'char_end': 2330, 'line': ' self.db.exec(sql)\n'}, {'line_no': 58, 'char_start': 3400, 'char_end': 3524, 'line': ' sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES (\'{}\', \'{}\', \'{}\');"".format(url, user, name)\n'}, {'line_no': 59, 'char_start': 3524, 'char_end': 3562, 'line': ' self.db.exec(sql)\n'}, {'line_no': 68, 'char_start': 3918, 'char_end': 4010, 'line': ' sql = ""SELECT first,last FROM valids WHERE base_url = \'"" + str(base_url) + ""\';""\n'}, {'line_no': 69, 'char_start': 4010, 'char_end': 4049, 'line': ' result = self.db.exec(sql)\n'}, {'line_no': 93, 'char_start': 5077, 'char_end': 5188, 'line': ' sql = ""UPDATE valids SET last="" + str(new_last) + "" where base_url = \'""+str(base_url)+""\';""\n'}, {'line_no': 94, 'char_start': 5188, 'char_end': 5226, 'line': ' self.db.exec(sql)\n'}, {'line_no': 117, 'char_start': 6425, 'char_end': 6508, 'line': ' sql = ""INSERT INTO valids (base_url, first, last, scene) VALUES (""\n'}, {'line_no': 118, 'char_start': 6508, 'char_end': 6604, 'line': ' sql += ""\'""+str(base_url)+""\', ""+str(first)+ "", ""+str(last)+"", \'""+str(name)+""\');""\n'}, {'line_no': 119, 'char_start': 6604, 'char_end': 6638, 'line': ' self.db.exec(sql)\n'}], 'added': [{'line_no': 10, 'char_start': 402, 'char_end': 471, 'line': ' sql = ""SELECT * FROM user_analyzed WHERE user=\'{user}\';""\n'}, {'line_no': 11, 'char_start': 471, 'char_end': 505, 'line': "" args = {'user': user}\n""}, {'line_no': 12, 'char_start': 505, 'char_end': 551, 'line': ' results = self.db.exec(sql, args)\n'}, {'line_no': 22, 'char_start': 1248, 'char_end': 1345, 'line': ' sql = ""SELECT * FROM user_analyzed WHERE url=\'{bracket}\' AND user=\'{user}\';""\n'}, {'line_no': 23, 'char_start': 1345, 'char_end': 1407, 'line': "" args = {'bracket': bracket, 'user': user}\n""}, {'line_no': 24, 'char_start': 1407, 'char_end': 1461, 'line': ' results = self.db.exec(sql, args)\n'}, {'line_no': 38, 'char_start': 2244, 'char_end': 2363, 'line': ' sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES (\'{bracket}\', \'{user}\', \'{name}\');""\n'}, {'line_no': 39, 'char_start': 2363, 'char_end': 2441, 'line': "" args = {'bracket': bracket, 'user':user, 'name':name}\n""}, {'line_no': 40, 'char_start': 2441, 'char_end': 2489, 'line': ' self.db.exec(sql, args)\n'}, {'line_no': 61, 'char_start': 3559, 'char_end': 3670, 'line': ' sql = ""INSERT INTO user_analyzed (url, user, scene) VALUES (\'{url}\', \'{user}\', \'{name}\');""\n'}, {'line_no': 62, 'char_start': 3670, 'char_end': 3736, 'line': "" args = {'url': url, 'user':user, 'name':name}\n""}, {'line_no': 63, 'char_start': 3736, 'char_end': 3780, 'line': ' self.db.exec(sql, args)\n'}, {'line_no': 72, 'char_start': 4136, 'char_end': 4217, 'line': ' sql = ""SELECT first,last FROM valids WHERE base_url = \'{base_url}\';""\n'}, {'line_no': 73, 'char_start': 4217, 'char_end': 4259, 'line': "" args = {'base_url': base_url}\n""}, {'line_no': 74, 'char_start': 4259, 'char_end': 4304, 'line': ' result = self.db.exec(sql, args)\n'}, {'line_no': 98, 'char_start': 5332, 'char_end': 5423, 'line': ' sql = ""UPDATE valids SET last={new_last} where base_url=\'{base_url}\';""\n'}, {'line_no': 99, 'char_start': 5423, 'char_end': 5495, 'line': "" args = {'new_last': new_last, 'base_url': base_url}\n""}, {'line_no': 100, 'char_start': 5495, 'char_end': 5539, 'line': ' self.db.exec(sql, args)\n'}, {'line_no': 123, 'char_start': 6738, 'char_end': 6866, 'line': ' sql = ""INSERT INTO valids (base_url, first, last, scene) VALUES (\'{base_url}\', \'{first}\', \'{last}\', \'{name}\');""\n'}, {'line_no': 124, 'char_start': 6866, 'char_end': 6956, 'line': "" args = {'base_url': base_url, 'first': first, 'last': last, 'name': name}\n""}, {'line_no': 125, 'char_start': 6956, 'char_end': 6996, 'line': ' self.db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 466, 'char_end': 469, 'chars': '.fo'}, {'char_start': 470, 'char_end': 474, 'chars': 'mat('}, {'char_start': 478, 'char_end': 479, 'chars': ')'}, {'char_start': 1302, 'char_end': 1305, 'chars': '.fo'}, {'char_start': 1306, 'char_end': 1307, 'chars': 'm'}, {'char_start': 1309, 'char_end': 1310, 'chars': '('}, {'char_start': 1323, 'char_end': 1324, 'chars': ')'}, {'char_start': 2259, 'char_end': 2262, 'chars': '.fo'}, {'char_start': 2263, 'char_end': 2264, 'chars': 'm'}, {'char_start': 2266, 'char_end': 2267, 'chars': '('}, {'char_start': 2286, 'char_end': 2287, 'chars': ')'}, {'char_start': 3499, 'char_end': 3502, 'chars': '.fo'}, {'char_start': 3503, 'char_end': 3507, 'chars': 'mat('}, {'char_start': 3522, 'char_end': 3523, 'chars': ')'}, {'char_start': 3987, 'char_end': 3988, 'chars': '+'}, {'char_start': 3990, 'char_end': 3991, 'chars': 't'}, {'char_start': 3992, 'char_end': 3993, 'chars': '('}, {'char_start': 4001, 'char_end': 4009, 'chars': ') + ""\';""'}, {'char_start': 5127, 'char_end': 5135, 'chars': '"" + str('}, {'char_start': 5143, 'char_end': 5148, 'chars': ') + ""'}, {'char_start': 5167, 'char_end': 5169, 'chars': '""+'}, {'char_start': 5172, 'char_end': 5173, 'chars': '('}, {'char_start': 5181, 'char_end': 5187, 'chars': ')+""\';""'}, {'char_start': 6525, 'char_end': 6527, 'chars': 'ql'}, {'char_start': 6528, 'char_end': 6529, 'chars': '+'}, {'char_start': 6531, 'char_end': 6532, 'chars': '""'}, {'char_start': 6533, 'char_end': 6535, 'chars': '""+'}, {'char_start': 6536, 'char_end': 6537, 'chars': 't'}, {'char_start': 6538, 'char_end': 6539, 'chars': '('}, {'char_start': 6547, 'char_end': 6551, 'chars': ')+""\''}, {'char_start': 6553, 'char_end': 6555, 'chars': '""+'}, {'char_start': 6557, 'char_end': 6559, 'chars': 'r('}, {'char_start': 6564, 'char_end': 6568, 'chars': ')+ ""'}, {'char_start': 6570, 'char_end': 6572, 'chars': '""+'}, {'char_start': 6574, 'char_end': 6576, 'chars': 'r('}, {'char_start': 6580, 'char_end': 6583, 'chars': ')+""'}, {'char_start': 6586, 'char_end': 6592, 'chars': '""+str('}, {'char_start': 6596, 'char_end': 6599, 'chars': ')+""'}, {'char_start': 6600, 'char_end': 6603, 'chars': ');""'}], 'added': [{'char_start': 462, 'char_end': 466, 'chars': 'user'}, {'char_start': 470, 'char_end': 483, 'chars': '\n '}, {'char_start': 484, 'char_end': 492, 'chars': ""rgs = {'""}, {'char_start': 496, 'char_end': 504, 'chars': ""': user}""}, {'char_start': 543, 'char_end': 549, 'chars': ', args'}, {'char_start': 1315, 'char_end': 1322, 'chars': 'bracket'}, {'char_start': 1336, 'char_end': 1340, 'chars': 'user'}, {'char_start': 1344, 'char_end': 1366, 'chars': '\n a'}, {'char_start': 1367, 'char_end': 1376, 'chars': ""gs = {'br""}, {'char_start': 1377, 'char_end': 1380, 'chars': 'cke'}, {'char_start': 1381, 'char_end': 1384, 'chars': ""': ""}, {'char_start': 1393, 'char_end': 1394, 'chars': ""'""}, {'char_start': 1398, 'char_end': 1406, 'chars': ""': user}""}, {'char_start': 1453, 'char_end': 1459, 'chars': ', args'}, {'char_start': 2330, 'char_end': 2337, 'chars': 'bracket'}, {'char_start': 2343, 'char_end': 2347, 'chars': 'user'}, {'char_start': 2353, 'char_end': 2357, 'chars': 'name'}, {'char_start': 2362, 'char_end': 2388, 'chars': '\n a'}, {'char_start': 2389, 'char_end': 2398, 'chars': ""gs = {'br""}, {'char_start': 2399, 'char_end': 2402, 'chars': 'cke'}, {'char_start': 2403, 'char_end': 2406, 'chars': ""': ""}, {'char_start': 2415, 'char_end': 2422, 'chars': ""'user':""}, {'char_start': 2428, 'char_end': 2429, 'chars': ""'""}, {'char_start': 2433, 'char_end': 2440, 'chars': ""':name}""}, {'char_start': 2481, 'char_end': 2487, 'chars': ', args'}, {'char_start': 3641, 'char_end': 3644, 'chars': 'url'}, {'char_start': 3650, 'char_end': 3654, 'chars': 'user'}, {'char_start': 3660, 'char_end': 3664, 'chars': 'name'}, {'char_start': 3669, 'char_end': 3690, 'chars': '\n '}, {'char_start': 3691, 'char_end': 3705, 'chars': ""rgs = {'url': ""}, {'char_start': 3710, 'char_end': 3717, 'chars': ""'user':""}, {'char_start': 3723, 'char_end': 3724, 'chars': ""'""}, {'char_start': 3728, 'char_end': 3735, 'chars': ""':name}""}, {'char_start': 3772, 'char_end': 3778, 'chars': ', args'}, {'char_start': 4203, 'char_end': 4215, 'chars': ""{base_url}';""}, {'char_start': 4216, 'char_end': 4219, 'chars': '\n '}, {'char_start': 4220, 'char_end': 4225, 'chars': ' '}, {'char_start': 4226, 'char_end': 4230, 'chars': ' a'}, {'char_start': 4231, 'char_end': 4238, 'chars': ""gs = {'""}, {'char_start': 4247, 'char_end': 4258, 'chars': ': base_url}'}, {'char_start': 4296, 'char_end': 4302, 'chars': ', args'}, {'char_start': 5382, 'char_end': 5383, 'chars': '{'}, {'char_start': 5391, 'char_end': 5392, 'chars': '}'}, {'char_start': 5407, 'char_end': 5447, 'chars': '=\'{base_url}\';""\n args'}, {'char_start': 5450, 'char_end': 5451, 'chars': '{'}, {'char_start': 5452, 'char_end': 5469, 'chars': ""new_last': new_la""}, {'char_start': 5471, 'char_end': 5474, 'chars': "", '""}, {'char_start': 5483, 'char_end': 5494, 'chars': ': base_url}'}, {'char_start': 5531, 'char_end': 5537, 'chars': ', args'}, {'char_start': 6819, 'char_end': 6864, 'chars': ""'{base_url}', '{first}', '{last}', '{name}');""}, {'char_start': 6882, 'char_end': 6885, 'chars': 'arg'}, {'char_start': 6889, 'char_end': 6890, 'chars': '{'}, {'char_start': 6891, 'char_end': 6893, 'chars': 'ba'}, {'char_start': 6894, 'char_end': 6897, 'chars': 'e_u'}, {'char_start': 6898, 'char_end': 6902, 'chars': ""l': ""}, {'char_start': 6912, 'char_end': 6916, 'chars': ""'fir""}, {'char_start': 6918, 'char_end': 6921, 'chars': ""': ""}, {'char_start': 6928, 'char_end': 6931, 'chars': ""'la""}, {'char_start': 6933, 'char_end': 6936, 'chars': ""': ""}, {'char_start': 6948, 'char_end': 6955, 'chars': ': name}'}, {'char_start': 6988, 'char_end': 6994, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,validURLs.py,cwe-089,1504 cwe-089,getAllComments," def getAllComments(self): sqlText=""select comment from comments where userid=%d order by date;"" allposts=sql.queryDB(self.conn,sqlText) return allposts;"," def getAllComments(self): sqlText=""select comment from comments where userid=%s order by date;"" params = [self.userid] allposts=sql.queryDB(self.conn,sqlText,params) return allposts;","{'deleted': [{'line_no': 2, 'char_start': 30, 'char_end': 108, 'line': ' sqlText=""select comment from comments where userid=%d order by date;""\n'}, {'line_no': 3, 'char_start': 108, 'char_end': 156, 'line': ' allposts=sql.queryDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 2, 'char_start': 30, 'char_end': 108, 'line': ' sqlText=""select comment from comments where userid=%s order by date;""\n'}, {'line_no': 3, 'char_start': 108, 'char_end': 139, 'line': ' params = [self.userid]\n'}, {'line_no': 4, 'char_start': 139, 'char_end': 194, 'line': ' allposts=sql.queryDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 90, 'char_end': 91, 'chars': 'd'}], 'added': [{'char_start': 90, 'char_end': 91, 'chars': 's'}, {'char_start': 116, 'char_end': 147, 'chars': 'params = [self.userid]\n '}, {'char_start': 185, 'char_end': 192, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/users.py,cwe-089,40 cwe-078,_cliq_run," def _cliq_run(self, verb, cliq_args, check_exit_code=True): """"""Runs a CLIQ command over SSH, without doing any result parsing"""""" cliq_arg_strings = [] for k, v in cliq_args.items(): cliq_arg_strings.append("" %s=%s"" % (k, v)) cmd = verb + ''.join(cliq_arg_strings) return self._run_ssh(cmd, check_exit_code)"," def _cliq_run(self, verb, cliq_args, check_exit_code=True): """"""Runs a CLIQ command over SSH, without doing any result parsing"""""" cmd_list = [verb] for k, v in cliq_args.items(): cmd_list.append(""%s=%s"" % (k, v)) return self._run_ssh(cmd_list, check_exit_code)","{'deleted': [{'line_no': 3, 'char_start': 141, 'char_end': 171, 'line': ' cliq_arg_strings = []\n'}, {'line_no': 5, 'char_start': 210, 'char_end': 265, 'line': ' cliq_arg_strings.append("" %s=%s"" % (k, v))\n'}, {'line_no': 6, 'char_start': 265, 'char_end': 312, 'line': "" cmd = verb + ''.join(cliq_arg_strings)\n""}, {'line_no': 8, 'char_start': 313, 'char_end': 363, 'line': ' return self._run_ssh(cmd, check_exit_code)\n'}], 'added': [{'line_no': 3, 'char_start': 141, 'char_end': 167, 'line': ' cmd_list = [verb]\n'}, {'line_no': 5, 'char_start': 206, 'char_end': 252, 'line': ' cmd_list.append(""%s=%s"" % (k, v))\n'}, {'line_no': 7, 'char_start': 253, 'char_end': 308, 'line': ' return self._run_ssh(cmd_list, check_exit_code)\n'}]}","{'deleted': [{'char_start': 152, 'char_end': 158, 'chars': 'q_arg_'}, {'char_start': 160, 'char_end': 165, 'chars': 'rings'}, {'char_start': 225, 'char_end': 231, 'chars': 'q_arg_'}, {'char_start': 233, 'char_end': 238, 'chars': 'rings'}, {'char_start': 247, 'char_end': 248, 'chars': ' '}, {'char_start': 265, 'char_end': 312, 'chars': "" cmd = verb + ''.join(cliq_arg_strings)\n""}], 'added': [{'char_start': 150, 'char_end': 153, 'chars': 'md_'}, {'char_start': 161, 'char_end': 165, 'chars': 'verb'}, {'char_start': 219, 'char_end': 222, 'chars': 'md_'}, {'char_start': 285, 'char_end': 290, 'chars': '_list'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp_lefthand.py,cwe-078,95 cwe-089,getSubmissionDateFromDatabase,"def getSubmissionDateFromDatabase(submission): database = sqlite3.connect('database.db') cursor = database.cursor() return cursor.execute(""SELECT Date FROM ChallengeRankings WHERE SubmissionID = '"" + str(submission.id) + ""'"").fetchone()[0] database.close()","def getSubmissionDateFromDatabase(submission): database = sqlite3.connect('database.db') cursor = database.cursor() return cursor.execute(""SELECT Date FROM ChallengeRankings WHERE SubmissionID = ?"", [str(submission.id)]).fetchone()[0] database.close()","{'deleted': [{'line_no': 4, 'char_start': 124, 'char_end': 252, 'line': ' return cursor.execute(""SELECT Date FROM ChallengeRankings WHERE SubmissionID = \'"" + str(submission.id) + ""\'"").fetchone()[0]\n'}], 'added': [{'line_no': 4, 'char_start': 124, 'char_end': 247, 'line': ' return cursor.execute(""SELECT Date FROM ChallengeRankings WHERE SubmissionID = ?"", [str(submission.id)]).fetchone()[0]\n'}]}","{'deleted': [{'char_start': 207, 'char_end': 208, 'chars': ""'""}, {'char_start': 209, 'char_end': 211, 'chars': ' +'}, {'char_start': 230, 'char_end': 236, 'chars': ' + ""\'""'}], 'added': [{'char_start': 207, 'char_end': 208, 'chars': '?'}, {'char_start': 209, 'char_end': 210, 'chars': ','}, {'char_start': 211, 'char_end': 212, 'chars': '['}, {'char_start': 230, 'char_end': 231, 'chars': ']'}]}",github.com/LiquidFun/Reddit-GeoGuessr-Tracking-Bot/commit/0cad2d52e24b05da32789fbc8face7a9999a71f9,CheckAndPostForSeriesSubmissions.py,cwe-089,59 cwe-125,ReadVIFFImage,"static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,""NotAVIFFImage""); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,""comment"",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (number_pixels == 0) ThrowReaderException(CoderError,""ImageColumnOrRowSizeIsNotSupported""); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,""DataStorageTypeIsNotSupported""); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,""MapStorageTypeIsNotSupported""); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,""ColorspaceModelIsNotSupported""); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,""LocationTypeIsNotSupported""); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,""NumberOfImagesIsNotSupported""); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,""ColormapTypeNotSupported""); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(max_packets, bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,""NotAVIFFImage""); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,""comment"",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (number_pixels == 0) ThrowReaderException(CoderError,""ImageColumnOrRowSizeIsNotSupported""); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,""DataStorageTypeIsNotSupported""); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,""MapStorageTypeIsNotSupported""); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,""ColorspaceModelIsNotSupported""); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,""LocationTypeIsNotSupported""); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,""NumberOfImagesIsNotSupported""); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,""ColormapTypeNotSupported""); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels, max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","{'deleted': [{'line_no': 370, 'char_start': 12423, 'char_end': 12486, 'line': ' pixels=(unsigned char *) AcquireQuantumMemory(max_packets,\n'}, {'line_no': 371, 'char_start': 12486, 'char_end': 12526, 'line': ' bytes_per_pixel*sizeof(*pixels));\n'}], 'added': [{'line_no': 370, 'char_start': 12423, 'char_end': 12498, 'line': ' pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels,\n'}, {'line_no': 371, 'char_start': 12498, 'char_end': 12551, 'line': ' max_packets),bytes_per_pixel*sizeof(*pixels));\n'}]}","{'deleted': [{'char_start': 12473, 'char_end': 12474, 'chars': 'm'}, {'char_start': 12478, 'char_end': 12481, 'chars': 'ack'}, {'char_start': 12482, 'char_end': 12483, 'chars': 't'}], 'added': [{'char_start': 12473, 'char_end': 12480, 'chars': 'MagickM'}, {'char_start': 12482, 'char_end': 12489, 'chars': '(number'}, {'char_start': 12491, 'char_end': 12493, 'chars': 'ix'}, {'char_start': 12494, 'char_end': 12495, 'chars': 'l'}, {'char_start': 12504, 'char_end': 12517, 'chars': 'max_packets),'}]}",github.com/ImageMagick/ImageMagick/commit/ca0c886abd6d3ef335eb74150cd23b89ebd17135,coders/viff.c,cwe-125,5519 cwe-078,_find_host_from_wwpn," def _find_host_from_wwpn(self, connector): for wwpn in connector['wwpns']: ssh_cmd = 'svcinfo lsfabric -wwpn %s -delim !' % wwpn out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): # This WWPN is not in use continue host_lines = out.strip().split('\n') header = host_lines.pop(0).split('!') self._assert_ssh_return('remote_wwpn' in header and 'name' in header, '_find_host_from_wwpn', ssh_cmd, out, err) rmt_wwpn_idx = header.index('remote_wwpn') name_idx = header.index('name') wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines) if wwpn in wwpns: # All the wwpns will be the mapping for the same # host from this WWPN-based query. Just pick # the name from first line. hostname = host_lines[0].split('!')[name_idx] return hostname # Didn't find a host return None"," def _find_host_from_wwpn(self, connector): for wwpn in connector['wwpns']: ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!'] out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): # This WWPN is not in use continue host_lines = out.strip().split('\n') header = host_lines.pop(0).split('!') self._assert_ssh_return('remote_wwpn' in header and 'name' in header, '_find_host_from_wwpn', ssh_cmd, out, err) rmt_wwpn_idx = header.index('remote_wwpn') name_idx = header.index('name') wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines) if wwpn in wwpns: # All the wwpns will be the mapping for the same # host from this WWPN-based query. Just pick # the name from first line. hostname = host_lines[0].split('!')[name_idx] return hostname # Didn't find a host return None","{'deleted': [{'line_no': 3, 'char_start': 87, 'char_end': 153, 'line': "" ssh_cmd = 'svcinfo lsfabric -wwpn %s -delim !' % wwpn\n""}], 'added': [{'line_no': 3, 'char_start': 87, 'char_end': 163, 'line': "" ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!']\n""}]}","{'deleted': [{'char_start': 133, 'char_end': 135, 'chars': '%s'}, {'char_start': 145, 'char_end': 152, 'chars': ' % wwpn'}], 'added': [{'char_start': 109, 'char_end': 110, 'chars': '['}, {'char_start': 118, 'char_end': 120, 'chars': ""',""}, {'char_start': 121, 'char_end': 122, 'chars': ""'""}, {'char_start': 130, 'char_end': 132, 'chars': ""',""}, {'char_start': 133, 'char_end': 134, 'chars': ""'""}, {'char_start': 139, 'char_end': 141, 'chars': ""',""}, {'char_start': 142, 'char_end': 147, 'chars': 'wwpn,'}, {'char_start': 148, 'char_end': 149, 'chars': ""'""}, {'char_start': 155, 'char_end': 157, 'chars': ""',""}, {'char_start': 158, 'char_end': 159, 'chars': ""'""}, {'char_start': 161, 'char_end': 162, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,271 cwe-078,_execute_command_and_parse_attributes," def _execute_command_and_parse_attributes(self, ssh_cmd): """"""Execute command on the Storwize/SVC and parse attributes. Exception is raised if the information from the system can not be obtained. """""" LOG.debug(_('enter: _execute_command_and_parse_attributes: ' ' command %s') % ssh_cmd) try: out, err = self._run_ssh(ssh_cmd) except exception.ProcessExecutionError as e: # Didn't get details from the storage, return None LOG.error(_('CLI Exception output:\n command: %(cmd)s\n ' 'stdout: %(out)s\n stderr: %(err)s') % {'cmd': ssh_cmd, 'out': e.stdout, 'err': e.stderr}) return None self._assert_ssh_return(len(out), '_execute_command_and_parse_attributes', ssh_cmd, out, err) attributes = {} for attrib_line in out.split('\n'): # If '!' not found, return the string and two empty strings attrib_name, foo, attrib_value = attrib_line.partition('!') if attrib_name is not None and len(attrib_name.strip()): attributes[attrib_name] = attrib_value LOG.debug(_('leave: _execute_command_and_parse_attributes:\n' 'command: %(cmd)s\n' 'attributes: %(attr)s') % {'cmd': ssh_cmd, 'attr': str(attributes)}) return attributes"," def _execute_command_and_parse_attributes(self, ssh_cmd): """"""Execute command on the Storwize/SVC and parse attributes. Exception is raised if the information from the system can not be obtained. """""" LOG.debug(_('enter: _execute_command_and_parse_attributes: ' ' command %s') % str(ssh_cmd)) try: out, err = self._run_ssh(ssh_cmd) except exception.ProcessExecutionError as e: # Didn't get details from the storage, return None LOG.error(_('CLI Exception output:\n command: %(cmd)s\n ' 'stdout: %(out)s\n stderr: %(err)s') % {'cmd': ssh_cmd, 'out': e.stdout, 'err': e.stderr}) return None self._assert_ssh_return(len(out), '_execute_command_and_parse_attributes', ssh_cmd, out, err) attributes = {} for attrib_line in out.split('\n'): # If '!' not found, return the string and two empty strings attrib_name, foo, attrib_value = attrib_line.partition('!') if attrib_name is not None and len(attrib_name.strip()): attributes[attrib_name] = attrib_value LOG.debug(_('leave: _execute_command_and_parse_attributes:\n' 'command: %(cmd)s\n' 'attributes: %(attr)s') % {'cmd': str(ssh_cmd), 'attr': str(attributes)}) return attributes","{'deleted': [{'line_no': 10, 'char_start': 307, 'char_end': 353, 'line': "" ' command %s') % ssh_cmd)\n""}, {'line_no': 36, 'char_start': 1465, 'char_end': 1502, 'line': "" % {'cmd': ssh_cmd,\n""}], 'added': [{'line_no': 10, 'char_start': 307, 'char_end': 358, 'line': "" ' command %s') % str(ssh_cmd))\n""}, {'line_no': 36, 'char_start': 1470, 'char_end': 1512, 'line': "" % {'cmd': str(ssh_cmd),\n""}]}","{'deleted': [], 'added': [{'char_start': 345, 'char_end': 349, 'chars': 'tr(s'}, {'char_start': 355, 'char_end': 356, 'chars': ')'}, {'char_start': 1499, 'char_end': 1503, 'chars': 'tr(s'}, {'char_start': 1509, 'char_end': 1510, 'chars': ')'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,310 cwe-078,_port_conf_generator," def _port_conf_generator(self, cmd): ssh_cmd = '%s -delim !' % cmd out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): return port_lines = out.strip().split('\n') if not len(port_lines): return header = port_lines.pop(0) yield header for portip_line in port_lines: try: port_data = self._get_hdr_dic(header, portip_line, '!') except exception.VolumeBackendAPIException: with excutils.save_and_reraise_exception(): self._log_cli_output_error('_port_conf_generator', ssh_cmd, out, err) yield port_data"," def _port_conf_generator(self, cmd): ssh_cmd = cmd + ['-delim', '!'] out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): return port_lines = out.strip().split('\n') if not len(port_lines): return header = port_lines.pop(0) yield header for portip_line in port_lines: try: port_data = self._get_hdr_dic(header, portip_line, '!') except exception.VolumeBackendAPIException: with excutils.save_and_reraise_exception(): self._log_cli_output_error('_port_conf_generator', ssh_cmd, out, err) yield port_data","{'deleted': [{'line_no': 2, 'char_start': 41, 'char_end': 79, 'line': "" ssh_cmd = '%s -delim !' % cmd\n""}], 'added': [{'line_no': 2, 'char_start': 41, 'char_end': 81, 'line': "" ssh_cmd = cmd + ['-delim', '!']\n""}]}","{'deleted': [{'char_start': 59, 'char_end': 62, 'chars': ""'%s""}, {'char_start': 72, 'char_end': 78, 'chars': ' % cmd'}], 'added': [{'char_start': 59, 'char_end': 64, 'chars': 'cmd +'}, {'char_start': 65, 'char_end': 67, 'chars': ""['""}, {'char_start': 73, 'char_end': 75, 'chars': ""',""}, {'char_start': 76, 'char_end': 77, 'chars': ""'""}, {'char_start': 79, 'char_end': 80, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,153 cwe-089,save_accepted_transaction," def save_accepted_transaction(self, user_id, project_id, money): self.cursor.execute(""update users set money = money - %s where id = %s""%(money, user_id)) self.cursor.execute(""update projects set money = money + %s where id = %s"" % (money, project_id)) self.cursor.execute(""insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, %s, now(), 'accepted' )"" % (project_id, user_id, money)) self.db.commit()"," def save_accepted_transaction(self, user_id, project_id, money): self.cursor.execute(""update users set money = money - %s where id = %s"", (money, user_id)) self.cursor.execute(""update projects set money = money + %s where id = %s"", (money, project_id)) self.cursor.execute(""insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, "" ""%s, now(), 'accepted' )"", (project_id, user_id, money)) self.db.commit()","{'deleted': [{'line_no': 2, 'char_start': 69, 'char_end': 167, 'line': ' self.cursor.execute(""update users set money = money - %s where id = %s""%(money, user_id))\n'}, {'line_no': 3, 'char_start': 167, 'char_end': 273, 'line': ' self.cursor.execute(""update projects set money = money + %s where id = %s"" % (money, project_id))\n'}, {'line_no': 4, 'char_start': 273, 'char_end': 447, 'line': ' self.cursor.execute(""insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, %s, now(), \'accepted\' )"" % (project_id, user_id, money))\n'}], 'added': [{'line_no': 2, 'char_start': 69, 'char_end': 168, 'line': ' self.cursor.execute(""update users set money = money - %s where id = %s"", (money, user_id))\n'}, {'line_no': 3, 'char_start': 168, 'char_end': 273, 'line': ' self.cursor.execute(""update projects set money = money + %s where id = %s"", (money, project_id))\n'}, {'line_no': 4, 'char_start': 273, 'char_end': 392, 'line': ' self.cursor.execute(""insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, ""\n'}, {'line_no': 5, 'char_start': 392, 'char_end': 477, 'line': ' ""%s, now(), \'accepted\' )"", (project_id, user_id, money))\n'}]}","{'deleted': [{'char_start': 148, 'char_end': 149, 'chars': '%'}, {'char_start': 249, 'char_end': 251, 'chars': ' %'}, {'char_start': 414, 'char_end': 416, 'chars': ' %'}], 'added': [{'char_start': 148, 'char_end': 150, 'chars': ', '}, {'char_start': 250, 'char_end': 251, 'chars': ','}, {'char_start': 390, 'char_end': 421, 'chars': '""\n ""'}, {'char_start': 445, 'char_end': 446, 'chars': ','}]}",github.com/JLucka/kickstarter-dev/commit/e2ffa062697e060fdfbd2eccbb89a8c53a569e0b,backend/transactions/TransactionConnector.py,cwe-089,119 cwe-125,process_packet_tail,"void process_packet_tail(struct msg_digest *md) { struct state *st = md->st; enum state_kind from_state = md->v1_from_state; const struct state_v1_microcode *smc = md->smc; bool new_iv_set = md->new_iv_set; bool self_delete = FALSE; if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) { endpoint_buf b; dbg(""received encrypted packet from %s"", str_endpoint(&md->sender, &b)); if (st == NULL) { libreswan_log( ""discarding encrypted message for an unknown ISAKMP SA""); return; } if (st->st_skeyid_e_nss == NULL) { loglog(RC_LOG_SERIOUS, ""discarding encrypted message because we haven't yet negotiated keying material""); return; } /* Mark as encrypted */ md->encrypted = TRUE; /* do the specified decryption * * IV is from st->st_iv or (if new_iv_set) st->st_new_iv. * The new IV is placed in st->st_new_iv * * See RFC 2409 ""IKE"" Appendix B * * XXX The IV should only be updated really if the packet * is successfully processed. * We should keep this value, check for a success return * value from the parsing routines and then replace. * * Each post phase 1 exchange generates IVs from * the last phase 1 block, not the last block sent. */ const struct encrypt_desc *e = st->st_oakley.ta_encrypt; if (pbs_left(&md->message_pbs) % e->enc_blocksize != 0) { loglog(RC_LOG_SERIOUS, ""malformed message: not a multiple of encryption blocksize""); return; } /* XXX Detect weak keys */ /* grab a copy of raw packet (for duplicate packet detection) */ md->raw_packet = clone_bytes_as_chunk(md->packet_pbs.start, pbs_room(&md->packet_pbs), ""raw packet""); /* Decrypt everything after header */ if (!new_iv_set) { if (st->st_v1_iv.len == 0) { init_phase2_iv(st, &md->hdr.isa_msgid); } else { /* use old IV */ restore_new_iv(st, st->st_v1_iv); } } passert(st->st_v1_new_iv.len >= e->enc_blocksize); st->st_v1_new_iv.len = e->enc_blocksize; /* truncate */ if (DBGP(DBG_CRYPT)) { DBG_log(""decrypting %u bytes using algorithm %s"", (unsigned) pbs_left(&md->message_pbs), st->st_oakley.ta_encrypt->common.fqn); DBG_dump_hunk(""IV before:"", st->st_v1_new_iv); } e->encrypt_ops->do_crypt(e, md->message_pbs.cur, pbs_left(&md->message_pbs), st->st_enc_key_nss, st->st_v1_new_iv.ptr, FALSE); if (DBGP(DBG_CRYPT)) { DBG_dump_hunk(""IV after:"", st->st_v1_new_iv); DBG_log(""decrypted payload (starts at offset %td):"", md->message_pbs.cur - md->message_pbs.roof); DBG_dump(NULL, md->message_pbs.start, md->message_pbs.roof - md->message_pbs.start); } } else { /* packet was not encryped -- should it have been? */ if (smc->flags & SMF_INPUT_ENCRYPTED) { loglog(RC_LOG_SERIOUS, ""packet rejected: should have been encrypted""); SEND_NOTIFICATION(INVALID_FLAGS); return; } } /* Digest the message. * Padding must be removed to make hashing work. * Padding comes from encryption (so this code must be after decryption). * Padding rules are described before the definition of * struct isakmp_hdr in packet.h. */ { enum next_payload_types_ikev1 np = md->hdr.isa_np; lset_t needed = smc->req_payloads; const char *excuse = LIN(SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT, smc->flags) ? ""probable authentication failure (mismatch of preshared secrets?): "" : """"; while (np != ISAKMP_NEXT_NONE) { struct_desc *sd = v1_payload_desc(np); if (md->digest_roof >= elemsof(md->digest)) { loglog(RC_LOG_SERIOUS, ""more than %zu payloads in message; ignored"", elemsof(md->digest)); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } struct payload_digest *const pd = md->digest + md->digest_roof; /* * only do this in main mode. In aggressive mode, there * is no negotiation of NAT-T method. Get it right. */ if (st != NULL && st->st_connection != NULL && (st->st_connection->policy & POLICY_AGGRESSIVE) == LEMPTY) { switch (np) { case ISAKMP_NEXT_NATD_RFC: case ISAKMP_NEXT_NATOA_RFC: if ((st->hidden_variables.st_nat_traversal & NAT_T_WITH_RFC_VALUES) == LEMPTY) { /* * don't accept NAT-D/NAT-OA reloc directly in message, * unless we're using NAT-T RFC */ DBG(DBG_NATT, DBG_log(""st_nat_traversal was: %s"", bitnamesof(natt_bit_names, st->hidden_variables.st_nat_traversal))); sd = NULL; } break; default: break; } } if (sd == NULL) { /* payload type is out of range or requires special handling */ switch (np) { case ISAKMP_NEXT_ID: /* ??? two kinds of ID payloads */ sd = (IS_PHASE1(from_state) || IS_PHASE15(from_state)) ? &isakmp_identification_desc : &isakmp_ipsec_identification_desc; break; case ISAKMP_NEXT_NATD_DRAFTS: /* out of range */ /* * ISAKMP_NEXT_NATD_DRAFTS was a private use type before RFC-3947. * Since it has the same format as ISAKMP_NEXT_NATD_RFC, * just rewrite np and sd, and carry on. */ np = ISAKMP_NEXT_NATD_RFC; sd = &isakmp_nat_d_drafts; break; case ISAKMP_NEXT_NATOA_DRAFTS: /* out of range */ /* NAT-OA was a private use type before RFC-3947 -- same format */ np = ISAKMP_NEXT_NATOA_RFC; sd = &isakmp_nat_oa_drafts; break; case ISAKMP_NEXT_SAK: /* or ISAKMP_NEXT_NATD_BADDRAFTS */ /* * Official standards say that this is ISAKMP_NEXT_SAK, * a part of Group DOI, something we don't implement. * Old non-updated Cisco gear abused this number in ancient NAT drafts. * We ignore (rather than reject) this in support of people * with crufty Cisco machines. */ loglog(RC_LOG_SERIOUS, ""%smessage with unsupported payload ISAKMP_NEXT_SAK (or ISAKMP_NEXT_NATD_BADDRAFTS) ignored"", excuse); /* * Hack to discard payload, whatever it was. * Since we are skipping the rest of the loop * body we must do some things ourself: * - demarshall the payload * - grab the next payload number (np) * - don't keep payload (don't increment pd) * - skip rest of loop body */ if (!in_struct(&pd->payload, &isakmp_ignore_desc, &md->message_pbs, &pd->pbs)) { loglog(RC_LOG_SERIOUS, ""%smalformed payload in packet"", excuse); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } np = pd->payload.generic.isag_np; /* NOTE: we do not increment pd! */ continue; /* skip rest of the loop */ default: loglog(RC_LOG_SERIOUS, ""%smessage ignored because it contains an unknown or unexpected payload type (%s) at the outermost level"", excuse, enum_show(&ikev1_payload_names, np)); if (!md->encrypted) { SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE); } return; } passert(sd != NULL); } passert(np < LELEM_ROOF); { lset_t s = LELEM(np); if (LDISJOINT(s, needed | smc->opt_payloads | LELEM(ISAKMP_NEXT_VID) | LELEM(ISAKMP_NEXT_N) | LELEM(ISAKMP_NEXT_D) | LELEM(ISAKMP_NEXT_CR) | LELEM(ISAKMP_NEXT_CERT))) { loglog(RC_LOG_SERIOUS, ""%smessage ignored because it contains a payload type (%s) unexpected by state %s"", excuse, enum_show(&ikev1_payload_names, np), st->st_state->name); if (!md->encrypted) { SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE); } return; } DBG(DBG_PARSING, DBG_log(""got payload 0x%"" PRIxLSET"" (%s) needed: 0x%"" PRIxLSET "" opt: 0x%"" PRIxLSET, s, enum_show(&ikev1_payload_names, np), needed, smc->opt_payloads)); needed &= ~s; } /* * Read in the payload recording what type it * should be */ pd->payload_type = np; if (!in_struct(&pd->payload, sd, &md->message_pbs, &pd->pbs)) { loglog(RC_LOG_SERIOUS, ""%smalformed payload in packet"", excuse); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } /* do payload-type specific debugging */ switch (np) { case ISAKMP_NEXT_ID: case ISAKMP_NEXT_NATOA_RFC: /* dump ID section */ DBG(DBG_PARSING, DBG_dump("" obj: "", pd->pbs.cur, pbs_left(&pd->pbs))); break; default: break; } /* * Place payload at the end of the chain for this type. * This code appears in ikev1.c and ikev2.c. */ { /* np is a proper subscript for chain[] */ passert(np < elemsof(md->chain)); struct payload_digest **p = &md->chain[np]; while (*p != NULL) p = &(*p)->next; *p = pd; pd->next = NULL; } np = pd->payload.generic.isag_np; md->digest_roof++; /* since we've digested one payload happily, it is probably * the case that any decryption worked. So we will not suggest * encryption failure as an excuse for subsequent payload * problems. */ excuse = """"; } DBG(DBG_PARSING, { if (pbs_left(&md->message_pbs) != 0) DBG_log(""removing %d bytes of padding"", (int) pbs_left(&md->message_pbs)); }); md->message_pbs.roof = md->message_pbs.cur; /* check that all mandatory payloads appeared */ if (needed != 0) { loglog(RC_LOG_SERIOUS, ""message for %s is missing payloads %s"", finite_states[from_state]->name, bitnamesof(payload_name_ikev1, needed)); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } } if (!check_v1_HASH(smc->hash_type, smc->message, st, md)) { /*SEND_NOTIFICATION(INVALID_HASH_INFORMATION);*/ return; } /* more sanity checking: enforce most ordering constraints */ if (IS_PHASE1(from_state) || IS_PHASE15(from_state)) { /* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges: * ""The SA payload MUST precede all other payloads in a phase 1 exchange."" */ if (md->chain[ISAKMP_NEXT_SA] != NULL && md->hdr.isa_np != ISAKMP_NEXT_SA) { loglog(RC_LOG_SERIOUS, ""malformed Phase 1 message: does not start with an SA payload""); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } } else if (IS_QUICK(from_state)) { /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode * * ""In Quick Mode, a HASH payload MUST immediately follow the ISAKMP * header and a SA payload MUST immediately follow the HASH."" * [NOTE: there may be more than one SA payload, so this is not * totally reasonable. Probably all SAs should be so constrained.] * * ""If ISAKMP is acting as a client negotiator on behalf of another * party, the identities of the parties MUST be passed as IDci and * then IDcr."" * * ""With the exception of the HASH, SA, and the optional ID payloads, * there are no payload ordering restrictions on Quick Mode."" */ if (md->hdr.isa_np != ISAKMP_NEXT_HASH) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: does not start with a HASH payload""); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } { struct payload_digest *p; int i; p = md->chain[ISAKMP_NEXT_SA]; i = 1; while (p != NULL) { if (p != &md->digest[i]) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: SA payload is in wrong position""); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } p = p->next; i++; } } /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode: * ""If ISAKMP is acting as a client negotiator on behalf of another * party, the identities of the parties MUST be passed as IDci and * then IDcr."" */ { struct payload_digest *id = md->chain[ISAKMP_NEXT_ID]; if (id != NULL) { if (id->next == NULL || id->next->next != NULL) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: if any ID payload is present, there must be exactly two""); SEND_NOTIFICATION(PAYLOAD_MALFORMED); return; } if (id + 1 != id->next) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: the ID payloads are not adjacent""); SEND_NOTIFICATION(PAYLOAD_MALFORMED); return; } } } } /* * Ignore payloads that we don't handle: */ /* XXX Handle Notifications */ { struct payload_digest *p = md->chain[ISAKMP_NEXT_N]; while (p != NULL) { switch (p->payload.notification.isan_type) { case R_U_THERE: case R_U_THERE_ACK: case ISAKMP_N_CISCO_LOAD_BALANCE: case PAYLOAD_MALFORMED: case INVALID_MESSAGE_ID: case IPSEC_RESPONDER_LIFETIME: if (md->hdr.isa_xchg == ISAKMP_XCHG_INFO) { /* these are handled later on in informational() */ break; } /* FALL THROUGH */ default: if (st == NULL) { DBG(DBG_CONTROL, DBG_log( ""ignoring informational payload %s, no corresponding state"", enum_show(& ikev1_notify_names, p->payload.notification.isan_type))); } else { loglog(RC_LOG_SERIOUS, ""ignoring informational payload %s, msgid=%08"" PRIx32 "", length=%d"", enum_show(&ikev1_notify_names, p->payload.notification.isan_type), st->st_v1_msgid.id, p->payload.notification.isan_length); DBG_dump_pbs(&p->pbs); } } if (DBGP(DBG_BASE)) { DBG_dump(""info:"", p->pbs.cur, pbs_left(&p->pbs)); } p = p->next; } p = md->chain[ISAKMP_NEXT_D]; while (p != NULL) { self_delete |= accept_delete(md, p); if (DBGP(DBG_BASE)) { DBG_dump(""del:"", p->pbs.cur, pbs_left(&p->pbs)); } if (md->st != st) { pexpect(md->st == NULL); dbg(""zapping ST as accept_delete() zapped MD.ST""); st = md->st; } p = p->next; } p = md->chain[ISAKMP_NEXT_VID]; while (p != NULL) { handle_vendorid(md, (char *)p->pbs.cur, pbs_left(&p->pbs), FALSE); p = p->next; } } if (self_delete) { accept_self_delete(md); st = md->st; /* note: st ought to be NULL from here on */ } pexpect(st == md->st); statetime_t start = statetime_start(md->st); /* * XXX: danger - the .informational() processor deletes ST; * and then tunnels this loss through MD.ST. */ complete_v1_state_transition(md, smc->processor(st, md)); statetime_stop(&start, ""%s()"", __func__); /* our caller will release_any_md(mdp); */ }","void process_packet_tail(struct msg_digest *md) { struct state *st = md->st; enum state_kind from_state = md->v1_from_state; const struct state_v1_microcode *smc = md->smc; bool new_iv_set = md->new_iv_set; bool self_delete = FALSE; if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) { endpoint_buf b; dbg(""received encrypted packet from %s"", str_endpoint(&md->sender, &b)); if (st == NULL) { libreswan_log( ""discarding encrypted message for an unknown ISAKMP SA""); return; } if (st->st_skeyid_e_nss == NULL) { loglog(RC_LOG_SERIOUS, ""discarding encrypted message because we haven't yet negotiated keying material""); return; } /* Mark as encrypted */ md->encrypted = TRUE; /* do the specified decryption * * IV is from st->st_iv or (if new_iv_set) st->st_new_iv. * The new IV is placed in st->st_new_iv * * See RFC 2409 ""IKE"" Appendix B * * XXX The IV should only be updated really if the packet * is successfully processed. * We should keep this value, check for a success return * value from the parsing routines and then replace. * * Each post phase 1 exchange generates IVs from * the last phase 1 block, not the last block sent. */ const struct encrypt_desc *e = st->st_oakley.ta_encrypt; if (pbs_left(&md->message_pbs) % e->enc_blocksize != 0) { loglog(RC_LOG_SERIOUS, ""malformed message: not a multiple of encryption blocksize""); return; } /* XXX Detect weak keys */ /* grab a copy of raw packet (for duplicate packet detection) */ md->raw_packet = clone_bytes_as_chunk(md->packet_pbs.start, pbs_room(&md->packet_pbs), ""raw packet""); /* Decrypt everything after header */ if (!new_iv_set) { if (st->st_v1_iv.len == 0) { init_phase2_iv(st, &md->hdr.isa_msgid); } else { /* use old IV */ restore_new_iv(st, st->st_v1_iv); } } passert(st->st_v1_new_iv.len >= e->enc_blocksize); st->st_v1_new_iv.len = e->enc_blocksize; /* truncate */ if (DBGP(DBG_CRYPT)) { DBG_log(""decrypting %u bytes using algorithm %s"", (unsigned) pbs_left(&md->message_pbs), st->st_oakley.ta_encrypt->common.fqn); DBG_dump_hunk(""IV before:"", st->st_v1_new_iv); } e->encrypt_ops->do_crypt(e, md->message_pbs.cur, pbs_left(&md->message_pbs), st->st_enc_key_nss, st->st_v1_new_iv.ptr, FALSE); if (DBGP(DBG_CRYPT)) { DBG_dump_hunk(""IV after:"", st->st_v1_new_iv); DBG_log(""decrypted payload (starts at offset %td):"", md->message_pbs.cur - md->message_pbs.roof); DBG_dump(NULL, md->message_pbs.start, md->message_pbs.roof - md->message_pbs.start); } } else { /* packet was not encryped -- should it have been? */ if (smc->flags & SMF_INPUT_ENCRYPTED) { loglog(RC_LOG_SERIOUS, ""packet rejected: should have been encrypted""); SEND_NOTIFICATION(INVALID_FLAGS); return; } } /* Digest the message. * Padding must be removed to make hashing work. * Padding comes from encryption (so this code must be after decryption). * Padding rules are described before the definition of * struct isakmp_hdr in packet.h. */ { enum next_payload_types_ikev1 np = md->hdr.isa_np; lset_t needed = smc->req_payloads; const char *excuse = LIN(SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT, smc->flags) ? ""probable authentication failure (mismatch of preshared secrets?): "" : """"; while (np != ISAKMP_NEXT_NONE) { struct_desc *sd = v1_payload_desc(np); if (md->digest_roof >= elemsof(md->digest)) { loglog(RC_LOG_SERIOUS, ""more than %zu payloads in message; ignored"", elemsof(md->digest)); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } struct payload_digest *const pd = md->digest + md->digest_roof; /* * only do this in main mode. In aggressive mode, there * is no negotiation of NAT-T method. Get it right. */ if (st != NULL && st->st_connection != NULL && (st->st_connection->policy & POLICY_AGGRESSIVE) == LEMPTY) { switch (np) { case ISAKMP_NEXT_NATD_RFC: case ISAKMP_NEXT_NATOA_RFC: if ((st->hidden_variables.st_nat_traversal & NAT_T_WITH_RFC_VALUES) == LEMPTY) { /* * don't accept NAT-D/NAT-OA reloc directly in message, * unless we're using NAT-T RFC */ DBG(DBG_NATT, DBG_log(""st_nat_traversal was: %s"", bitnamesof(natt_bit_names, st->hidden_variables.st_nat_traversal))); sd = NULL; } break; default: break; } } if (sd == NULL) { /* payload type is out of range or requires special handling */ switch (np) { case ISAKMP_NEXT_ID: /* ??? two kinds of ID payloads */ sd = (IS_PHASE1(from_state) || IS_PHASE15(from_state)) ? &isakmp_identification_desc : &isakmp_ipsec_identification_desc; break; case ISAKMP_NEXT_NATD_DRAFTS: /* out of range */ /* * ISAKMP_NEXT_NATD_DRAFTS was a private use type before RFC-3947. * Since it has the same format as ISAKMP_NEXT_NATD_RFC, * just rewrite np and sd, and carry on. */ np = ISAKMP_NEXT_NATD_RFC; sd = &isakmp_nat_d_drafts; break; case ISAKMP_NEXT_NATOA_DRAFTS: /* out of range */ /* NAT-OA was a private use type before RFC-3947 -- same format */ np = ISAKMP_NEXT_NATOA_RFC; sd = &isakmp_nat_oa_drafts; break; case ISAKMP_NEXT_SAK: /* or ISAKMP_NEXT_NATD_BADDRAFTS */ /* * Official standards say that this is ISAKMP_NEXT_SAK, * a part of Group DOI, something we don't implement. * Old non-updated Cisco gear abused this number in ancient NAT drafts. * We ignore (rather than reject) this in support of people * with crufty Cisco machines. */ loglog(RC_LOG_SERIOUS, ""%smessage with unsupported payload ISAKMP_NEXT_SAK (or ISAKMP_NEXT_NATD_BADDRAFTS) ignored"", excuse); /* * Hack to discard payload, whatever it was. * Since we are skipping the rest of the loop * body we must do some things ourself: * - demarshall the payload * - grab the next payload number (np) * - don't keep payload (don't increment pd) * - skip rest of loop body */ if (!in_struct(&pd->payload, &isakmp_ignore_desc, &md->message_pbs, &pd->pbs)) { loglog(RC_LOG_SERIOUS, ""%smalformed payload in packet"", excuse); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } np = pd->payload.generic.isag_np; /* NOTE: we do not increment pd! */ continue; /* skip rest of the loop */ default: loglog(RC_LOG_SERIOUS, ""%smessage ignored because it contains an unknown or unexpected payload type (%s) at the outermost level"", excuse, enum_show(&ikev1_payload_names, np)); if (!md->encrypted) { SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE); } return; } passert(sd != NULL); } passert(np < LELEM_ROOF); { lset_t s = LELEM(np); if (LDISJOINT(s, needed | smc->opt_payloads | LELEM(ISAKMP_NEXT_VID) | LELEM(ISAKMP_NEXT_N) | LELEM(ISAKMP_NEXT_D) | LELEM(ISAKMP_NEXT_CR) | LELEM(ISAKMP_NEXT_CERT))) { loglog(RC_LOG_SERIOUS, ""%smessage ignored because it contains a payload type (%s) unexpected by state %s"", excuse, enum_show(&ikev1_payload_names, np), finite_states[smc->state]->name); if (!md->encrypted) { SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE); } return; } DBG(DBG_PARSING, DBG_log(""got payload 0x%"" PRIxLSET"" (%s) needed: 0x%"" PRIxLSET "" opt: 0x%"" PRIxLSET, s, enum_show(&ikev1_payload_names, np), needed, smc->opt_payloads)); needed &= ~s; } /* * Read in the payload recording what type it * should be */ pd->payload_type = np; if (!in_struct(&pd->payload, sd, &md->message_pbs, &pd->pbs)) { loglog(RC_LOG_SERIOUS, ""%smalformed payload in packet"", excuse); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } /* do payload-type specific debugging */ switch (np) { case ISAKMP_NEXT_ID: case ISAKMP_NEXT_NATOA_RFC: /* dump ID section */ DBG(DBG_PARSING, DBG_dump("" obj: "", pd->pbs.cur, pbs_left(&pd->pbs))); break; default: break; } /* * Place payload at the end of the chain for this type. * This code appears in ikev1.c and ikev2.c. */ { /* np is a proper subscript for chain[] */ passert(np < elemsof(md->chain)); struct payload_digest **p = &md->chain[np]; while (*p != NULL) p = &(*p)->next; *p = pd; pd->next = NULL; } np = pd->payload.generic.isag_np; md->digest_roof++; /* since we've digested one payload happily, it is probably * the case that any decryption worked. So we will not suggest * encryption failure as an excuse for subsequent payload * problems. */ excuse = """"; } DBG(DBG_PARSING, { if (pbs_left(&md->message_pbs) != 0) DBG_log(""removing %d bytes of padding"", (int) pbs_left(&md->message_pbs)); }); md->message_pbs.roof = md->message_pbs.cur; /* check that all mandatory payloads appeared */ if (needed != 0) { loglog(RC_LOG_SERIOUS, ""message for %s is missing payloads %s"", finite_states[from_state]->name, bitnamesof(payload_name_ikev1, needed)); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } } if (!check_v1_HASH(smc->hash_type, smc->message, st, md)) { /*SEND_NOTIFICATION(INVALID_HASH_INFORMATION);*/ return; } /* more sanity checking: enforce most ordering constraints */ if (IS_PHASE1(from_state) || IS_PHASE15(from_state)) { /* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges: * ""The SA payload MUST precede all other payloads in a phase 1 exchange."" */ if (md->chain[ISAKMP_NEXT_SA] != NULL && md->hdr.isa_np != ISAKMP_NEXT_SA) { loglog(RC_LOG_SERIOUS, ""malformed Phase 1 message: does not start with an SA payload""); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } } else if (IS_QUICK(from_state)) { /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode * * ""In Quick Mode, a HASH payload MUST immediately follow the ISAKMP * header and a SA payload MUST immediately follow the HASH."" * [NOTE: there may be more than one SA payload, so this is not * totally reasonable. Probably all SAs should be so constrained.] * * ""If ISAKMP is acting as a client negotiator on behalf of another * party, the identities of the parties MUST be passed as IDci and * then IDcr."" * * ""With the exception of the HASH, SA, and the optional ID payloads, * there are no payload ordering restrictions on Quick Mode."" */ if (md->hdr.isa_np != ISAKMP_NEXT_HASH) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: does not start with a HASH payload""); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } { struct payload_digest *p; int i; p = md->chain[ISAKMP_NEXT_SA]; i = 1; while (p != NULL) { if (p != &md->digest[i]) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: SA payload is in wrong position""); if (!md->encrypted) { SEND_NOTIFICATION(PAYLOAD_MALFORMED); } return; } p = p->next; i++; } } /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode: * ""If ISAKMP is acting as a client negotiator on behalf of another * party, the identities of the parties MUST be passed as IDci and * then IDcr."" */ { struct payload_digest *id = md->chain[ISAKMP_NEXT_ID]; if (id != NULL) { if (id->next == NULL || id->next->next != NULL) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: if any ID payload is present, there must be exactly two""); SEND_NOTIFICATION(PAYLOAD_MALFORMED); return; } if (id + 1 != id->next) { loglog(RC_LOG_SERIOUS, ""malformed Quick Mode message: the ID payloads are not adjacent""); SEND_NOTIFICATION(PAYLOAD_MALFORMED); return; } } } } /* * Ignore payloads that we don't handle: */ /* XXX Handle Notifications */ { struct payload_digest *p = md->chain[ISAKMP_NEXT_N]; while (p != NULL) { switch (p->payload.notification.isan_type) { case R_U_THERE: case R_U_THERE_ACK: case ISAKMP_N_CISCO_LOAD_BALANCE: case PAYLOAD_MALFORMED: case INVALID_MESSAGE_ID: case IPSEC_RESPONDER_LIFETIME: if (md->hdr.isa_xchg == ISAKMP_XCHG_INFO) { /* these are handled later on in informational() */ break; } /* FALL THROUGH */ default: if (st == NULL) { DBG(DBG_CONTROL, DBG_log( ""ignoring informational payload %s, no corresponding state"", enum_show(& ikev1_notify_names, p->payload.notification.isan_type))); } else { loglog(RC_LOG_SERIOUS, ""ignoring informational payload %s, msgid=%08"" PRIx32 "", length=%d"", enum_show(&ikev1_notify_names, p->payload.notification.isan_type), st->st_v1_msgid.id, p->payload.notification.isan_length); DBG_dump_pbs(&p->pbs); } } if (DBGP(DBG_BASE)) { DBG_dump(""info:"", p->pbs.cur, pbs_left(&p->pbs)); } p = p->next; } p = md->chain[ISAKMP_NEXT_D]; while (p != NULL) { self_delete |= accept_delete(md, p); if (DBGP(DBG_BASE)) { DBG_dump(""del:"", p->pbs.cur, pbs_left(&p->pbs)); } if (md->st != st) { pexpect(md->st == NULL); dbg(""zapping ST as accept_delete() zapped MD.ST""); st = md->st; } p = p->next; } p = md->chain[ISAKMP_NEXT_VID]; while (p != NULL) { handle_vendorid(md, (char *)p->pbs.cur, pbs_left(&p->pbs), FALSE); p = p->next; } } if (self_delete) { accept_self_delete(md); st = md->st; /* note: st ought to be NULL from here on */ } pexpect(st == md->st); statetime_t start = statetime_start(md->st); /* * XXX: danger - the .informational() processor deletes ST; * and then tunnels this loss through MD.ST. */ complete_v1_state_transition(md, smc->processor(st, md)); statetime_stop(&start, ""%s()"", __func__); /* our caller will release_any_md(mdp); */ }","{'deleted': [{'line_no': 244, 'char_start': 7553, 'char_end': 7580, 'line': '\t\t\t\t\t\tst->st_state->name);\n'}], 'added': [{'line_no': 244, 'char_start': 7553, 'char_end': 7593, 'line': '\t\t\t\t\t\tfinite_states[smc->state]->name);\n'}]}","{'deleted': [{'char_start': 7565, 'char_end': 7568, 'chars': '_st'}], 'added': [{'char_start': 7559, 'char_end': 7566, 'chars': 'finite_'}, {'char_start': 7568, 'char_end': 7576, 'chars': 'ates[smc'}, {'char_start': 7583, 'char_end': 7584, 'chars': ']'}]}",github.com/libreswan/libreswan/commit/471a3e41a449d7c753bc4edbba4239501bb62ba8,programs/pluto/ikev1.c,cwe-125,4302 cwe-787,decode_zbuf,"static int decode_zbuf(AVBPrint *bp, const uint8_t *data, const uint8_t *data_end) { z_stream zstream; unsigned char *buf; unsigned buf_size; int ret; zstream.zalloc = ff_png_zalloc; zstream.zfree = ff_png_zfree; zstream.opaque = NULL; if (inflateInit(&zstream) != Z_OK) return AVERROR_EXTERNAL; zstream.next_in = (unsigned char *)data; zstream.avail_in = data_end - data; av_bprint_init(bp, 0, -1); while (zstream.avail_in > 0) { av_bprint_get_buffer(bp, 1, &buf, &buf_size); if (!buf_size) { ret = AVERROR(ENOMEM); goto fail; } zstream.next_out = buf; zstream.avail_out = buf_size; ret = inflate(&zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { ret = AVERROR_EXTERNAL; goto fail; } bp->len += zstream.next_out - buf; if (ret == Z_STREAM_END) break; } inflateEnd(&zstream); bp->str[bp->len] = 0; return 0; fail: inflateEnd(&zstream); av_bprint_finalize(bp, NULL); return ret; }","static int decode_zbuf(AVBPrint *bp, const uint8_t *data, const uint8_t *data_end) { z_stream zstream; unsigned char *buf; unsigned buf_size; int ret; zstream.zalloc = ff_png_zalloc; zstream.zfree = ff_png_zfree; zstream.opaque = NULL; if (inflateInit(&zstream) != Z_OK) return AVERROR_EXTERNAL; zstream.next_in = (unsigned char *)data; zstream.avail_in = data_end - data; av_bprint_init(bp, 0, -1); while (zstream.avail_in > 0) { av_bprint_get_buffer(bp, 2, &buf, &buf_size); if (buf_size < 2) { ret = AVERROR(ENOMEM); goto fail; } zstream.next_out = buf; zstream.avail_out = buf_size - 1; ret = inflate(&zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { ret = AVERROR_EXTERNAL; goto fail; } bp->len += zstream.next_out - buf; if (ret == Z_STREAM_END) break; } inflateEnd(&zstream); bp->str[bp->len] = 0; return 0; fail: inflateEnd(&zstream); av_bprint_finalize(bp, NULL); return ret; }","{'deleted': [{'line_no': 19, 'char_start': 514, 'char_end': 568, 'line': ' av_bprint_get_buffer(bp, 1, &buf, &buf_size);\n'}, {'line_no': 20, 'char_start': 568, 'char_end': 593, 'line': ' if (!buf_size) {\n'}, {'line_no': 25, 'char_start': 694, 'char_end': 732, 'line': ' zstream.avail_out = buf_size;\n'}], 'added': [{'line_no': 19, 'char_start': 514, 'char_end': 568, 'line': ' av_bprint_get_buffer(bp, 2, &buf, &buf_size);\n'}, {'line_no': 20, 'char_start': 568, 'char_end': 596, 'line': ' if (buf_size < 2) {\n'}, {'line_no': 25, 'char_start': 697, 'char_end': 739, 'line': ' zstream.avail_out = buf_size - 1;\n'}]}","{'deleted': [{'char_start': 547, 'char_end': 548, 'chars': '1'}, {'char_start': 580, 'char_end': 581, 'chars': '!'}], 'added': [{'char_start': 547, 'char_end': 548, 'chars': '2'}, {'char_start': 588, 'char_end': 592, 'chars': ' < 2'}, {'char_start': 733, 'char_end': 737, 'chars': ' - 1'}]}",github.com/FFmpeg/FFmpeg/commit/e371f031b942d73e02c090170975561fabd5c264,libavcodec/pngdec.c,cwe-787,323 cwe-125,forward_search_range,"forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s, UChar* range, UChar** low, UChar** high, UChar** low_prev) { UChar *p, *pprev = (UChar* )NULL; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, ""forward_search_range: str: %d, end: %d, s: %d, range: %d\n"", (int )str, (int )end, (int )s, (int )range); #endif p = s; if (reg->dmin > 0) { if (ONIGENC_IS_SINGLEBYTE(reg->enc)) { p += reg->dmin; } else { UChar *q = p + reg->dmin; while (p < q) p += enclen(reg->enc, p); } } retry: switch (reg->optimize) { case ONIG_OPTIMIZE_EXACT: p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_IC: p = slow_search_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM: p = bm_search(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM_NOT_REV: p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_MAP: p = map_search(reg->enc, reg->map, p, range); break; } if (p && p < range) { if (p - reg->dmin < s) { retry_gate: pprev = p; p += enclen(reg->enc, p); goto retry; } if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCHOR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; } break; case ANCHOR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = (UChar* )onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) goto retry_gate; break; } } if (reg->dmax == 0) { *low = p; if (low_prev) { if (*low > s) *low_prev = onigenc_get_prev_char_head(reg->enc, s, p); else *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); } } else { if (reg->dmax != ONIG_INFINITE_DISTANCE) { *low = p - reg->dmax; if (*low > s) { *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s, *low, (const UChar** )low_prev); if (low_prev && IS_NULL(*low_prev)) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : s), *low); } else { if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), *low); } } } /* no needs to adjust *high, *high is used as range check only */ *high = p - reg->dmin; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, ""forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n"", (int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax); #endif return 1; /* success */ } return 0; /* fail */ }","forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s, UChar* range, UChar** low, UChar** high, UChar** low_prev) { UChar *p, *pprev = (UChar* )NULL; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, ""forward_search_range: str: %d, end: %d, s: %d, range: %d\n"", (int )str, (int )end, (int )s, (int )range); #endif p = s; if (reg->dmin > 0) { if (ONIGENC_IS_SINGLEBYTE(reg->enc)) { p += reg->dmin; } else { UChar *q = p + reg->dmin; if (q >= end) return 0; /* fail */ while (p < q) p += enclen(reg->enc, p); } } retry: switch (reg->optimize) { case ONIG_OPTIMIZE_EXACT: p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_IC: p = slow_search_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM: p = bm_search(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM_NOT_REV: p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_MAP: p = map_search(reg->enc, reg->map, p, range); break; } if (p && p < range) { if (p - reg->dmin < s) { retry_gate: pprev = p; p += enclen(reg->enc, p); goto retry; } if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCHOR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; } break; case ANCHOR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = (UChar* )onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) goto retry_gate; break; } } if (reg->dmax == 0) { *low = p; if (low_prev) { if (*low > s) *low_prev = onigenc_get_prev_char_head(reg->enc, s, p); else *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); } } else { if (reg->dmax != ONIG_INFINITE_DISTANCE) { *low = p - reg->dmax; if (*low > s) { *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s, *low, (const UChar** )low_prev); if (low_prev && IS_NULL(*low_prev)) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : s), *low); } else { if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), *low); } } } /* no needs to adjust *high, *high is used as range check only */ *high = p - reg->dmin; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, ""forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n"", (int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax); #endif return 1; /* success */ } return 0; /* fail */ }","{'deleted': [], 'added': [{'line_no': 18, 'char_start': 493, 'char_end': 494, 'line': '\n'}, {'line_no': 19, 'char_start': 494, 'char_end': 535, 'line': ' if (q >= end) return 0; /* fail */\n'}]}","{'deleted': [], 'added': [{'char_start': 493, 'char_end': 535, 'chars': '\n if (q >= end) return 0; /* fail */\n'}]}",github.com/kkos/oniguruma/commit/9690d3ab1f9bcd2db8cbe1fe3ee4a5da606b8814,src/regexec.c,cwe-125,1062 cwe-022,HPHP::extractFileTo,"static bool extractFileTo(zip* zip, const std::string &file, std::string& to, char* buf, size_t len) { auto sep = file.rfind('/'); if (sep != std::string::npos) { auto path = to + file.substr(0, sep); if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) { return false; } if (sep == file.length() - 1) { return true; } } to.append(file); struct zip_stat zipStat; if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) { return false; } auto zipFile = zip_fopen_index(zip, zipStat.index, 0); FAIL_IF_INVALID_PTR(zipFile); auto outFile = fopen(to.c_str(), ""wb""); if (outFile == nullptr) { zip_fclose(zipFile); return false; } for (auto n = zip_fread(zipFile, buf, len); n != 0; n = zip_fread(zipFile, buf, len)) { if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) { zip_fclose(zipFile); fclose(outFile); remove(to.c_str()); return false; } } zip_fclose(zipFile); if (fclose(outFile) != 0) { return false; } return true; }","static bool extractFileTo(zip* zip, const std::string &file, std::string& to, char* buf, size_t len) { struct zip_stat zipStat; // Verify the file to be extracted is actually in the zip file if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) { return false; } auto clean_file = file; auto sep = std::string::npos; // Normally would just use std::string::rfind here, but if we want to be // consistent between Windows and Linux, even if techincally Linux won't use // backslash for a separator, we are checking for both types. int idx = file.length() - 1; while (idx >= 0) { if (FileUtil::isDirSeparator(file[idx])) { sep = idx; break; } idx--; } if (sep != std::string::npos) { // make_relative_path so we do not try to put files or dirs in bad // places. This securely ""cleans"" the file. clean_file = make_relative_path(file); std::string path = to + clean_file; bool is_dir_only = true; if (sep < file.length() - 1) { // not just a directory auto clean_file_dir = HHVM_FN(dirname)(clean_file); path = to + clean_file_dir.toCppString(); is_dir_only = false; } // Make sure the directory path to extract to exists or can be created if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) { return false; } // If we have a good directory to extract to above, we now check whether // the ""file"" parameter passed in is a directory or actually a file. if (is_dir_only) { // directory, like /usr/bin/ return true; } // otherwise file is actually a file, so we actually extract. } // We have ensured that clean_file will be added to a relative path by the // time we get here. to.append(clean_file); auto zipFile = zip_fopen_index(zip, zipStat.index, 0); FAIL_IF_INVALID_PTR(zipFile); auto outFile = fopen(to.c_str(), ""wb""); if (outFile == nullptr) { zip_fclose(zipFile); return false; } for (auto n = zip_fread(zipFile, buf, len); n != 0; n = zip_fread(zipFile, buf, len)) { if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) { zip_fclose(zipFile); fclose(outFile); remove(to.c_str()); return false; } } zip_fclose(zipFile); if (fclose(outFile) != 0) { return false; } return true; }","{'deleted': [{'line_no': 3, 'char_start': 129, 'char_end': 159, 'line': "" auto sep = file.rfind('/');\n""}, {'line_no': 5, 'char_start': 193, 'char_end': 235, 'line': ' auto path = to + file.substr(0, sep);\n'}, {'line_no': 10, 'char_start': 333, 'char_end': 369, 'line': ' if (sep == file.length() - 1) {\n'}, {'line_no': 15, 'char_start': 399, 'char_end': 418, 'line': ' to.append(file);\n'}, {'line_no': 16, 'char_start': 418, 'char_end': 445, 'line': ' struct zip_stat zipStat;\n'}, {'line_no': 17, 'char_start': 445, 'char_end': 500, 'line': ' if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n'}, {'line_no': 18, 'char_start': 500, 'char_end': 518, 'line': ' return false;\n'}, {'line_no': 19, 'char_start': 518, 'char_end': 522, 'line': ' }\n'}], 'added': [{'line_no': 3, 'char_start': 129, 'char_end': 130, 'line': '\n'}, {'line_no': 4, 'char_start': 130, 'char_end': 157, 'line': ' struct zip_stat zipStat;\n'}, {'line_no': 6, 'char_start': 222, 'char_end': 277, 'line': ' if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n'}, {'line_no': 7, 'char_start': 277, 'char_end': 295, 'line': ' return false;\n'}, {'line_no': 8, 'char_start': 295, 'char_end': 299, 'line': ' }\n'}, {'line_no': 9, 'char_start': 299, 'char_end': 300, 'line': '\n'}, {'line_no': 10, 'char_start': 300, 'char_end': 326, 'line': ' auto clean_file = file;\n'}, {'line_no': 11, 'char_start': 326, 'char_end': 358, 'line': ' auto sep = std::string::npos;\n'}, {'line_no': 15, 'char_start': 576, 'char_end': 607, 'line': ' int idx = file.length() - 1;\n'}, {'line_no': 16, 'char_start': 607, 'char_end': 628, 'line': ' while (idx >= 0) {\n'}, {'line_no': 17, 'char_start': 628, 'char_end': 675, 'line': ' if (FileUtil::isDirSeparator(file[idx])) {\n'}, {'line_no': 18, 'char_start': 675, 'char_end': 692, 'line': ' sep = idx;\n'}, {'line_no': 19, 'char_start': 692, 'char_end': 705, 'line': ' break;\n'}, {'line_no': 20, 'char_start': 705, 'char_end': 711, 'line': ' }\n'}, {'line_no': 21, 'char_start': 711, 'char_end': 722, 'line': ' idx--;\n'}, {'line_no': 22, 'char_start': 722, 'char_end': 726, 'line': ' }\n'}, {'line_no': 26, 'char_start': 879, 'char_end': 922, 'line': ' clean_file = make_relative_path(file);\n'}, {'line_no': 27, 'char_start': 922, 'char_end': 962, 'line': ' std::string path = to + clean_file;\n'}, {'line_no': 28, 'char_start': 962, 'char_end': 991, 'line': ' bool is_dir_only = true;\n'}, {'line_no': 29, 'char_start': 991, 'char_end': 1050, 'line': ' if (sep < file.length() - 1) { // not just a directory\n'}, {'line_no': 30, 'char_start': 1050, 'char_end': 1108, 'line': ' auto clean_file_dir = HHVM_FN(dirname)(clean_file);\n'}, {'line_no': 31, 'char_start': 1108, 'char_end': 1156, 'line': ' path = to + clean_file_dir.toCppString();\n'}, {'line_no': 32, 'char_start': 1156, 'char_end': 1183, 'line': ' is_dir_only = false;\n'}, {'line_no': 33, 'char_start': 1183, 'char_end': 1189, 'line': ' }\n'}, {'line_no': 34, 'char_start': 1189, 'char_end': 1190, 'line': '\n'}, {'line_no': 42, 'char_start': 1513, 'char_end': 1565, 'line': ' if (is_dir_only) { // directory, like /usr/bin/\n'}, {'line_no': 50, 'char_start': 1761, 'char_end': 1786, 'line': ' to.append(clean_file);\n'}]}","{'deleted': [{'char_start': 132, 'char_end': 133, 'chars': 'u'}, {'char_start': 140, 'char_end': 141, 'chars': '='}, {'char_start': 152, 'char_end': 154, 'chars': ""('""}, {'char_start': 218, 'char_end': 219, 'chars': '.'}, {'char_start': 221, 'char_end': 222, 'chars': 'b'}, {'char_start': 224, 'char_end': 225, 'chars': 'r'}, {'char_start': 226, 'char_end': 228, 'chars': '0,'}, {'char_start': 337, 'char_end': 338, 'chars': 'i'}, {'char_start': 340, 'char_end': 342, 'chars': '(s'}, {'char_start': 343, 'char_end': 344, 'chars': 'p'}, {'char_start': 345, 'char_end': 347, 'chars': '=='}, {'char_start': 352, 'char_end': 354, 'chars': '.l'}, {'char_start': 356, 'char_end': 357, 'chars': 'g'}, {'char_start': 358, 'char_end': 359, 'chars': 'h'}, {'char_start': 362, 'char_end': 363, 'chars': '-'}, {'char_start': 364, 'char_end': 366, 'chars': '1)'}, {'char_start': 367, 'char_end': 368, 'chars': '{'}, {'char_start': 396, 'char_end': 399, 'chars': '}\n\n'}, {'char_start': 402, 'char_end': 407, 'chars': 'o.app'}, {'char_start': 408, 'char_end': 411, 'chars': 'nd('}, {'char_start': 415, 'char_end': 418, 'chars': ');\n'}, {'char_start': 420, 'char_end': 421, 'chars': 's'}, {'char_start': 422, 'char_end': 423, 'chars': 'r'}, {'char_start': 424, 'char_end': 426, 'chars': 'ct'}, {'char_start': 427, 'char_end': 428, 'chars': 'z'}, {'char_start': 429, 'char_end': 431, 'chars': 'p_'}, {'char_start': 432, 'char_end': 433, 'chars': 't'}, {'char_start': 436, 'char_end': 440, 'chars': 'zipS'}, {'char_start': 443, 'char_end': 444, 'chars': ';'}, {'char_start': 447, 'char_end': 449, 'chars': 'if'}, {'char_start': 450, 'char_end': 455, 'chars': '(zip_'}, {'char_start': 459, 'char_end': 464, 'chars': '(zip,'}, {'char_start': 469, 'char_end': 473, 'chars': '.c_s'}, {'char_start': 474, 'char_end': 478, 'chars': 'r(),'}, {'char_start': 479, 'char_end': 481, 'chars': '0,'}, {'char_start': 482, 'char_end': 484, 'chars': '&z'}, {'char_start': 486, 'char_end': 488, 'chars': 'St'}, {'char_start': 490, 'char_end': 491, 'chars': ')'}, {'char_start': 492, 'char_end': 494, 'chars': '!='}, {'char_start': 495, 'char_end': 499, 'chars': '0) {'}, {'char_start': 507, 'char_end': 509, 'chars': 'ur'}, {'char_start': 510, 'char_end': 512, 'chars': ' f'}, {'char_start': 514, 'char_end': 515, 'chars': 's'}, {'char_start': 517, 'char_end': 521, 'chars': '\n }'}], 'added': [{'char_start': 129, 'char_end': 326, 'chars': '\n struct zip_stat zipStat;\n // Verify the file to be extracted is actually in the zip file\n if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n return false;\n }\n\n auto clean_file = file;\n'}, {'char_start': 339, 'char_end': 401, 'chars': 'std::string::npos;\n // Normally would just use std::string::r'}, {'char_start': 403, 'char_end': 492, 'chars': 'nd here, but if we want to be\n // consistent between Windows and Linux, even if techinca'}, {'char_start': 493, 'char_end': 510, 'chars': ""ly Linux won't us""}, {'char_start': 511, 'char_end': 541, 'chars': '\n // backslash for a separato'}, {'char_start': 542, 'char_end': 560, 'chars': ', we are checking '}, {'char_start': 561, 'char_end': 578, 'chars': 'or both types.\n '}, {'char_start': 580, 'char_end': 583, 'chars': 't i'}, {'char_start': 584, 'char_end': 599, 'chars': 'x = file.length'}, {'char_start': 601, 'char_end': 605, 'chars': ' - 1'}, {'char_start': 609, 'char_end': 728, 'chars': 'while (idx >= 0) {\n if (FileUtil::isDirSeparator(file[idx])) {\n sep = idx;\n break;\n }\n idx--;\n }\n '}, {'char_start': 764, 'char_end': 768, 'chars': '// m'}, {'char_start': 769, 'char_end': 807, 'chars': 'ke_relative_path so we do not try to p'}, {'char_start': 809, 'char_end': 816, 'chars': ' files '}, {'char_start': 817, 'char_end': 937, 'chars': 'r dirs in bad\n // places. This securely ""cleans"" the file.\n clean_file = make_relative_path(file);\n std::string'}, {'char_start': 950, 'char_end': 956, 'chars': 'clean_'}, {'char_start': 960, 'char_end': 972, 'chars': ';\n bool i'}, {'char_start': 973, 'char_end': 987, 'chars': '_dir_only = tr'}, {'char_start': 988, 'char_end': 999, 'chars': 'e;\n if ('}, {'char_start': 1000, 'char_end': 1014, 'chars': 'ep < file.leng'}, {'char_start': 1015, 'char_end': 1042, 'chars': 'h() - 1) { // not just a di'}, {'char_start': 1043, 'char_end': 1085, 'chars': 'ectory\n auto clean_file_dir = HHVM_FN'}, {'char_start': 1086, 'char_end': 1125, 'chars': 'dirname)(clean_file);\n path = to +'}, {'char_start': 1126, 'char_end': 1128, 'chars': 'cl'}, {'char_start': 1129, 'char_end': 1144, 'chars': 'an_file_dir.toC'}, {'char_start': 1145, 'char_end': 1153, 'chars': 'pString('}, {'char_start': 1156, 'char_end': 1265, 'chars': ' is_dir_only = false;\n }\n\n // Make sure the directory path to extract to exists or can be created\n'}, {'char_start': 1367, 'char_end': 1389, 'chars': '// If we have a good d'}, {'char_start': 1390, 'char_end': 1431, 'chars': 'rectory to extract to above, we now check'}, {'char_start': 1432, 'char_end': 1437, 'chars': 'wheth'}, {'char_start': 1438, 'char_end': 1442, 'chars': 'r\n '}, {'char_start': 1444, 'char_end': 1452, 'chars': '// the ""'}, {'char_start': 1456, 'char_end': 1463, 'chars': '"" param'}, {'char_start': 1464, 'char_end': 1476, 'chars': 'ter passed i'}, {'char_start': 1477, 'char_end': 1488, 'chars': ' is a direc'}, {'char_start': 1489, 'char_end': 1492, 'chars': 'ory'}, {'char_start': 1493, 'char_end': 1495, 'chars': 'or'}, {'char_start': 1496, 'char_end': 1532, 'chars': 'actually a file.\n if (is_dir_only'}, {'char_start': 1535, 'char_end': 1564, 'chars': ' // directory, like /usr/bin/'}, {'char_start': 1594, 'char_end': 1598, 'chars': '// o'}, {'char_start': 1599, 'char_end': 1605, 'chars': 'herwis'}, {'char_start': 1606, 'char_end': 1607, 'chars': ' '}, {'char_start': 1612, 'char_end': 1614, 'chars': 'is'}, {'char_start': 1615, 'char_end': 1617, 'chars': 'ac'}, {'char_start': 1619, 'char_end': 1623, 'chars': 'ally'}, {'char_start': 1624, 'char_end': 1627, 'chars': 'a f'}, {'char_start': 1628, 'char_end': 1632, 'chars': 'le, '}, {'char_start': 1633, 'char_end': 1640, 'chars': 'o we ac'}, {'char_start': 1641, 'char_end': 1642, 'chars': 'u'}, {'char_start': 1643, 'char_end': 1646, 'chars': 'lly'}, {'char_start': 1647, 'char_end': 1649, 'chars': 'ex'}, {'char_start': 1650, 'char_end': 1651, 'chars': 'r'}, {'char_start': 1652, 'char_end': 1653, 'chars': 'c'}, {'char_start': 1654, 'char_end': 1655, 'chars': '.'}, {'char_start': 1658, 'char_end': 1661, 'chars': '}\n\n'}, {'char_start': 1662, 'char_end': 1676, 'chars': ' // We have en'}, {'char_start': 1677, 'char_end': 1682, 'chars': 'ured '}, {'char_start': 1683, 'char_end': 1684, 'chars': 'h'}, {'char_start': 1687, 'char_end': 1693, 'chars': 'clean_'}, {'char_start': 1697, 'char_end': 1712, 'chars': ' will be added '}, {'char_start': 1713, 'char_end': 1714, 'chars': 'o'}, {'char_start': 1715, 'char_end': 1716, 'chars': 'a'}, {'char_start': 1717, 'char_end': 1722, 'chars': 'relat'}, {'char_start': 1723, 'char_end': 1726, 'chars': 've '}, {'char_start': 1729, 'char_end': 1730, 'chars': 'h'}, {'char_start': 1731, 'char_end': 1733, 'chars': 'by'}, {'char_start': 1734, 'char_end': 1739, 'chars': 'the\n '}, {'char_start': 1740, 'char_end': 1742, 'chars': '//'}, {'char_start': 1743, 'char_end': 1747, 'chars': 'time'}, {'char_start': 1748, 'char_end': 1750, 'chars': 'we'}, {'char_start': 1751, 'char_end': 1754, 'chars': 'get'}, {'char_start': 1755, 'char_end': 1757, 'chars': 'he'}, {'char_start': 1759, 'char_end': 1763, 'chars': '.\n '}, {'char_start': 1764, 'char_end': 1770, 'chars': 'o.appe'}, {'char_start': 1771, 'char_end': 1779, 'chars': 'd(clean_'}, {'char_start': 1780, 'char_end': 1781, 'chars': 'i'}, {'char_start': 1783, 'char_end': 1784, 'chars': ')'}]}",github.com/facebook/hhvm/commit/65c95a01541dd2fbc9c978ac53bed235b5376686,hphp/runtime/ext/zip/ext_zip.cpp,cwe-022,336 cwe-078,_create_vdisk," def _create_vdisk(self, name, size, units, opts): """"""Create a new vdisk."""""" LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name) model_update = None autoex = '-autoexpand' if opts['autoexpand'] else '' easytier = '-easytier on' if opts['easytier'] else '-easytier off' # Set space-efficient options if opts['rsize'] == -1: ssh_cmd_se_opt = '' else: ssh_cmd_se_opt = ( '-rsize %(rsize)d%% %(autoex)s -warning %(warn)d%%' % {'rsize': opts['rsize'], 'autoex': autoex, 'warn': opts['warning']}) if opts['compression']: ssh_cmd_se_opt = ssh_cmd_se_opt + ' -compressed' else: ssh_cmd_se_opt = ssh_cmd_se_opt + ( ' -grainsize %d' % opts['grainsize']) ssh_cmd = ('svctask mkvdisk -name %(name)s -mdiskgrp %(mdiskgrp)s ' '-iogrp 0 -size %(size)s -unit ' '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s' % {'name': name, 'mdiskgrp': self.configuration.storwize_svc_volpool_name, 'size': size, 'unit': units, 'easytier': easytier, 'ssh_cmd_se_opt': ssh_cmd_se_opt}) out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), '_create_vdisk', ssh_cmd, out, err) # Ensure that the output is as expected match_obj = re.search('Virtual Disk, id \[([0-9]+)\], ' 'successfully created', out) # Make sure we got a ""successfully created"" message with vdisk id self._driver_assert( match_obj is not None, _('_create_vdisk %(name)s - did not find ' 'success message in CLI output.\n ' 'stdout: %(out)s\n stderr: %(err)s') % {'name': name, 'out': str(out), 'err': str(err)}) LOG.debug(_('leave: _create_vdisk: volume %s ') % name)"," def _create_vdisk(self, name, size, units, opts): """"""Create a new vdisk."""""" LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name) model_update = None easytier = 'on' if opts['easytier'] else 'off' # Set space-efficient options if opts['rsize'] == -1: ssh_cmd_se_opt = [] else: ssh_cmd_se_opt = ['-rsize', '%s%%' % str(opts['rsize']), '-autoexpand', '-warning', '%s%%' % str(opts['warning'])] if not opts['autoexpand']: ssh_cmd_se_opt.remove('-autoexpand') if opts['compression']: ssh_cmd_se_opt.append('-compressed') else: ssh_cmd_se_opt.extend(['-grainsize', str(opts['grainsize'])]) ssh_cmd = ['svctask', 'mkvdisk', '-name', name, '-mdiskgrp', self.configuration.storwize_svc_volpool_name, '-iogrp', '0', '-size', size, '-unit', units, '-easytier', easytier] + ssh_cmd_se_opt out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), '_create_vdisk', ssh_cmd, out, err) # Ensure that the output is as expected match_obj = re.search('Virtual Disk, id \[([0-9]+)\], ' 'successfully created', out) # Make sure we got a ""successfully created"" message with vdisk id self._driver_assert( match_obj is not None, _('_create_vdisk %(name)s - did not find ' 'success message in CLI output.\n ' 'stdout: %(out)s\n stderr: %(err)s') % {'name': name, 'out': str(out), 'err': str(err)}) LOG.debug(_('leave: _create_vdisk: volume %s ') % name)","{'deleted': [{'line_no': 7, 'char_start': 181, 'char_end': 242, 'line': "" autoex = '-autoexpand' if opts['autoexpand'] else ''\n""}, {'line_no': 8, 'char_start': 242, 'char_end': 317, 'line': "" easytier = '-easytier on' if opts['easytier'] else '-easytier off'\n""}, {'line_no': 12, 'char_start': 388, 'char_end': 420, 'line': "" ssh_cmd_se_opt = ''\n""}, {'line_no': 14, 'char_start': 434, 'char_end': 465, 'line': ' ssh_cmd_se_opt = (\n'}, {'line_no': 15, 'char_start': 465, 'char_end': 535, 'line': "" '-rsize %(rsize)d%% %(autoex)s -warning %(warn)d%%' %\n""}, {'line_no': 16, 'char_start': 535, 'char_end': 576, 'line': "" {'rsize': opts['rsize'],\n""}, {'line_no': 17, 'char_start': 576, 'char_end': 611, 'line': "" 'autoex': autoex,\n""}, {'line_no': 18, 'char_start': 611, 'char_end': 654, 'line': "" 'warn': opts['warning']})\n""}, {'line_no': 20, 'char_start': 690, 'char_end': 755, 'line': "" ssh_cmd_se_opt = ssh_cmd_se_opt + ' -compressed'\n""}, {'line_no': 22, 'char_start': 773, 'char_end': 825, 'line': ' ssh_cmd_se_opt = ssh_cmd_se_opt + (\n'}, {'line_no': 23, 'char_start': 825, 'char_end': 883, 'line': "" ' -grainsize %d' % opts['grainsize'])\n""}, {'line_no': 24, 'char_start': 883, 'char_end': 884, 'line': '\n'}, {'line_no': 25, 'char_start': 884, 'char_end': 960, 'line': "" ssh_cmd = ('svctask mkvdisk -name %(name)s -mdiskgrp %(mdiskgrp)s '\n""}, {'line_no': 26, 'char_start': 960, 'char_end': 1012, 'line': "" '-iogrp 0 -size %(size)s -unit '\n""}, {'line_no': 27, 'char_start': 1012, 'char_end': 1074, 'line': "" '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'\n""}, {'line_no': 28, 'char_start': 1074, 'char_end': 1110, 'line': "" % {'name': name,\n""}, {'line_no': 29, 'char_start': 1110, 'char_end': 1187, 'line': "" 'mdiskgrp': self.configuration.storwize_svc_volpool_name,\n""}, {'line_no': 30, 'char_start': 1187, 'char_end': 1257, 'line': "" 'size': size, 'unit': units, 'easytier': easytier,\n""}, {'line_no': 31, 'char_start': 1257, 'char_end': 1311, 'line': "" 'ssh_cmd_se_opt': ssh_cmd_se_opt})\n""}], 'added': [{'line_no': 7, 'char_start': 181, 'char_end': 236, 'line': "" easytier = 'on' if opts['easytier'] else 'off'\n""}, {'line_no': 11, 'char_start': 307, 'char_end': 339, 'line': ' ssh_cmd_se_opt = []\n'}, {'line_no': 13, 'char_start': 353, 'char_end': 422, 'line': "" ssh_cmd_se_opt = ['-rsize', '%s%%' % str(opts['rsize']),\n""}, {'line_no': 14, 'char_start': 422, 'char_end': 479, 'line': "" '-autoexpand', '-warning',\n""}, {'line_no': 15, 'char_start': 479, 'char_end': 540, 'line': "" '%s%%' % str(opts['warning'])]\n""}, {'line_no': 16, 'char_start': 540, 'char_end': 579, 'line': "" if not opts['autoexpand']:\n""}, {'line_no': 17, 'char_start': 579, 'char_end': 632, 'line': "" ssh_cmd_se_opt.remove('-autoexpand')\n""}, {'line_no': 18, 'char_start': 632, 'char_end': 633, 'line': '\n'}, {'line_no': 20, 'char_start': 669, 'char_end': 722, 'line': "" ssh_cmd_se_opt.append('-compressed')\n""}, {'line_no': 22, 'char_start': 740, 'char_end': 818, 'line': "" ssh_cmd_se_opt.extend(['-grainsize', str(opts['grainsize'])])\n""}, {'line_no': 23, 'char_start': 818, 'char_end': 819, 'line': '\n'}, {'line_no': 24, 'char_start': 819, 'char_end': 888, 'line': "" ssh_cmd = ['svctask', 'mkvdisk', '-name', name, '-mdiskgrp',\n""}, {'line_no': 25, 'char_start': 888, 'char_end': 953, 'line': ' self.configuration.storwize_svc_volpool_name,\n'}, {'line_no': 26, 'char_start': 953, 'char_end': 1011, 'line': "" '-iogrp', '0', '-size', size, '-unit',\n""}, {'line_no': 27, 'char_start': 1011, 'char_end': 1077, 'line': "" units, '-easytier', easytier] + ssh_cmd_se_opt\n""}]}","{'deleted': [{'char_start': 189, 'char_end': 250, 'chars': ""autoex = '-autoexpand' if opts['autoexpand'] else ''\n ""}, {'char_start': 262, 'char_end': 272, 'chars': '-easytier '}, {'char_start': 302, 'char_end': 312, 'chars': '-easytier '}, {'char_start': 417, 'char_end': 419, 'chars': ""''""}, {'char_start': 483, 'char_end': 503, 'chars': 'rsize %(rsize)d%% %('}, {'char_start': 509, 'char_end': 511, 'chars': ')s'}, {'char_start': 521, 'char_end': 535, 'chars': ""%(warn)d%%' %\n""}, {'char_start': 551, 'char_end': 552, 'chars': '{'}, {'char_start': 553, 'char_end': 554, 'chars': 'r'}, {'char_start': 555, 'char_end': 558, 'chars': 'ize'}, {'char_start': 559, 'char_end': 560, 'chars': ':'}, {'char_start': 568, 'char_end': 569, 'chars': 's'}, {'char_start': 570, 'char_end': 572, 'chars': 'ze'}, {'char_start': 574, 'char_end': 575, 'chars': ','}, {'char_start': 590, 'char_end': 593, 'chars': ' '}, {'char_start': 602, 'char_end': 610, 'chars': ' autoex,'}, {'char_start': 627, 'char_end': 628, 'chars': ' '}, {'char_start': 629, 'char_end': 630, 'chars': 'w'}, {'char_start': 631, 'char_end': 636, 'chars': ""rn': ""}, {'char_start': 638, 'char_end': 643, 'chars': ""ts['w""}, {'char_start': 644, 'char_end': 645, 'chars': 'r'}, {'char_start': 646, 'char_end': 649, 'chars': 'ing'}, {'char_start': 650, 'char_end': 652, 'chars': ']}'}, {'char_start': 720, 'char_end': 735, 'chars': ' = ssh_cmd_se_o'}, {'char_start': 736, 'char_end': 740, 'chars': 't + '}, {'char_start': 741, 'char_end': 742, 'chars': ' '}, {'char_start': 803, 'char_end': 815, 'chars': ' = ssh_cmd_s'}, {'char_start': 816, 'char_end': 819, 'chars': '_op'}, {'char_start': 820, 'char_end': 823, 'chars': ' + '}, {'char_start': 824, 'char_end': 845, 'chars': '\n '}, {'char_start': 846, 'char_end': 847, 'chars': ' '}, {'char_start': 857, 'char_end': 860, 'chars': ' %d'}, {'char_start': 862, 'char_end': 864, 'chars': '% '}, {'char_start': 902, 'char_end': 903, 'chars': '('}, {'char_start': 926, 'char_end': 928, 'chars': '%('}, {'char_start': 932, 'char_end': 934, 'chars': ')s'}, {'char_start': 944, 'char_end': 958, 'chars': ' %(mdiskgrp)s '}, {'char_start': 959, 'char_end': 1108, 'chars': ""\n '-iogrp 0 -size %(size)s -unit '\n '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'\n % {'name': name""}, {'char_start': 1128, 'char_end': 1140, 'chars': "" 'mdiskgrp':""}, {'char_start': 1212, 'char_end': 1213, 'chars': ':'}, {'char_start': 1226, 'char_end': 1227, 'chars': ':'}, {'char_start': 1245, 'char_end': 1246, 'chars': ':'}, {'char_start': 1255, 'char_end': 1275, 'chars': ',\n '}, {'char_start': 1276, 'char_end': 1293, 'chars': ""'ssh_cmd_se_opt':""}, {'char_start': 1308, 'char_end': 1310, 'chars': '})'}], 'added': [{'char_start': 336, 'char_end': 338, 'chars': '[]'}, {'char_start': 382, 'char_end': 405, 'chars': ""['-rsize', '%s%%' % str""}, {'char_start': 406, 'char_end': 421, 'chars': ""opts['rsize']),""}, {'char_start': 439, 'char_end': 440, 'chars': ' '}, {'char_start': 441, 'char_end': 454, 'chars': "" '-""}, {'char_start': 460, 'char_end': 466, 'chars': ""pand',""}, {'char_start': 467, 'char_end': 468, 'chars': ""'""}, {'char_start': 477, 'char_end': 478, 'chars': ','}, {'char_start': 495, 'char_end': 509, 'chars': ' '}, {'char_start': 510, 'char_end': 511, 'chars': '%'}, {'char_start': 512, 'char_end': 514, 'chars': '%%'}, {'char_start': 515, 'char_end': 517, 'chars': ' %'}, {'char_start': 518, 'char_end': 522, 'chars': 'str('}, {'char_start': 528, 'char_end': 530, 'chars': 'wa'}, {'char_start': 531, 'char_end': 532, 'chars': 'n'}, {'char_start': 533, 'char_end': 535, 'chars': 'ng'}, {'char_start': 537, 'char_end': 539, 'chars': ')]'}, {'char_start': 552, 'char_end': 554, 'chars': 'if'}, {'char_start': 555, 'char_end': 558, 'chars': 'not'}, {'char_start': 559, 'char_end': 564, 'chars': 'opts['}, {'char_start': 571, 'char_end': 575, 'chars': 'pand'}, {'char_start': 576, 'char_end': 577, 'chars': ']'}, {'char_start': 595, 'char_end': 606, 'chars': 'ssh_cmd_se_'}, {'char_start': 609, 'char_end': 617, 'chars': '.remove('}, {'char_start': 618, 'char_end': 619, 'chars': '-'}, {'char_start': 620, 'char_end': 627, 'chars': 'utoexpa'}, {'char_start': 628, 'char_end': 629, 'chars': 'd'}, {'char_start': 631, 'char_end': 632, 'chars': '\n'}, {'char_start': 699, 'char_end': 705, 'chars': '.appen'}, {'char_start': 706, 'char_end': 707, 'chars': '('}, {'char_start': 720, 'char_end': 721, 'chars': ')'}, {'char_start': 770, 'char_end': 771, 'chars': '.'}, {'char_start': 772, 'char_end': 773, 'chars': 'x'}, {'char_start': 774, 'char_end': 777, 'chars': 'end'}, {'char_start': 778, 'char_end': 779, 'chars': '['}, {'char_start': 791, 'char_end': 792, 'chars': ','}, {'char_start': 793, 'char_end': 797, 'chars': 'str('}, {'char_start': 813, 'char_end': 815, 'chars': '])'}, {'char_start': 837, 'char_end': 838, 'chars': '['}, {'char_start': 846, 'char_end': 848, 'chars': ""',""}, {'char_start': 849, 'char_end': 850, 'chars': ""'""}, {'char_start': 857, 'char_end': 859, 'chars': ""',""}, {'char_start': 860, 'char_end': 861, 'chars': ""'""}, {'char_start': 866, 'char_end': 868, 'chars': ""',""}, {'char_start': 873, 'char_end': 874, 'chars': ','}, {'char_start': 875, 'char_end': 876, 'chars': ""'""}, {'char_start': 973, 'char_end': 989, 'chars': ""-iogrp', '0', '-""}, {'char_start': 994, 'char_end': 995, 'chars': ','}, {'char_start': 1003, 'char_end': 1004, 'chars': '-'}, {'char_start': 1009, 'char_end': 1029, 'chars': ',\n '}, {'char_start': 1038, 'char_end': 1039, 'chars': '-'}, {'char_start': 1048, 'char_end': 1049, 'chars': ','}, {'char_start': 1058, 'char_end': 1059, 'chars': ']'}, {'char_start': 1060, 'char_end': 1061, 'chars': '+'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,512 cwe-125,pure_strcmp,"int pure_strcmp(const char * const s1, const char * const s2) { return pure_memcmp(s1, s2, strlen(s1) + 1U); }","int pure_strcmp(const char * const s1, const char * const s2) { const size_t s1_len = strlen(s1); const size_t s2_len = strlen(s2); if (s1_len != s2_len) { return -1; } return pure_memcmp(s1, s2, s1_len); }","{'deleted': [{'line_no': 3, 'char_start': 64, 'char_end': 113, 'line': ' return pure_memcmp(s1, s2, strlen(s1) + 1U);\n'}], 'added': [{'line_no': 3, 'char_start': 64, 'char_end': 102, 'line': ' const size_t s1_len = strlen(s1);\n'}, {'line_no': 4, 'char_start': 102, 'char_end': 140, 'line': ' const size_t s2_len = strlen(s2);\n'}, {'line_no': 5, 'char_start': 140, 'char_end': 141, 'line': '\n'}, {'line_no': 6, 'char_start': 141, 'char_end': 169, 'line': ' if (s1_len != s2_len) {\n'}, {'line_no': 7, 'char_start': 169, 'char_end': 188, 'line': ' return -1;\n'}, {'line_no': 8, 'char_start': 188, 'char_end': 194, 'line': ' }\n'}, {'line_no': 9, 'char_start': 194, 'char_end': 234, 'line': ' return pure_memcmp(s1, s2, s1_len);\n'}]}","{'deleted': [{'char_start': 96, 'char_end': 98, 'chars': 'tr'}, {'char_start': 101, 'char_end': 110, 'chars': '(s1) + 1U'}], 'added': [{'char_start': 68, 'char_end': 198, 'chars': 'const size_t s1_len = strlen(s1);\n const size_t s2_len = strlen(s2);\n\n if (s1_len != s2_len) {\n return -1;\n }\n '}, {'char_start': 226, 'char_end': 228, 'chars': '1_'}]}",github.com/jedisct1/pure-ftpd/commit/36c6d268cb190282a2c17106acfd31863121b58e,src/utils.c,cwe-125,39 cwe-089,like,"@mod.route('/like/', methods=['GET', 'POST']) def like(msg_id): if request.method == 'GET': user_id = session['logged_id'] c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') sql = ""INSERT INTO like_msg(msg_id, user_id,c_time) "" + \ ""VALUES(%d,'%s','%s');"" % (msg_id, user_id, c_time) cursor.execute(sql) conn.commit() return redirect(url_for('show_entries'))","@mod.route('/like/', methods=['GET', 'POST']) def like(msg_id): if request.method == 'GET': user_id = session['logged_id'] c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') cursor.execute(""INSERT INTO like_msg(msg_id, user_id,c_time) VALUES(%s,%s,%s);"", (msg_id, user_id, c_time)) conn.commit() return redirect(url_for('show_entries'))","{'deleted': [{'line_no': 6, 'char_start': 209, 'char_end': 275, 'line': ' sql = ""INSERT INTO like_msg(msg_id, user_id,c_time) "" + \\\n'}, {'line_no': 7, 'char_start': 275, 'char_end': 343, 'line': ' ""VALUES(%d,\'%s\',\'%s\');"" % (msg_id, user_id, c_time)\n'}, {'line_no': 8, 'char_start': 343, 'char_end': 371, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 6, 'char_start': 209, 'char_end': 325, 'line': ' cursor.execute(""INSERT INTO like_msg(msg_id, user_id,c_time) VALUES(%s,%s,%s);"", (msg_id, user_id, c_time))\n'}]}","{'deleted': [{'char_start': 218, 'char_end': 223, 'chars': 'ql = '}, {'char_start': 269, 'char_end': 292, 'chars': '"" + \\\n ""'}, {'char_start': 300, 'char_end': 301, 'chars': 'd'}, {'char_start': 302, 'char_end': 303, 'chars': ""'""}, {'char_start': 305, 'char_end': 306, 'chars': ""'""}, {'char_start': 307, 'char_end': 308, 'chars': ""'""}, {'char_start': 310, 'char_end': 311, 'chars': ""'""}, {'char_start': 314, 'char_end': 316, 'chars': ' %'}, {'char_start': 342, 'char_end': 369, 'chars': '\n cursor.execute(sql'}], 'added': [{'char_start': 217, 'char_end': 220, 'chars': 'cur'}, {'char_start': 221, 'char_end': 232, 'chars': 'or.execute('}, {'char_start': 286, 'char_end': 287, 'chars': 's'}, {'char_start': 296, 'char_end': 297, 'chars': ','}]}",github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9,flaskr/flaskr/views/like_msg.py,cwe-089,119 cwe-078,_copy_volume," def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None, tpvv=True): # Virtual volume sets are not supported with the -online option cmd = 'createvvcopy -p %s -online ' % src_name if snap_cpg: cmd += '-snp_cpg %s ' % snap_cpg if tpvv: cmd += '-tpvv ' if cpg: cmd += cpg + ' ' cmd += dest_name LOG.debug('Creating clone of a volume with %s' % cmd) self._cli_run(cmd, None)"," def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None, tpvv=True): # Virtual volume sets are not supported with the -online option cmd = ['createvvcopy', '-p', src_name, '-online'] if snap_cpg: cmd.extend(['-snp_cpg', snap_cpg]) if tpvv: cmd.append('-tpvv') if cpg: cmd.append(cpg) cmd.append(dest_name) LOG.debug('Creating clone of a volume with %s' % cmd) self._cli_run(cmd)","{'deleted': [{'line_no': 4, 'char_start': 178, 'char_end': 233, 'line': "" cmd = 'createvvcopy -p %s -online ' % src_name\n""}, {'line_no': 6, 'char_start': 254, 'char_end': 299, 'line': "" cmd += '-snp_cpg %s ' % snap_cpg\n""}, {'line_no': 8, 'char_start': 316, 'char_end': 344, 'line': "" cmd += '-tpvv '\n""}, {'line_no': 10, 'char_start': 360, 'char_end': 389, 'line': "" cmd += cpg + ' '\n""}, {'line_no': 11, 'char_start': 389, 'char_end': 414, 'line': ' cmd += dest_name\n'}, {'line_no': 13, 'char_start': 476, 'char_end': 508, 'line': ' self._cli_run(cmd, None)\n'}], 'added': [{'line_no': 4, 'char_start': 178, 'char_end': 236, 'line': "" cmd = ['createvvcopy', '-p', src_name, '-online']\n""}, {'line_no': 6, 'char_start': 257, 'char_end': 304, 'line': "" cmd.extend(['-snp_cpg', snap_cpg])\n""}, {'line_no': 8, 'char_start': 321, 'char_end': 353, 'line': "" cmd.append('-tpvv')\n""}, {'line_no': 10, 'char_start': 369, 'char_end': 397, 'line': ' cmd.append(cpg)\n'}, {'line_no': 11, 'char_start': 397, 'char_end': 427, 'line': ' cmd.append(dest_name)\n'}, {'line_no': 13, 'char_start': 489, 'char_end': 515, 'line': ' self._cli_run(cmd)\n'}]}","{'deleted': [{'char_start': 209, 'char_end': 210, 'chars': '%'}, {'char_start': 219, 'char_end': 220, 'chars': ' '}, {'char_start': 221, 'char_end': 232, 'chars': ' % src_name'}, {'char_start': 269, 'char_end': 273, 'chars': ' += '}, {'char_start': 282, 'char_end': 286, 'chars': ' %s '}, {'char_start': 287, 'char_end': 289, 'chars': ' %'}, {'char_start': 331, 'char_end': 335, 'chars': ' += '}, {'char_start': 341, 'char_end': 342, 'chars': ' '}, {'char_start': 375, 'char_end': 379, 'chars': ' += '}, {'char_start': 382, 'char_end': 388, 'chars': "" + ' '""}, {'char_start': 400, 'char_end': 404, 'chars': ' += '}, {'char_start': 501, 'char_end': 507, 'chars': ', None'}], 'added': [{'char_start': 192, 'char_end': 193, 'chars': '['}, {'char_start': 206, 'char_end': 208, 'chars': ""',""}, {'char_start': 209, 'char_end': 210, 'chars': ""'""}, {'char_start': 212, 'char_end': 214, 'chars': ""',""}, {'char_start': 216, 'char_end': 224, 'chars': 'rc_name,'}, {'char_start': 225, 'char_end': 226, 'chars': ""'""}, {'char_start': 234, 'char_end': 235, 'chars': ']'}, {'char_start': 272, 'char_end': 281, 'chars': '.extend(['}, {'char_start': 291, 'char_end': 292, 'chars': ','}, {'char_start': 301, 'char_end': 303, 'chars': '])'}, {'char_start': 336, 'char_end': 344, 'chars': '.append('}, {'char_start': 351, 'char_end': 352, 'chars': ')'}, {'char_start': 384, 'char_end': 392, 'chars': '.append('}, {'char_start': 395, 'char_end': 396, 'chars': ')'}, {'char_start': 408, 'char_end': 416, 'chars': '.append('}, {'char_start': 425, 'char_end': 426, 'chars': ')'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,138 cwe-476,AP4_AtomFactory::CreateAtomFromStream,"AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream, AP4_UI32 type, AP4_UI32 size_32, AP4_UI64 size_64, AP4_Atom*& atom) { bool atom_is_large = (size_32 == 1); bool force_64 = (size_32==1 && ((size_64>>32) == 0)); // create the atom if (GetContext() == AP4_ATOM_TYPE_STSD) { // sample entry if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; switch (type) { case AP4_ATOM_TYPE_MP4A: atom = new AP4_Mp4aSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_MP4V: atom = new AP4_Mp4vSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_MP4S: atom = new AP4_Mp4sSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_ENCA: atom = new AP4_EncaSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_ENCV: atom = new AP4_EncvSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_DRMS: atom = new AP4_DrmsSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_DRMI: atom = new AP4_DrmiSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_AVC1: case AP4_ATOM_TYPE_AVC2: case AP4_ATOM_TYPE_AVC3: case AP4_ATOM_TYPE_AVC4: case AP4_ATOM_TYPE_DVAV: case AP4_ATOM_TYPE_DVA1: atom = new AP4_AvcSampleEntry(type, size_32, stream, *this); break; case AP4_ATOM_TYPE_HEV1: case AP4_ATOM_TYPE_HVC1: case AP4_ATOM_TYPE_DVHE: case AP4_ATOM_TYPE_DVH1: atom = new AP4_HevcSampleEntry(type, size_32, stream, *this); break; case AP4_ATOM_TYPE_ALAC: case AP4_ATOM_TYPE_AC_3: case AP4_ATOM_TYPE_EC_3: case AP4_ATOM_TYPE_DTSC: case AP4_ATOM_TYPE_DTSH: case AP4_ATOM_TYPE_DTSL: case AP4_ATOM_TYPE_DTSE: atom = new AP4_AudioSampleEntry(type, size_32, stream, *this); break; case AP4_ATOM_TYPE_RTP_: atom = new AP4_RtpHintSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_STPP: atom = new AP4_SubtitleSampleEntry(type, size_32, stream, *this); break; default: { // try all the external type handlers AP4_List::Item* handler_item = m_TypeHandlers.FirstItem(); while (handler_item) { TypeHandler* handler = handler_item->GetData(); if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) { break; } handler_item = handler_item->GetNext(); } // no custom handler, create a generic entry if (atom == NULL) { atom = new AP4_UnknownSampleEntry(type, (AP4_UI32)size_64, stream); } break; } } } else { // regular atom switch (type) { case AP4_ATOM_TYPE_MOOV: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MoovAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_MVHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MvhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MEHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MehdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MFHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MfhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TRAK: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrakAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_TREX: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrexAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HDLR: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HdlrAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TKHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TkhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TFHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TfhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TRUN: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrunAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TFRA: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TfraAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MFRO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MfroAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MDHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MdhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STSD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StsdAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_STSC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StscAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STCO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StcoAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_CO64: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_Co64Atom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STSZ: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StszAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STZ2: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_Stz2Atom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STTS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SttsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_CTTS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_CttsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STSS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StssAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_IODS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IodsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ESDS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_EsdsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_AVCC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_AvccAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HVCC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HvccAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_DVCC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_DvccAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HVCE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HvccAtom::Create(size_32, stream); atom->SetType(AP4_ATOM_TYPE_HVCE); break; case AP4_ATOM_TYPE_AVCE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_AvccAtom::Create(size_32, stream); atom->SetType(AP4_ATOM_TYPE_AVCE); break; #if !defined(AP4_CONFIG_MINI_BUILD) case AP4_ATOM_TYPE_UUID: { AP4_UI08 uuid[16]; AP4_Result result = stream.Read(uuid, 16); if (AP4_FAILED(result)) return result; if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0) { atom = AP4_PiffTrackEncryptionAtom::Create((AP4_UI32)size_64, stream); } else if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0) { atom = AP4_PiffSampleEncryptionAtom::Create((AP4_UI32)size_64, stream); } else { atom = new AP4_UnknownUuidAtom(size_64, uuid, stream); } break; } case AP4_ATOM_TYPE_8ID_: atom = new AP4_NullTerminatedStringAtom(type, size_64, stream); break; case AP4_ATOM_TYPE_8BDL: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_8bdlAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_DREF: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_DrefAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_URL: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_UrlAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ELST: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_ElstAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_VMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_VmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_NMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_NmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SthdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_FRMA: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_FrmaAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SCHM: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SchmAtom::Create(size_32, &m_ContextStack, stream); break; case AP4_ATOM_TYPE_FTYP: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_FtypAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TIMS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TimsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SDP_: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SdpAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_IKMS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IkmsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ISFM: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IsfmAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ISLT: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IsltAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ODHE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_OdheAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_OHDR: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_OhdrAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_ODDA: atom = AP4_OddaAtom::Create(size_64, stream); break; case AP4_ATOM_TYPE_ODAF: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_OdafAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_GRPI: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_GrpiAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_IPRO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IproAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_RTP_: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_RtpAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TFDT: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TfdtAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TENC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TencAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SENC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SencAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SAIZ: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SaizAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SAIO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SaioAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_PDIN: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_PdinAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_BLOC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_BlocAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_AINF: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_AinfAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_PSSH: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_PsshAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SIDX: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SidxAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SBGP: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SbgpAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SGPD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SgpdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MKID: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; if (GetContext() == AP4_ATOM_TYPE_MARL) { atom = AP4_MkidAtom::Create(size_32, stream); } break; case AP4_ATOM_TYPE_DEC3: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; if (GetContext() == AP4_ATOM_TYPE_EC_3 || GetContext() == AP4_ATOM_TYPE_ENCA) { atom = AP4_Dec3Atom::Create(size_32, stream); } break; // track ref types case AP4_ATOM_TYPE_HINT: case AP4_ATOM_TYPE_CDSC: case AP4_ATOM_TYPE_SYNC: case AP4_ATOM_TYPE_MPOD: case AP4_ATOM_TYPE_DPND: case AP4_ATOM_TYPE_IPIR: case AP4_ATOM_TYPE_ALIS: case AP4_ATOM_TYPE_CHAP: if (GetContext() == AP4_ATOM_TYPE_TREF) { if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrefTypeAtom::Create(type, size_32, stream); } break; #endif // AP4_CONFIG_MINI_BUILD // container atoms case AP4_ATOM_TYPE_MOOF: case AP4_ATOM_TYPE_MVEX: case AP4_ATOM_TYPE_TRAF: case AP4_ATOM_TYPE_TREF: case AP4_ATOM_TYPE_MFRA: case AP4_ATOM_TYPE_HNTI: case AP4_ATOM_TYPE_STBL: case AP4_ATOM_TYPE_MDIA: case AP4_ATOM_TYPE_DINF: case AP4_ATOM_TYPE_MINF: case AP4_ATOM_TYPE_SCHI: case AP4_ATOM_TYPE_SINF: case AP4_ATOM_TYPE_UDTA: case AP4_ATOM_TYPE_ILST: case AP4_ATOM_TYPE_EDTS: case AP4_ATOM_TYPE_MDRI: case AP4_ATOM_TYPE_WAVE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this); break; // containers, only at the top case AP4_ATOM_TYPE_MARL: if (GetContext() == 0) { atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this); } break; // full container atoms case AP4_ATOM_TYPE_META: case AP4_ATOM_TYPE_ODRM: case AP4_ATOM_TYPE_ODKM: atom = AP4_ContainerAtom::Create(type, size_64, true, force_64, stream, *this); break; case AP4_ATOM_TYPE_FREE: case AP4_ATOM_TYPE_WIDE: case AP4_ATOM_TYPE_MDAT: // generic atoms break; default: { // try all the external type handlers AP4_List::Item* handler_item = m_TypeHandlers.FirstItem(); while (handler_item) { TypeHandler* handler = handler_item->GetData(); if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) { break; } handler_item = handler_item->GetNext(); } break; } } } return AP4_SUCCESS; }","AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream, AP4_UI32 type, AP4_UI32 size_32, AP4_UI64 size_64, AP4_Atom*& atom) { bool atom_is_large = (size_32 == 1); bool force_64 = (size_32==1 && ((size_64>>32) == 0)); // create the atom if (GetContext() == AP4_ATOM_TYPE_STSD) { // sample entry if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; switch (type) { case AP4_ATOM_TYPE_MP4A: atom = new AP4_Mp4aSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_MP4V: atom = new AP4_Mp4vSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_MP4S: atom = new AP4_Mp4sSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_ENCA: atom = new AP4_EncaSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_ENCV: atom = new AP4_EncvSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_DRMS: atom = new AP4_DrmsSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_DRMI: atom = new AP4_DrmiSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_AVC1: case AP4_ATOM_TYPE_AVC2: case AP4_ATOM_TYPE_AVC3: case AP4_ATOM_TYPE_AVC4: case AP4_ATOM_TYPE_DVAV: case AP4_ATOM_TYPE_DVA1: atom = new AP4_AvcSampleEntry(type, size_32, stream, *this); break; case AP4_ATOM_TYPE_HEV1: case AP4_ATOM_TYPE_HVC1: case AP4_ATOM_TYPE_DVHE: case AP4_ATOM_TYPE_DVH1: atom = new AP4_HevcSampleEntry(type, size_32, stream, *this); break; case AP4_ATOM_TYPE_ALAC: case AP4_ATOM_TYPE_AC_3: case AP4_ATOM_TYPE_EC_3: case AP4_ATOM_TYPE_DTSC: case AP4_ATOM_TYPE_DTSH: case AP4_ATOM_TYPE_DTSL: case AP4_ATOM_TYPE_DTSE: atom = new AP4_AudioSampleEntry(type, size_32, stream, *this); break; case AP4_ATOM_TYPE_RTP_: atom = new AP4_RtpHintSampleEntry(size_32, stream, *this); break; case AP4_ATOM_TYPE_STPP: atom = new AP4_SubtitleSampleEntry(type, size_32, stream, *this); break; default: { // try all the external type handlers AP4_List::Item* handler_item = m_TypeHandlers.FirstItem(); while (handler_item) { TypeHandler* handler = handler_item->GetData(); if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) { break; } handler_item = handler_item->GetNext(); } // no custom handler, create a generic entry if (atom == NULL) { atom = new AP4_UnknownSampleEntry(type, (AP4_UI32)size_64, stream); } break; } } } else { // regular atom switch (type) { case AP4_ATOM_TYPE_MOOV: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MoovAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_MVHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MvhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MEHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MehdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MFHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MfhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TRAK: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrakAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_TREX: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrexAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HDLR: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HdlrAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TKHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TkhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TFHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TfhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TRUN: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrunAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TFRA: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TfraAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MFRO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MfroAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MDHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_MdhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STSD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StsdAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_STSC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StscAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STCO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StcoAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_CO64: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_Co64Atom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STSZ: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StszAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STZ2: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_Stz2Atom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STTS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SttsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_CTTS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_CttsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STSS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_StssAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_IODS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IodsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ESDS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_EsdsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_AVCC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_AvccAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HVCC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HvccAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_DVCC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_DvccAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HVCE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HvccAtom::Create(size_32, stream); if (atom) { atom->SetType(AP4_ATOM_TYPE_HVCE); } break; case AP4_ATOM_TYPE_AVCE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_AvccAtom::Create(size_32, stream); if (atom) { atom->SetType(AP4_ATOM_TYPE_AVCE); } break; #if !defined(AP4_CONFIG_MINI_BUILD) case AP4_ATOM_TYPE_UUID: { AP4_UI08 uuid[16]; AP4_Result result = stream.Read(uuid, 16); if (AP4_FAILED(result)) return result; if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0) { atom = AP4_PiffTrackEncryptionAtom::Create((AP4_UI32)size_64, stream); } else if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0) { atom = AP4_PiffSampleEncryptionAtom::Create((AP4_UI32)size_64, stream); } else { atom = new AP4_UnknownUuidAtom(size_64, uuid, stream); } break; } case AP4_ATOM_TYPE_8ID_: atom = new AP4_NullTerminatedStringAtom(type, size_64, stream); break; case AP4_ATOM_TYPE_8BDL: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_8bdlAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_DREF: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_DrefAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_URL: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_UrlAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ELST: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_ElstAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_VMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_VmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_NMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_NmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_STHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SthdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_HMHD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_HmhdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_FRMA: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_FrmaAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SCHM: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SchmAtom::Create(size_32, &m_ContextStack, stream); break; case AP4_ATOM_TYPE_FTYP: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_FtypAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TIMS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TimsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SDP_: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SdpAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_IKMS: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IkmsAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ISFM: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IsfmAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ISLT: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IsltAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_ODHE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_OdheAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_OHDR: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_OhdrAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_ODDA: atom = AP4_OddaAtom::Create(size_64, stream); break; case AP4_ATOM_TYPE_ODAF: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_OdafAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_GRPI: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_GrpiAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_IPRO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_IproAtom::Create(size_32, stream, *this); break; case AP4_ATOM_TYPE_RTP_: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_RtpAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TFDT: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TfdtAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_TENC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TencAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SENC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SencAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SAIZ: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SaizAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SAIO: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SaioAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_PDIN: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_PdinAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_BLOC: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_BlocAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_AINF: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_AinfAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_PSSH: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_PsshAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SIDX: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SidxAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SBGP: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SbgpAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_SGPD: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_SgpdAtom::Create(size_32, stream); break; case AP4_ATOM_TYPE_MKID: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; if (GetContext() == AP4_ATOM_TYPE_MARL) { atom = AP4_MkidAtom::Create(size_32, stream); } break; case AP4_ATOM_TYPE_DEC3: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; if (GetContext() == AP4_ATOM_TYPE_EC_3 || GetContext() == AP4_ATOM_TYPE_ENCA) { atom = AP4_Dec3Atom::Create(size_32, stream); } break; // track ref types case AP4_ATOM_TYPE_HINT: case AP4_ATOM_TYPE_CDSC: case AP4_ATOM_TYPE_SYNC: case AP4_ATOM_TYPE_MPOD: case AP4_ATOM_TYPE_DPND: case AP4_ATOM_TYPE_IPIR: case AP4_ATOM_TYPE_ALIS: case AP4_ATOM_TYPE_CHAP: if (GetContext() == AP4_ATOM_TYPE_TREF) { if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_TrefTypeAtom::Create(type, size_32, stream); } break; #endif // AP4_CONFIG_MINI_BUILD // container atoms case AP4_ATOM_TYPE_MOOF: case AP4_ATOM_TYPE_MVEX: case AP4_ATOM_TYPE_TRAF: case AP4_ATOM_TYPE_TREF: case AP4_ATOM_TYPE_MFRA: case AP4_ATOM_TYPE_HNTI: case AP4_ATOM_TYPE_STBL: case AP4_ATOM_TYPE_MDIA: case AP4_ATOM_TYPE_DINF: case AP4_ATOM_TYPE_MINF: case AP4_ATOM_TYPE_SCHI: case AP4_ATOM_TYPE_SINF: case AP4_ATOM_TYPE_UDTA: case AP4_ATOM_TYPE_ILST: case AP4_ATOM_TYPE_EDTS: case AP4_ATOM_TYPE_MDRI: case AP4_ATOM_TYPE_WAVE: if (atom_is_large) return AP4_ERROR_INVALID_FORMAT; atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this); break; // containers, only at the top case AP4_ATOM_TYPE_MARL: if (GetContext() == 0) { atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this); } break; // full container atoms case AP4_ATOM_TYPE_META: case AP4_ATOM_TYPE_ODRM: case AP4_ATOM_TYPE_ODKM: atom = AP4_ContainerAtom::Create(type, size_64, true, force_64, stream, *this); break; case AP4_ATOM_TYPE_FREE: case AP4_ATOM_TYPE_WIDE: case AP4_ATOM_TYPE_MDAT: // generic atoms break; default: { // try all the external type handlers AP4_List::Item* handler_item = m_TypeHandlers.FirstItem(); while (handler_item) { TypeHandler* handler = handler_item->GetData(); if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) { break; } handler_item = handler_item->GetNext(); } break; } } } return AP4_SUCCESS; }","{'deleted': [{'line_no': 237, 'char_start': 8331, 'char_end': 8378, 'line': ' atom->SetType(AP4_ATOM_TYPE_HVCE);\n'}, {'line_no': 243, 'char_start': 8555, 'char_end': 8602, 'line': ' atom->SetType(AP4_ATOM_TYPE_AVCE);\n'}], 'added': [{'line_no': 237, 'char_start': 8331, 'char_end': 8355, 'line': ' if (atom) {\n'}, {'line_no': 238, 'char_start': 8355, 'char_end': 8406, 'line': ' atom->SetType(AP4_ATOM_TYPE_HVCE);\n'}, {'line_no': 239, 'char_start': 8406, 'char_end': 8420, 'line': ' }\n'}, {'line_no': 245, 'char_start': 8597, 'char_end': 8621, 'line': ' if (atom) {\n'}, {'line_no': 246, 'char_start': 8621, 'char_end': 8672, 'line': ' atom->SetType(AP4_ATOM_TYPE_AVCE);\n'}, {'line_no': 247, 'char_start': 8672, 'char_end': 8686, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 8343, 'char_end': 8371, 'chars': 'if (atom) {\n '}, {'char_start': 8405, 'char_end': 8419, 'chars': '\n }'}, {'char_start': 8609, 'char_end': 8637, 'chars': 'if (atom) {\n '}, {'char_start': 8671, 'char_end': 8685, 'chars': '\n }'}]}",github.com/axiomatic-systems/Bento4/commit/be7185faf7f52674028977dcf501c6039ff03aa5,Source/C++/Core/Ap4AtomFactory.cpp,cwe-476,4745 cwe-089,lookup_assets,"@app.route('/lookup_assets') def lookup_assets(): start = request.args.get('start') con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT aname FROM assets WHERE aname LIKE '""+start+""%'"" cur.execute(query) results = cur.fetchall() con.close() return jsonify(results)","@app.route('/lookup_assets') def lookup_assets(): start = request.args.get('start') con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT aname FROM assets WHERE aname LIKE %s"" cur.execute(query, (start+'%',)) results = cur.fetchall() con.close() return jsonify(results)","{'deleted': [{'line_no': 8, 'char_start': 159, 'char_end': 228, 'line': ' query = ""SELECT aname FROM assets WHERE aname LIKE \'""+start+""%\'""\n'}, {'line_no': 9, 'char_start': 228, 'char_end': 251, 'line': ' cur.execute(query)\n'}], 'added': [{'line_no': 8, 'char_start': 159, 'char_end': 218, 'line': ' query = ""SELECT aname FROM assets WHERE aname LIKE %s""\n'}, {'line_no': 9, 'char_start': 218, 'char_end': 255, 'line': "" cur.execute(query, (start+'%',))\n""}]}","{'deleted': [{'char_start': 214, 'char_end': 224, 'chars': '\'""+start+""'}, {'char_start': 225, 'char_end': 226, 'chars': ""'""}], 'added': [{'char_start': 214, 'char_end': 215, 'chars': '%'}, {'char_start': 239, 'char_end': 253, 'chars': "", (start+'%',)""}]}",github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60,api.py,cwe-089,74 cwe-089,view_page_record,"@app.route('//history/record') def view_page_record(page_name): content_id = request.args.get('id') query = db.query(""select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = '%s'"" % content_id) page_record = query.namedresult()[0] return render_template( 'page_record.html', page_name = page_name, page_record = page_record )","@app.route('//history/record') def view_page_record(page_name): content_id = request.args.get('id') query = db.query(""select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = $1"", content_id) page_record = query.namedresult()[0] return render_template( 'page_record.html', page_name = page_name, page_record = page_record )","{'deleted': [{'line_no': 4, 'char_start': 115, 'char_end': 292, 'line': ' query = db.query(""select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = \'%s\'"" % content_id)\n'}], 'added': [{'line_no': 4, 'char_start': 115, 'char_end': 289, 'line': ' query = db.query(""select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = $1"", content_id)\n'}]}","{'deleted': [{'char_start': 272, 'char_end': 276, 'chars': ""'%s'""}, {'char_start': 277, 'char_end': 279, 'chars': ' %'}], 'added': [{'char_start': 272, 'char_end': 274, 'chars': '$1'}, {'char_start': 275, 'char_end': 276, 'chars': ','}]}",github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b,server.py,cwe-089,104 cwe-125,ssl_parse_server_key_exchange,"static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; unsigned char *p = NULL, *end = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( ""=> parse server key exchange"" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= skip parse server key exchange"" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ""ssl_get_ecdh_params_from_cert"", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= skip parse server key exchange"" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ssl_read_record"", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server * doesn't use a psk_identity_hint */ if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE ) { if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* Current message is probably either * CertificateRequest or ServerHelloDone */ ssl->keep_current_message = 1; goto exit; } MBEDTLS_SSL_DEBUG_MSG( 1, ( ""server key exchange message must "" ""not be skipped"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; MBEDTLS_SSL_DEBUG_BUF( 3, ""server key exchange"", p, end - p ); #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } /* FALLTROUGH */ #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) ; /* nothing more to do */ else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ecjpake_read_round_two"", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""should never happen"" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t sig_len, hashlen; unsigned char hash[64]; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); size_t params_len = p - params; /* * Handle the digitally-signed structure */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( ssl_parse_signature_algorithm( ssl, &p, end, &md_alg, &pk_alg ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); /* Default hash for ECDSA is SHA-1 */ if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE ) md_alg = MBEDTLS_MD_SHA1; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""should never happen"" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Read signature */ if( p > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } sig_len = ( p[0] << 8 ) | p[1]; p += 2; if( end != p + sig_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_BUF( 3, ""signature"", p, sig_len ); /* * Compute the hash that has been signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params, params_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { /* Info from md_alg will be used instead */ hashlen = 0; ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params, params_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""should never happen"" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, ""parameters hash"", hash, hashlen != 0 ? hashlen : (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) ); if( ssl->session_negotiate->peer_cert == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( ""certificate required"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * Verify signature */ if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk, md_alg, hash, hashlen, p, sig_len ) ) != 0 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR ); MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_pk_verify"", ret ); return( ret ); } } #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */ exit: ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= parse server key exchange"" ) ); return( 0 ); }","static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; unsigned char *p = NULL, *end = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( ""=> parse server key exchange"" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= skip parse server key exchange"" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ""ssl_get_ecdh_params_from_cert"", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= skip parse server key exchange"" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ssl_read_record"", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server * doesn't use a psk_identity_hint */ if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE ) { if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* Current message is probably either * CertificateRequest or ServerHelloDone */ ssl->keep_current_message = 1; goto exit; } MBEDTLS_SSL_DEBUG_MSG( 1, ( ""server key exchange message must "" ""not be skipped"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; MBEDTLS_SSL_DEBUG_BUF( 3, ""server key exchange"", p, end - p ); #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } /* FALLTROUGH */ #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) ; /* nothing more to do */ else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ecjpake_read_round_two"", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""should never happen"" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t sig_len, hashlen; unsigned char hash[64]; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); size_t params_len = p - params; /* * Handle the digitally-signed structure */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( ssl_parse_signature_algorithm( ssl, &p, end, &md_alg, &pk_alg ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); /* Default hash for ECDSA is SHA-1 */ if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE ) md_alg = MBEDTLS_MD_SHA1; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""should never happen"" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Read signature */ if( p > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } sig_len = ( p[0] << 8 ) | p[1]; p += 2; if( p != end - sig_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_BUF( 3, ""signature"", p, sig_len ); /* * Compute the hash that has been signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params, params_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { /* Info from md_alg will be used instead */ hashlen = 0; ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params, params_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""should never happen"" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, ""parameters hash"", hash, hashlen != 0 ? hashlen : (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) ); if( ssl->session_negotiate->peer_cert == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( ""certificate required"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * Verify signature */ if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message"" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk, md_alg, hash, hashlen, p, sig_len ) ) != 0 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR ); MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_pk_verify"", ret ); return( ret ); } } #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */ exit: ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= parse server key exchange"" ) ); return( 0 ); }","{'deleted': [{'line_no': 229, 'char_start': 9573, 'char_end': 9606, 'line': ' if( end != p + sig_len )\n'}], 'added': [{'line_no': 229, 'char_start': 9573, 'char_end': 9606, 'line': ' if( p != end - sig_len )\n'}]}","{'deleted': [{'char_start': 9585, 'char_end': 9588, 'chars': 'end'}, {'char_start': 9592, 'char_end': 9593, 'chars': 'p'}, {'char_start': 9594, 'char_end': 9595, 'chars': '+'}], 'added': [{'char_start': 9585, 'char_end': 9586, 'chars': 'p'}, {'char_start': 9590, 'char_end': 9593, 'chars': 'end'}, {'char_start': 9594, 'char_end': 9595, 'chars': '-'}]}",github.com/ARMmbed/mbedtls/commit/027f84c69f4ef30c0693832a6c396ef19e563ca1,library/ssl_cli.c,cwe-125,3155 cwe-089,get_last_active_users," @staticmethod def get_last_active_users(limit): """""" Get from the database a tuple of users who have been recently using the bot :param limit: integer that specifies how much users to get :return: tuple of tuples with users info """""" log.info('Evaluating last active users with date of ' 'last time when they used bot...') # From photo_queries_table2 we take chat_id of the last # active users and from 'users' table we take info about these # users by chat_id which is a foreign key query = ('SELECT p.chat_id, u.first_name, u.nickname, u.last_name, ' 'u.language ' 'FROM photo_queries_table2 p ' 'INNER JOIN users u ' 'ON p.chat_id = u.chat_id ' 'GROUP BY u.chat_id, u.first_name, u.nickname, u.last_name, ' 'u.language ' 'ORDER BY MAX(time)' f'DESC LIMIT {limit}') try: cursor = db.execute_query(query) except DatabaseConnectionError: log.error(""Cannot get the last active users because of some "" ""problems with the database"") raise last_active_users = cursor.fetchall() return last_active_users"," @staticmethod def get_last_active_users(limit): """""" Get from the database a tuple of users who have been recently using the bot :param limit: integer that specifies how much users to get :return: tuple of tuples with users info """""" log.info('Evaluating last active users with date of ' 'last time when they used bot...') # From photo_queries_table2 we take chat_id of the last # active users and from 'users' table we take info about these # users by chat_id which is a foreign key query = ('SELECT p.chat_id, u.first_name, u.nickname, u.last_name, ' 'u.language ' 'FROM photo_queries_table2 p ' 'INNER JOIN users u ' 'ON p.chat_id = u.chat_id ' 'GROUP BY u.chat_id, u.first_name, u.nickname, u.last_name, ' 'u.language ' 'ORDER BY MAX(time)' f'DESC LIMIT %s') parameters = limit, try: cursor = db.execute_query(query, parameters) except DatabaseConnectionError: log.error(""Cannot get the last active users because of some "" ""problems with the database"") raise last_active_users = cursor.fetchall() return last_active_users","{'deleted': [{'line_no': 23, 'char_start': 976, 'char_end': 1016, 'line': "" f'DESC LIMIT {limit}')\n""}, {'line_no': 26, 'char_start': 1030, 'char_end': 1075, 'line': ' cursor = db.execute_query(query)\n'}], 'added': [{'line_no': 23, 'char_start': 976, 'char_end': 1011, 'line': "" f'DESC LIMIT %s')\n""}, {'line_no': 24, 'char_start': 1011, 'char_end': 1012, 'line': '\n'}, {'line_no': 25, 'char_start': 1012, 'char_end': 1040, 'line': ' parameters = limit,\n'}, {'line_no': 28, 'char_start': 1054, 'char_end': 1111, 'line': ' cursor = db.execute_query(query, parameters)\n'}]}","{'deleted': [{'char_start': 1006, 'char_end': 1007, 'chars': '{'}, {'char_start': 1012, 'char_end': 1015, 'chars': ""}')""}], 'added': [{'char_start': 1006, 'char_end': 1033, 'chars': ""%s')\n\n parameters = ""}, {'char_start': 1038, 'char_end': 1039, 'chars': ','}, {'char_start': 1097, 'char_end': 1109, 'chars': ', parameters'}]}",github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a,photogpsbot/users.py,cwe-089,274 cwe-022,dd_load_text_ext,"char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags) { // if (!dd->locked) // error_msg_and_die(""dump_dir is not opened""); /* bug */ /* Compat with old abrt dumps. Remove in abrt-2.1 */ if (strcmp(name, ""release"") == 0) name = FILENAME_OS_RELEASE; char *full_path = concat_path_file(dd->dd_dirname, name); char *ret = load_text_file(full_path, flags); free(full_path); return ret; }","char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags) { // if (!dd->locked) // error_msg_and_die(""dump_dir is not opened""); /* bug */ if (!str_is_correct_filename(name)) { error_msg(""Cannot load text. '%s' is not a valid file name"", name); if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE)) xfunc_die(); } /* Compat with old abrt dumps. Remove in abrt-2.1 */ if (strcmp(name, ""release"") == 0) name = FILENAME_OS_RELEASE; char *full_path = concat_path_file(dd->dd_dirname, name); char *ret = load_text_file(full_path, flags); free(full_path); return ret; }","{'deleted': [], 'added': [{'line_no': 6, 'char_start': 175, 'char_end': 215, 'line': ' if (!str_is_correct_filename(name))\n'}, {'line_no': 7, 'char_start': 215, 'char_end': 221, 'line': ' {\n'}, {'line_no': 8, 'char_start': 221, 'char_end': 297, 'line': ' error_msg(""Cannot load text. \'%s\' is not a valid file name"", name);\n'}, {'line_no': 9, 'char_start': 297, 'char_end': 357, 'line': ' if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))\n'}, {'line_no': 10, 'char_start': 357, 'char_end': 382, 'line': ' xfunc_die();\n'}, {'line_no': 11, 'char_start': 382, 'char_end': 388, 'line': ' }\n'}, {'line_no': 12, 'char_start': 388, 'char_end': 389, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 179, 'char_end': 393, 'chars': 'if (!str_is_correct_filename(name))\n {\n error_msg(""Cannot load text. \'%s\' is not a valid file name"", name);\n if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))\n xfunc_die();\n }\n\n '}]}",github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277,src/lib/dump_dir.c,cwe-022,126 cwe-787,tcp_test,"int tcp_test(const char* ip_str, const short port) { int sock, i; struct sockaddr_in s_in; int packetsize = 1024; unsigned char packet[packetsize]; struct timeval tv, tv2, tv3; int caplen = 0; int times[REQUESTS]; int min, avg, max, len; struct net_hdr nh; tv3.tv_sec=0; tv3.tv_usec=1; s_in.sin_family = PF_INET; s_in.sin_port = htons(port); if (!inet_aton(ip_str, &s_in.sin_addr)) return -1; if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1) return -1; /* avoid blocking on reading the socket */ if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 ) { perror( ""fcntl(O_NONBLOCK) failed"" ); return( 1 ); } gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) { if(errno != EINPROGRESS && errno != EALREADY) { perror(""connect""); close(sock); printf(""Failed to connect\n""); return -1; } } else { gettimeofday( &tv2, NULL ); break; } gettimeofday( &tv2, NULL ); //wait 3000ms for a successful connect if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000)) { printf(""Connection timed out\n""); close(sock); return(-1); } usleep(10); } PCT; printf(""TCP connection successful\n""); //trying to identify airserv-ng memset(&nh, 0, sizeof(nh)); // command: GET_CHAN nh.nh_type = 2; nh.nh_len = htonl(0); if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh)) { perror(""send""); return -1; } gettimeofday( &tv, NULL ); i=0; while (1) //waiting for GET_CHAN answer { caplen = read(sock, &nh, sizeof(nh)); if(caplen == -1) { if( errno != EAGAIN ) { perror(""read""); return -1; } } if( (unsigned)caplen == sizeof(nh)) { len = ntohl(nh.nh_len); if( nh.nh_type == 1 && i==0 ) { i=1; caplen = read(sock, packet, len); if(caplen == len) { i=2; break; } else { i=0; } } else { caplen = read(sock, packet, len); } } gettimeofday( &tv2, NULL ); //wait 1000ms for an answer if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000)) { break; } if(caplen == -1) usleep(10); } if(i==2) { PCT; printf(""airserv-ng found\n""); } else { PCT; printf(""airserv-ng NOT found\n""); } close(sock); for(i=0; i (1000*1000)) { break; } //simple ""high-precision"" usleep select(1, NULL, NULL, NULL, &tv3); } times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)); printf( ""\r%d/%d\r"", i, REQUESTS); fflush(stdout); close(sock); } min = INT_MAX; avg = 0; max = 0; for(i=0; i max) max = times[i]; avg += times[i]; } avg /= REQUESTS; PCT; printf(""ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n"", ip_str, port, min/1000.0, avg/1000.0, max/1000.0); return 0; }","int tcp_test(const char* ip_str, const short port) { int sock, i; struct sockaddr_in s_in; int packetsize = 1024; unsigned char packet[packetsize]; struct timeval tv, tv2, tv3; int caplen = 0; int times[REQUESTS]; int min, avg, max, len; struct net_hdr nh; tv3.tv_sec=0; tv3.tv_usec=1; s_in.sin_family = PF_INET; s_in.sin_port = htons(port); if (!inet_aton(ip_str, &s_in.sin_addr)) return -1; if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1) return -1; /* avoid blocking on reading the socket */ if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 ) { perror( ""fcntl(O_NONBLOCK) failed"" ); return( 1 ); } gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) { if(errno != EINPROGRESS && errno != EALREADY) { perror(""connect""); close(sock); printf(""Failed to connect\n""); return -1; } } else { gettimeofday( &tv2, NULL ); break; } gettimeofday( &tv2, NULL ); //wait 3000ms for a successful connect if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000)) { printf(""Connection timed out\n""); close(sock); return(-1); } usleep(10); } PCT; printf(""TCP connection successful\n""); //trying to identify airserv-ng memset(&nh, 0, sizeof(nh)); // command: GET_CHAN nh.nh_type = 2; nh.nh_len = htonl(0); if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh)) { perror(""send""); return -1; } gettimeofday( &tv, NULL ); i=0; while (1) //waiting for GET_CHAN answer { caplen = read(sock, &nh, sizeof(nh)); if(caplen == -1) { if( errno != EAGAIN ) { perror(""read""); return -1; } } if( (unsigned)caplen == sizeof(nh)) { len = ntohl(nh.nh_len); if (len > 1024 || len < 0) continue; if( nh.nh_type == 1 && i==0 ) { i=1; caplen = read(sock, packet, len); if(caplen == len) { i=2; break; } else { i=0; } } else { caplen = read(sock, packet, len); } } gettimeofday( &tv2, NULL ); //wait 1000ms for an answer if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000)) { break; } if(caplen == -1) usleep(10); } if(i==2) { PCT; printf(""airserv-ng found\n""); } else { PCT; printf(""airserv-ng NOT found\n""); } close(sock); for(i=0; i (1000*1000)) { break; } //simple ""high-precision"" usleep select(1, NULL, NULL, NULL, &tv3); } times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)); printf( ""\r%d/%d\r"", i, REQUESTS); fflush(stdout); close(sock); } min = INT_MAX; avg = 0; max = 0; for(i=0; i max) max = times[i]; avg += times[i]; } avg /= REQUESTS; PCT; printf(""ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n"", ip_str, port, min/1000.0, avg/1000.0, max/1000.0); return 0; }","{'deleted': [], 'added': [{'line_no': 97, 'char_start': 2251, 'char_end': 2290, 'line': ' if (len > 1024 || len < 0)\n'}, {'line_no': 98, 'char_start': 2290, 'char_end': 2316, 'line': ' continue;\n'}]}","{'deleted': [], 'added': [{'char_start': 2265, 'char_end': 2330, 'chars': ' (len > 1024 || len < 0)\n continue;\n if'}]}",github.com/aircrack-ng/aircrack-ng/commit/091b153f294b9b695b0b2831e65936438b550d7b,src/aireplay-ng.c,cwe-787,1385 cwe-125,parse_string,"static const char *parse_string(cJSON *item,const char *str,const char **ep) { const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\""') {*ep=str;return 0;} /* not a string! */ while (*end_ptr!='\""' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */ out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */ item->type=cJSON_String; ptr=str+1;ptr2=out; while (ptr < end_ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */ if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ { if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */ if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */ uc2=parse_hex4(ptr+3);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */ uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\""') ptr++; return ptr; }","static const char *parse_string(cJSON *item,const char *str,const char **ep) { const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\""') {*ep=str;return 0;} /* not a string! */ while (*end_ptr!='\""' && *end_ptr && ++len) { if (*end_ptr++ == '\\') { if (*end_ptr == '\0') { /* prevent buffer overflow when last input character is a backslash */ return 0; } end_ptr++; /* Skip escaped quotes. */ } } out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */ item->type=cJSON_String; ptr=str+1;ptr2=out; while (ptr < end_ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */ if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ { if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */ if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */ uc2=parse_hex4(ptr+3);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */ uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\""') ptr++; return ptr; }","{'deleted': [{'line_no': 5, 'char_start': 222, 'char_end': 224, 'line': '\t\n'}, {'line_no': 6, 'char_start': 224, 'char_end': 331, 'line': '\twhile (*end_ptr!=\'\\""\' && *end_ptr && ++len) if (*end_ptr++ == \'\\\\\') end_ptr++;\t/* Skip escaped quotes. */\n'}, {'line_no': 7, 'char_start': 331, 'char_end': 333, 'line': '\t\n'}], 'added': [{'line_no': 5, 'char_start': 222, 'char_end': 223, 'line': '\n'}, {'line_no': 6, 'char_start': 223, 'char_end': 268, 'line': '\twhile (*end_ptr!=\'\\""\' && *end_ptr && ++len)\n'}, {'line_no': 7, 'char_start': 268, 'char_end': 271, 'line': '\t{\n'}, {'line_no': 8, 'char_start': 271, 'char_end': 300, 'line': ""\t if (*end_ptr++ == '\\\\')\n""}, {'line_no': 9, 'char_start': 300, 'char_end': 307, 'line': '\t {\n'}, {'line_no': 10, 'char_start': 307, 'char_end': 331, 'line': ""\t\tif (*end_ptr == '\\0')\n""}, {'line_no': 11, 'char_start': 331, 'char_end': 335, 'line': '\t\t{\n'}, {'line_no': 12, 'char_start': 335, 'char_end': 412, 'line': '\t\t /* prevent buffer overflow when last input character is a backslash */\n'}, {'line_no': 13, 'char_start': 412, 'char_end': 428, 'line': '\t\t return 0;\n'}, {'line_no': 14, 'char_start': 428, 'char_end': 432, 'line': '\t\t}\n'}, {'line_no': 15, 'char_start': 432, 'char_end': 472, 'line': '\t\tend_ptr++;\t/* Skip escaped quotes. */\n'}, {'line_no': 16, 'char_start': 472, 'char_end': 479, 'line': '\t }\n'}, {'line_no': 17, 'char_start': 479, 'char_end': 482, 'line': '\t}\n'}, {'line_no': 18, 'char_start': 482, 'char_end': 483, 'line': '\n'}]}","{'deleted': [{'char_start': 222, 'char_end': 223, 'chars': '\t'}], 'added': [{'char_start': 267, 'char_end': 275, 'chars': '\n\t{\n\t '}, {'char_start': 299, 'char_end': 301, 'chars': '\n\t'}, {'char_start': 302, 'char_end': 434, 'chars': "" {\n\t\tif (*end_ptr == '\\0')\n\t\t{\n\t\t /* prevent buffer overflow when last input character is a backslash */\n\t\t return 0;\n\t\t}\n\t\t""}, {'char_start': 473, 'char_end': 482, 'chars': ' }\n\t}\n'}]}",github.com/DaveGamble/cJSON/commit/94df772485c92866ca417d92137747b2e3b0a917,cJSON.c,cwe-125,788 cwe-089,edit,"@mod.route('/edit/', methods=['GET', 'POST']) def edit(msg_id): m = None if request.method == 'GET': sql = ""SELECT * FROM message where msg_id = %d;"" % (msg_id) cursor.execute(sql) m = cursor.fetchone() return render_template('message/edit.html', m=m, msg_id=msg_id) if request.method == 'POST': content = request.form['content'] sql = ""UPDATE message SET content = '%s' where msg_id = '%d';"" \ % (content, msg_id) cursor.execute(sql) conn.commit() flash('Edit Success!') return redirect(url_for('show_entries')) return render_template('message/edit.html', m=m, msg_id=msg_id)","@mod.route('/edit/', methods=['GET', 'POST']) def edit(msg_id): m = None if request.method == 'GET': cursor.execute(""SELECT * FROM message where msg_id = %s;"", (msg_id,)) m = cursor.fetchone() return render_template('message/edit.html', m=m, msg_id=msg_id) if request.method == 'POST': content = request.form['content'] cursor.execute(""UPDATE message SET content = %s where msg_id = %s;"", (content, msg_id)) conn.commit() flash('Edit Success!') return redirect(url_for('show_entries')) return render_template('message/edit.html', m=m, msg_id=msg_id)","{'deleted': [{'line_no': 5, 'char_start': 121, 'char_end': 189, 'line': ' sql = ""SELECT * FROM message where msg_id = %d;"" % (msg_id)\n'}, {'line_no': 6, 'char_start': 189, 'char_end': 217, 'line': ' cursor.execute(sql)\n'}, {'line_no': 12, 'char_start': 395, 'char_end': 468, 'line': ' sql = ""UPDATE message SET content = \'%s\' where msg_id = \'%d\';"" \\\n'}, {'line_no': 13, 'char_start': 468, 'char_end': 500, 'line': ' % (content, msg_id)\n'}, {'line_no': 14, 'char_start': 500, 'char_end': 528, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 5, 'char_start': 121, 'char_end': 199, 'line': ' cursor.execute(""SELECT * FROM message where msg_id = %s;"", (msg_id,))\n'}, {'line_no': 11, 'char_start': 377, 'char_end': 473, 'line': ' cursor.execute(""UPDATE message SET content = %s where msg_id = %s;"", (content, msg_id))\n'}]}","{'deleted': [{'char_start': 130, 'char_end': 135, 'chars': 'ql = '}, {'char_start': 174, 'char_end': 175, 'chars': 'd'}, {'char_start': 177, 'char_end': 179, 'chars': ' %'}, {'char_start': 188, 'char_end': 215, 'chars': '\n cursor.execute(sql'}, {'char_start': 404, 'char_end': 409, 'chars': 'ql = '}, {'char_start': 439, 'char_end': 440, 'chars': ""'""}, {'char_start': 442, 'char_end': 443, 'chars': ""'""}, {'char_start': 459, 'char_end': 460, 'chars': ""'""}, {'char_start': 461, 'char_end': 463, 'chars': ""d'""}, {'char_start': 465, 'char_end': 481, 'chars': ' \\\n %'}, {'char_start': 499, 'char_end': 526, 'chars': '\n cursor.execute(sql'}], 'added': [{'char_start': 129, 'char_end': 132, 'chars': 'cur'}, {'char_start': 133, 'char_end': 144, 'chars': 'or.execute('}, {'char_start': 183, 'char_end': 184, 'chars': 's'}, {'char_start': 186, 'char_end': 187, 'chars': ','}, {'char_start': 195, 'char_end': 196, 'chars': ','}, {'char_start': 385, 'char_end': 388, 'chars': 'cur'}, {'char_start': 389, 'char_end': 400, 'chars': 'or.execute('}, {'char_start': 449, 'char_end': 450, 'chars': 's'}, {'char_start': 452, 'char_end': 453, 'chars': ','}]}",github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9,flaskr/flaskr/views/message.py,cwe-089,170 cwe-089,load_user,"@login_manager.user_loader def load_user(s_id): email = str(s_id) query = '''select * from usr where email like\'''' + email + '\'' cursor = g.conn.execute(query) user = User() for row in cursor: user.name = str(row.name) user.email = str(row.email) break return user","@login_manager.user_loader def load_user(s_id): email = str(s_id) query = 'select * from usr where email like %s' cursor = g.conn.execute(query, (email, )) user = User() for row in cursor: user.name = str(row.name) user.email = str(row.email) break return user","{'deleted': [{'line_no': 4, 'char_start': 70, 'char_end': 140, 'line': "" query = '''select * from usr where email like\\'''' + email + '\\''\n""}, {'line_no': 5, 'char_start': 140, 'char_end': 175, 'line': ' cursor = g.conn.execute(query)\n'}], 'added': [{'line_no': 4, 'char_start': 70, 'char_end': 122, 'line': "" query = 'select * from usr where email like %s'\n""}, {'line_no': 5, 'char_start': 122, 'char_end': 168, 'line': ' cursor = g.conn.execute(query, (email, ))\n'}]}","{'deleted': [{'char_start': 83, 'char_end': 85, 'chars': ""''""}, {'char_start': 119, 'char_end': 124, 'chars': ""\\''''""}, {'char_start': 125, 'char_end': 138, 'chars': ""+ email + '\\'""}], 'added': [{'char_start': 118, 'char_end': 120, 'chars': '%s'}, {'char_start': 155, 'char_end': 166, 'chars': ', (email, )'}]}",github.com/Daniel-Bu/w4111-project1/commit/fe04bedc72e62fd4c4ee046a9af29fd81e9b3340,Web-app/Server.py,cwe-089,78 cwe-089,get_first_ranked_month,"def get_first_ranked_month(db, scene, player): sql = ""select date from ranks where scene='{}' and player='{}' order by date limit 1;"".format(scene, player) res = db.exec(sql) date = res[0][0] return date","def get_first_ranked_month(db, scene, player): sql = ""select date from ranks where scene='{scene}' and player='{player}' order by date limit 1;"" args = {'scene': scene, 'player': player} res = db.exec(sql, args) date = res[0][0] return date","{'deleted': [{'line_no': 2, 'char_start': 47, 'char_end': 160, 'line': ' sql = ""select date from ranks where scene=\'{}\' and player=\'{}\' order by date limit 1;"".format(scene, player)\n'}, {'line_no': 3, 'char_start': 160, 'char_end': 183, 'line': ' res = db.exec(sql)\n'}], 'added': [{'line_no': 2, 'char_start': 47, 'char_end': 149, 'line': ' sql = ""select date from ranks where scene=\'{scene}\' and player=\'{player}\' order by date limit 1;""\n'}, {'line_no': 3, 'char_start': 149, 'char_end': 195, 'line': "" args = {'scene': scene, 'player': player}\n""}, {'line_no': 4, 'char_start': 195, 'char_end': 224, 'line': ' res = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 137, 'char_end': 140, 'chars': '.fo'}, {'char_start': 141, 'char_end': 145, 'chars': 'mat('}, {'char_start': 158, 'char_end': 159, 'chars': ')'}], 'added': [{'char_start': 95, 'char_end': 100, 'chars': 'scene'}, {'char_start': 116, 'char_end': 122, 'chars': 'player'}, {'char_start': 148, 'char_end': 153, 'chars': '\n '}, {'char_start': 154, 'char_end': 170, 'chars': ""rgs = {'scene': ""}, {'char_start': 177, 'char_end': 178, 'chars': ""'""}, {'char_start': 184, 'char_end': 194, 'chars': ""': player}""}, {'char_start': 216, 'char_end': 222, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,bracket_utils.py,cwe-089,62 cwe-078,_ensure_vdisk_no_fc_mappings," def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True): # Ensure vdisk has no FlashCopy mappings mapping_ids = self._get_vdisk_fc_mappings(name) while len(mapping_ids): wait_for_copy = False for map_id in mapping_ids: attrs = self._get_flashcopy_mapping_attributes(map_id) if not attrs: continue source = attrs['source_vdisk_name'] target = attrs['target_vdisk_name'] copy_rate = attrs['copy_rate'] status = attrs['status'] if copy_rate == '0': # Case #2: A vdisk that has snapshots if source == name: if not allow_snaps: return False ssh_cmd = ('svctask chfcmap -copyrate 50 ' '-autodelete on %s' % map_id) out, err = self._run_ssh(ssh_cmd) wait_for_copy = True # Case #3: A snapshot else: msg = (_('Vdisk %(name)s not involved in ' 'mapping %(src)s -> %(tgt)s') % {'name': name, 'src': source, 'tgt': target}) self._driver_assert(target == name, msg) if status in ['copying', 'prepared']: self._run_ssh('svctask stopfcmap %s' % map_id) elif status in ['stopping', 'preparing']: wait_for_copy = True else: self._run_ssh('svctask rmfcmap -force %s' % map_id) # Case 4: Copy in progress - wait and will autodelete else: if status == 'prepared': self._run_ssh('svctask stopfcmap %s' % map_id) self._run_ssh('svctask rmfcmap -force %s' % map_id) elif status == 'idle_or_copied': # Prepare failed self._run_ssh('svctask rmfcmap -force %s' % map_id) else: wait_for_copy = True if wait_for_copy: time.sleep(5) mapping_ids = self._get_vdisk_fc_mappings(name) return True"," def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True): # Ensure vdisk has no FlashCopy mappings mapping_ids = self._get_vdisk_fc_mappings(name) while len(mapping_ids): wait_for_copy = False for map_id in mapping_ids: attrs = self._get_flashcopy_mapping_attributes(map_id) if not attrs: continue source = attrs['source_vdisk_name'] target = attrs['target_vdisk_name'] copy_rate = attrs['copy_rate'] status = attrs['status'] if copy_rate == '0': # Case #2: A vdisk that has snapshots if source == name: if not allow_snaps: return False ssh_cmd = ['svctask', 'chfcmap', '-copyrate', '50', '-autodelete', 'on', map_id] out, err = self._run_ssh(ssh_cmd) wait_for_copy = True # Case #3: A snapshot else: msg = (_('Vdisk %(name)s not involved in ' 'mapping %(src)s -> %(tgt)s') % {'name': name, 'src': source, 'tgt': target}) self._driver_assert(target == name, msg) if status in ['copying', 'prepared']: self._run_ssh(['svctask', 'stopfcmap', map_id]) elif status in ['stopping', 'preparing']: wait_for_copy = True else: self._run_ssh(['svctask', 'rmfcmap', '-force', map_id]) # Case 4: Copy in progress - wait and will autodelete else: if status == 'prepared': self._run_ssh(['svctask', 'stopfcmap', map_id]) self._run_ssh(['svctask', 'rmfcmap', '-force', map_id]) elif status == 'idle_or_copied': # Prepare failed self._run_ssh(['svctask', 'rmfcmap', '-force', map_id]) else: wait_for_copy = True if wait_for_copy: time.sleep(5) mapping_ids = self._get_vdisk_fc_mappings(name) return True","{'deleted': [{'line_no': 20, 'char_start': 820, 'char_end': 887, 'line': "" ssh_cmd = ('svctask chfcmap -copyrate 50 '\n""}, {'line_no': 21, 'char_start': 887, 'char_end': 952, 'line': "" '-autodelete on %s' % map_id)\n""}, {'line_no': 31, 'char_start': 1459, 'char_end': 1534, 'line': "" self._run_ssh('svctask stopfcmap %s' % map_id)\n""}, {'line_no': 35, 'char_start': 1679, 'char_end': 1759, 'line': "" self._run_ssh('svctask rmfcmap -force %s' % map_id)\n""}, {'line_no': 39, 'char_start': 1896, 'char_end': 1967, 'line': "" self._run_ssh('svctask stopfcmap %s' % map_id)\n""}, {'line_no': 40, 'char_start': 1967, 'char_end': 2043, 'line': "" self._run_ssh('svctask rmfcmap -force %s' % map_id)\n""}, {'line_no': 43, 'char_start': 2137, 'char_end': 2213, 'line': "" self._run_ssh('svctask rmfcmap -force %s' % map_id)\n""}], 'added': [{'line_no': 20, 'char_start': 820, 'char_end': 896, 'line': "" ssh_cmd = ['svctask', 'chfcmap', '-copyrate', '50',\n""}, {'line_no': 21, 'char_start': 896, 'char_end': 960, 'line': "" '-autodelete', 'on', map_id]\n""}, {'line_no': 31, 'char_start': 1467, 'char_end': 1543, 'line': "" self._run_ssh(['svctask', 'stopfcmap', map_id])\n""}, {'line_no': 35, 'char_start': 1688, 'char_end': 1763, 'line': "" self._run_ssh(['svctask', 'rmfcmap', '-force',\n""}, {'line_no': 36, 'char_start': 1763, 'char_end': 1815, 'line': ' map_id])\n'}, {'line_no': 40, 'char_start': 1952, 'char_end': 2024, 'line': "" self._run_ssh(['svctask', 'stopfcmap', map_id])\n""}, {'line_no': 41, 'char_start': 2024, 'char_end': 2104, 'line': "" self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n""}, {'line_no': 44, 'char_start': 2198, 'char_end': 2278, 'line': "" self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n""}]}","{'deleted': [{'char_start': 854, 'char_end': 855, 'chars': '('}, {'char_start': 884, 'char_end': 885, 'chars': ' '}, {'char_start': 937, 'char_end': 940, 'chars': ' %s'}, {'char_start': 941, 'char_end': 943, 'chars': ' %'}, {'char_start': 950, 'char_end': 951, 'chars': ')'}, {'char_start': 1519, 'char_end': 1522, 'chars': ' %s'}, {'char_start': 1523, 'char_end': 1525, 'chars': ' %'}, {'char_start': 1745, 'char_end': 1748, 'chars': ""%s'""}, {'char_start': 1749, 'char_end': 1750, 'chars': '%'}, {'char_start': 1952, 'char_end': 1955, 'chars': ' %s'}, {'char_start': 1956, 'char_end': 1958, 'chars': ' %'}, {'char_start': 2028, 'char_end': 2031, 'chars': ' %s'}, {'char_start': 2032, 'char_end': 2034, 'chars': ' %'}, {'char_start': 2198, 'char_end': 2201, 'chars': ' %s'}, {'char_start': 2202, 'char_end': 2204, 'chars': ' %'}], 'added': [{'char_start': 854, 'char_end': 855, 'chars': '['}, {'char_start': 863, 'char_end': 865, 'chars': ""',""}, {'char_start': 866, 'char_end': 867, 'chars': ""'""}, {'char_start': 874, 'char_end': 876, 'chars': ""',""}, {'char_start': 877, 'char_end': 878, 'chars': ""'""}, {'char_start': 887, 'char_end': 889, 'chars': ""',""}, {'char_start': 890, 'char_end': 891, 'chars': ""'""}, {'char_start': 894, 'char_end': 895, 'chars': ','}, {'char_start': 943, 'char_end': 945, 'chars': ""',""}, {'char_start': 946, 'char_end': 947, 'chars': ""'""}, {'char_start': 950, 'char_end': 951, 'chars': ','}, {'char_start': 958, 'char_end': 959, 'chars': ']'}, {'char_start': 1509, 'char_end': 1510, 'chars': '['}, {'char_start': 1518, 'char_end': 1520, 'chars': ""',""}, {'char_start': 1521, 'char_end': 1522, 'chars': ""'""}, {'char_start': 1532, 'char_end': 1533, 'chars': ','}, {'char_start': 1540, 'char_end': 1541, 'chars': ']'}, {'char_start': 1730, 'char_end': 1731, 'chars': '['}, {'char_start': 1739, 'char_end': 1741, 'chars': ""',""}, {'char_start': 1742, 'char_end': 1743, 'chars': ""'""}, {'char_start': 1750, 'char_end': 1752, 'chars': ""',""}, {'char_start': 1753, 'char_end': 1754, 'chars': ""'""}, {'char_start': 1760, 'char_end': 1767, 'chars': ""',\n ""}, {'char_start': 1768, 'char_end': 1775, 'chars': ' '}, {'char_start': 1776, 'char_end': 1805, 'chars': ' '}, {'char_start': 1812, 'char_end': 1813, 'chars': ']'}, {'char_start': 1990, 'char_end': 1991, 'chars': '['}, {'char_start': 1999, 'char_end': 2001, 'chars': ""',""}, {'char_start': 2002, 'char_end': 2003, 'chars': ""'""}, {'char_start': 2013, 'char_end': 2014, 'chars': ','}, {'char_start': 2021, 'char_end': 2022, 'chars': ']'}, {'char_start': 2062, 'char_end': 2063, 'chars': '['}, {'char_start': 2071, 'char_end': 2073, 'chars': ""',""}, {'char_start': 2074, 'char_end': 2075, 'chars': ""'""}, {'char_start': 2082, 'char_end': 2084, 'chars': ""',""}, {'char_start': 2085, 'char_end': 2086, 'chars': ""'""}, {'char_start': 2093, 'char_end': 2094, 'chars': ','}, {'char_start': 2101, 'char_end': 2102, 'chars': ']'}, {'char_start': 2236, 'char_end': 2237, 'chars': '['}, {'char_start': 2245, 'char_end': 2247, 'chars': ""',""}, {'char_start': 2248, 'char_end': 2249, 'chars': ""'""}, {'char_start': 2256, 'char_end': 2258, 'chars': ""',""}, {'char_start': 2259, 'char_end': 2260, 'chars': ""'""}, {'char_start': 2267, 'char_end': 2268, 'chars': ','}, {'char_start': 2275, 'char_end': 2276, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,489 cwe-078,talk,"def talk(myText): if( myText.find( ""twitter"" ) >= 0 ): myText += ""0"" myText = myText[7:-1] try: myText = twitter.getTweet( myText ) except: print( ""!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions."") return os.system( ""espeak \"",...\"" 2>/dev/null"" ) # Sometimes the beginning of audio can get cut off. Insert silence. time.sleep( 0.5 ) os.system( ""espeak -w speech.wav \"""" + myText + ""\"" -s 130"" ) audio.play(""speech.wav"") return myText","def talk(myText): if( myText.find( ""twitter"" ) >= 0 ): myText += ""0"" myText = myText[7:-1] try: myText = twitter.getTweet( myText ) except: print( ""!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions."") return os.system( ""espeak \"",...\"" 2>/dev/null"" ) # Sometimes the beginning of audio can get cut off. Insert silence. time.sleep( 0.5 ) subprocess.call([""espeak"", ""-w"", ""speech.wav"", myText, ""-s"", ""130""]) audio.play(""speech.wav"") return myText","{'deleted': [{'line_no': 13, 'char_start': 441, 'char_end': 508, 'line': ' os.system( ""espeak -w speech.wav \\"""" + myText + ""\\"" -s 130"" )\r\n'}], 'added': [{'line_no': 13, 'char_start': 441, 'char_end': 515, 'line': ' subprocess.call([""espeak"", ""-w"", ""speech.wav"", myText, ""-s"", ""130""])\r\n'}]}","{'deleted': [{'char_start': 447, 'char_end': 448, 'chars': '.'}, {'char_start': 449, 'char_end': 454, 'chars': 'ystem'}, {'char_start': 455, 'char_end': 456, 'chars': ' '}, {'char_start': 477, 'char_end': 479, 'chars': ' \\'}, {'char_start': 480, 'char_end': 483, 'chars': '"" +'}, {'char_start': 490, 'char_end': 492, 'chars': ' +'}, {'char_start': 494, 'char_end': 497, 'chars': '\\"" '}, {'char_start': 504, 'char_end': 505, 'chars': ' '}], 'added': [{'char_start': 445, 'char_end': 450, 'chars': 'subpr'}, {'char_start': 451, 'char_end': 454, 'chars': 'ces'}, {'char_start': 456, 'char_end': 460, 'chars': 'call'}, {'char_start': 461, 'char_end': 462, 'chars': '['}, {'char_start': 469, 'char_end': 471, 'chars': '"",'}, {'char_start': 472, 'char_end': 473, 'chars': '""'}, {'char_start': 475, 'char_end': 477, 'chars': '"",'}, {'char_start': 478, 'char_end': 479, 'chars': '""'}, {'char_start': 490, 'char_end': 491, 'chars': ','}, {'char_start': 498, 'char_end': 499, 'chars': ','}, {'char_start': 503, 'char_end': 505, 'chars': '"",'}, {'char_start': 506, 'char_end': 507, 'chars': '""'}, {'char_start': 511, 'char_end': 512, 'chars': ']'}]}",github.com/ntc-chip-revived/ChippyRuxpin/commit/0cd7d78e4d806852fd75fee03c24cce322f76014,chippyRuxpin.py,cwe-078,156 cwe-125,ComplexImages,"MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag ""Complex/Image"" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, ""ImageSequenceRequired"",""`%s'"",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,""complex:snr""); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L) #endif for (y=0; y < (ssize_t) Cr_image->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) Cr_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]); Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]); Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); }","MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag ""Complex/Image"" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; size_t number_channels; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, ""ImageSequenceRequired"",""`%s'"",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,""complex:snr""); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; number_channels=MagickMin(MagickMin(MagickMin( Ar_image->number_channels,Ai_image->number_channels),MagickMin( Br_image->number_channels,Bi_image->number_channels)),MagickMin( Cr_image->number_channels,Ci_image->number_channels)); Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L) #endif for (y=0; y < (ssize_t) Cr_image->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) Cr_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_channels; i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]); Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]); Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); }","{'deleted': [{'line_no': 137, 'char_start': 3900, 'char_end': 3963, 'line': ' for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)\n'}], 'added': [{'line_no': 38, 'char_start': 511, 'char_end': 520, 'line': ' size_t\n'}, {'line_no': 39, 'char_start': 520, 'char_end': 541, 'line': ' number_channels;\n'}, {'line_no': 40, 'char_start': 541, 'char_end': 542, 'line': '\n'}, {'line_no': 93, 'char_start': 2196, 'char_end': 2245, 'line': ' number_channels=MagickMin(MagickMin(MagickMin(\n'}, {'line_no': 94, 'char_start': 2245, 'char_end': 2313, 'line': ' Ar_image->number_channels,Ai_image->number_channels),MagickMin(\n'}, {'line_no': 95, 'char_start': 2313, 'char_end': 2382, 'line': ' Br_image->number_channels,Bi_image->number_channels)),MagickMin(\n'}, {'line_no': 96, 'char_start': 2382, 'char_end': 2441, 'line': ' Cr_image->number_channels,Ci_image->number_channels));\n'}, {'line_no': 144, 'char_start': 4176, 'char_end': 4228, 'line': ' for (i=0; i < (ssize_t) number_channels; i++)\n'}]}","{'deleted': [{'char_start': 521, 'char_end': 521, 'chars': ''}, {'char_start': 3930, 'char_end': 3931, 'chars': 'G'}, {'char_start': 3932, 'char_end': 3939, 'chars': 'tPixelC'}, {'char_start': 3946, 'char_end': 3956, 'chars': '(Cr_image)'}], 'added': [{'char_start': 514, 'char_end': 545, 'chars': 'ize_t\n number_channels;\n\n s'}, {'char_start': 2196, 'char_end': 2441, 'chars': ' number_channels=MagickMin(MagickMin(MagickMin(\n Ar_image->number_channels,Ai_image->number_channels),MagickMin(\n Br_image->number_channels,Bi_image->number_channels)),MagickMin(\n Cr_image->number_channels,Ci_image->number_channels));\n'}, {'char_start': 4206, 'char_end': 4210, 'chars': 'numb'}, {'char_start': 4211, 'char_end': 4214, 'chars': 'r_c'}]}",github.com/ImageMagick/ImageMagick/commit/d5089971bd792311aaab5cb73460326d7ef7f32d,MagickCore/fourier.c,cwe-125,1796 cwe-089,showPoll,"@hook.command(autohelp=False) def showPoll(pollID, db=None): """"""Shows the answers for a given poll."""""" if not db_ready: db_init(db) if pollID == None: poll = db.execute(""SELECT pollID, question FROM polls WHERE active = 1"") if len(poll) == 0: reply(""There's no poll open."") return else: poll = db.execute(""SELECT pollID, question FROM polls WHERE pollID = '{}'"".format(pollID)) if len(poll) == 0: reply(""No such poll found."") return pollID = poll[0][0] question = poll[0][1] reply(question) for (index, answer, votes) in db.execute(""SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = {} GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC"".format(pollID, )): reply(""%s. %s (%s)"" % (index, answer, votes))","@hook.command(autohelp=False) def showPoll(pollID, db=None): """"""Shows the answers for a given poll."""""" if not db_ready: db_init(db) if pollID == None: poll = db.execute(""SELECT pollID, question FROM polls WHERE active = 1"") if len(poll) == 0: reply(""There's no poll open."") return else: poll = db.execute(""SELECT pollID, question FROM polls WHERE pollID = ?"", (pollID,)) if len(poll) == 0: reply(""No such poll found."") return pollID = poll[0][0] question = poll[0][1] reply(question) for (index, answer, votes) in db.execute(""SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = ? GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC"", (pollID, )): reply(""%s. %s (%s)"" % (index, answer, votes))","{'deleted': [{'line_no': 11, 'char_start': 343, 'char_end': 442, 'line': ' poll = db.execute(""SELECT pollID, question FROM polls WHERE pollID = \'{}\'"".format(pollID))\n'}, {'line_no': 18, 'char_start': 599, 'char_end': 851, 'line': ' for (index, answer, votes) in db.execute(""SELECT \'index\', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = {} GROUP BY answers.answerID, \'index\', answer ORDER BY \'index\' ASC"".format(pollID, )):\n'}], 'added': [{'line_no': 11, 'char_start': 343, 'char_end': 435, 'line': ' poll = db.execute(""SELECT pollID, question FROM polls WHERE pollID = ?"", (pollID,))\n'}, {'line_no': 18, 'char_start': 592, 'char_end': 838, 'line': ' for (index, answer, votes) in db.execute(""SELECT \'index\', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = ? GROUP BY answers.answerID, \'index\', answer ORDER BY \'index\' ASC"", (pollID, )):\n'}]}","{'deleted': [{'char_start': 420, 'char_end': 424, 'chars': ""'{}'""}, {'char_start': 425, 'char_end': 432, 'chars': '.format'}, {'char_start': 764, 'char_end': 766, 'chars': '{}'}, {'char_start': 831, 'char_end': 838, 'chars': '.format'}], 'added': [{'char_start': 420, 'char_end': 421, 'chars': '?'}, {'char_start': 422, 'char_end': 424, 'chars': ', '}, {'char_start': 431, 'char_end': 432, 'chars': ','}, {'char_start': 757, 'char_end': 758, 'chars': '?'}, {'char_start': 823, 'char_end': 825, 'chars': ', '}]}",github.com/FrozenPigs/Taigabot/commit/ea9b83a66ae1f0f38a1895f3e8dfa2833d77e3a6,plugins/poll.py,cwe-089,240 cwe-089,insertUsage,"def insertUsage(user, command): c, conn = getConnection() date = now() c.execute(""INSERT INTO usage (date,user,command) VALUES ('""+date+""','""+str(user)+""','""+command+""')"") conn.commit() conn.close()","def insertUsage(user, command): c, conn = getConnection() date = now() c.execute(""INSERT INTO usage (date,user,command) VALUES (?,?,?)"",(date,str(user),command)) conn.commit() conn.close()","{'deleted': [{'line_no': 4, 'char_start': 73, 'char_end': 175, 'line': '\tc.execute(""INSERT INTO usage (date,user,command) VALUES (\'""+date+""\',\'""+str(user)+""\',\'""+command+""\')"")\n'}], 'added': [{'line_no': 4, 'char_start': 73, 'char_end': 165, 'line': '\tc.execute(""INSERT INTO usage (date,user,command) VALUES (?,?,?)"",(date,str(user),command))\n'}]}","{'deleted': [{'char_start': 131, 'char_end': 132, 'chars': ""'""}, {'char_start': 133, 'char_end': 134, 'chars': '+'}, {'char_start': 138, 'char_end': 141, 'chars': '+""\''}, {'char_start': 142, 'char_end': 145, 'chars': '\'""+'}, {'char_start': 154, 'char_end': 157, 'chars': '+""\''}, {'char_start': 158, 'char_end': 161, 'chars': '\'""+'}, {'char_start': 168, 'char_end': 171, 'chars': '+""\''}, {'char_start': 172, 'char_end': 173, 'chars': '""'}], 'added': [{'char_start': 131, 'char_end': 137, 'chars': '?,?,?)'}, {'char_start': 138, 'char_end': 140, 'chars': ',('}]}",github.com/DangerBlack/DungeonsAndDragonsMasterBot/commit/63f980c6dff746f5fcf3005d0646b6c24f81cdc0,database.py,cwe-089,48 cwe-125,AdaptiveThresholdImage,"MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag ""Threshold/Image"" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); }","MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag ""Threshold/Image"" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); }","{'deleted': [], 'added': [{'line_no': 38, 'char_start': 875, 'char_end': 893, 'line': ' if (width == 0)\n'}, {'line_no': 39, 'char_start': 893, 'char_end': 922, 'line': ' return(threshold_image);\n'}]}","{'deleted': [], 'added': [{'char_start': 881, 'char_end': 928, 'chars': 'width == 0)\n return(threshold_image);\n if ('}]}",github.com/ImageMagick/ImageMagick6/commit/55e6dc49f1a381d9d511ee2f888fdc3e3c3e3953,magick/threshold.c,cwe-125,1601 cwe-416,SetImageType,"MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type) { const char *artifact; ImageInfo *image_info; MagickBooleanType status; QuantizeInfo *quantize_info; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""...""); assert(image->signature == MagickSignature); status=MagickTrue; image_info=AcquireImageInfo(); image_info->dither=image->dither; artifact=GetImageArtifact(image,""dither""); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,""dither"",artifact); switch (type) { case BilevelType: { if (SetImageMonochrome(image,&image->exception) == MagickFalse) { status=TransformImageColorspace(image,GRAYColorspace); (void) NormalizeImage(image); quantize_info=AcquireQuantizeInfo(image_info); quantize_info->number_colors=2; quantize_info->colorspace=GRAYColorspace; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); } image->colors=2; image->matte=MagickFalse; break; } case GrayscaleType: { if (SetImageGray(image,&image->exception) == MagickFalse) status=TransformImageColorspace(image,GRAYColorspace); image->matte=MagickFalse; break; } case GrayscaleMatteType: { if (SetImageGray(image,&image->exception) == MagickFalse) status=TransformImageColorspace(image,GRAYColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case PaletteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if ((image->storage_class == DirectClass) || (image->colors > 256)) { quantize_info=AcquireQuantizeInfo(image_info); quantize_info->number_colors=256; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); } image->matte=MagickFalse; break; } case PaletteBilevelMatteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); (void) BilevelImageChannel(image,AlphaChannel,(double) QuantumRange/2.0); quantize_info=AcquireQuantizeInfo(image_info); status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); break; } case PaletteMatteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); quantize_info=AcquireQuantizeInfo(image_info); quantize_info->colorspace=TransparentColorspace; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); break; } case TrueColorType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); image->matte=MagickFalse; break; } case TrueColorMatteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case ColorSeparationType: { if (image->colorspace != CMYKColorspace) { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); status=TransformImageColorspace(image,CMYKColorspace); } if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); image->matte=MagickFalse; break; } case ColorSeparationMatteType: { if (image->colorspace != CMYKColorspace) { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); status=TransformImageColorspace(image,CMYKColorspace); } if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case OptimizeType: case UndefinedType: break; } image_info=DestroyImageInfo(image_info); if (status == MagickFalse) return(MagickFalse); image->type=type; return(MagickTrue); }","MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type) { const char *artifact; ImageInfo *image_info; MagickBooleanType status; QuantizeInfo *quantize_info; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""...""); assert(image->signature == MagickSignature); status=MagickTrue; image_info=AcquireImageInfo(); image_info->dither=image->dither; artifact=GetImageArtifact(image,""dither""); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,""dither"",artifact); switch (type) { case BilevelType: { if (SetImageMonochrome(image,&image->exception) == MagickFalse) { status=TransformImageColorspace(image,GRAYColorspace); (void) NormalizeImage(image); quantize_info=AcquireQuantizeInfo(image_info); quantize_info->number_colors=2; quantize_info->colorspace=GRAYColorspace; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); } status=AcquireImageColormap(image,2); image->matte=MagickFalse; break; } case GrayscaleType: { if (SetImageGray(image,&image->exception) == MagickFalse) status=TransformImageColorspace(image,GRAYColorspace); image->matte=MagickFalse; break; } case GrayscaleMatteType: { if (SetImageGray(image,&image->exception) == MagickFalse) status=TransformImageColorspace(image,GRAYColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case PaletteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if ((image->storage_class == DirectClass) || (image->colors > 256)) { quantize_info=AcquireQuantizeInfo(image_info); quantize_info->number_colors=256; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); } image->matte=MagickFalse; break; } case PaletteBilevelMatteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); (void) BilevelImageChannel(image,AlphaChannel,(double) QuantumRange/2.0); quantize_info=AcquireQuantizeInfo(image_info); status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); break; } case PaletteMatteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); quantize_info=AcquireQuantizeInfo(image_info); quantize_info->colorspace=TransparentColorspace; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); break; } case TrueColorType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); image->matte=MagickFalse; break; } case TrueColorMatteType: { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) status=TransformImageColorspace(image,sRGBColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case ColorSeparationType: { if (image->colorspace != CMYKColorspace) { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); status=TransformImageColorspace(image,CMYKColorspace); } if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); image->matte=MagickFalse; break; } case ColorSeparationMatteType: { if (image->colorspace != CMYKColorspace) { if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); status=TransformImageColorspace(image,CMYKColorspace); } if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case OptimizeType: case UndefinedType: break; } image_info=DestroyImageInfo(image_info); if (status == MagickFalse) return(MagickFalse); image->type=type; return(MagickTrue); }","{'deleted': [{'line_no': 39, 'char_start': 1127, 'char_end': 1150, 'line': ' image->colors=2;\n'}], 'added': [{'line_no': 39, 'char_start': 1127, 'char_end': 1171, 'line': ' status=AcquireImageColormap(image,2);\n'}]}","{'deleted': [{'char_start': 1138, 'char_end': 1141, 'chars': '->c'}, {'char_start': 1145, 'char_end': 1147, 'chars': 's='}], 'added': [{'char_start': 1133, 'char_end': 1144, 'chars': 'status=Acqu'}, {'char_start': 1145, 'char_end': 1148, 'chars': 'reI'}, {'char_start': 1152, 'char_end': 1153, 'chars': 'C'}, {'char_start': 1157, 'char_end': 1167, 'chars': 'map(image,'}, {'char_start': 1168, 'char_end': 1169, 'chars': ')'}]}",github.com/ImageMagick/ImageMagick/commit/d63a3c5729df59f183e9e110d5d8385d17caaad0,magick/attribute.c,cwe-416,1272 cwe-476,__rds_rdma_map,"static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args, u64 *cookie_ret, struct rds_mr **mr_ret) { struct rds_mr *mr = NULL, *found; unsigned int nr_pages; struct page **pages = NULL; struct scatterlist *sg; void *trans_private; unsigned long flags; rds_rdma_cookie_t cookie; unsigned int nents; long i; int ret; if (rs->rs_bound_addr == 0) { ret = -ENOTCONN; /* XXX not a great errno */ goto out; } if (!rs->rs_transport->get_mr) { ret = -EOPNOTSUPP; goto out; } nr_pages = rds_pages_in_vec(&args->vec); if (nr_pages == 0) { ret = -EINVAL; goto out; } /* Restrict the size of mr irrespective of underlying transport * To account for unaligned mr regions, subtract one from nr_pages */ if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) { ret = -EMSGSIZE; goto out; } rdsdebug(""RDS: get_mr addr %llx len %llu nr_pages %u\n"", args->vec.addr, args->vec.bytes, nr_pages); /* XXX clamp nr_pages to limit the size of this alloc? */ pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL); if (!mr) { ret = -ENOMEM; goto out; } refcount_set(&mr->r_refcount, 1); RB_CLEAR_NODE(&mr->r_rb_node); mr->r_trans = rs->rs_transport; mr->r_sock = rs; if (args->flags & RDS_RDMA_USE_ONCE) mr->r_use_once = 1; if (args->flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; if (args->flags & RDS_RDMA_READWRITE) mr->r_write = 1; /* * Pin the pages that make up the user buffer and transfer the page * pointers to the mr's sg array. We check to see if we've mapped * the whole region after transferring the partial page references * to the sg array so that we can have one page ref cleanup path. * * For now we have no flag that tells us whether the mapping is * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to * the zero page. */ ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1); if (ret < 0) goto out; nents = ret; sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL); if (!sg) { ret = -ENOMEM; goto out; } WARN_ON(!nents); sg_init_table(sg, nents); /* Stick all pages into the scatterlist */ for (i = 0 ; i < nents; i++) sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0); rdsdebug(""RDS: trans_private nents is %u\n"", nents); /* Obtain a transport specific MR. If this succeeds, the * s/g list is now owned by the MR. * Note that dma_map() implies that pending writes are * flushed to RAM, so no dma_sync is needed here. */ trans_private = rs->rs_transport->get_mr(sg, nents, rs, &mr->r_key); if (IS_ERR(trans_private)) { for (i = 0 ; i < nents; i++) put_page(sg_page(&sg[i])); kfree(sg); ret = PTR_ERR(trans_private); goto out; } mr->r_trans_private = trans_private; rdsdebug(""RDS: get_mr put_user key is %x cookie_addr %p\n"", mr->r_key, (void *)(unsigned long) args->cookie_addr); /* The user may pass us an unaligned address, but we can only * map page aligned regions. So we keep the offset, and build * a 64bit cookie containing and pass that * around. */ cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK); if (cookie_ret) *cookie_ret = cookie; if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) { ret = -EFAULT; goto out; } /* Inserting the new MR into the rbtree bumps its * reference count. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); BUG_ON(found && found != mr); rdsdebug(""RDS: get_mr key is %x\n"", mr->r_key); if (mr_ret) { refcount_inc(&mr->r_refcount); *mr_ret = mr; } ret = 0; out: kfree(pages); if (mr) rds_mr_put(mr); return ret; }","static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args, u64 *cookie_ret, struct rds_mr **mr_ret) { struct rds_mr *mr = NULL, *found; unsigned int nr_pages; struct page **pages = NULL; struct scatterlist *sg; void *trans_private; unsigned long flags; rds_rdma_cookie_t cookie; unsigned int nents; long i; int ret; if (rs->rs_bound_addr == 0 || !rs->rs_transport) { ret = -ENOTCONN; /* XXX not a great errno */ goto out; } if (!rs->rs_transport->get_mr) { ret = -EOPNOTSUPP; goto out; } nr_pages = rds_pages_in_vec(&args->vec); if (nr_pages == 0) { ret = -EINVAL; goto out; } /* Restrict the size of mr irrespective of underlying transport * To account for unaligned mr regions, subtract one from nr_pages */ if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) { ret = -EMSGSIZE; goto out; } rdsdebug(""RDS: get_mr addr %llx len %llu nr_pages %u\n"", args->vec.addr, args->vec.bytes, nr_pages); /* XXX clamp nr_pages to limit the size of this alloc? */ pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL); if (!mr) { ret = -ENOMEM; goto out; } refcount_set(&mr->r_refcount, 1); RB_CLEAR_NODE(&mr->r_rb_node); mr->r_trans = rs->rs_transport; mr->r_sock = rs; if (args->flags & RDS_RDMA_USE_ONCE) mr->r_use_once = 1; if (args->flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; if (args->flags & RDS_RDMA_READWRITE) mr->r_write = 1; /* * Pin the pages that make up the user buffer and transfer the page * pointers to the mr's sg array. We check to see if we've mapped * the whole region after transferring the partial page references * to the sg array so that we can have one page ref cleanup path. * * For now we have no flag that tells us whether the mapping is * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to * the zero page. */ ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1); if (ret < 0) goto out; nents = ret; sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL); if (!sg) { ret = -ENOMEM; goto out; } WARN_ON(!nents); sg_init_table(sg, nents); /* Stick all pages into the scatterlist */ for (i = 0 ; i < nents; i++) sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0); rdsdebug(""RDS: trans_private nents is %u\n"", nents); /* Obtain a transport specific MR. If this succeeds, the * s/g list is now owned by the MR. * Note that dma_map() implies that pending writes are * flushed to RAM, so no dma_sync is needed here. */ trans_private = rs->rs_transport->get_mr(sg, nents, rs, &mr->r_key); if (IS_ERR(trans_private)) { for (i = 0 ; i < nents; i++) put_page(sg_page(&sg[i])); kfree(sg); ret = PTR_ERR(trans_private); goto out; } mr->r_trans_private = trans_private; rdsdebug(""RDS: get_mr put_user key is %x cookie_addr %p\n"", mr->r_key, (void *)(unsigned long) args->cookie_addr); /* The user may pass us an unaligned address, but we can only * map page aligned regions. So we keep the offset, and build * a 64bit cookie containing and pass that * around. */ cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK); if (cookie_ret) *cookie_ret = cookie; if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) { ret = -EFAULT; goto out; } /* Inserting the new MR into the rbtree bumps its * reference count. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); BUG_ON(found && found != mr); rdsdebug(""RDS: get_mr key is %x\n"", mr->r_key); if (mr_ret) { refcount_inc(&mr->r_refcount); *mr_ret = mr; } ret = 0; out: kfree(pages); if (mr) rds_mr_put(mr); return ret; }","{'deleted': [{'line_no': 15, 'char_start': 349, 'char_end': 380, 'line': '\tif (rs->rs_bound_addr == 0) {\n'}], 'added': [{'line_no': 15, 'char_start': 349, 'char_end': 401, 'line': '\tif (rs->rs_bound_addr == 0 || !rs->rs_transport) {\n'}]}","{'deleted': [], 'added': [{'char_start': 376, 'char_end': 397, 'chars': ' || !rs->rs_transport'}]}",github.com/torvalds/linux/commit/f3069c6d33f6ae63a1668737bc78aaaa51bff7ca,net/rds/rdma.c,cwe-476,1215 cwe-787,InsertRow,"static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); switch (bpp) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if (!SyncAuthenticPixels(image,exception)) break; break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 8: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } break; case 24: /* Convert DirectColor scanline. */ q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (!SyncAuthenticPixels(image,exception)) break; break; } }","static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); switch (bpp) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if (!SyncAuthenticPixels(image,exception)) break; break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 8: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } break; case 24: /* Convert DirectColor scanline. */ q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (!SyncAuthenticPixels(image,exception)) break; break; } }","{'deleted': [{'line_no': 62, 'char_start': 1585, 'char_end': 1643, 'line': ' for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n'}], 'added': [{'line_no': 62, 'char_start': 1585, 'char_end': 1643, 'line': ' for (x=0; x < ((ssize_t) image->columns-1); x+=4)\n'}]}","{'deleted': [{'char_start': 1640, 'char_end': 1641, 'chars': '2'}], 'added': [{'char_start': 1640, 'char_end': 1641, 'chars': '4'}]}",github.com/ImageMagick/ImageMagick/commit/b6ae2f9e0ab13343c0281732d479757a8e8979c7,coders/wpg.c,cwe-787,1451 cwe-416,PHP_MINIT_FUNCTION,"static PHP_MINIT_FUNCTION(zip) { #ifdef PHP_ZIP_USE_OO zend_class_entry ce; memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); zip_object_handlers.clone_obj = NULL; zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr; zip_object_handlers.get_gc = php_zip_get_gc; zip_object_handlers.get_properties = php_zip_get_properties; zip_object_handlers.read_property = php_zip_read_property; zip_object_handlers.has_property = php_zip_has_property; INIT_CLASS_ENTRY(ce, ""ZipArchive"", zip_class_functions); ce.create_object = php_zip_object_new; zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC); zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1); php_zip_register_prop_handler(&zip_prop_handlers, ""status"", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""statusSys"", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""numFiles"", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""filename"", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""comment"", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC); REGISTER_ZIP_CLASS_CONST_LONG(""CREATE"", ZIP_CREATE); REGISTER_ZIP_CLASS_CONST_LONG(""EXCL"", ZIP_EXCL); REGISTER_ZIP_CLASS_CONST_LONG(""CHECKCONS"", ZIP_CHECKCONS); REGISTER_ZIP_CLASS_CONST_LONG(""OVERWRITE"", ZIP_OVERWRITE); REGISTER_ZIP_CLASS_CONST_LONG(""FL_NOCASE"", ZIP_FL_NOCASE); REGISTER_ZIP_CLASS_CONST_LONG(""FL_NODIR"", ZIP_FL_NODIR); REGISTER_ZIP_CLASS_CONST_LONG(""FL_COMPRESSED"", ZIP_FL_COMPRESSED); REGISTER_ZIP_CLASS_CONST_LONG(""FL_UNCHANGED"", ZIP_FL_UNCHANGED); REGISTER_ZIP_CLASS_CONST_LONG(""CM_DEFAULT"", ZIP_CM_DEFAULT); REGISTER_ZIP_CLASS_CONST_LONG(""CM_STORE"", ZIP_CM_STORE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_SHRINK"", ZIP_CM_SHRINK); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_1"", ZIP_CM_REDUCE_1); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_2"", ZIP_CM_REDUCE_2); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_3"", ZIP_CM_REDUCE_3); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_4"", ZIP_CM_REDUCE_4); REGISTER_ZIP_CLASS_CONST_LONG(""CM_IMPLODE"", ZIP_CM_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_DEFLATE"", ZIP_CM_DEFLATE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_DEFLATE64"", ZIP_CM_DEFLATE64); REGISTER_ZIP_CLASS_CONST_LONG(""CM_PKWARE_IMPLODE"", ZIP_CM_PKWARE_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_BZIP2"", ZIP_CM_BZIP2); REGISTER_ZIP_CLASS_CONST_LONG(""CM_LZMA"", ZIP_CM_LZMA); REGISTER_ZIP_CLASS_CONST_LONG(""CM_TERSE"", ZIP_CM_TERSE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_LZ77"", ZIP_CM_LZ77); REGISTER_ZIP_CLASS_CONST_LONG(""CM_WAVPACK"", ZIP_CM_WAVPACK); REGISTER_ZIP_CLASS_CONST_LONG(""CM_PPMD"", ZIP_CM_PPMD); /* Error code */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_OK"", ZIP_ER_OK); /* N No error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_MULTIDISK"", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_RENAME"", ZIP_ER_RENAME); /* S Renaming temporary file failed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_CLOSE"", ZIP_ER_CLOSE); /* S Closing zip archive failed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_SEEK"", ZIP_ER_SEEK); /* S Seek error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_READ"", ZIP_ER_READ); /* S Read error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_WRITE"", ZIP_ER_WRITE); /* S Write error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_CRC"", ZIP_ER_CRC); /* N CRC error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_ZIPCLOSED"", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_NOENT"", ZIP_ER_NOENT); /* N No such file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_EXISTS"", ZIP_ER_EXISTS); /* N File already exists */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_OPEN"", ZIP_ER_OPEN); /* S Can't open file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_TMPOPEN"", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_ZLIB"", ZIP_ER_ZLIB); /* Z Zlib error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_MEMORY"", ZIP_ER_MEMORY); /* N Malloc failure */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_CHANGED"", ZIP_ER_CHANGED); /* N Entry has been changed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_COMPNOTSUPP"", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_EOF"", ZIP_ER_EOF); /* N Premature EOF */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_INVAL"", ZIP_ER_INVAL); /* N Invalid argument */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_NOZIP"", ZIP_ER_NOZIP); /* N Not a zip archive */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_INTERNAL"", ZIP_ER_INTERNAL); /* N Internal error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_INCONS"", ZIP_ER_INCONS); /* N Zip archive inconsistent */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_REMOVE"", ZIP_ER_REMOVE); /* S Can't remove file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_DELETED"", ZIP_ER_DELETED); /* N Entry has been deleted */ php_register_url_stream_wrapper(""zip"", &php_stream_zip_wrapper TSRMLS_CC); #endif le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number); le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number); return SUCCESS; }","static PHP_MINIT_FUNCTION(zip) { #ifdef PHP_ZIP_USE_OO zend_class_entry ce; memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); zip_object_handlers.clone_obj = NULL; zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr; zip_object_handlers.get_gc = php_zip_get_gc; zip_object_handlers.get_properties = php_zip_get_properties; zip_object_handlers.read_property = php_zip_read_property; zip_object_handlers.has_property = php_zip_has_property; INIT_CLASS_ENTRY(ce, ""ZipArchive"", zip_class_functions); ce.create_object = php_zip_object_new; zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC); zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1); php_zip_register_prop_handler(&zip_prop_handlers, ""status"", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""statusSys"", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""numFiles"", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""filename"", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, ""comment"", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC); REGISTER_ZIP_CLASS_CONST_LONG(""CREATE"", ZIP_CREATE); REGISTER_ZIP_CLASS_CONST_LONG(""EXCL"", ZIP_EXCL); REGISTER_ZIP_CLASS_CONST_LONG(""CHECKCONS"", ZIP_CHECKCONS); REGISTER_ZIP_CLASS_CONST_LONG(""OVERWRITE"", ZIP_OVERWRITE); REGISTER_ZIP_CLASS_CONST_LONG(""FL_NOCASE"", ZIP_FL_NOCASE); REGISTER_ZIP_CLASS_CONST_LONG(""FL_NODIR"", ZIP_FL_NODIR); REGISTER_ZIP_CLASS_CONST_LONG(""FL_COMPRESSED"", ZIP_FL_COMPRESSED); REGISTER_ZIP_CLASS_CONST_LONG(""FL_UNCHANGED"", ZIP_FL_UNCHANGED); REGISTER_ZIP_CLASS_CONST_LONG(""CM_DEFAULT"", ZIP_CM_DEFAULT); REGISTER_ZIP_CLASS_CONST_LONG(""CM_STORE"", ZIP_CM_STORE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_SHRINK"", ZIP_CM_SHRINK); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_1"", ZIP_CM_REDUCE_1); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_2"", ZIP_CM_REDUCE_2); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_3"", ZIP_CM_REDUCE_3); REGISTER_ZIP_CLASS_CONST_LONG(""CM_REDUCE_4"", ZIP_CM_REDUCE_4); REGISTER_ZIP_CLASS_CONST_LONG(""CM_IMPLODE"", ZIP_CM_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_DEFLATE"", ZIP_CM_DEFLATE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_DEFLATE64"", ZIP_CM_DEFLATE64); REGISTER_ZIP_CLASS_CONST_LONG(""CM_PKWARE_IMPLODE"", ZIP_CM_PKWARE_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_BZIP2"", ZIP_CM_BZIP2); REGISTER_ZIP_CLASS_CONST_LONG(""CM_LZMA"", ZIP_CM_LZMA); REGISTER_ZIP_CLASS_CONST_LONG(""CM_TERSE"", ZIP_CM_TERSE); REGISTER_ZIP_CLASS_CONST_LONG(""CM_LZ77"", ZIP_CM_LZ77); REGISTER_ZIP_CLASS_CONST_LONG(""CM_WAVPACK"", ZIP_CM_WAVPACK); REGISTER_ZIP_CLASS_CONST_LONG(""CM_PPMD"", ZIP_CM_PPMD); /* Error code */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_OK"", ZIP_ER_OK); /* N No error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_MULTIDISK"", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_RENAME"", ZIP_ER_RENAME); /* S Renaming temporary file failed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_CLOSE"", ZIP_ER_CLOSE); /* S Closing zip archive failed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_SEEK"", ZIP_ER_SEEK); /* S Seek error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_READ"", ZIP_ER_READ); /* S Read error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_WRITE"", ZIP_ER_WRITE); /* S Write error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_CRC"", ZIP_ER_CRC); /* N CRC error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_ZIPCLOSED"", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_NOENT"", ZIP_ER_NOENT); /* N No such file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_EXISTS"", ZIP_ER_EXISTS); /* N File already exists */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_OPEN"", ZIP_ER_OPEN); /* S Can't open file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_TMPOPEN"", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_ZLIB"", ZIP_ER_ZLIB); /* Z Zlib error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_MEMORY"", ZIP_ER_MEMORY); /* N Malloc failure */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_CHANGED"", ZIP_ER_CHANGED); /* N Entry has been changed */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_COMPNOTSUPP"", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_EOF"", ZIP_ER_EOF); /* N Premature EOF */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_INVAL"", ZIP_ER_INVAL); /* N Invalid argument */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_NOZIP"", ZIP_ER_NOZIP); /* N Not a zip archive */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_INTERNAL"", ZIP_ER_INTERNAL); /* N Internal error */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_INCONS"", ZIP_ER_INCONS); /* N Zip archive inconsistent */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_REMOVE"", ZIP_ER_REMOVE); /* S Can't remove file */ REGISTER_ZIP_CLASS_CONST_LONG(""ER_DELETED"", ZIP_ER_DELETED); /* N Entry has been deleted */ php_register_url_stream_wrapper(""zip"", &php_stream_zip_wrapper TSRMLS_CC); #endif le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number); le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number); return SUCCESS; }","{'deleted': [], 'added': [{'line_no': 10, 'char_start': 286, 'char_end': 341, 'line': '\tzip_object_handlers.get_gc = php_zip_get_gc;\n'}]}","{'deleted': [], 'added': []}",github.com/php/php-src/commit/f6aef68089221c5ea047d4a74224ee3deead99a6?w=1,ext/zip/php_zip.c,cwe-416,1510 cwe-416,opj_j2k_write_mco,"static OPJ_BOOL opj_j2k_write_mco( opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_mco_size; opj_tcp_t * l_tcp = 00; opj_simple_mcc_decorrelation_data_t * l_mcc_record; OPJ_UINT32 i; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp =&(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; l_mco_size = 5 + l_tcp->m_nb_mcc_records; if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, ""Not enough memory to write MCO marker\n""); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size; } opj_write_bytes(l_current_data,J2K_MS_MCO,2); /* MCO */ l_current_data += 2; opj_write_bytes(l_current_data,l_mco_size-2,2); /* Lmco */ l_current_data += 2; opj_write_bytes(l_current_data,l_tcp->m_nb_mcc_records,1); /* Nmco : only one tranform stage*/ ++l_current_data; l_mcc_record = l_tcp->m_mcc_records; for (i=0;im_nb_mcc_records;++i) { opj_write_bytes(l_current_data,l_mcc_record->m_index,1);/* Imco -> use the mcc indicated by 1*/ ++l_current_data; ++l_mcc_record; } if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mco_size,p_manager) != l_mco_size) { return OPJ_FALSE; } return OPJ_TRUE; }","static OPJ_BOOL opj_j2k_write_mco( opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_mco_size; opj_tcp_t * l_tcp = 00; opj_simple_mcc_decorrelation_data_t * l_mcc_record; OPJ_UINT32 i; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp =&(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); l_mco_size = 5 + l_tcp->m_nb_mcc_records; if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, ""Not enough memory to write MCO marker\n""); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data,J2K_MS_MCO,2); /* MCO */ l_current_data += 2; opj_write_bytes(l_current_data,l_mco_size-2,2); /* Lmco */ l_current_data += 2; opj_write_bytes(l_current_data,l_tcp->m_nb_mcc_records,1); /* Nmco : only one tranform stage*/ ++l_current_data; l_mcc_record = l_tcp->m_mcc_records; for (i=0;im_nb_mcc_records;++i) { opj_write_bytes(l_current_data,l_mcc_record->m_index,1);/* Imco -> use the mcc indicated by 1*/ ++l_current_data; ++l_mcc_record; } if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mco_size,p_manager) != l_mco_size) { return OPJ_FALSE; } return OPJ_TRUE; }","{'deleted': [{'line_no': 18, 'char_start': 636, 'char_end': 715, 'line': ' l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;\n'}, {'line_no': 19, 'char_start': 715, 'char_end': 716, 'line': '\n'}, {'line_no': 45, 'char_start': 2061, 'char_end': 2115, 'line': ' for (i=0;im_nb_mcc_records;++i) {\n'}, {'line_no': 48, 'char_start': 2261, 'char_end': 2262, 'line': '\n'}], 'added': [{'line_no': 18, 'char_start': 636, 'char_end': 638, 'line': '\t\n'}, {'line_no': 33, 'char_start': 1577, 'char_end': 1656, 'line': ' l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;\n'}, {'line_no': 34, 'char_start': 1656, 'char_end': 1657, 'line': '\n'}, {'line_no': 46, 'char_start': 2063, 'char_end': 2113, 'line': ' for (i=0;im_nb_mcc_records;++i) {\n'}]}","{'deleted': [{'char_start': 636, 'char_end': 715, 'chars': ' l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;\n'}, {'char_start': 2073, 'char_end': 2077, 'chars': ' '}, {'char_start': 2260, 'char_end': 2261, 'chars': '\n'}], 'added': [{'char_start': 636, 'char_end': 637, 'chars': '\t'}, {'char_start': 1577, 'char_end': 1657, 'chars': ' l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;\n\n'}]}",github.com/uclouvain/openjpeg/commit/940100c28ae28931722290794889cf84a92c5f6f,src/lib/openjp2/j2k.c,cwe-416,641 cwe-125,str_lower_case_match,"str_lower_case_match(OnigEncoding enc, int case_fold_flag, const UChar* t, const UChar* tend, const UChar* p, const UChar* end) { int lowlen; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; while (t < tend) { lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf); q = lowbuf; while (lowlen > 0) { if (*t++ != *q++) return 0; lowlen--; } } return 1; }","str_lower_case_match(OnigEncoding enc, int case_fold_flag, const UChar* t, const UChar* tend, const UChar* p, const UChar* end) { int lowlen; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; while (t < tend) { lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf); q = lowbuf; while (lowlen > 0) { if (t >= tend) return 0; if (*t++ != *q++) return 0; lowlen--; } } return 1; }","{'deleted': [], 'added': [{'line_no': 12, 'char_start': 373, 'char_end': 407, 'line': ' if (t >= tend) return 0;\n'}]}","{'deleted': [], 'added': [{'char_start': 383, 'char_end': 417, 'chars': 't >= tend) return 0;\n if ('}]}",github.com/kkos/oniguruma/commit/d3e402928b6eb3327f8f7d59a9edfa622fec557b,src/regexec.c,cwe-125,144 cwe-089,quiz,"@app.route('/quiz') def quiz(): varga = request.args.get('varga') try: rows =[] with sql.connect('amara.db') as con: con.row_factory = sql.Row cur = con.cursor() cur.execute(""select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = '%s' order by random() limit 1;"" % varga) rows = cur.fetchall(); artha = rows[0][""artha""]; cur.execute(""select pada from pada where varga = '%s' and artha = '%s' order by id"" % (varga, artha)); paryaya = cur.fetchall(); return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga) finally: con.close()","@app.route('/quiz') def quiz(): varga = request.args.get('varga') try: rows =[] with sql.connect('amara.db') as con: con.row_factory = sql.Row cur = con.cursor() cur.execute(""select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = ? order by random() limit 1;"", [varga]) rows = cur.fetchall(); artha = rows[0][""artha""]; cur.execute(""select pada from pada where varga = ? and artha = ? order by id"", [varga, artha]); paryaya = cur.fetchall(); return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga) finally: con.close()","{'deleted': [{'line_no': 12, 'char_start': 213, 'char_end': 371, 'line': ' cur.execute(""select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = \'%s\' order by random() limit 1;"" % varga)\n'}, {'line_no': 16, 'char_start': 445, 'char_end': 560, 'line': ' cur.execute(""select pada from pada where varga = \'%s\' and artha = \'%s\' order by id"" % (varga, artha));\n'}], 'added': [{'line_no': 12, 'char_start': 213, 'char_end': 369, 'line': ' cur.execute(""select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = ? order by random() limit 1;"", [varga])\n'}, {'line_no': 16, 'char_start': 443, 'char_end': 551, 'line': ' cur.execute(""select pada from pada where varga = ? and artha = ? order by id"", [varga, artha]);\n'}]}","{'deleted': [{'char_start': 329, 'char_end': 333, 'chars': ""'%s'""}, {'char_start': 361, 'char_end': 363, 'chars': ' %'}, {'char_start': 506, 'char_end': 510, 'chars': ""'%s'""}, {'char_start': 523, 'char_end': 527, 'chars': ""'%s'""}, {'char_start': 540, 'char_end': 542, 'chars': ' %'}, {'char_start': 543, 'char_end': 544, 'chars': '('}, {'char_start': 556, 'char_end': 557, 'chars': ')'}], 'added': [{'char_start': 329, 'char_end': 330, 'chars': '?'}, {'char_start': 358, 'char_end': 359, 'chars': ','}, {'char_start': 360, 'char_end': 361, 'chars': '['}, {'char_start': 366, 'char_end': 367, 'chars': ']'}, {'char_start': 504, 'char_end': 505, 'chars': '?'}, {'char_start': 518, 'char_end': 519, 'chars': '?'}, {'char_start': 532, 'char_end': 533, 'chars': ','}, {'char_start': 534, 'char_end': 535, 'chars': '['}, {'char_start': 547, 'char_end': 548, 'chars': ']'}]}",github.com/aupasana/amara-quiz/commit/6ceb5dc8ec38b4a3f1399e578ab970f7e3354922,docker/app.py,cwe-089,188 cwe-078,_get_conn_fc_wwpns," def _get_conn_fc_wwpns(self, host_name): wwpns = [] cmd = 'svcinfo lsfabric -host %s' % host_name generator = self._port_conf_generator(cmd) header = next(generator, None) if not header: return wwpns for port_data in generator: try: wwpns.append(port_data['local_wwpn']) except KeyError as e: self._handle_keyerror('lsfabric', header) return wwpns"," def _get_conn_fc_wwpns(self, host_name): wwpns = [] cmd = ['svcinfo', 'lsfabric', '-host', host_name] generator = self._port_conf_generator(cmd) header = next(generator, None) if not header: return wwpns for port_data in generator: try: wwpns.append(port_data['local_wwpn']) except KeyError as e: self._handle_keyerror('lsfabric', header) return wwpns","{'deleted': [{'line_no': 3, 'char_start': 64, 'char_end': 118, 'line': "" cmd = 'svcinfo lsfabric -host %s' % host_name\n""}], 'added': [{'line_no': 3, 'char_start': 64, 'char_end': 122, 'line': "" cmd = ['svcinfo', 'lsfabric', '-host', host_name]\n""}]}","{'deleted': [{'char_start': 101, 'char_end': 104, 'chars': ' %s'}, {'char_start': 105, 'char_end': 107, 'chars': ' %'}], 'added': [{'char_start': 78, 'char_end': 79, 'chars': '['}, {'char_start': 87, 'char_end': 89, 'chars': ""',""}, {'char_start': 90, 'char_end': 91, 'chars': ""'""}, {'char_start': 99, 'char_end': 101, 'chars': ""',""}, {'char_start': 102, 'char_end': 103, 'chars': ""'""}, {'char_start': 109, 'char_end': 110, 'chars': ','}, {'char_start': 120, 'char_end': 121, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,114 cwe-022,set," def set(self, key, value, replace=False): path = os.path.join(self.namespace, key) try: self.etcd.write(path, value, prevExist=replace) except etcd.EtcdAlreadyExist as err: raise CSStoreExists(str(err)) except etcd.EtcdException as err: log_error(""Error storing key %s: [%r]"" % (key, repr(err))) raise CSStoreError('Error occurred while trying to store key')"," def set(self, key, value, replace=False): path = self._absolute_key(key) try: self.etcd.write(path, value, prevExist=replace) except etcd.EtcdAlreadyExist as err: raise CSStoreExists(str(err)) except etcd.EtcdException as err: log_error(""Error storing key %s: [%r]"" % (key, repr(err))) raise CSStoreError('Error occurred while trying to store key')","{'deleted': [{'line_no': 2, 'char_start': 46, 'char_end': 95, 'line': ' path = os.path.join(self.namespace, key)\n'}], 'added': [{'line_no': 2, 'char_start': 46, 'char_end': 85, 'line': ' path = self._absolute_key(key)\n'}]}","{'deleted': [{'char_start': 61, 'char_end': 74, 'chars': 'os.path.join('}, {'char_start': 79, 'char_end': 80, 'chars': 'n'}, {'char_start': 81, 'char_end': 83, 'chars': 'me'}, {'char_start': 84, 'char_end': 87, 'chars': 'pac'}, {'char_start': 88, 'char_end': 90, 'chars': ', '}], 'added': [{'char_start': 66, 'char_end': 67, 'chars': '_'}, {'char_start': 68, 'char_end': 74, 'chars': 'bsolut'}, {'char_start': 75, 'char_end': 77, 'chars': '_k'}, {'char_start': 78, 'char_end': 80, 'chars': 'y('}]}",github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4,custodia/store/etcdstore.py,cwe-022,105 cwe-787,PHP_FUNCTION,"PHP_FUNCTION(imagegammacorrect) { zval *IM; gdImagePtr im; int i; double input, output; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""rdd"", &IM, &input, &output) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, ""Image"", le_gd); if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColorAlpha( (int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5), gdTrueColorGetAlpha(c) ) ); } } RETURN_TRUE; } for (i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5); } RETURN_TRUE; }","PHP_FUNCTION(imagegammacorrect) { zval *IM; gdImagePtr im; int i; double input, output; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""rdd"", &IM, &input, &output) == FAILURE) { return; } if ( input <= 0.0 || output <= 0.0 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Gamma values should be positive""); RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, ""Image"", le_gd); if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColorAlpha( (int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5), gdTrueColorGetAlpha(c) ) ); } } RETURN_TRUE; } for (i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5); } RETURN_TRUE; }","{'deleted': [], 'added': [{'line_no': 12, 'char_start': 204, 'char_end': 244, 'line': '\tif ( input <= 0.0 || output <= 0.0 ) {\n'}, {'line_no': 13, 'char_start': 244, 'char_end': 326, 'line': '\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, ""Gamma values should be positive"");\n'}, {'line_no': 14, 'char_start': 326, 'char_end': 342, 'line': '\t\tRETURN_FALSE;\n'}, {'line_no': 15, 'char_start': 342, 'char_end': 345, 'line': '\t}\n'}, {'line_no': 16, 'char_start': 345, 'char_end': 346, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 205, 'char_end': 347, 'chars': 'if ( input <= 0.0 || output <= 0.0 ) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, ""Gamma values should be positive"");\n\t\tRETURN_FALSE;\n\t}\n\n\t'}]}",github.com/php/php-src/commit/1bd103df00f49cf4d4ade2cfe3f456ac058a4eae,ext/gd/gd.c,cwe-787,498 cwe-125,repodata_schema2id,"repodata_schema2id(Repodata *data, Id *schema, int create) { int h, len, i; Id *sp, cid; Id *schematahash; if (!*schema) return 0; /* XXX: allow empty schema? */ if ((schematahash = data->schematahash) == 0) { data->schematahash = schematahash = solv_calloc(256, sizeof(Id)); for (i = 1; i < data->nschemata; i++) { for (sp = data->schemadata + data->schemata[i], h = 0; *sp;) h = h * 7 + *sp++; h &= 255; schematahash[h] = i; } data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK); } for (sp = schema, len = 0, h = 0; *sp; len++) h = h * 7 + *sp++; h &= 255; len++; cid = schematahash[h]; if (cid) { if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; /* cache conflict, do a slow search */ for (cid = 1; cid < data->nschemata; cid++) if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; } /* a new one */ if (!create) return 0; data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK); /* add schema */ memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id)); data->schemata[data->nschemata] = data->schemadatalen; data->schemadatalen += len; schematahash[h] = data->nschemata; #if 0 fprintf(stderr, ""schema2id: new schema\n""); #endif return data->nschemata++; }","repodata_schema2id(Repodata *data, Id *schema, int create) { int h, len, i; Id *sp, cid; Id *schematahash; if (!*schema) return 0; /* XXX: allow empty schema? */ if ((schematahash = data->schematahash) == 0) { data->schematahash = schematahash = solv_calloc(256, sizeof(Id)); for (i = 1; i < data->nschemata; i++) { for (sp = data->schemadata + data->schemata[i], h = 0; *sp;) h = h * 7 + *sp++; h &= 255; schematahash[h] = i; } data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK); } for (sp = schema, len = 0, h = 0; *sp; len++) h = h * 7 + *sp++; h &= 255; len++; cid = schematahash[h]; if (cid) { if ((data->schemata[cid] + len <= data->schemadatalen) && !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; /* cache conflict, do a slow search */ for (cid = 1; cid < data->nschemata; cid++) if ((data->schemata[cid] + len <= data->schemadatalen) && !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; } /* a new one */ if (!create) return 0; data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK); /* add schema */ memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id)); data->schemata[data->nschemata] = data->schemadatalen; data->schemadatalen += len; schematahash[h] = data->nschemata; #if 0 fprintf(stderr, ""schema2id: new schema\n""); #endif return data->nschemata++; }","{'deleted': [{'line_no': 31, 'char_start': 838, 'char_end': 923, 'line': ' if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n'}, {'line_no': 35, 'char_start': 1038, 'char_end': 1125, 'line': ' if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n'}], 'added': [{'line_no': 31, 'char_start': 838, 'char_end': 902, 'line': ' if ((data->schemata[cid] + len <= data->schemadatalen) &&\n'}, {'line_no': 32, 'char_start': 902, 'char_end': 982, 'line': '\t\t\t !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n'}, {'line_no': 36, 'char_start': 1097, 'char_end': 1163, 'line': ' if ((data->schemata[cid] + len <= data->schemadatalen) &&\n'}, {'line_no': 37, 'char_start': 1163, 'char_end': 1242, 'line': '\t\t\t\t!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n'}]}","{'deleted': [], 'added': [{'char_start': 848, 'char_end': 907, 'chars': '(data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t '}, {'char_start': 1109, 'char_end': 1167, 'chars': '(data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t\t'}]}",github.com/openSUSE/libsolv/commit/fdb9c9c03508990e4583046b590c30d958f272da,src/repodata.c,cwe-125,584 cwe-078,_add_volume_to_volume_set," def _add_volume_to_volume_set(self, volume, volume_name, cpg, vvs_name, qos): if vvs_name is not None: # Admin has set a volume set name to add the volume to self._cli_run('createvvset -add %s %s' % (vvs_name, volume_name), None) else: vvs_name = self._get_3par_vvs_name(volume['id']) domain = self.get_domain(cpg) self._cli_run('createvvset -domain %s %s' % (domain, vvs_name), None) self._set_qos_rule(qos, vvs_name) self._cli_run('createvvset -add %s %s' % (vvs_name, volume_name), None)"," def _add_volume_to_volume_set(self, volume, volume_name, cpg, vvs_name, qos): if vvs_name is not None: # Admin has set a volume set name to add the volume to self._cli_run(['createvvset', '-add', vvs_name, volume_name]) else: vvs_name = self._get_3par_vvs_name(volume['id']) domain = self.get_domain(cpg) self._cli_run(['createvvset', '-domain', domain, vvs_name]) self._set_qos_rule(qos, vvs_name) self._cli_run(['createvvset', '-add', vvs_name, volume_name])","{'deleted': [{'line_no': 5, 'char_start': 216, 'char_end': 280, 'line': "" self._cli_run('createvvset -add %s %s' % (vvs_name,\n""}, {'line_no': 6, 'char_start': 280, 'char_end': 354, 'line': ' volume_name), None)\n'}, {'line_no': 10, 'char_start': 471, 'char_end': 536, 'line': "" self._cli_run('createvvset -domain %s %s' % (domain,\n""}, {'line_no': 11, 'char_start': 536, 'char_end': 610, 'line': ' vvs_name), None)\n'}, {'line_no': 13, 'char_start': 656, 'char_end': 720, 'line': "" self._cli_run('createvvset -add %s %s' % (vvs_name,\n""}, {'line_no': 14, 'char_start': 720, 'char_end': 793, 'line': ' volume_name), None)\n'}], 'added': [{'line_no': 5, 'char_start': 216, 'char_end': 290, 'line': "" self._cli_run(['createvvset', '-add', vvs_name, volume_name])\n""}, {'line_no': 9, 'char_start': 407, 'char_end': 479, 'line': "" self._cli_run(['createvvset', '-domain', domain, vvs_name])\n""}, {'line_no': 11, 'char_start': 525, 'char_end': 598, 'line': "" self._cli_run(['createvvset', '-add', vvs_name, volume_name])\n""}]}","{'deleted': [{'char_start': 259, 'char_end': 265, 'chars': ' %s %s'}, {'char_start': 266, 'char_end': 268, 'chars': ' %'}, {'char_start': 269, 'char_end': 270, 'chars': '('}, {'char_start': 279, 'char_end': 333, 'chars': '\n '}, {'char_start': 345, 'char_end': 352, 'chars': '), None'}, {'char_start': 517, 'char_end': 523, 'chars': ' %s %s'}, {'char_start': 524, 'char_end': 526, 'chars': ' %'}, {'char_start': 527, 'char_end': 528, 'chars': '('}, {'char_start': 535, 'char_end': 592, 'chars': '\n '}, {'char_start': 601, 'char_end': 608, 'chars': '), None'}, {'char_start': 699, 'char_end': 705, 'chars': ' %s %s'}, {'char_start': 706, 'char_end': 708, 'chars': ' %'}, {'char_start': 709, 'char_end': 710, 'chars': '('}, {'char_start': 719, 'char_end': 773, 'chars': '\n '}, {'char_start': 785, 'char_end': 792, 'chars': '), None'}], 'added': [{'char_start': 242, 'char_end': 243, 'chars': '['}, {'char_start': 255, 'char_end': 257, 'chars': ""',""}, {'char_start': 258, 'char_end': 259, 'chars': ""'""}, {'char_start': 264, 'char_end': 265, 'chars': ','}, {'char_start': 287, 'char_end': 288, 'chars': ']'}, {'char_start': 433, 'char_end': 434, 'chars': '['}, {'char_start': 446, 'char_end': 448, 'chars': ""',""}, {'char_start': 449, 'char_end': 450, 'chars': ""'""}, {'char_start': 458, 'char_end': 459, 'chars': ','}, {'char_start': 476, 'char_end': 477, 'chars': ']'}, {'char_start': 551, 'char_end': 552, 'chars': '['}, {'char_start': 564, 'char_end': 566, 'chars': ""',""}, {'char_start': 567, 'char_end': 568, 'chars': ""'""}, {'char_start': 573, 'char_end': 574, 'chars': ','}, {'char_start': 596, 'char_end': 597, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,175 cwe-089,create_cf_base,"def create_cf_base(): url = 'http://codeforces.com/problemset/' r = requests.get(url) max_page = 0 soup = BeautifulSoup(r.text, ""lxml"") base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\cf.db"") conn = base.cursor() conn.execute(""create table problems (problem INTEGER, diff CHAR)"") for i in available_tags: conn.execute(""create table "" + i + "" (problems INTEGER, diff CHAR)"") for link in soup.find_all(attrs={""class"" : ""page-index""}): s = link.find('a') s2 = s.get(""href"").split('/') max_page = max(max_page, int(s2[3])) a = 0 b = 0 f = False for i in range(1, max_page + 1): r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i)) soup = BeautifulSoup(r.text, ""lxml"") old = '' for link in soup.find_all('a'): s = link.get('href') if s != None and s.find('/problemset') != -1: s = s.split('/') if len(s) == 5 and old != s[3] + s[4]: a = s[3] b = s[4] old = s[3] + s[4] if not f: f = True last_update = old conn.execute(""insert into problems values (?, ?)"", (a, b)) if len(s) == 4 and s[3] in available_tags: conn.execute(""insert into "" + s[3] + "" values (?, ?)"", (a, b)) base.commit() base.close() settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") conn = settings.cursor() conn.execute(""create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)"") conn.execute(""create table last_update_problemset (problem STRING)"") conn.execute(""insert into last_update_problemset values (?)"", (last_update, )) settings.commit() settings.close()","def create_cf_base(): url = 'http://codeforces.com/problemset/' r = requests.get(url) max_page = 0 soup = BeautifulSoup(r.text, ""lxml"") base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\cf.db"") conn = base.cursor() conn.execute(""create table problems (problem INTEGER, diff CHAR)"") for i in available_tags: conn.execute(""create table ? (problems INTEGER, diff CHAR)"", (i,)) for link in soup.find_all(attrs={""class"" : ""page-index""}): s = link.find('a') s2 = s.get(""href"").split('/') max_page = max(max_page, int(s2[3])) a = 0 b = 0 f = False for i in range(1, max_page + 1): r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i)) soup = BeautifulSoup(r.text, ""lxml"") old = '' for link in soup.find_all('a'): s = link.get('href') if s != None and s.find('/problemset') != -1: s = s.split('/') if len(s) == 5 and old != s[3] + s[4]: a = s[3] b = s[4] old = s[3] + s[4] if not f: f = True last_update = old conn.execute(""insert into problems values (?, ?)"", (a, b)) if len(s) == 4 and s[3] in available_tags: conn.execute(""insert into ? values (?, ?)"", (s[3], a, b)) base.commit() base.close() settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") conn = settings.cursor() conn.execute(""create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)"") conn.execute(""create table last_update_problemset (problem STRING)"") conn.execute(""insert into last_update_problemset values (?)"", (last_update, )) settings.commit() settings.close()","{'deleted': [{'line_no': 10, 'char_start': 360, 'char_end': 437, 'line': ' conn.execute(""create table "" + i + "" (problems INTEGER, diff CHAR)"")\n'}, {'line_no': 37, 'char_start': 1385, 'char_end': 1468, 'line': ' conn.execute(""insert into "" + s[3] + "" values (?, ?)"", (a, b))\n'}], 'added': [{'line_no': 10, 'char_start': 360, 'char_end': 435, 'line': ' conn.execute(""create table ? (problems INTEGER, diff CHAR)"", (i,))\n'}, {'line_no': 37, 'char_start': 1383, 'char_end': 1461, 'line': ' conn.execute(""insert into ? values (?, ?)"", (s[3], a, b))\n'}]}","{'deleted': [{'char_start': 395, 'char_end': 404, 'chars': '"" + i + ""'}, {'char_start': 1431, 'char_end': 1443, 'chars': '"" + s[3] + ""'}], 'added': [{'char_start': 395, 'char_end': 396, 'chars': '?'}, {'char_start': 427, 'char_end': 433, 'chars': ', (i,)'}, {'char_start': 1429, 'char_end': 1430, 'chars': '?'}, {'char_start': 1448, 'char_end': 1454, 'chars': 's[3], '}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bases/createcfbase.py,cwe-089,483 cwe-416,__mdiobus_register,"int __mdiobus_register(struct mii_bus *bus, struct module *owner) { struct mdio_device *mdiodev; int i, err; struct gpio_desc *gpiod; if (NULL == bus || NULL == bus->name || NULL == bus->read || NULL == bus->write) return -EINVAL; BUG_ON(bus->state != MDIOBUS_ALLOCATED && bus->state != MDIOBUS_UNREGISTERED); bus->owner = owner; bus->dev.parent = bus->parent; bus->dev.class = &mdio_bus_class; bus->dev.groups = NULL; dev_set_name(&bus->dev, ""%s"", bus->id); err = device_register(&bus->dev); if (err) { pr_err(""mii_bus %s failed to register\n"", bus->id); put_device(&bus->dev); return -EINVAL; } mutex_init(&bus->mdio_lock); /* de-assert bus level PHY GPIO reset */ gpiod = devm_gpiod_get_optional(&bus->dev, ""reset"", GPIOD_OUT_LOW); if (IS_ERR(gpiod)) { dev_err(&bus->dev, ""mii_bus %s couldn't get reset GPIO\n"", bus->id); device_del(&bus->dev); return PTR_ERR(gpiod); } else if (gpiod) { bus->reset_gpiod = gpiod; gpiod_set_value_cansleep(gpiod, 1); udelay(bus->reset_delay_us); gpiod_set_value_cansleep(gpiod, 0); } if (bus->reset) bus->reset(bus); for (i = 0; i < PHY_MAX_ADDR; i++) { if ((bus->phy_mask & (1 << i)) == 0) { struct phy_device *phydev; phydev = mdiobus_scan(bus, i); if (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) { err = PTR_ERR(phydev); goto error; } } } mdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device); bus->state = MDIOBUS_REGISTERED; pr_info(""%s: probed\n"", bus->name); return 0; error: while (--i >= 0) { mdiodev = bus->mdio_map[i]; if (!mdiodev) continue; mdiodev->device_remove(mdiodev); mdiodev->device_free(mdiodev); } /* Put PHYs in RESET to save power */ if (bus->reset_gpiod) gpiod_set_value_cansleep(bus->reset_gpiod, 1); device_del(&bus->dev); return err; }","int __mdiobus_register(struct mii_bus *bus, struct module *owner) { struct mdio_device *mdiodev; int i, err; struct gpio_desc *gpiod; if (NULL == bus || NULL == bus->name || NULL == bus->read || NULL == bus->write) return -EINVAL; BUG_ON(bus->state != MDIOBUS_ALLOCATED && bus->state != MDIOBUS_UNREGISTERED); bus->owner = owner; bus->dev.parent = bus->parent; bus->dev.class = &mdio_bus_class; bus->dev.groups = NULL; dev_set_name(&bus->dev, ""%s"", bus->id); err = device_register(&bus->dev); if (err) { pr_err(""mii_bus %s failed to register\n"", bus->id); return -EINVAL; } mutex_init(&bus->mdio_lock); /* de-assert bus level PHY GPIO reset */ gpiod = devm_gpiod_get_optional(&bus->dev, ""reset"", GPIOD_OUT_LOW); if (IS_ERR(gpiod)) { dev_err(&bus->dev, ""mii_bus %s couldn't get reset GPIO\n"", bus->id); device_del(&bus->dev); return PTR_ERR(gpiod); } else if (gpiod) { bus->reset_gpiod = gpiod; gpiod_set_value_cansleep(gpiod, 1); udelay(bus->reset_delay_us); gpiod_set_value_cansleep(gpiod, 0); } if (bus->reset) bus->reset(bus); for (i = 0; i < PHY_MAX_ADDR; i++) { if ((bus->phy_mask & (1 << i)) == 0) { struct phy_device *phydev; phydev = mdiobus_scan(bus, i); if (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) { err = PTR_ERR(phydev); goto error; } } } mdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device); bus->state = MDIOBUS_REGISTERED; pr_info(""%s: probed\n"", bus->name); return 0; error: while (--i >= 0) { mdiodev = bus->mdio_map[i]; if (!mdiodev) continue; mdiodev->device_remove(mdiodev); mdiodev->device_free(mdiodev); } /* Put PHYs in RESET to save power */ if (bus->reset_gpiod) gpiod_set_value_cansleep(bus->reset_gpiod, 1); device_del(&bus->dev); return err; }","{'deleted': [{'line_no': 23, 'char_start': 589, 'char_end': 614, 'line': '\t\tput_device(&bus->dev);\n'}], 'added': []}","{'deleted': [{'char_start': 591, 'char_end': 616, 'chars': 'put_device(&bus->dev);\n\t\t'}], 'added': []}",github.com/torvalds/linux/commit/6ff7b060535e87c2ae14dd8548512abfdda528fb,drivers/net/phy/mdio_bus.c,cwe-416,621 cwe-476,crypto_skcipher_init_tfm,"static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = alg->setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; }","static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = skcipher_setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; }","{'deleted': [{'line_no': 13, 'char_start': 464, 'char_end': 497, 'line': '\tskcipher->setkey = alg->setkey;\n'}], 'added': [{'line_no': 13, 'char_start': 464, 'char_end': 501, 'line': '\tskcipher->setkey = skcipher_setkey;\n'}]}","{'deleted': [{'char_start': 484, 'char_end': 489, 'chars': 'alg->'}], 'added': [{'char_start': 484, 'char_end': 493, 'chars': 'skcipher_'}]}",github.com/torvalds/linux/commit/9933e113c2e87a9f46a40fde8dafbf801dca1ab9,crypto/skcipher.c,cwe-476,240 cwe-078,test_get_iscsi_ip," def test_get_iscsi_ip(self): self.flags(lock_path=self.tempdir) #record driver set up self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_port_cmd = 'showport' _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) show_port_i_cmd = 'showport -iscsi' _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), '']) show_port_i_cmd = 'showport -iscsiname' _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), '']) #record show_vlun_cmd = 'showvlun -a -host fakehost' show_vlun_ret = 'no vluns listed\r\n' _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), '']) show_vlun_cmd = 'showvlun -a -showcols Port' _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) self.mox.ReplayAll() config = self.setup_configuration() config.iscsi_ip_address = '10.10.10.10' config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252'] self.setup_driver(config, set_up_fakes=False) ip = self.driver._get_iscsi_ip('fakehost') self.assertEqual(ip, '10.10.220.252')"," def test_get_iscsi_ip(self): self.flags(lock_path=self.tempdir) #record driver set up self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_port_cmd = ['showport'] _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), '']) show_port_i_cmd = ['showport', '-iscsi'] _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET), '']) show_port_i_cmd = ['showport', '-iscsiname'] _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), '']) #record show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost'] show_vlun_ret = 'no vluns listed\r\n' _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), '']) show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port'] _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) self.mox.ReplayAll() config = self.setup_configuration() config.iscsi_ip_address = '10.10.10.10' config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252'] self.setup_driver(config, set_up_fakes=False) ip = self.driver._get_iscsi_ip('fakehost') self.assertEqual(ip, '10.10.220.252')","{'deleted': [{'line_no': 9, 'char_start': 290, 'char_end': 325, 'line': "" show_port_cmd = 'showport'\n""}, {'line_no': 12, 'char_start': 397, 'char_end': 441, 'line': "" show_port_i_cmd = 'showport -iscsi'\n""}, {'line_no': 16, 'char_start': 579, 'char_end': 627, 'line': "" show_port_i_cmd = 'showport -iscsiname'\n""}, {'line_no': 20, 'char_start': 724, 'char_end': 777, 'line': "" show_vlun_cmd = 'showvlun -a -host fakehost'\n""}, {'line_no': 23, 'char_start': 899, 'char_end': 952, 'line': "" show_vlun_cmd = 'showvlun -a -showcols Port'\n""}], 'added': [{'line_no': 9, 'char_start': 290, 'char_end': 327, 'line': "" show_port_cmd = ['showport']\n""}, {'line_no': 12, 'char_start': 399, 'char_end': 448, 'line': "" show_port_i_cmd = ['showport', '-iscsi']\n""}, {'line_no': 16, 'char_start': 586, 'char_end': 639, 'line': "" show_port_i_cmd = ['showport', '-iscsiname']\n""}, {'line_no': 20, 'char_start': 736, 'char_end': 800, 'line': "" show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']\n""}, {'line_no': 23, 'char_start': 922, 'char_end': 986, 'line': "" show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n""}]}","{'deleted': [], 'added': [{'char_start': 314, 'char_end': 315, 'chars': '['}, {'char_start': 325, 'char_end': 326, 'chars': ']'}, {'char_start': 425, 'char_end': 426, 'chars': '['}, {'char_start': 435, 'char_end': 437, 'chars': ""',""}, {'char_start': 438, 'char_end': 439, 'chars': ""'""}, {'char_start': 446, 'char_end': 447, 'chars': ']'}, {'char_start': 612, 'char_end': 613, 'chars': '['}, {'char_start': 622, 'char_end': 624, 'chars': ""',""}, {'char_start': 625, 'char_end': 626, 'chars': ""'""}, {'char_start': 637, 'char_end': 638, 'chars': ']'}, {'char_start': 760, 'char_end': 761, 'chars': '['}, {'char_start': 770, 'char_end': 772, 'chars': ""',""}, {'char_start': 773, 'char_end': 774, 'chars': ""'""}, {'char_start': 776, 'char_end': 778, 'chars': ""',""}, {'char_start': 779, 'char_end': 780, 'chars': ""'""}, {'char_start': 785, 'char_end': 787, 'chars': ""',""}, {'char_start': 788, 'char_end': 789, 'chars': ""'""}, {'char_start': 798, 'char_end': 799, 'chars': ']'}, {'char_start': 946, 'char_end': 947, 'chars': '['}, {'char_start': 956, 'char_end': 958, 'chars': ""',""}, {'char_start': 959, 'char_end': 960, 'chars': ""'""}, {'char_start': 962, 'char_end': 964, 'chars': ""',""}, {'char_start': 965, 'char_end': 966, 'chars': ""'""}, {'char_start': 975, 'char_end': 977, 'chars': ""',""}, {'char_start': 978, 'char_end': 979, 'chars': ""'""}, {'char_start': 984, 'char_end': 985, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078,409 cwe-190,copyaudiodata,"bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid) { int frameSize = afGetVirtualFrameSize(infile, trackid, 1); const int kBufferFrameCount = 65536; void *buffer = malloc(kBufferFrameCount * frameSize); AFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK); AFframecount totalFramesWritten = 0; bool success = true; while (totalFramesWritten < totalFrames) { AFframecount framesToRead = totalFrames - totalFramesWritten; if (framesToRead > kBufferFrameCount) framesToRead = kBufferFrameCount; AFframecount framesRead = afReadFrames(infile, trackid, buffer, framesToRead); if (framesRead < framesToRead) { fprintf(stderr, ""Bad read of audio track data.\n""); success = false; break; } AFframecount framesWritten = afWriteFrames(outfile, trackid, buffer, framesRead); if (framesWritten < framesRead) { fprintf(stderr, ""Bad write of audio track data.\n""); success = false; break; } totalFramesWritten += framesWritten; } free(buffer); return success; }","bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid) { int frameSize = afGetVirtualFrameSize(infile, trackid, 1); int kBufferFrameCount = 65536; int bufferSize; while (multiplyCheckOverflow(kBufferFrameCount, frameSize, &bufferSize)) kBufferFrameCount /= 2; void *buffer = malloc(bufferSize); AFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK); AFframecount totalFramesWritten = 0; bool success = true; while (totalFramesWritten < totalFrames) { AFframecount framesToRead = totalFrames - totalFramesWritten; if (framesToRead > kBufferFrameCount) framesToRead = kBufferFrameCount; AFframecount framesRead = afReadFrames(infile, trackid, buffer, framesToRead); if (framesRead < framesToRead) { fprintf(stderr, ""Bad read of audio track data.\n""); success = false; break; } AFframecount framesWritten = afWriteFrames(outfile, trackid, buffer, framesRead); if (framesWritten < framesRead) { fprintf(stderr, ""Bad write of audio track data.\n""); success = false; break; } totalFramesWritten += framesWritten; } free(buffer); return success; }","{'deleted': [{'line_no': 5, 'char_start': 139, 'char_end': 177, 'line': '\tconst int kBufferFrameCount = 65536;\n'}, {'line_no': 6, 'char_start': 177, 'char_end': 232, 'line': '\tvoid *buffer = malloc(kBufferFrameCount * frameSize);\n'}], 'added': [{'line_no': 5, 'char_start': 139, 'char_end': 171, 'line': '\tint kBufferFrameCount = 65536;\n'}, {'line_no': 6, 'char_start': 171, 'char_end': 188, 'line': '\tint bufferSize;\n'}, {'line_no': 7, 'char_start': 188, 'char_end': 262, 'line': '\twhile (multiplyCheckOverflow(kBufferFrameCount, frameSize, &bufferSize))\n'}, {'line_no': 8, 'char_start': 262, 'char_end': 288, 'line': '\t\tkBufferFrameCount /= 2;\n'}, {'line_no': 9, 'char_start': 288, 'char_end': 324, 'line': '\tvoid *buffer = malloc(bufferSize);\n'}]}","{'deleted': [{'char_start': 140, 'char_end': 146, 'chars': 'const '}, {'char_start': 178, 'char_end': 180, 'chars': 'vo'}, {'char_start': 181, 'char_end': 182, 'chars': 'd'}, {'char_start': 183, 'char_end': 184, 'chars': '*'}, {'char_start': 190, 'char_end': 192, 'chars': ' ='}, {'char_start': 194, 'char_end': 195, 'chars': 'a'}, {'char_start': 198, 'char_end': 199, 'chars': 'c'}, {'char_start': 218, 'char_end': 219, 'chars': '*'}], 'added': [{'char_start': 173, 'char_end': 175, 'chars': 'nt'}, {'char_start': 182, 'char_end': 194, 'chars': 'Size;\n\twhile'}, {'char_start': 195, 'char_end': 196, 'chars': '('}, {'char_start': 197, 'char_end': 198, 'chars': 'u'}, {'char_start': 199, 'char_end': 202, 'chars': 'tip'}, {'char_start': 203, 'char_end': 207, 'chars': 'yChe'}, {'char_start': 208, 'char_end': 217, 'chars': 'kOverflow'}, {'char_start': 235, 'char_end': 236, 'chars': ','}, {'char_start': 237, 'char_end': 247, 'chars': 'frameSize,'}, {'char_start': 248, 'char_end': 251, 'chars': '&bu'}, {'char_start': 252, 'char_end': 272, 'chars': 'ferSize))\n\t\tkBufferF'}, {'char_start': 276, 'char_end': 317, 'chars': 'Count /= 2;\n\tvoid *buffer = malloc(buffer'}]}",github.com/antlarr/audiofile/commit/7d65f89defb092b63bcbc5d98349fb222ca73b3c,sfcommands/sfconvert.c,cwe-190,287 cwe-787,next_state_class,"next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; }","next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } if (*state != CCS_START) *state = CCS_VALUE; *type = CCV_CLASS; return 0; }","{'deleted': [{'line_no': 18, 'char_start': 456, 'char_end': 478, 'line': ' *state = CCS_VALUE;\n'}], 'added': [{'line_no': 18, 'char_start': 456, 'char_end': 483, 'line': ' if (*state != CCS_START)\n'}, {'line_no': 19, 'char_start': 483, 'char_end': 507, 'line': ' *state = CCS_VALUE;\n'}, {'line_no': 20, 'char_start': 507, 'char_end': 508, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 458, 'char_end': 487, 'chars': 'if (*state != CCS_START)\n '}, {'char_start': 506, 'char_end': 507, 'chars': '\n'}]}",github.com/kkos/oniguruma/commit/3b63d12038c8d8fc278e81c942fa9bec7c704c8b,src/regparse.c,cwe-787,170 cwe-125,rtc_irq_eoi_tracking_reset,"static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic) { ioapic->rtc_status.pending_eoi = 0; bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS); }","static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic) { ioapic->rtc_status.pending_eoi = 0; bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPU_ID); }","{'deleted': [{'line_no': 4, 'char_start': 105, 'char_end': 167, 'line': '\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS);\n'}], 'added': [{'line_no': 4, 'char_start': 105, 'char_end': 169, 'line': '\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPU_ID);\n'}]}","{'deleted': [{'char_start': 163, 'char_end': 164, 'chars': 'S'}], 'added': [{'char_start': 163, 'char_end': 166, 'chars': '_ID'}]}",github.com/torvalds/linux/commit/81cdb259fb6d8c1c4ecfeea389ff5a73c07f5755,arch/x86/kvm/ioapic.c,cwe-125,53 cwe-416,get_net_ns_by_id,"struct net *get_net_ns_by_id(struct net *net, int id) { struct net *peer; if (id < 0) return NULL; rcu_read_lock(); spin_lock_bh(&net->nsid_lock); peer = idr_find(&net->netns_ids, id); if (peer) get_net(peer); spin_unlock_bh(&net->nsid_lock); rcu_read_unlock(); return peer; }","struct net *get_net_ns_by_id(struct net *net, int id) { struct net *peer; if (id < 0) return NULL; rcu_read_lock(); spin_lock_bh(&net->nsid_lock); peer = idr_find(&net->netns_ids, id); if (peer) peer = maybe_get_net(peer); spin_unlock_bh(&net->nsid_lock); rcu_read_unlock(); return peer; }","{'deleted': [{'line_no': 12, 'char_start': 205, 'char_end': 222, 'line': '\t\tget_net(peer);\n'}], 'added': [{'line_no': 12, 'char_start': 205, 'char_end': 235, 'line': '\t\tpeer = maybe_get_net(peer);\n'}]}","{'deleted': [], 'added': [{'char_start': 207, 'char_end': 220, 'chars': 'peer = maybe_'}]}",github.com/torvalds/linux/commit/21b5944350052d2583e82dd59b19a9ba94a007f0,net/core/net_namespace.c,cwe-416,91 cwe-078,_create_host," def _create_host(self, connector): """"""Create a new host on the storage system. We create a host name and associate it with the given connection information. """""" LOG.debug(_('enter: _create_host: host %s') % connector['host']) rand_id = str(random.randint(0, 99999999)).zfill(8) host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector), rand_id) # Get all port information from the connector ports = [] if 'initiator' in connector: ports.append('-iscsiname %s' % connector['initiator']) if 'wwpns' in connector: for wwpn in connector['wwpns']: ports.append('-hbawwpn %s' % wwpn) # When creating a host, we need one port self._driver_assert(len(ports), _('_create_host: No connector ports')) port1 = ports.pop(0) ssh_cmd = ('svctask mkhost -force %(port1)s -name ""%(host_name)s""' % {'port1': port1, 'host_name': host_name}) out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return('successfully created' in out, '_create_host', ssh_cmd, out, err) # Add any additional ports to the host for port in ports: ssh_cmd = ('svctask addhostport -force %s %s' % (port, host_name)) out, err = self._run_ssh(ssh_cmd) LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') % {'host': connector['host'], 'host_name': host_name}) return host_name"," def _create_host(self, connector): """"""Create a new host on the storage system. We create a host name and associate it with the given connection information. """""" LOG.debug(_('enter: _create_host: host %s') % connector['host']) rand_id = str(random.randint(0, 99999999)).zfill(8) host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector), rand_id) # Get all port information from the connector ports = [] if 'initiator' in connector: ports.append('-iscsiname %s' % connector['initiator']) if 'wwpns' in connector: for wwpn in connector['wwpns']: ports.append('-hbawwpn %s' % wwpn) # When creating a host, we need one port self._driver_assert(len(ports), _('_create_host: No connector ports')) port1 = ports.pop(0) arg_name, arg_val = port1.split() ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name', '""%s""' % host_name] out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return('successfully created' in out, '_create_host', ssh_cmd, out, err) # Add any additional ports to the host for port in ports: arg_name, arg_val = port.split() ssh_cmd = ['svctask', 'addhostport', '-force', arg_name, arg_val, host_name] out, err = self._run_ssh(ssh_cmd) LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') % {'host': connector['host'], 'host_name': host_name}) return host_name","{'deleted': [{'line_no': 26, 'char_start': 916, 'char_end': 993, 'line': ' ssh_cmd = (\'svctask mkhost -force %(port1)s -name ""%(host_name)s""\' %\n'}, {'line_no': 27, 'char_start': 993, 'char_end': 1054, 'line': "" {'port1': port1, 'host_name': host_name})\n""}, {'line_no': 34, 'char_start': 1301, 'char_end': 1380, 'line': "" ssh_cmd = ('svctask addhostport -force %s %s' % (port, host_name))\n""}], 'added': [{'line_no': 26, 'char_start': 916, 'char_end': 958, 'line': ' arg_name, arg_val = port1.split()\n'}, {'line_no': 27, 'char_start': 958, 'char_end': 1036, 'line': "" ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name',\n""}, {'line_no': 28, 'char_start': 1036, 'char_end': 1075, 'line': ' \'""%s""\' % host_name]\n'}, {'line_no': 35, 'char_start': 1322, 'char_end': 1367, 'line': ' arg_name, arg_val = port.split()\n'}, {'line_no': 36, 'char_start': 1367, 'char_end': 1445, 'line': "" ssh_cmd = ['svctask', 'addhostport', '-force', arg_name, arg_val,\n""}, {'line_no': 37, 'char_start': 1445, 'char_end': 1479, 'line': ' host_name]\n'}]}","{'deleted': [{'char_start': 934, 'char_end': 935, 'chars': '('}, {'char_start': 958, 'char_end': 962, 'chars': '%(po'}, {'char_start': 963, 'char_end': 969, 'chars': 't1)s -'}, {'char_start': 974, 'char_end': 981, 'chars': '""%(host'}, {'char_start': 986, 'char_end': 989, 'chars': ')s""'}, {'char_start': 990, 'char_end': 992, 'chars': ' %'}, {'char_start': 1012, 'char_end': 1013, 'chars': '{'}, {'char_start': 1014, 'char_end': 1019, 'chars': 'port1'}, {'char_start': 1020, 'char_end': 1021, 'chars': ':'}, {'char_start': 1022, 'char_end': 1041, 'chars': ""port1, 'host_name':""}, {'char_start': 1051, 'char_end': 1053, 'chars': '})'}, {'char_start': 1323, 'char_end': 1324, 'chars': '('}, {'char_start': 1351, 'char_end': 1357, 'chars': ' %s %s'}, {'char_start': 1359, 'char_end': 1360, 'chars': '%'}, {'char_start': 1361, 'char_end': 1364, 'chars': '(po'}, {'char_start': 1365, 'char_end': 1366, 'chars': 't'}, {'char_start': 1377, 'char_end': 1379, 'chars': '))'}], 'added': [{'char_start': 924, 'char_end': 966, 'chars': 'arg_name, arg_val = port1.split()\n '}, {'char_start': 976, 'char_end': 977, 'chars': '['}, {'char_start': 985, 'char_end': 987, 'chars': ""',""}, {'char_start': 988, 'char_end': 989, 'chars': ""'""}, {'char_start': 995, 'char_end': 997, 'chars': ""',""}, {'char_start': 998, 'char_end': 999, 'chars': ""'""}, {'char_start': 1005, 'char_end': 1007, 'chars': ""',""}, {'char_start': 1008, 'char_end': 1009, 'chars': 'a'}, {'char_start': 1010, 'char_end': 1012, 'chars': 'g_'}, {'char_start': 1016, 'char_end': 1017, 'chars': ','}, {'char_start': 1018, 'char_end': 1021, 'chars': 'arg'}, {'char_start': 1022, 'char_end': 1029, 'chars': ""val, '-""}, {'char_start': 1034, 'char_end': 1035, 'chars': ','}, {'char_start': 1056, 'char_end': 1060, 'chars': '""%s""'}, {'char_start': 1062, 'char_end': 1063, 'chars': '%'}, {'char_start': 1073, 'char_end': 1074, 'chars': ']'}, {'char_start': 1322, 'char_end': 1367, 'chars': ' arg_name, arg_val = port.split()\n'}, {'char_start': 1389, 'char_end': 1390, 'chars': '['}, {'char_start': 1398, 'char_end': 1400, 'chars': ""',""}, {'char_start': 1401, 'char_end': 1402, 'chars': ""'""}, {'char_start': 1413, 'char_end': 1415, 'chars': ""',""}, {'char_start': 1416, 'char_end': 1417, 'chars': ""'""}, {'char_start': 1424, 'char_end': 1425, 'chars': ','}, {'char_start': 1426, 'char_end': 1435, 'chars': 'arg_name,'}, {'char_start': 1436, 'char_end': 1437, 'chars': 'a'}, {'char_start': 1438, 'char_end': 1443, 'chars': 'g_val'}, {'char_start': 1444, 'char_end': 1467, 'chars': '\n '}, {'char_start': 1477, 'char_end': 1478, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,395 cwe-089,placings,"@endpoints.route(""/placings"") def placings(): if db == None: init() tag = request.args.get('tag', default='christmas mike') # Get all the urls that this player has participated in sql = ""SELECT * FROM placings WHERE player = '{}'"".format(tag) results = list(db.exec(sql)) results.sort(key=lambda x: int(x[2])) return json.dumps(results)","@endpoints.route(""/placings"") def placings(): if db == None: init() tag = request.args.get('tag', default='christmas mike') # Get all the urls that this player has participated in sql = ""SELECT * FROM placings WHERE player = '{tag}'"" args = {'tag': tag} results = list(db.exec(sql, args)) results.sort(key=lambda x: int(x[2])) return json.dumps(results)","{'deleted': [{'line_no': 9, 'char_start': 202, 'char_end': 269, 'line': ' sql = ""SELECT * FROM placings WHERE player = \'{}\'"".format(tag)\n'}, {'line_no': 10, 'char_start': 269, 'char_end': 302, 'line': ' results = list(db.exec(sql))\n'}], 'added': [{'line_no': 9, 'char_start': 202, 'char_end': 260, 'line': ' sql = ""SELECT * FROM placings WHERE player = \'{tag}\'""\n'}, {'line_no': 10, 'char_start': 260, 'char_end': 284, 'line': "" args = {'tag': tag}\n""}, {'line_no': 11, 'char_start': 284, 'char_end': 323, 'line': ' results = list(db.exec(sql, args))\n'}]}","{'deleted': [{'char_start': 256, 'char_end': 259, 'chars': '.fo'}, {'char_start': 260, 'char_end': 261, 'chars': 'm'}, {'char_start': 262, 'char_end': 264, 'chars': 't('}, {'char_start': 267, 'char_end': 268, 'chars': ')'}], 'added': [{'char_start': 253, 'char_end': 256, 'chars': 'tag'}, {'char_start': 259, 'char_end': 265, 'chars': '\n a'}, {'char_start': 266, 'char_end': 273, 'chars': ""gs = {'""}, {'char_start': 274, 'char_end': 279, 'chars': ""ag': ""}, {'char_start': 282, 'char_end': 283, 'chars': '}'}, {'char_start': 314, 'char_end': 320, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,endpoints.py,cwe-089,92 cwe-089,openPoll,"@hook.command(adminonly=True) def openPoll(question, reply=None, db=None): """"""Creates a new poll."""""" if not db_ready: db_init(db) try: active = db.execute(""SELECT pollID FROM polls WHERE active = 1"").fetchone()[0] if active: reply(""There already is an open poll."") return except: db.execute(""INSERT INTO polls (question, active) VALUES ('{}', 1)"".format(question)) reply(""Opened new poll: {}"".format(question)) #reply(""Poll opened!"") return","@hook.command(adminonly=True) def openPoll(question, reply=None, db=None): """"""Creates a new poll."""""" if not db_ready: db_init(db) try: active = db.execute(""SELECT pollID FROM polls WHERE active = 1"").fetchone()[0] if active: reply(""There already is an open poll."") return except: db.execute(""INSERT INTO polls (question, active) VALUES (?, 1)"", (question,)) reply(""Opened new poll: {}"".format(question)) #reply(""Poll opened!"") return","{'deleted': [{'line_no': 11, 'char_start': 337, 'char_end': 430, 'line': ' db.execute(""INSERT INTO polls (question, active) VALUES (\'{}\', 1)"".format(question))\n'}], 'added': [{'line_no': 11, 'char_start': 337, 'char_end': 423, 'line': ' db.execute(""INSERT INTO polls (question, active) VALUES (?, 1)"", (question,))\n'}]}","{'deleted': [{'char_start': 402, 'char_end': 406, 'chars': ""'{}'""}, {'char_start': 411, 'char_end': 418, 'chars': '.format'}], 'added': [{'char_start': 402, 'char_end': 403, 'chars': '?'}, {'char_start': 408, 'char_end': 410, 'chars': ', '}, {'char_start': 419, 'char_end': 420, 'chars': ','}]}",github.com/FrozenPigs/Taigabot/commit/ea9b83a66ae1f0f38a1895f3e8dfa2833d77e3a6,plugins/poll.py,cwe-089,123 cwe-089,insert,"def insert(key, value): connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD']) cur = connection.cursor() try: cur.execute(""insert into reply_map values('{}', '{}')"".format(key, value)) connection.commit() except: pass","def insert(key, value): connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD']) cur = connection.cursor() try: cur.execute(""insert into reply_map values(?, ?)"", (key, value)) connection.commit() except: pass","{'deleted': [{'line_no': 5, 'char_start': 214, 'char_end': 297, 'line': ' cur.execute(""insert into reply_map values(\'{}\', \'{}\')"".format(key, value))\n'}], 'added': [{'line_no': 5, 'char_start': 214, 'char_end': 286, 'line': ' cur.execute(""insert into reply_map values(?, ?)"", (key, value))\n'}]}","{'deleted': [{'char_start': 264, 'char_end': 268, 'chars': ""'{}'""}, {'char_start': 270, 'char_end': 274, 'chars': ""'{}'""}, {'char_start': 276, 'char_end': 283, 'chars': '.format'}], 'added': [{'char_start': 264, 'char_end': 265, 'chars': '?'}, {'char_start': 267, 'char_end': 268, 'chars': '?'}, {'char_start': 270, 'char_end': 272, 'chars': ', '}]}",github.com/tadaren/reply_bot/commit/5aeafa7e9597a766992af9ff8189e1f050b6579b,db.py,cwe-089,74 cwe-078,_get_vdisk_fc_mappings," def _get_vdisk_fc_mappings(self, vdisk_name): """"""Return FlashCopy mappings that this vdisk is associated with."""""" ssh_cmd = 'svcinfo lsvdiskfcmappings -nohdr %s' % vdisk_name out, err = self._run_ssh(ssh_cmd) mapping_ids = [] if (len(out.strip())): lines = out.strip().split('\n') mapping_ids = [line.split()[0] for line in lines] return mapping_ids"," def _get_vdisk_fc_mappings(self, vdisk_name): """"""Return FlashCopy mappings that this vdisk is associated with."""""" ssh_cmd = ['svcinfo', 'lsvdiskfcmappings', '-nohdr', vdisk_name] out, err = self._run_ssh(ssh_cmd) mapping_ids = [] if (len(out.strip())): lines = out.strip().split('\n') mapping_ids = [line.split()[0] for line in lines] return mapping_ids","{'deleted': [{'line_no': 4, 'char_start': 127, 'char_end': 196, 'line': "" ssh_cmd = 'svcinfo lsvdiskfcmappings -nohdr %s' % vdisk_name\n""}], 'added': [{'line_no': 4, 'char_start': 127, 'char_end': 200, 'line': "" ssh_cmd = ['svcinfo', 'lsvdiskfcmappings', '-nohdr', vdisk_name]\n""}]}","{'deleted': [{'char_start': 178, 'char_end': 181, 'chars': ' %s'}, {'char_start': 182, 'char_end': 184, 'chars': ' %'}], 'added': [{'char_start': 145, 'char_end': 146, 'chars': '['}, {'char_start': 154, 'char_end': 156, 'chars': ""',""}, {'char_start': 157, 'char_end': 158, 'chars': ""'""}, {'char_start': 175, 'char_end': 177, 'chars': ""',""}, {'char_start': 178, 'char_end': 179, 'chars': ""'""}, {'char_start': 186, 'char_end': 187, 'chars': ','}, {'char_start': 198, 'char_end': 199, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,107 cwe-089,tag_to_tag_num," def tag_to_tag_num(self, tag): ''' Returns tag_num given tag. ''' q = ""SELECT rowid FROM tags WHERE tag = '"" + tag + ""'"" self.query(q) return self.c.fetchone()[0]"," def tag_to_tag_num(self, tag): ''' Returns tag_num given tag. ''' q = ""SELECT rowid FROM tags WHERE tag = ?"" self.query(q, tag) return self.c.fetchone()[0]","{'deleted': [{'line_no': 4, 'char_start': 79, 'char_end': 142, 'line': ' q = ""SELECT rowid FROM tags WHERE tag = \'"" + tag + ""\'""\n'}, {'line_no': 5, 'char_start': 142, 'char_end': 164, 'line': ' self.query(q)\n'}], 'added': [{'line_no': 4, 'char_start': 79, 'char_end': 130, 'line': ' q = ""SELECT rowid FROM tags WHERE tag = ?""\n'}, {'line_no': 5, 'char_start': 130, 'char_end': 157, 'line': ' self.query(q, tag)\n'}]}","{'deleted': [{'char_start': 127, 'char_end': 140, 'chars': '\'"" + tag + ""\''}], 'added': [{'char_start': 127, 'char_end': 128, 'chars': '?'}, {'char_start': 150, 'char_end': 155, 'chars': ', tag'}]}",github.com/pukkapies/urop2019/commit/3ca2e2c291d2d5fe262d20a8e0520bdfb622432b,modules/query_lastfm.py,cwe-089,50 cwe-190,cs_winkernel_malloc,"void * CAPSTONE_API cs_winkernel_malloc(size_t size) { // Disallow zero length allocation because they waste pool header space and, // in many cases, indicate a potential validation issue in the calling code. NT_ASSERT(size); // FP; a use of NonPagedPool is required for Windows 7 support #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; }","void * CAPSTONE_API cs_winkernel_malloc(size_t size) { // Disallow zero length allocation because they waste pool header space and, // in many cases, indicate a potential validation issue in the calling code. NT_ASSERT(size); // FP; a use of NonPagedPool is required for Windows 7 support #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory size_t number_of_bytes = 0; CS_WINKERNEL_MEMBLOCK *block = NULL; // A specially crafted size value can trigger the overflow. // If the sum in a value that overflows or underflows the capacity of the type, // the function returns NULL. if (!NT_SUCCESS(RtlSizeTAdd(size, sizeof(CS_WINKERNEL_MEMBLOCK), &number_of_bytes))) { return NULL; } block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, number_of_bytes, CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; }","{'deleted': [{'line_no': 9, 'char_start': 371, 'char_end': 451, 'line': '\tCS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag(\n'}, {'line_no': 10, 'char_start': 451, 'char_end': 530, 'line': '\t\t\tNonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG);\n'}], 'added': [{'line_no': 9, 'char_start': 371, 'char_end': 400, 'line': '\tsize_t number_of_bytes = 0;\n'}, {'line_no': 10, 'char_start': 400, 'char_end': 438, 'line': '\tCS_WINKERNEL_MEMBLOCK *block = NULL;\n'}, {'line_no': 14, 'char_start': 611, 'char_end': 699, 'line': '\tif (!NT_SUCCESS(RtlSizeTAdd(size, sizeof(CS_WINKERNEL_MEMBLOCK), &number_of_bytes))) {\n'}, {'line_no': 15, 'char_start': 699, 'char_end': 714, 'line': '\t\treturn NULL;\n'}, {'line_no': 16, 'char_start': 714, 'char_end': 717, 'line': '\t}\n'}, {'line_no': 17, 'char_start': 717, 'char_end': 774, 'line': '\tblock = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag(\n'}, {'line_no': 18, 'char_start': 774, 'char_end': 832, 'line': '\t\t\tNonPagedPool, number_of_bytes, CS_WINKERNEL_POOL_TAG);\n'}]}","{'deleted': [{'char_start': 468, 'char_end': 478, 'chars': 'size + siz'}, {'char_start': 481, 'char_end': 484, 'chars': '(CS'}, {'char_start': 485, 'char_end': 504, 'chars': 'WINKERNEL_MEMBLOCK)'}], 'added': [{'char_start': 372, 'char_end': 401, 'chars': 'size_t number_of_bytes = 0;\n\t'}, {'char_start': 432, 'char_end': 726, 'chars': 'NULL;\n\t// A specially crafted size value can trigger the overflow.\n\t// If the sum in a value that overflows or underflows the capacity of the type,\n\t// the function returns NULL.\n\tif (!NT_SUCCESS(RtlSizeTAdd(size, sizeof(CS_WINKERNEL_MEMBLOCK), &number_of_bytes))) {\n\t\treturn NULL;\n\t}\n\tblock = '}, {'char_start': 791, 'char_end': 795, 'chars': 'numb'}, {'char_start': 796, 'char_end': 798, 'chars': 'r_'}, {'char_start': 801, 'char_end': 806, 'chars': 'bytes'}]}",github.com/aquynh/capstone/commit/6fe86eef621b9849f51a5e1e5d73258a93440403,windows/winkernel_mm.c,cwe-190,166 cwe-022,updateKey,"def updateKey(client): """"""Updates the contents of a key that already exists in our system. Returns an error if the specified key doesn't exist for the specified user. """""" global NOT_FOUND global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) # Use 'w' flag to replace existing key file with the new key data if os.path.isfile('keys/%s/%s.key' % (client, token_data['name'])): with open('keys/%s/%s.key' % (client, token_data['name']), 'w') as f: f.write(token_data['key']) else: raise FoxlockError(NOT_FOUND, ""Key '%s' not found"" % token_data['name']) return 'Key successfully updated', CREATED","def updateKey(client): """"""Updates the contents of a key that already exists in our system. Returns an error if the specified key doesn't exist for the specified user. """""" global NOT_FOUND global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) validateKeyName(token_data['name']) # Use 'w' flag to replace existing key file with the new key data if os.path.isfile('keys/%s/%s.key' % (client, token_data['name'])): with open('keys/%s/%s.key' % (client, token_data['name']), 'w') as f: f.write(token_data['key']) else: raise FoxlockError(NOT_FOUND, ""Key '%s' not found"" % token_data['name']) return 'Key successfully updated', CREATED","{'deleted': [{'line_no': 9, 'char_start': 233, 'char_end': 234, 'line': '\n'}], 'added': [{'line_no': 12, 'char_start': 371, 'char_end': 408, 'line': ""\tvalidateKeyName(token_data['name'])\n""}]}","{'deleted': [{'char_start': 233, 'char_end': 234, 'chars': '\n'}], 'added': [{'char_start': 369, 'char_end': 406, 'chars': "")\n\tvalidateKeyName(token_data['name']""}]}",github.com/Mimickal/FoxLock/commit/7c665e556987f4e2c1a75e143a1e80ae066ad833,impl.py,cwe-022,186 cwe-078,usage,"def usage(args=None): ''' Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD': cmd = 'df -kP' else: cmd = 'df' if args: cmd = cmd + ' -' + args ret = {} out = __salt__['cmd.run'](cmd).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.warn(""Problem parsing disk usage information"") ret = {} return ret","def usage(args=None): ''' Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage ''' flags = '' allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: break if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD': cmd = 'df -kP' else: cmd = 'df' if args: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.warn(""Problem parsing disk usage information"") ret = {} return ret","{'deleted': [{'line_no': 18, 'char_start': 346, 'char_end': 378, 'line': "" cmd = cmd + ' -' + args\n""}], 'added': [{'line_no': 11, 'char_start': 175, 'char_end': 190, 'line': "" flags = ''\n""}, {'line_no': 12, 'char_start': 190, 'char_end': 265, 'line': "" allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')\n""}, {'line_no': 13, 'char_start': 265, 'char_end': 287, 'line': ' for flag in args:\n'}, {'line_no': 14, 'char_start': 287, 'char_end': 315, 'line': ' if flag in allowed:\n'}, {'line_no': 15, 'char_start': 315, 'char_end': 341, 'line': ' flags += flag\n'}, {'line_no': 16, 'char_start': 341, 'char_end': 355, 'line': ' else:\n'}, {'line_no': 17, 'char_start': 355, 'char_end': 373, 'line': ' break\n'}, {'line_no': 25, 'char_start': 544, 'char_end': 581, 'line': "" cmd += ' -{0}'.format(flags)\n""}]}","{'deleted': [{'char_start': 215, 'char_end': 215, 'chars': ''}, {'char_start': 359, 'char_end': 365, 'chars': ' cmd +'}, {'char_start': 370, 'char_end': 373, 'chars': ' + '}, {'char_start': 374, 'char_end': 375, 'chars': 'r'}], 'added': [{'char_start': 179, 'char_end': 377, 'chars': ""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 ""}, {'char_start': 557, 'char_end': 558, 'chars': '='}, {'char_start': 562, 'char_end': 565, 'chars': '{0}'}, {'char_start': 566, 'char_end': 571, 'chars': '.form'}, {'char_start': 572, 'char_end': 577, 'chars': 't(fla'}, {'char_start': 579, 'char_end': 580, 'chars': ')'}]}",github.com/saltstack/salt/commit/ebdef37b7e5d2b95a01d34b211c61c61da67e46a,salt/modules/disk.py,cwe-078,371 cwe-125,dex_loadcode,"static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; // doublecheck?? if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); // TODO: is this posible after R_MIN ?? if (bin->header.strings_size > bin->size) { eprintf (""Invalid strings size\n""); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf (""Class #%d -\n"", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size - 1) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char "";"" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf (""%s.method.%s%s"", class_name, method_name, signature); imp->type = r_str_const (""FUNC""); imp->bind = r_str_const (""NONE""); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf (""imp.%s"", imp->name); sym->type = r_str_const (""FUNC""); sym->bind = r_str_const (""NONE""); //XXX so damn unsafe check buffer boundaries!!!! //XXX use r_buf API!! sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, ""method.%d"", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; }","static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; // doublecheck?? if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); // TODO: is this posible after R_MIN ?? if (bin->header.strings_size > bin->size) { eprintf (""Invalid strings size\n""); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf (""Class #%d -\n"", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char "";"" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf (""%s.method.%s%s"", class_name, method_name, signature); imp->type = r_str_const (""FUNC""); imp->bind = r_str_const (""NONE""); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf (""imp.%s"", imp->name); sym->type = r_str_const (""FUNC""); sym->bind = r_str_const (""NONE""); //XXX so damn unsafe check buffer boundaries!!!! //XXX use r_buf API!! sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, ""method.%d"", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; }","{'deleted': [{'line_no': 75, 'char_start': 1978, 'char_end': 2042, 'line': '\t\t\tif (bin->methods[i].class_id > bin->header.types_size - 1) {\n'}], 'added': [{'line_no': 75, 'char_start': 1978, 'char_end': 2038, 'line': '\t\t\tif (bin->methods[i].class_id > bin->header.types_size) {\n'}]}","{'deleted': [{'char_start': 2034, 'char_end': 2038, 'chars': ' - 1'}], 'added': []}",github.com/radare/radare2/commit/ead645853a63bf83d8386702cad0cf23b31d7eeb,libr/bin/p/bin_dex.c,cwe-125,1084 cwe-089,fetch_data," def fetch_data(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, sid) query = (""SELECT data FROM %s WHERE identifier = '%s';"" % (self.table, sid) ) res = self._query(query) try: data = res.dictresult()[0]['data'] except IndexError: raise ObjectDoesNotExistException(id) try: ndata = pg.unescape_bytea(data) except: # insufficient PyGreSQL version ndata = data.replace(""\\'"", ""'"") ndata = ndata.replace('\\000\\001', nonTextToken) ndata = ndata.replace('\\012', '\n') return ndata"," def fetch_data(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, sid) query = (""SELECT data FROM %s WHERE identifier = $1;"" % (self.table) ) res = self._query(query, sid) try: data = res.dictresult()[0]['data'] except IndexError: raise ObjectDoesNotExistException(id) try: ndata = pg.unescape_bytea(data) except: # insufficient PyGreSQL version ndata = data.replace(""\\'"", ""'"") ndata = ndata.replace('\\000\\001', nonTextToken) ndata = ndata.replace('\\012', '\n') return ndata","{'deleted': [{'line_no': 6, 'char_start': 207, 'char_end': 273, 'line': ' query = (""SELECT data FROM %s WHERE identifier = \'%s\';"" %\n'}, {'line_no': 7, 'char_start': 273, 'char_end': 308, 'line': ' (self.table, sid)\n'}, {'line_no': 9, 'char_start': 327, 'char_end': 360, 'line': ' res = self._query(query)\n'}], 'added': [{'line_no': 6, 'char_start': 207, 'char_end': 271, 'line': ' query = (""SELECT data FROM %s WHERE identifier = $1;"" %\n'}, {'line_no': 7, 'char_start': 271, 'char_end': 301, 'line': ' (self.table)\n'}, {'line_no': 9, 'char_start': 320, 'char_end': 358, 'line': ' res = self._query(query, sid)\n'}]}","{'deleted': [{'char_start': 264, 'char_end': 268, 'chars': ""'%s'""}, {'char_start': 301, 'char_end': 306, 'chars': ', sid'}], 'added': [{'char_start': 264, 'char_end': 266, 'chars': '$1'}, {'char_start': 351, 'char_end': 356, 'chars': ', sid'}]}",github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e,cheshire3/sql/postgresStore.py,cwe-089,181 cwe-078,bin_symbols,"static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) { RBinInfo *info = r_bin_get_info (r->bin); RList *entries = r_bin_get_entries (r->bin); RBinSymbol *symbol; RBinAddr *entry; RListIter *iter; bool firstexp = true; bool printHere = false; int i = 0, lastfs = 's'; bool bin_demangle = r_config_get_i (r->config, ""bin.demangle""); if (!info) { return 0; } if (args && *args == '.') { printHere = true; } bool is_arm = info && info->arch && !strncmp (info->arch, ""arm"", 3); const char *lang = bin_demangle ? r_config_get (r->config, ""bin.lang"") : NULL; RList *symbols = r_bin_get_symbols (r->bin); r_spaces_push (&r->anal->meta_spaces, ""bin""); if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf (""[""); } else if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS); } else if (!at && exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf (""fs exports\n""); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? """" : ""[Exports]\n""); } } else if (!at && !exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf (""fs symbols\n""); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? """" : ""[Symbols]\n""); } } if (IS_MODE_NORMAL (mode)) { r_cons_printf (""Num Paddr Vaddr Bind Type Size Name\n""); } size_t count = 0; r_list_foreach (symbols, iter, symbol) { if (!symbol->name) { continue; } char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true); ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va); int len = symbol->size ? symbol->size : 32; SymName sn = {0}; if (exponly && !isAnExport (symbol)) { free (r_symbol_name); continue; } if (name && strcmp (r_symbol_name, name)) { free (r_symbol_name); continue; } if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) { free (r_symbol_name); continue; } if ((printHere && !is_in_range (r->offset, symbol->paddr, len)) && (printHere && !is_in_range (r->offset, addr, len))) { free (r_symbol_name); continue; } count ++; snInit (r, &sn, symbol, lang); if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) { /* * Skip section symbols because they will have their own flag. * Skip also file symbols because not useful for now. */ } else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) { if (is_arm) { handle_arm_special_symbol (r, symbol, va); } } else if (IS_MODE_SET (mode)) { // TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata if (is_arm) { handle_arm_symbol (r, symbol, info, va); } select_flag_space (r, symbol); /* If that's a Classed symbol (method or so) */ if (sn.classname) { RFlagItem *fi = r_flag_get (r->flags, sn.methflag); if (r->bin->prefix) { char *prname = r_str_newf (""%s.%s"", r->bin->prefix, sn.methflag); r_name_filter (sn.methflag, -1); free (sn.methflag); sn.methflag = prname; } if (fi) { r_flag_item_set_realname (fi, sn.methname); if ((fi->offset - r->flags->base) == addr) { // char *comment = fi->comment ? strdup (fi->comment) : NULL; r_flag_unset (r->flags, fi); } } else { fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size); char *comment = fi->comment ? strdup (fi->comment) : NULL; if (comment) { r_flag_item_set_comment (fi, comment); R_FREE (comment); } } } else { const char *n = sn.demname ? sn.demname : sn.name; const char *fn = sn.demflag ? sn.demflag : sn.nameflag; char *fnp = (r->bin->prefix) ? r_str_newf (""%s.%s"", r->bin->prefix, fn): strdup (fn); RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size); if (fi) { r_flag_item_set_realname (fi, n); fi->demangled = (bool)(size_t)sn.demname; } else { if (fn) { eprintf (""[Warning] Can't find flag (%s)\n"", fn); } } free (fnp); } if (sn.demname) { r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, symbol->size, sn.demname); } r_flag_space_pop (r->flags); } else if (IS_MODE_JSON (mode)) { char *str = r_str_escape_utf8_for_json (r_symbol_name, -1); // str = r_str_replace (str, ""\"""", ""\\\"""", 1); r_cons_printf (""%s{\""name\"":\""%s\"","" ""\""demname\"":\""%s\"","" ""\""flagname\"":\""%s\"","" ""\""ordinal\"":%d,"" ""\""bind\"":\""%s\"","" ""\""size\"":%d,"" ""\""type\"":\""%s\"","" ""\""vaddr\"":%""PFMT64d"","" ""\""paddr\"":%""PFMT64d""}"", ((exponly && firstexp) || printHere) ? """" : (iter->p ? "","" : """"), str, sn.demname? sn.demname: """", sn.nameflag, symbol->ordinal, symbol->bind, (int)symbol->size, symbol->type, (ut64)addr, (ut64)symbol->paddr); free (str); } else if (IS_MODE_SIMPLE (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf (""0x%08""PFMT64x"" %d %s\n"", addr, (int)symbol->size, name); } else if (IS_MODE_SIMPLEST (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf (""%s\n"", name); } else if (IS_MODE_RAD (mode)) { /* Skip special symbols because we do not flag them and * they shouldn't be printed in the rad format either */ if (is_special_symbol (symbol)) { goto next; } RBinFile *binfile; RBinPlugin *plugin; const char *name = sn.demname? sn.demname: r_symbol_name; if (!name) { goto next; } if (!strncmp (name, ""imp."", 4)) { if (lastfs != 'i') { r_cons_printf (""fs imports\n""); } lastfs = 'i'; } else { if (lastfs != 's') { const char *fs = exponly? ""exports"": ""symbols""; r_cons_printf (""fs %s\n"", fs); } lastfs = 's'; } if (r->bin->prefix || *name) { // we don't want unnamed symbol flags char *flagname = construct_symbol_flagname (""sym"", name, MAXFLAG_LEN_DEFAULT); if (!flagname) { goto next; } r_cons_printf (""\""f %s%s%s %u 0x%08"" PFMT64x ""\""\n"", r->bin->prefix ? r->bin->prefix : """", r->bin->prefix ? ""."" : """", flagname, symbol->size, addr); free (flagname); } binfile = r_bin_cur (r->bin); plugin = r_bin_file_cur_plugin (binfile); if (plugin && plugin->name) { if (r_str_startswith (plugin->name, ""pe"")) { char *module = strdup (r_symbol_name); char *p = strstr (module, "".dll_""); if (p && strstr (module, ""imp."")) { char *symname = __filterShell (p + 5); char *m = __filterShell (module); *p = 0; if (r->bin->prefix) { r_cons_printf (""k bin/pe/%s/%d=%s.%s\n"", module, symbol->ordinal, r->bin->prefix, symname); } else { r_cons_printf (""k bin/pe/%s/%d=%s\n"", module, symbol->ordinal, symname); } free (symname); free (m); } free (module); } } } else { const char *bind = symbol->bind? symbol->bind: ""NONE""; const char *type = symbol->type? symbol->type: ""NONE""; const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name); // const char *fwd = r_str_get (symbol->forwarder); r_cons_printf (""%03u"", symbol->ordinal); if (symbol->paddr == UT64_MAX) { r_cons_printf ("" ----------""); } else { r_cons_printf ("" 0x%08""PFMT64x, symbol->paddr); } r_cons_printf ("" 0x%08""PFMT64x"" %6s %6s %4d%s%s\n"", addr, bind, type, symbol->size, *name? "" "": """", name); } next: snFini (&sn); i++; free (r_symbol_name); if (exponly && firstexp) { firstexp = false; } if (printHere) { break; } } if (count == 0 && IS_MODE_JSON (mode)) { r_cons_printf (""{}""); } //handle thumb and arm for entry point since they are not present in symbols if (is_arm) { r_list_foreach (entries, iter, entry) { if (IS_MODE_SET (mode)) { handle_arm_entry (r, entry, info, va); } } } if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf (""]""); } r_spaces_pop (&r->anal->meta_spaces); return true; }","static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) { RBinInfo *info = r_bin_get_info (r->bin); RList *entries = r_bin_get_entries (r->bin); RBinSymbol *symbol; RBinAddr *entry; RListIter *iter; bool firstexp = true; bool printHere = false; int i = 0, lastfs = 's'; bool bin_demangle = r_config_get_i (r->config, ""bin.demangle""); if (!info) { return 0; } if (args && *args == '.') { printHere = true; } bool is_arm = info && info->arch && !strncmp (info->arch, ""arm"", 3); const char *lang = bin_demangle ? r_config_get (r->config, ""bin.lang"") : NULL; RList *symbols = r_bin_get_symbols (r->bin); r_spaces_push (&r->anal->meta_spaces, ""bin""); if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf (""[""); } else if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS); } else if (!at && exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf (""fs exports\n""); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? """" : ""[Exports]\n""); } } else if (!at && !exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf (""fs symbols\n""); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? """" : ""[Symbols]\n""); } } if (IS_MODE_NORMAL (mode)) { r_cons_printf (""Num Paddr Vaddr Bind Type Size Name\n""); } size_t count = 0; r_list_foreach (symbols, iter, symbol) { if (!symbol->name) { continue; } char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true); ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va); int len = symbol->size ? symbol->size : 32; SymName sn = {0}; if (exponly && !isAnExport (symbol)) { free (r_symbol_name); continue; } if (name && strcmp (r_symbol_name, name)) { free (r_symbol_name); continue; } if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) { free (r_symbol_name); continue; } if ((printHere && !is_in_range (r->offset, symbol->paddr, len)) && (printHere && !is_in_range (r->offset, addr, len))) { free (r_symbol_name); continue; } count ++; snInit (r, &sn, symbol, lang); if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) { /* * Skip section symbols because they will have their own flag. * Skip also file symbols because not useful for now. */ } else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) { if (is_arm) { handle_arm_special_symbol (r, symbol, va); } } else if (IS_MODE_SET (mode)) { // TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata if (is_arm) { handle_arm_symbol (r, symbol, info, va); } select_flag_space (r, symbol); /* If that's a Classed symbol (method or so) */ if (sn.classname) { RFlagItem *fi = r_flag_get (r->flags, sn.methflag); if (r->bin->prefix) { char *prname = r_str_newf (""%s.%s"", r->bin->prefix, sn.methflag); r_name_filter (sn.methflag, -1); free (sn.methflag); sn.methflag = prname; } if (fi) { r_flag_item_set_realname (fi, sn.methname); if ((fi->offset - r->flags->base) == addr) { // char *comment = fi->comment ? strdup (fi->comment) : NULL; r_flag_unset (r->flags, fi); } } else { fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size); char *comment = fi->comment ? strdup (fi->comment) : NULL; if (comment) { r_flag_item_set_comment (fi, comment); R_FREE (comment); } } } else { const char *n = sn.demname ? sn.demname : sn.name; const char *fn = sn.demflag ? sn.demflag : sn.nameflag; char *fnp = (r->bin->prefix) ? r_str_newf (""%s.%s"", r->bin->prefix, fn): strdup (fn); RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size); if (fi) { r_flag_item_set_realname (fi, n); fi->demangled = (bool)(size_t)sn.demname; } else { if (fn) { eprintf (""[Warning] Can't find flag (%s)\n"", fn); } } free (fnp); } if (sn.demname) { r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, symbol->size, sn.demname); } r_flag_space_pop (r->flags); } else if (IS_MODE_JSON (mode)) { char *str = r_str_escape_utf8_for_json (r_symbol_name, -1); // str = r_str_replace (str, ""\"""", ""\\\"""", 1); r_cons_printf (""%s{\""name\"":\""%s\"","" ""\""demname\"":\""%s\"","" ""\""flagname\"":\""%s\"","" ""\""ordinal\"":%d,"" ""\""bind\"":\""%s\"","" ""\""size\"":%d,"" ""\""type\"":\""%s\"","" ""\""vaddr\"":%""PFMT64d"","" ""\""paddr\"":%""PFMT64d""}"", ((exponly && firstexp) || printHere) ? """" : (iter->p ? "","" : """"), str, sn.demname? sn.demname: """", sn.nameflag, symbol->ordinal, symbol->bind, (int)symbol->size, symbol->type, (ut64)addr, (ut64)symbol->paddr); free (str); } else if (IS_MODE_SIMPLE (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf (""0x%08""PFMT64x"" %d %s\n"", addr, (int)symbol->size, name); } else if (IS_MODE_SIMPLEST (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf (""%s\n"", name); } else if (IS_MODE_RAD (mode)) { /* Skip special symbols because we do not flag them and * they shouldn't be printed in the rad format either */ if (is_special_symbol (symbol)) { goto next; } RBinFile *binfile; RBinPlugin *plugin; const char *name = sn.demname? sn.demname: r_symbol_name; if (!name) { goto next; } if (!strncmp (name, ""imp."", 4)) { if (lastfs != 'i') { r_cons_printf (""fs imports\n""); } lastfs = 'i'; } else { if (lastfs != 's') { const char *fs = exponly? ""exports"": ""symbols""; r_cons_printf (""fs %s\n"", fs); } lastfs = 's'; } if (r->bin->prefix || *name) { // we don't want unnamed symbol flags char *flagname = construct_symbol_flagname (""sym"", name, MAXFLAG_LEN_DEFAULT); if (!flagname) { goto next; } r_cons_printf (""\""f %s%s%s %u 0x%08"" PFMT64x ""\""\n"", r->bin->prefix ? r->bin->prefix : """", r->bin->prefix ? ""."" : """", flagname, symbol->size, addr); free (flagname); } binfile = r_bin_cur (r->bin); plugin = r_bin_file_cur_plugin (binfile); if (plugin && plugin->name) { if (r_str_startswith (plugin->name, ""pe"")) { char *module = strdup (r_symbol_name); char *p = strstr (module, "".dll_""); if (p && strstr (module, ""imp."")) { char *symname = __filterShell (p + 5); char *m = __filterShell (module); *p = 0; if (r->bin->prefix) { r_cons_printf (""\""k bin/pe/%s/%d=%s.%s\""\n"", module, symbol->ordinal, r->bin->prefix, symname); } else { r_cons_printf (""\""k bin/pe/%s/%d=%s\""\n"", module, symbol->ordinal, symname); } free (symname); free (m); } free (module); } } } else { const char *bind = symbol->bind? symbol->bind: ""NONE""; const char *type = symbol->type? symbol->type: ""NONE""; const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name); // const char *fwd = r_str_get (symbol->forwarder); r_cons_printf (""%03u"", symbol->ordinal); if (symbol->paddr == UT64_MAX) { r_cons_printf ("" ----------""); } else { r_cons_printf ("" 0x%08""PFMT64x, symbol->paddr); } r_cons_printf ("" 0x%08""PFMT64x"" %6s %6s %4d%s%s\n"", addr, bind, type, symbol->size, *name? "" "": """", name); } next: snFini (&sn); i++; free (r_symbol_name); if (exponly && firstexp) { firstexp = false; } if (printHere) { break; } } if (count == 0 && IS_MODE_JSON (mode)) { r_cons_printf (""{}""); } //handle thumb and arm for entry point since they are not present in symbols if (is_arm) { r_list_foreach (entries, iter, entry) { if (IS_MODE_SET (mode)) { handle_arm_entry (r, entry, info, va); } } } if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf (""]""); } r_spaces_pop (&r->anal->meta_spaces); return true; }","{'deleted': [{'line_no': 211, 'char_start': 6599, 'char_end': 6647, 'line': '\t\t\t\t\t\t\tr_cons_printf (""k bin/pe/%s/%d=%s.%s\\n"",\n'}, {'line_no': 214, 'char_start': 6721, 'char_end': 6766, 'line': '\t\t\t\t\t\t\tr_cons_printf (""k bin/pe/%s/%d=%s\\n"",\n'}], 'added': [{'line_no': 211, 'char_start': 6599, 'char_end': 6651, 'line': '\t\t\t\t\t\t\tr_cons_printf (""\\""k bin/pe/%s/%d=%s.%s\\""\\n"",\n'}, {'line_no': 214, 'char_start': 6725, 'char_end': 6774, 'line': '\t\t\t\t\t\t\tr_cons_printf (""\\""k bin/pe/%s/%d=%s\\""\\n"",\n'}]}","{'deleted': [], 'added': [{'char_start': 6622, 'char_end': 6624, 'chars': '\\""'}, {'char_start': 6644, 'char_end': 6646, 'chars': '\\""'}, {'char_start': 6748, 'char_end': 6750, 'chars': '\\""'}, {'char_start': 6767, 'char_end': 6769, 'chars': '\\""'}]}",github.com/radareorg/radare2/commit/5411543a310a470b1257fb93273cdd6e8dfcb3af,libr/core/cbin.c,cwe-078,2669 cwe-476,lexer_process_char_literal,"lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */","lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } if (length == 0) { has_escape = false; } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */","{'deleted': [], 'added': [{'line_no': 41, 'char_start': 1556, 'char_end': 1575, 'line': ' if (length == 0)\n'}, {'line_no': 42, 'char_start': 1575, 'char_end': 1579, 'line': ' {\n'}, {'line_no': 43, 'char_start': 1579, 'char_end': 1603, 'line': ' has_escape = false;\n'}, {'line_no': 44, 'char_start': 1603, 'char_end': 1607, 'line': ' }\n'}, {'line_no': 45, 'char_start': 1607, 'char_end': 1608, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1558, 'char_end': 1610, 'chars': 'if (length == 0)\n {\n has_escape = false;\n }\n\n '}]}",github.com/jerryscript-project/jerryscript/commit/e58f2880df608652aff7fd35c45b242467ec0e79,jerry-core/parser/js/js-lexer.c,cwe-476,532 cwe-079,gravatar,"@register.tag @basictag(takes_context=True) def gravatar(context, user, size=None): """""" Outputs the HTML for displaying a user's gravatar. This can take an optional size of the image (defaults to 80 if not specified). This is also influenced by the following settings: GRAVATAR_SIZE - Default size for gravatars GRAVATAR_RATING - Maximum allowed rating (g, pg, r, x) GRAVATAR_DEFAULT - Default image set to show if the user hasn't specified a gravatar (identicon, monsterid, wavatar) See http://www.gravatar.com/ for more information. """""" url = get_gravatar_url(context['request'], user, size) if url: return ('' % (url, size, size, user.get_full_name() or user.username)) else: return ''","@register.tag @basictag(takes_context=True) def gravatar(context, user, size=None): """""" Outputs the HTML for displaying a user's gravatar. This can take an optional size of the image (defaults to 80 if not specified). This is also influenced by the following settings: GRAVATAR_SIZE - Default size for gravatars GRAVATAR_RATING - Maximum allowed rating (g, pg, r, x) GRAVATAR_DEFAULT - Default image set to show if the user hasn't specified a gravatar (identicon, monsterid, wavatar) See http://www.gravatar.com/ for more information. """""" url = get_gravatar_url(context['request'], user, size) if url: return format_html( '', url, size, user.get_full_name() or user.username) else: return ''","{'deleted': [{'line_no': 22, 'char_start': 698, 'char_end': 763, 'line': ' return (\'\' %\n'}, {'line_no': 24, 'char_start': 807, 'char_end': 881, 'line': ' (url, size, size, user.get_full_name() or user.username))\n'}], 'added': [{'line_no': 22, 'char_start': 698, 'char_end': 726, 'line': ' return format_html(\n'}, {'line_no': 23, 'char_start': 726, 'char_end': 791, 'line': ' \'\',\n'}, {'line_no': 25, 'char_start': 825, 'char_end': 887, 'line': ' url, size, user.get_full_name() or user.username)\n'}]}","{'deleted': [{'char_start': 725, 'char_end': 727, 'chars': '%s'}, {'char_start': 736, 'char_end': 738, 'chars': '%s'}, {'char_start': 748, 'char_end': 750, 'chars': '%s'}, {'char_start': 757, 'char_end': 759, 'chars': '%s'}, {'char_start': 775, 'char_end': 779, 'chars': ' '}, {'char_start': 780, 'char_end': 785, 'chars': ' '}, {'char_start': 804, 'char_end': 806, 'chars': ' %'}, {'char_start': 807, 'char_end': 811, 'chars': ' '}, {'char_start': 823, 'char_end': 824, 'chars': '('}, {'char_start': 827, 'char_end': 833, 'chars': ', size'}, {'char_start': 878, 'char_end': 879, 'chars': ')'}], 'added': [{'char_start': 713, 'char_end': 724, 'chars': 'format_html'}, {'char_start': 725, 'char_end': 738, 'chars': '\n '}, {'char_start': 749, 'char_end': 752, 'chars': '{0}'}, {'char_start': 761, 'char_end': 764, 'chars': '{1}'}, {'char_start': 774, 'char_end': 777, 'chars': '{1}'}, {'char_start': 784, 'char_end': 787, 'chars': '{2}'}, {'char_start': 823, 'char_end': 824, 'chars': ','}]}",github.com/djblets/djblets/commit/77ac64642ad530bf69e390c51fc6fdcb8914c8e7,djblets/gravatars/templatetags/gravatars.py,cwe-079,222 cwe-190,__get_data_block,"static int __get_data_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create, int flag, pgoff_t *next_pgofs) { struct f2fs_map_blocks map; int err; map.m_lblk = iblock; map.m_len = bh->b_size >> inode->i_blkbits; map.m_next_pgofs = next_pgofs; err = f2fs_map_blocks(inode, &map, create, flag); if (!err) { map_bh(bh, inode->i_sb, map.m_pblk); bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags; bh->b_size = map.m_len << inode->i_blkbits; } return err; }","static int __get_data_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create, int flag, pgoff_t *next_pgofs) { struct f2fs_map_blocks map; int err; map.m_lblk = iblock; map.m_len = bh->b_size >> inode->i_blkbits; map.m_next_pgofs = next_pgofs; err = f2fs_map_blocks(inode, &map, create, flag); if (!err) { map_bh(bh, inode->i_sb, map.m_pblk); bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags; bh->b_size = (u64)map.m_len << inode->i_blkbits; } return err; }","{'deleted': [{'line_no': 16, 'char_start': 447, 'char_end': 493, 'line': '\t\tbh->b_size = map.m_len << inode->i_blkbits;\n'}], 'added': [{'line_no': 16, 'char_start': 447, 'char_end': 498, 'line': '\t\tbh->b_size = (u64)map.m_len << inode->i_blkbits;\n'}]}","{'deleted': [], 'added': [{'char_start': 462, 'char_end': 467, 'chars': '(u64)'}]}",github.com/torvalds/linux/commit/b86e33075ed1909d8002745b56ecf73b833db143,fs/f2fs/data.c,cwe-190,169 cwe-416,snd_seq_device_dev_free,"static int snd_seq_device_dev_free(struct snd_device *device) { struct snd_seq_device *dev = device->device_data; put_device(&dev->dev); return 0; }","static int snd_seq_device_dev_free(struct snd_device *device) { struct snd_seq_device *dev = device->device_data; cancel_autoload_drivers(); put_device(&dev->dev); return 0; }","{'deleted': [], 'added': [{'line_no': 5, 'char_start': 116, 'char_end': 144, 'line': '\tcancel_autoload_drivers();\n'}]}","{'deleted': [], 'added': [{'char_start': 117, 'char_end': 145, 'chars': 'cancel_autoload_drivers();\n\t'}]}",github.com/torvalds/linux/commit/fc27fe7e8deef2f37cba3f2be2d52b6ca5eb9d57,sound/core/seq_device.c,cwe-416,38 cwe-476,x86_decode_insn,"int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len) { int rc = X86EMUL_CONTINUE; int mode = ctxt->mode; int def_op_bytes, def_ad_bytes, goffset, simd_prefix; bool op_prefix = false; bool has_seg_override = false; struct opcode opcode; ctxt->memop.type = OP_NONE; ctxt->memopp = NULL; ctxt->_eip = ctxt->eip; ctxt->fetch.ptr = ctxt->fetch.data; ctxt->fetch.end = ctxt->fetch.data + insn_len; ctxt->opcode_len = 1; if (insn_len > 0) memcpy(ctxt->fetch.data, insn, insn_len); else { rc = __do_insn_fetch_bytes(ctxt, 1); if (rc != X86EMUL_CONTINUE) return rc; } switch (mode) { case X86EMUL_MODE_REAL: case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: def_op_bytes = def_ad_bytes = 2; break; case X86EMUL_MODE_PROT32: def_op_bytes = def_ad_bytes = 4; break; #ifdef CONFIG_X86_64 case X86EMUL_MODE_PROT64: def_op_bytes = 4; def_ad_bytes = 8; break; #endif default: return EMULATION_FAILED; } ctxt->op_bytes = def_op_bytes; ctxt->ad_bytes = def_ad_bytes; /* Legacy prefixes. */ for (;;) { switch (ctxt->b = insn_fetch(u8, ctxt)) { case 0x66: /* operand-size override */ op_prefix = true; /* switch between 2/4 bytes */ ctxt->op_bytes = def_op_bytes ^ 6; break; case 0x67: /* address-size override */ if (mode == X86EMUL_MODE_PROT64) /* switch between 4/8 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 12; else /* switch between 2/4 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 6; break; case 0x26: /* ES override */ case 0x2e: /* CS override */ case 0x36: /* SS override */ case 0x3e: /* DS override */ has_seg_override = true; ctxt->seg_override = (ctxt->b >> 3) & 3; break; case 0x64: /* FS override */ case 0x65: /* GS override */ has_seg_override = true; ctxt->seg_override = ctxt->b & 7; break; case 0x40 ... 0x4f: /* REX */ if (mode != X86EMUL_MODE_PROT64) goto done_prefixes; ctxt->rex_prefix = ctxt->b; continue; case 0xf0: /* LOCK */ ctxt->lock_prefix = 1; break; case 0xf2: /* REPNE/REPNZ */ case 0xf3: /* REP/REPE/REPZ */ ctxt->rep_prefix = ctxt->b; break; default: goto done_prefixes; } /* Any legacy prefix after a REX prefix nullifies its effect. */ ctxt->rex_prefix = 0; } done_prefixes: /* REX prefix. */ if (ctxt->rex_prefix & 8) ctxt->op_bytes = 8; /* REX.W */ /* Opcode byte(s). */ opcode = opcode_table[ctxt->b]; /* Two-byte opcode? */ if (ctxt->b == 0x0f) { ctxt->opcode_len = 2; ctxt->b = insn_fetch(u8, ctxt); opcode = twobyte_table[ctxt->b]; /* 0F_38 opcode map */ if (ctxt->b == 0x38) { ctxt->opcode_len = 3; ctxt->b = insn_fetch(u8, ctxt); opcode = opcode_map_0f_38[ctxt->b]; } } ctxt->d = opcode.flags; if (ctxt->d & ModRM) ctxt->modrm = insn_fetch(u8, ctxt); /* vex-prefix instructions are not implemented */ if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) && (mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) { ctxt->d = NotImpl; } while (ctxt->d & GroupMask) { switch (ctxt->d & GroupMask) { case Group: goffset = (ctxt->modrm >> 3) & 7; opcode = opcode.u.group[goffset]; break; case GroupDual: goffset = (ctxt->modrm >> 3) & 7; if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.gdual->mod3[goffset]; else opcode = opcode.u.gdual->mod012[goffset]; break; case RMExt: goffset = ctxt->modrm & 7; opcode = opcode.u.group[goffset]; break; case Prefix: if (ctxt->rep_prefix && op_prefix) return EMULATION_FAILED; simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix; switch (simd_prefix) { case 0x00: opcode = opcode.u.gprefix->pfx_no; break; case 0x66: opcode = opcode.u.gprefix->pfx_66; break; case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break; case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break; } break; case Escape: if (ctxt->modrm > 0xbf) opcode = opcode.u.esc->high[ctxt->modrm - 0xc0]; else opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7]; break; case InstrDual: if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.idual->mod3; else opcode = opcode.u.idual->mod012; break; case ModeDual: if (ctxt->mode == X86EMUL_MODE_PROT64) opcode = opcode.u.mdual->mode64; else opcode = opcode.u.mdual->mode32; break; default: return EMULATION_FAILED; } ctxt->d &= ~(u64)GroupMask; ctxt->d |= opcode.flags; } /* Unrecognised? */ if (ctxt->d == 0) return EMULATION_FAILED; ctxt->execute = opcode.u.execute; if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD))) return EMULATION_FAILED; if (unlikely(ctxt->d & (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch| No16))) { /* * These are copied unconditionally here, and checked unconditionally * in x86_emulate_insn. */ ctxt->check_perm = opcode.check_perm; ctxt->intercept = opcode.intercept; if (ctxt->d & NotImpl) return EMULATION_FAILED; if (mode == X86EMUL_MODE_PROT64) { if (ctxt->op_bytes == 4 && (ctxt->d & Stack)) ctxt->op_bytes = 8; else if (ctxt->d & NearBranch) ctxt->op_bytes = 8; } if (ctxt->d & Op3264) { if (mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; else ctxt->op_bytes = 4; } if ((ctxt->d & No16) && ctxt->op_bytes == 2) ctxt->op_bytes = 4; if (ctxt->d & Sse) ctxt->op_bytes = 16; else if (ctxt->d & Mmx) ctxt->op_bytes = 8; } /* ModRM and SIB bytes. */ if (ctxt->d & ModRM) { rc = decode_modrm(ctxt, &ctxt->memop); if (!has_seg_override) { has_seg_override = true; ctxt->seg_override = ctxt->modrm_seg; } } else if (ctxt->d & MemAbs) rc = decode_abs(ctxt, &ctxt->memop); if (rc != X86EMUL_CONTINUE) goto done; if (!has_seg_override) ctxt->seg_override = VCPU_SREG_DS; ctxt->memop.addr.mem.seg = ctxt->seg_override; /* * Decode and fetch the source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* * Decode and fetch the second source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* Decode and fetch the destination operand: register or memory. */ rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask); if (ctxt->rip_relative) ctxt->memopp->addr.mem.ea = address_mask(ctxt, ctxt->memopp->addr.mem.ea + ctxt->_eip); done: return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK; }","int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len) { int rc = X86EMUL_CONTINUE; int mode = ctxt->mode; int def_op_bytes, def_ad_bytes, goffset, simd_prefix; bool op_prefix = false; bool has_seg_override = false; struct opcode opcode; ctxt->memop.type = OP_NONE; ctxt->memopp = NULL; ctxt->_eip = ctxt->eip; ctxt->fetch.ptr = ctxt->fetch.data; ctxt->fetch.end = ctxt->fetch.data + insn_len; ctxt->opcode_len = 1; if (insn_len > 0) memcpy(ctxt->fetch.data, insn, insn_len); else { rc = __do_insn_fetch_bytes(ctxt, 1); if (rc != X86EMUL_CONTINUE) return rc; } switch (mode) { case X86EMUL_MODE_REAL: case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: def_op_bytes = def_ad_bytes = 2; break; case X86EMUL_MODE_PROT32: def_op_bytes = def_ad_bytes = 4; break; #ifdef CONFIG_X86_64 case X86EMUL_MODE_PROT64: def_op_bytes = 4; def_ad_bytes = 8; break; #endif default: return EMULATION_FAILED; } ctxt->op_bytes = def_op_bytes; ctxt->ad_bytes = def_ad_bytes; /* Legacy prefixes. */ for (;;) { switch (ctxt->b = insn_fetch(u8, ctxt)) { case 0x66: /* operand-size override */ op_prefix = true; /* switch between 2/4 bytes */ ctxt->op_bytes = def_op_bytes ^ 6; break; case 0x67: /* address-size override */ if (mode == X86EMUL_MODE_PROT64) /* switch between 4/8 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 12; else /* switch between 2/4 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 6; break; case 0x26: /* ES override */ case 0x2e: /* CS override */ case 0x36: /* SS override */ case 0x3e: /* DS override */ has_seg_override = true; ctxt->seg_override = (ctxt->b >> 3) & 3; break; case 0x64: /* FS override */ case 0x65: /* GS override */ has_seg_override = true; ctxt->seg_override = ctxt->b & 7; break; case 0x40 ... 0x4f: /* REX */ if (mode != X86EMUL_MODE_PROT64) goto done_prefixes; ctxt->rex_prefix = ctxt->b; continue; case 0xf0: /* LOCK */ ctxt->lock_prefix = 1; break; case 0xf2: /* REPNE/REPNZ */ case 0xf3: /* REP/REPE/REPZ */ ctxt->rep_prefix = ctxt->b; break; default: goto done_prefixes; } /* Any legacy prefix after a REX prefix nullifies its effect. */ ctxt->rex_prefix = 0; } done_prefixes: /* REX prefix. */ if (ctxt->rex_prefix & 8) ctxt->op_bytes = 8; /* REX.W */ /* Opcode byte(s). */ opcode = opcode_table[ctxt->b]; /* Two-byte opcode? */ if (ctxt->b == 0x0f) { ctxt->opcode_len = 2; ctxt->b = insn_fetch(u8, ctxt); opcode = twobyte_table[ctxt->b]; /* 0F_38 opcode map */ if (ctxt->b == 0x38) { ctxt->opcode_len = 3; ctxt->b = insn_fetch(u8, ctxt); opcode = opcode_map_0f_38[ctxt->b]; } } ctxt->d = opcode.flags; if (ctxt->d & ModRM) ctxt->modrm = insn_fetch(u8, ctxt); /* vex-prefix instructions are not implemented */ if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) && (mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) { ctxt->d = NotImpl; } while (ctxt->d & GroupMask) { switch (ctxt->d & GroupMask) { case Group: goffset = (ctxt->modrm >> 3) & 7; opcode = opcode.u.group[goffset]; break; case GroupDual: goffset = (ctxt->modrm >> 3) & 7; if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.gdual->mod3[goffset]; else opcode = opcode.u.gdual->mod012[goffset]; break; case RMExt: goffset = ctxt->modrm & 7; opcode = opcode.u.group[goffset]; break; case Prefix: if (ctxt->rep_prefix && op_prefix) return EMULATION_FAILED; simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix; switch (simd_prefix) { case 0x00: opcode = opcode.u.gprefix->pfx_no; break; case 0x66: opcode = opcode.u.gprefix->pfx_66; break; case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break; case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break; } break; case Escape: if (ctxt->modrm > 0xbf) opcode = opcode.u.esc->high[ctxt->modrm - 0xc0]; else opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7]; break; case InstrDual: if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.idual->mod3; else opcode = opcode.u.idual->mod012; break; case ModeDual: if (ctxt->mode == X86EMUL_MODE_PROT64) opcode = opcode.u.mdual->mode64; else opcode = opcode.u.mdual->mode32; break; default: return EMULATION_FAILED; } ctxt->d &= ~(u64)GroupMask; ctxt->d |= opcode.flags; } /* Unrecognised? */ if (ctxt->d == 0) return EMULATION_FAILED; ctxt->execute = opcode.u.execute; if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD))) return EMULATION_FAILED; if (unlikely(ctxt->d & (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch| No16))) { /* * These are copied unconditionally here, and checked unconditionally * in x86_emulate_insn. */ ctxt->check_perm = opcode.check_perm; ctxt->intercept = opcode.intercept; if (ctxt->d & NotImpl) return EMULATION_FAILED; if (mode == X86EMUL_MODE_PROT64) { if (ctxt->op_bytes == 4 && (ctxt->d & Stack)) ctxt->op_bytes = 8; else if (ctxt->d & NearBranch) ctxt->op_bytes = 8; } if (ctxt->d & Op3264) { if (mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; else ctxt->op_bytes = 4; } if ((ctxt->d & No16) && ctxt->op_bytes == 2) ctxt->op_bytes = 4; if (ctxt->d & Sse) ctxt->op_bytes = 16; else if (ctxt->d & Mmx) ctxt->op_bytes = 8; } /* ModRM and SIB bytes. */ if (ctxt->d & ModRM) { rc = decode_modrm(ctxt, &ctxt->memop); if (!has_seg_override) { has_seg_override = true; ctxt->seg_override = ctxt->modrm_seg; } } else if (ctxt->d & MemAbs) rc = decode_abs(ctxt, &ctxt->memop); if (rc != X86EMUL_CONTINUE) goto done; if (!has_seg_override) ctxt->seg_override = VCPU_SREG_DS; ctxt->memop.addr.mem.seg = ctxt->seg_override; /* * Decode and fetch the source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* * Decode and fetch the second source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* Decode and fetch the destination operand: register or memory. */ rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask); if (ctxt->rip_relative && likely(ctxt->memopp)) ctxt->memopp->addr.mem.ea = address_mask(ctxt, ctxt->memopp->addr.mem.ea + ctxt->_eip); done: return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK; }","{'deleted': [{'line_no': 262, 'char_start': 6416, 'char_end': 6441, 'line': '\tif (ctxt->rip_relative)\n'}], 'added': [{'line_no': 262, 'char_start': 6416, 'char_end': 6465, 'line': '\tif (ctxt->rip_relative && likely(ctxt->memopp))\n'}]}","{'deleted': [], 'added': [{'char_start': 6439, 'char_end': 6463, 'chars': ' && likely(ctxt->memopp)'}]}",github.com/torvalds/linux/commit/d9092f52d7e61dd1557f2db2400ddb430e85937e,arch/x86/kvm/emulate.c,cwe-476,2337 cwe-125,ReadRLEImage,"static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, one, offset, pixel_info_length; ssize_t count, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,""\122\314"",2) != 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 64) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,""comment"",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes)) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixel_info_length=image->columns*image->rows*MagickMax(number_planes,4); pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,""UnableToReadImageData""); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,""UnableToReadImageData""); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,""UnableToReadImageData""); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,""\122\314"",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,""\122\314"",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, offset, pixel_info_length; ssize_t count, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,""\122\314"",2) != 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 64) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,""comment"",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixel_info_length=image->columns*image->rows*number_planes_filled; pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,""UnableToReadImageData""); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,""UnableToReadImageData""); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,""UnableToReadImageData""); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,""\122\314"",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,""\122\314"",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","{'deleted': [{'line_no': 185, 'char_start': 4971, 'char_end': 5052, 'line': ' if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes))\n'}, {'line_no': 187, 'char_start': 5125, 'char_end': 5202, 'line': ' pixel_info_length=image->columns*image->rows*MagickMax(number_planes,4);\n'}], 'added': [{'line_no': 50, 'char_start': 643, 'char_end': 669, 'line': ' number_planes_filled,\n'}, {'line_no': 186, 'char_start': 4997, 'char_end': 5065, 'line': ' number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n'}, {'line_no': 187, 'char_start': 5065, 'char_end': 5088, 'line': ' number_planes+1;\n'}, {'line_no': 188, 'char_start': 5088, 'char_end': 5161, 'line': ' if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*\n'}, {'line_no': 189, 'char_start': 5161, 'char_end': 5193, 'line': ' number_planes_filled))\n'}, {'line_no': 191, 'char_start': 5266, 'char_end': 5337, 'line': ' pixel_info_length=image->columns*image->rows*number_planes_filled;\n'}]}","{'deleted': [{'char_start': 5174, 'char_end': 5184, 'chars': 'MagickMax('}, {'char_start': 5197, 'char_end': 5200, 'chars': ',4)'}], 'added': [{'char_start': 647, 'char_end': 673, 'chars': 'number_planes_filled,\n '}, {'char_start': 5001, 'char_end': 5092, 'chars': 'number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n number_planes+1;\n '}, {'char_start': 5124, 'char_end': 5131, 'chars': '_filled'}, {'char_start': 5160, 'char_end': 5170, 'chars': '\n '}, {'char_start': 5183, 'char_end': 5190, 'chars': '_filled'}, {'char_start': 5328, 'char_end': 5335, 'chars': '_filled'}]}",github.com/ImageMagick/ImageMagick/commit/2ad6d33493750a28a5a655d319a8e0b16c392de1,coders/rle.c,cwe-125,4175 cwe-078,_run_ssh," def _run_ssh(self, command, check_exit=True, attempts=1): if not self.sshpool: self.sshpool = utils.SSHPool(self.config.san_ip, self.config.san_ssh_port, self.config.ssh_conn_timeout, self.config.san_login, password=self.config.san_password, privatekey= self.config.san_private_key, min_size= self.config.ssh_min_pool_conn, max_size= self.config.ssh_max_pool_conn) try: total_attempts = attempts with self.sshpool.item() as ssh: while attempts > 0: attempts -= 1 try: return self._ssh_execute(ssh, command, check_exit_code=check_exit) except Exception as e: LOG.error(e) greenthread.sleep(randint(20, 500) / 100.0) msg = (_(""SSH Command failed after '%(total_attempts)r' "" ""attempts : '%(command)s'"") % {'total_attempts': total_attempts, 'command': command}) raise paramiko.SSHException(msg) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_(""Error running ssh command: %s"") % command)"," def _run_ssh(self, cmd_list, check_exit=True, attempts=1): utils.check_ssh_injection(cmd_list) command = ' '. join(cmd_list) if not self.sshpool: self.sshpool = utils.SSHPool(self.config.san_ip, self.config.san_ssh_port, self.config.ssh_conn_timeout, self.config.san_login, password=self.config.san_password, privatekey= self.config.san_private_key, min_size= self.config.ssh_min_pool_conn, max_size= self.config.ssh_max_pool_conn) try: total_attempts = attempts with self.sshpool.item() as ssh: while attempts > 0: attempts -= 1 try: return self._ssh_execute(ssh, command, check_exit_code=check_exit) except Exception as e: LOG.error(e) greenthread.sleep(randint(20, 500) / 100.0) msg = (_(""SSH Command failed after '%(total_attempts)r' "" ""attempts : '%(command)s'"") % {'total_attempts': total_attempts, 'command': command}) raise paramiko.SSHException(msg) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_(""Error running ssh command: %s"") % command)","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 62, 'line': ' def _run_ssh(self, command, check_exit=True, attempts=1):\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 63, 'line': ' def _run_ssh(self, cmd_list, check_exit=True, attempts=1):\n'}, {'line_no': 2, 'char_start': 63, 'char_end': 107, 'line': ' utils.check_ssh_injection(cmd_list)\n'}, {'line_no': 3, 'char_start': 107, 'char_end': 145, 'line': "" command = ' '. join(cmd_list)\n""}, {'line_no': 4, 'char_start': 145, 'char_end': 146, 'line': '\n'}]}","{'deleted': [{'char_start': 24, 'char_end': 25, 'chars': 'o'}, {'char_start': 26, 'char_end': 29, 'chars': 'man'}], 'added': [{'char_start': 26, 'char_end': 31, 'chars': '_list'}, {'char_start': 62, 'char_end': 145, 'chars': ""\n utils.check_ssh_injection(cmd_list)\n command = ' '. join(cmd_list)\n""}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,281 cwe-125,ares_parse_a_reply,"int ares_parse_a_reply(const unsigned char *abuf, int alen, struct hostent **host) { unsigned int qdcount, ancount; int status, i, rr_type, rr_class, rr_len, naddrs; long int len; int naliases; const unsigned char *aptr; char *hostname, *rr_name, *rr_data, **aliases; struct in_addr *addrs; struct hostent *hostent; /* Set *host to NULL for all failure cases. */ *host = NULL; /* Give up if abuf doesn't have room for a header. */ if (alen < HFIXEDSZ) return ARES_EBADRESP; /* Fetch the question and answer count from the header. */ qdcount = DNS_HEADER_QDCOUNT(abuf); ancount = DNS_HEADER_ANCOUNT(abuf); if (qdcount != 1) return ARES_EBADRESP; /* Expand the name from the question, and skip past the question. */ aptr = abuf + HFIXEDSZ; status = ares_expand_name(aptr, abuf, alen, &hostname, &len); if (status != ARES_SUCCESS) return status; if (aptr + len + QFIXEDSZ > abuf + alen) { free(hostname); return ARES_EBADRESP; } aptr += len + QFIXEDSZ; /* Allocate addresses and aliases; ancount gives an upper bound for both. */ addrs = malloc(ancount * sizeof(struct in_addr)); if (!addrs) { free(hostname); return ARES_ENOMEM; } aliases = malloc((ancount + 1) * sizeof(char *)); if (!aliases) { free(hostname); free(addrs); return ARES_ENOMEM; } naddrs = 0; naliases = 0; /* Examine each answer resource record (RR) in turn. */ for (i = 0; i < (int)ancount; i++) { /* Decode the RR up to the data field. */ status = ares_expand_name(aptr, abuf, alen, &rr_name, &len); if (status != ARES_SUCCESS) break; aptr += len; if (aptr + RRFIXEDSZ > abuf + alen) { free(rr_name); status = ARES_EBADRESP; break; } rr_type = DNS_RR_TYPE(aptr); rr_class = DNS_RR_CLASS(aptr); rr_len = DNS_RR_LEN(aptr); aptr += RRFIXEDSZ; if (rr_class == C_IN && rr_type == T_A && rr_len == sizeof(struct in_addr) && strcasecmp(rr_name, hostname) == 0) { memcpy(&addrs[naddrs], aptr, sizeof(struct in_addr)); naddrs++; status = ARES_SUCCESS; } if (rr_class == C_IN && rr_type == T_CNAME) { /* Record the RR name as an alias. */ aliases[naliases] = rr_name; naliases++; /* Decode the RR data and replace the hostname with it. */ status = ares_expand_name(aptr, abuf, alen, &rr_data, &len); if (status != ARES_SUCCESS) break; free(hostname); hostname = rr_data; } else free(rr_name); aptr += rr_len; if (aptr > abuf + alen) { status = ARES_EBADRESP; break; } } if (status == ARES_SUCCESS && naddrs == 0) status = ARES_ENODATA; if (status == ARES_SUCCESS) { /* We got our answer. Allocate memory to build the host entry. */ aliases[naliases] = NULL; hostent = malloc(sizeof(struct hostent)); if (hostent) { hostent->h_addr_list = malloc((naddrs + 1) * sizeof(char *)); if (hostent->h_addr_list) { /* Fill in the hostent and return successfully. */ hostent->h_name = hostname; hostent->h_aliases = aliases; hostent->h_addrtype = AF_INET; hostent->h_length = sizeof(struct in_addr); for (i = 0; i < naddrs; i++) hostent->h_addr_list[i] = (char *) &addrs[i]; hostent->h_addr_list[naddrs] = NULL; *host = hostent; return ARES_SUCCESS; } free(hostent); } status = ARES_ENOMEM; } for (i = 0; i < naliases; i++) free(aliases[i]); free(aliases); free(addrs); free(hostname); return status; }","int ares_parse_a_reply(const unsigned char *abuf, int alen, struct hostent **host) { unsigned int qdcount, ancount; int status, i, rr_type, rr_class, rr_len, naddrs; long int len; int naliases; const unsigned char *aptr; char *hostname, *rr_name, *rr_data, **aliases; struct in_addr *addrs; struct hostent *hostent; /* Set *host to NULL for all failure cases. */ *host = NULL; /* Give up if abuf doesn't have room for a header. */ if (alen < HFIXEDSZ) return ARES_EBADRESP; /* Fetch the question and answer count from the header. */ qdcount = DNS_HEADER_QDCOUNT(abuf); ancount = DNS_HEADER_ANCOUNT(abuf); if (qdcount != 1) return ARES_EBADRESP; /* Expand the name from the question, and skip past the question. */ aptr = abuf + HFIXEDSZ; status = ares_expand_name(aptr, abuf, alen, &hostname, &len); if (status != ARES_SUCCESS) return status; if (aptr + len + QFIXEDSZ > abuf + alen) { free(hostname); return ARES_EBADRESP; } aptr += len + QFIXEDSZ; /* Allocate addresses and aliases; ancount gives an upper bound for both. */ addrs = malloc(ancount * sizeof(struct in_addr)); if (!addrs) { free(hostname); return ARES_ENOMEM; } aliases = malloc((ancount + 1) * sizeof(char *)); if (!aliases) { free(hostname); free(addrs); return ARES_ENOMEM; } naddrs = 0; naliases = 0; /* Examine each answer resource record (RR) in turn. */ for (i = 0; i < (int)ancount; i++) { /* Decode the RR up to the data field. */ status = ares_expand_name(aptr, abuf, alen, &rr_name, &len); if (status != ARES_SUCCESS) break; aptr += len; if (aptr + RRFIXEDSZ > abuf + alen) { free(rr_name); status = ARES_EBADRESP; break; } rr_type = DNS_RR_TYPE(aptr); rr_class = DNS_RR_CLASS(aptr); rr_len = DNS_RR_LEN(aptr); aptr += RRFIXEDSZ; if (aptr + rr_len > abuf + alen) { free(rr_name); status = ARES_EBADRESP; break; } if (rr_class == C_IN && rr_type == T_A && rr_len == sizeof(struct in_addr) && strcasecmp(rr_name, hostname) == 0) { memcpy(&addrs[naddrs], aptr, sizeof(struct in_addr)); naddrs++; status = ARES_SUCCESS; } if (rr_class == C_IN && rr_type == T_CNAME) { /* Record the RR name as an alias. */ aliases[naliases] = rr_name; naliases++; /* Decode the RR data and replace the hostname with it. */ status = ares_expand_name(aptr, abuf, alen, &rr_data, &len); if (status != ARES_SUCCESS) break; free(hostname); hostname = rr_data; } else free(rr_name); aptr += rr_len; if (aptr > abuf + alen) { status = ARES_EBADRESP; break; } } if (status == ARES_SUCCESS && naddrs == 0) status = ARES_ENODATA; if (status == ARES_SUCCESS) { /* We got our answer. Allocate memory to build the host entry. */ aliases[naliases] = NULL; hostent = malloc(sizeof(struct hostent)); if (hostent) { hostent->h_addr_list = malloc((naddrs + 1) * sizeof(char *)); if (hostent->h_addr_list) { /* Fill in the hostent and return successfully. */ hostent->h_name = hostname; hostent->h_aliases = aliases; hostent->h_addrtype = AF_INET; hostent->h_length = sizeof(struct in_addr); for (i = 0; i < naddrs; i++) hostent->h_addr_list[i] = (char *) &addrs[i]; hostent->h_addr_list[naddrs] = NULL; *host = hostent; return ARES_SUCCESS; } free(hostent); } status = ARES_ENOMEM; } for (i = 0; i < naliases; i++) free(aliases[i]); free(aliases); free(addrs); free(hostname); return status; }","{'deleted': [], 'added': [{'line_no': 73, 'char_start': 1933, 'char_end': 1972, 'line': ' if (aptr + rr_len > abuf + alen)\n'}, {'line_no': 74, 'char_start': 1972, 'char_end': 1975, 'line': '\t{\n'}, {'line_no': 75, 'char_start': 1975, 'char_end': 1993, 'line': '\t free(rr_name);\n'}, {'line_no': 76, 'char_start': 1993, 'char_end': 2020, 'line': '\t status = ARES_EBADRESP;\n'}, {'line_no': 77, 'char_start': 2020, 'char_end': 2030, 'line': '\t break;\n'}, {'line_no': 78, 'char_start': 2030, 'char_end': 2033, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 1933, 'char_end': 2033, 'chars': ' if (aptr + rr_len > abuf + alen)\n\t{\n\t free(rr_name);\n\t status = ARES_EBADRESP;\n\t break;\n\t}\n'}]}",github.com/resiprocate/resiprocate/commit/d67a9ca6fd06ca65d23e313bdbad1ef4dd3aa0df,rutil/dns/ares/ares_parse_a_reply.c,cwe-125,1099 cwe-079,get," @auth.public def get(self, build_id): try: build_id = int(build_id) except ValueError as ex: self.response.write(ex.message) self.abort(400) build = model.Build.get_by_id(build_id) can_view = build and user.can_view_build_async(build).get_result() if not can_view: if auth.get_current_identity().is_anonymous: return self.redirect(gae_users.create_login_url(self.request.url)) self.response.write('build %d not found' % build_id) self.abort(404) return self.redirect(str(build.url))"," @auth.public def get(self, build_id): try: build_id = int(build_id) except ValueError: self.response.write('invalid build id') self.abort(400) build = model.Build.get_by_id(build_id) can_view = build and user.can_view_build_async(build).get_result() if not can_view: if auth.get_current_identity().is_anonymous: return self.redirect(self.create_login_url(self.request.url)) self.response.write('build %d not found' % build_id) self.abort(404) return self.redirect(str(build.url))","{'deleted': [{'line_no': 5, 'char_start': 82, 'char_end': 111, 'line': ' except ValueError as ex:\n'}, {'line_no': 6, 'char_start': 111, 'char_end': 149, 'line': ' self.response.write(ex.message)\n'}, {'line_no': 14, 'char_start': 360, 'char_end': 435, 'line': ' return self.redirect(gae_users.create_login_url(self.request.url))\n'}], 'added': [{'line_no': 5, 'char_start': 82, 'char_end': 105, 'line': ' except ValueError:\n'}, {'line_no': 6, 'char_start': 105, 'char_end': 151, 'line': "" self.response.write('invalid build id')\n""}, {'line_no': 14, 'char_start': 362, 'char_end': 432, 'line': ' return self.redirect(self.create_login_url(self.request.url))\n'}]}","{'deleted': [{'char_start': 103, 'char_end': 109, 'chars': ' as ex'}, {'char_start': 137, 'char_end': 144, 'chars': 'ex.mess'}, {'char_start': 145, 'char_end': 147, 'chars': 'ge'}, {'char_start': 389, 'char_end': 394, 'chars': 'gae_u'}, {'char_start': 396, 'char_end': 398, 'chars': 'rs'}], 'added': [{'char_start': 131, 'char_end': 135, 'chars': ""'inv""}, {'char_start': 136, 'char_end': 149, 'chars': ""lid build id'""}, {'char_start': 393, 'char_end': 395, 'chars': 'lf'}]}",github.com/asdfghjjklllllaaa/infra/commit/2f39f3df54fb79b56744f00bcf97583b3807851f,appengine/cr-buildbucket/handlers.py,cwe-079,134 cwe-190,read_SubStreamsInfo,"read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, struct _7z_folder *f, size_t numFolders) { const unsigned char *p; uint64_t *usizes; size_t unpack_streams; int type; unsigned i; uint32_t numDigests; memset(ss, 0, sizeof(*ss)); for (i = 0; i < numFolders; i++) f[i].numUnpackStreams = 1; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kNumUnPackStream) { unpack_streams = 0; for (i = 0; i < numFolders; i++) { if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) return (-1); if (UMAX_ENTRY < f[i].numUnpackStreams) return (-1); unpack_streams += (size_t)f[i].numUnpackStreams; } if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } else unpack_streams = numFolders; ss->unpack_streams = unpack_streams; if (unpack_streams) { ss->unpackSizes = calloc(unpack_streams, sizeof(*ss->unpackSizes)); ss->digestsDefined = calloc(unpack_streams, sizeof(*ss->digestsDefined)); ss->digests = calloc(unpack_streams, sizeof(*ss->digests)); if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || ss->digests == NULL) return (-1); } usizes = ss->unpackSizes; for (i = 0; i < numFolders; i++) { unsigned pack; uint64_t sum; if (f[i].numUnpackStreams == 0) continue; sum = 0; if (type == kSize) { for (pack = 1; pack < f[i].numUnpackStreams; pack++) { if (parse_7zip_uint64(a, usizes) < 0) return (-1); sum += *usizes++; } } *usizes++ = folder_uncompressed_size(&f[i]) - sum; } if (type == kSize) { if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } for (i = 0; i < unpack_streams; i++) { ss->digestsDefined[i] = 0; ss->digests[i] = 0; } numDigests = 0; for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) numDigests += (uint32_t)f[i].numUnpackStreams; } if (type == kCRC) { struct _7z_digests tmpDigests; unsigned char *digestsDefined = ss->digestsDefined; uint32_t * digests = ss->digests; int di = 0; memset(&tmpDigests, 0, sizeof(tmpDigests)); if (read_Digests(a, &(tmpDigests), numDigests) < 0) { free_Digest(&tmpDigests); return (-1); } for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { *digestsDefined++ = 1; *digests++ = f[i].digest; } else { unsigned j; for (j = 0; j < f[i].numUnpackStreams; j++, di++) { *digestsDefined++ = tmpDigests.defineds[di]; *digests++ = tmpDigests.digests[di]; } } } free_Digest(&tmpDigests); if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } /* * Must be kEnd. */ if (type != kEnd) return (-1); return (0); }","read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, struct _7z_folder *f, size_t numFolders) { const unsigned char *p; uint64_t *usizes; size_t unpack_streams; int type; unsigned i; uint32_t numDigests; memset(ss, 0, sizeof(*ss)); for (i = 0; i < numFolders; i++) f[i].numUnpackStreams = 1; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kNumUnPackStream) { unpack_streams = 0; for (i = 0; i < numFolders; i++) { if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) return (-1); if (UMAX_ENTRY < f[i].numUnpackStreams) return (-1); if (unpack_streams > SIZE_MAX - UMAX_ENTRY) { return (-1); } unpack_streams += (size_t)f[i].numUnpackStreams; } if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } else unpack_streams = numFolders; ss->unpack_streams = unpack_streams; if (unpack_streams) { ss->unpackSizes = calloc(unpack_streams, sizeof(*ss->unpackSizes)); ss->digestsDefined = calloc(unpack_streams, sizeof(*ss->digestsDefined)); ss->digests = calloc(unpack_streams, sizeof(*ss->digests)); if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || ss->digests == NULL) return (-1); } usizes = ss->unpackSizes; for (i = 0; i < numFolders; i++) { unsigned pack; uint64_t sum; if (f[i].numUnpackStreams == 0) continue; sum = 0; if (type == kSize) { for (pack = 1; pack < f[i].numUnpackStreams; pack++) { if (parse_7zip_uint64(a, usizes) < 0) return (-1); sum += *usizes++; } } *usizes++ = folder_uncompressed_size(&f[i]) - sum; } if (type == kSize) { if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } for (i = 0; i < unpack_streams; i++) { ss->digestsDefined[i] = 0; ss->digests[i] = 0; } numDigests = 0; for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) numDigests += (uint32_t)f[i].numUnpackStreams; } if (type == kCRC) { struct _7z_digests tmpDigests; unsigned char *digestsDefined = ss->digestsDefined; uint32_t * digests = ss->digests; int di = 0; memset(&tmpDigests, 0, sizeof(tmpDigests)); if (read_Digests(a, &(tmpDigests), numDigests) < 0) { free_Digest(&tmpDigests); return (-1); } for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { *digestsDefined++ = 1; *digests++ = f[i].digest; } else { unsigned j; for (j = 0; j < f[i].numUnpackStreams; j++, di++) { *digestsDefined++ = tmpDigests.defineds[di]; *digests++ = tmpDigests.digests[di]; } } } free_Digest(&tmpDigests); if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } /* * Must be kEnd. */ if (type != kEnd) return (-1); return (0); }","{'deleted': [], 'added': [{'line_no': 27, 'char_start': 626, 'char_end': 675, 'line': '\t\t\tif (unpack_streams > SIZE_MAX - UMAX_ENTRY) {\n'}, {'line_no': 28, 'char_start': 675, 'char_end': 692, 'line': '\t\t\t\treturn (-1);\n'}, {'line_no': 29, 'char_start': 692, 'char_end': 697, 'line': '\t\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 629, 'char_end': 700, 'chars': 'if (unpack_streams > SIZE_MAX - UMAX_ENTRY) {\n\t\t\t\treturn (-1);\n\t\t\t}\n\t\t\t'}]}",github.com/libarchive/libarchive/commit/e79ef306afe332faf22e9b442a2c6b59cb175573,libarchive/archive_read_support_format_7zip.c,cwe-190,970 cwe-416,vips_foreign_load_gif_scan_image,"vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif ); GifFileType *file = gif->file; ColorMapObject *map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap; GifByteType *extension; if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) { vips_foreign_load_gif_error( gif ); return( -1 ); } /* Check that the frame looks sane. Perhaps giflib checks * this for us. */ if( file->Image.Left < 0 || file->Image.Width < 1 || file->Image.Width > 10000 || file->Image.Left + file->Image.Width > file->SWidth || file->Image.Top < 0 || file->Image.Height < 1 || file->Image.Height > 10000 || file->Image.Top + file->Image.Height > file->SHeight ) { vips_error( class->nickname, ""%s"", _( ""bad frame size"" ) ); return( -1 ); } /* Test for a non-greyscale colourmap for this frame. */ if( !gif->has_colour && map ) { int i; for( i = 0; i < map->ColorCount; i++ ) if( map->Colors[i].Red != map->Colors[i].Green || map->Colors[i].Green != map->Colors[i].Blue ) { gif->has_colour = TRUE; break; } } /* Step over compressed image data. */ do { if( vips_foreign_load_gif_code_next( gif, &extension ) ) return( -1 ); } while( extension != NULL ); return( 0 ); }","vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif ); GifFileType *file = gif->file; ColorMapObject *map; GifByteType *extension; if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) { vips_foreign_load_gif_error( gif ); return( -1 ); } /* Check that the frame looks sane. Perhaps giflib checks * this for us. */ if( file->Image.Left < 0 || file->Image.Width < 1 || file->Image.Width > 10000 || file->Image.Left + file->Image.Width > file->SWidth || file->Image.Top < 0 || file->Image.Height < 1 || file->Image.Height > 10000 || file->Image.Top + file->Image.Height > file->SHeight ) { vips_error( class->nickname, ""%s"", _( ""bad frame size"" ) ); return( -1 ); } /* Test for a non-greyscale colourmap for this frame. */ map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap; if( !gif->has_colour && map ) { int i; for( i = 0; i < map->ColorCount; i++ ) if( map->Colors[i].Red != map->Colors[i].Green || map->Colors[i].Green != map->Colors[i].Blue ) { gif->has_colour = TRUE; break; } } /* Step over compressed image data. */ do { if( vips_foreign_load_gif_code_next( gif, &extension ) ) return( -1 ); } while( extension != NULL ); return( 0 ); }","{'deleted': [{'line_no': 5, 'char_start': 151, 'char_end': 197, 'line': '\tColorMapObject *map = file->Image.ColorMap ?\n'}, {'line_no': 6, 'char_start': 197, 'char_end': 239, 'line': '\t\tfile->Image.ColorMap : file->SColorMap;\n'}], 'added': [{'line_no': 6, 'char_start': 152, 'char_end': 174, 'line': '\tColorMapObject *map;\n'}, {'line_no': 31, 'char_start': 824, 'char_end': 894, 'line': '\tmap = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap;\n'}]}","{'deleted': [{'char_start': 171, 'char_end': 237, 'chars': ' = file->Image.ColorMap ?\n\t\tfile->Image.ColorMap : file->SColorMap'}, {'char_start': 238, 'char_end': 239, 'chars': '\n'}], 'added': [{'char_start': 151, 'char_end': 152, 'chars': '\n'}, {'char_start': 823, 'char_end': 893, 'chars': '\n\tmap = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap;'}]}",github.com/libvips/libvips/commit/ce684dd008532ea0bf9d4a1d89bacb35f4a83f4d,libvips/foreign/gifload.c,cwe-416,415 cwe-089,cancelFollow," def cancelFollow(self,userid,friendid): sqlText=""delete from friends where userid=%d and friendid=%d;""%(userid,friendid) result=sql.deleteDB(self.conn,sqlText) return result;"," def cancelFollow(self,userid,friendid): sqlText=""delete from friends where userid=%d and friendid=%s;"" params=[userid,friendid] result=sql.deleteDB(self.conn,sqlText,params) return result;","{'deleted': [{'line_no': 2, 'char_start': 44, 'char_end': 133, 'line': ' sqlText=""delete from friends where userid=%d and friendid=%d;""%(userid,friendid)\n'}, {'line_no': 3, 'char_start': 133, 'char_end': 180, 'line': ' result=sql.deleteDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 2, 'char_start': 44, 'char_end': 115, 'line': ' sqlText=""delete from friends where userid=%d and friendid=%s;""\n'}, {'line_no': 3, 'char_start': 115, 'char_end': 148, 'line': ' params=[userid,friendid]\n'}, {'line_no': 4, 'char_start': 148, 'char_end': 202, 'line': ' result=sql.deleteDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 111, 'char_end': 112, 'chars': 'd'}, {'char_start': 114, 'char_end': 116, 'chars': '%('}, {'char_start': 131, 'char_end': 132, 'chars': ')'}], 'added': [{'char_start': 111, 'char_end': 112, 'chars': 's'}, {'char_start': 114, 'char_end': 131, 'chars': '\n params=['}, {'char_start': 146, 'char_end': 147, 'chars': ']'}, {'char_start': 193, 'char_end': 200, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/users.py,cwe-089,50 cwe-787,track_header,"static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size) { int i, j, ret; int64_t off; int val_1; int num_video; AVIOContext pb0, *pb = &pb0; ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL); ffio_read_varlen(pb); // track_header_len avio_r8(pb); // '1' val_1 = ffio_read_varlen(pb); for (i=0;iid = i; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_VP6; off = avio_tell(pb); off += ffio_read_varlen(pb); avio_r8(pb); // '3' avio_r8(pb); // val_7 num = avio_rl32(pb); // frame_time den = avio_rl32(pb); // time_base avpriv_set_pts_info(st, 64, num, den); st->nb_frames = avio_rl32(pb); // n frames st->codecpar->width = avio_rl16(pb); // width st->codecpar->height = avio_rl16(pb); // height avio_r8(pb); // val_8 avio_rl32(pb); // val_9 avio_seek(pb, off, SEEK_SET); } off = avio_tell(pb); off += ffio_read_varlen(pb); // val_10 avio_r8(pb); // '4' viv->num_audio = avio_r8(pb); avio_seek(pb, off, SEEK_SET); if (viv->num_audio != 1) av_log(s, AV_LOG_WARNING, ""number of audio tracks %d is not 1\n"", viv->num_audio); for(i=0;inum_audio;i++) { int q; AVStream *st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->id = num_video + i; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_VORBIS; off = avio_tell(pb); off += ffio_read_varlen(pb); // length avio_r8(pb); // '5' avio_r8(pb); //codec_id avio_rl16(pb); //codec_subid st->codecpar->channels = avio_rl16(pb); // channels st->codecpar->sample_rate = avio_rl32(pb); // sample_rate avio_seek(pb, 10, SEEK_CUR); // data_1 q = avio_r8(pb); avio_seek(pb, q, SEEK_CUR); // data_2 avio_r8(pb); // zeropad if (avio_tell(pb) < off) { int num_data; int xd_size = 0; int data_len[256]; int offset = 1; uint8_t *p; ffio_read_varlen(pb); // val_13 avio_r8(pb); // '19' ffio_read_varlen(pb); // len_3 num_data = avio_r8(pb); for (j = 0; j < num_data; j++) { uint64_t len = ffio_read_varlen(pb); if (len > INT_MAX/2 - xd_size) { return AVERROR_INVALIDDATA; } data_len[j] = len; xd_size += len; } ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255); if (ret < 0) return ret; p = st->codecpar->extradata; p[0] = 2; for (j = 0; j < num_data - 1; j++) { unsigned delta = av_xiphlacing(&p[offset], data_len[j]); if (delta > data_len[j]) { return AVERROR_INVALIDDATA; } offset += delta; } for (j = 0; j < num_data; j++) { int ret = avio_read(pb, &p[offset], data_len[j]); if (ret < data_len[j]) { st->codecpar->extradata_size = 0; av_freep(&st->codecpar->extradata); break; } offset += data_len[j]; } if (offset < st->codecpar->extradata_size) st->codecpar->extradata_size = offset; } } return 0; }","static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size) { int i, j, ret; int64_t off; int val_1; int num_video; AVIOContext pb0, *pb = &pb0; ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL); ffio_read_varlen(pb); // track_header_len avio_r8(pb); // '1' val_1 = ffio_read_varlen(pb); for (i=0;iid = i; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_VP6; off = avio_tell(pb); off += ffio_read_varlen(pb); avio_r8(pb); // '3' avio_r8(pb); // val_7 num = avio_rl32(pb); // frame_time den = avio_rl32(pb); // time_base avpriv_set_pts_info(st, 64, num, den); st->nb_frames = avio_rl32(pb); // n frames st->codecpar->width = avio_rl16(pb); // width st->codecpar->height = avio_rl16(pb); // height avio_r8(pb); // val_8 avio_rl32(pb); // val_9 avio_seek(pb, off, SEEK_SET); } off = avio_tell(pb); off += ffio_read_varlen(pb); // val_10 avio_r8(pb); // '4' viv->num_audio = avio_r8(pb); avio_seek(pb, off, SEEK_SET); if (viv->num_audio != 1) av_log(s, AV_LOG_WARNING, ""number of audio tracks %d is not 1\n"", viv->num_audio); for(i=0;inum_audio;i++) { int q; AVStream *st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->id = num_video + i; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_VORBIS; off = avio_tell(pb); off += ffio_read_varlen(pb); // length avio_r8(pb); // '5' avio_r8(pb); //codec_id avio_rl16(pb); //codec_subid st->codecpar->channels = avio_rl16(pb); // channels st->codecpar->sample_rate = avio_rl32(pb); // sample_rate avio_seek(pb, 10, SEEK_CUR); // data_1 q = avio_r8(pb); avio_seek(pb, q, SEEK_CUR); // data_2 avio_r8(pb); // zeropad if (avio_tell(pb) < off) { int num_data; int xd_size = 1; int data_len[256]; int offset = 1; uint8_t *p; ffio_read_varlen(pb); // val_13 avio_r8(pb); // '19' ffio_read_varlen(pb); // len_3 num_data = avio_r8(pb); for (j = 0; j < num_data; j++) { uint64_t len = ffio_read_varlen(pb); if (len > INT_MAX/2 - xd_size) { return AVERROR_INVALIDDATA; } data_len[j] = len; xd_size += len + 1 + len/255; } ret = ff_alloc_extradata(st->codecpar, xd_size); if (ret < 0) return ret; p = st->codecpar->extradata; p[0] = 2; for (j = 0; j < num_data - 1; j++) { unsigned delta = av_xiphlacing(&p[offset], data_len[j]); av_assert0(delta <= xd_size - offset); offset += delta; } for (j = 0; j < num_data; j++) { int ret = avio_read(pb, &p[offset], data_len[j]); if (ret < data_len[j]) { st->codecpar->extradata_size = 0; av_freep(&st->codecpar->extradata); break; } av_assert0(data_len[j] <= xd_size - offset); offset += data_len[j]; } if (offset < st->codecpar->extradata_size) st->codecpar->extradata_size = offset; } } return 0; }","{'deleted': [{'line_no': 104, 'char_start': 2925, 'char_end': 2954, 'line': ' int xd_size = 0;\n'}, {'line_no': 118, 'char_start': 3441, 'char_end': 3473, 'line': ' xd_size += len;\n'}, {'line_no': 121, 'char_start': 3488, 'char_end': 3570, 'line': ' ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255);\n'}, {'line_no': 130, 'char_start': 3810, 'char_end': 3853, 'line': ' if (delta > data_len[j]) {\n'}, {'line_no': 131, 'char_start': 3853, 'char_end': 3901, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 132, 'char_start': 3901, 'char_end': 3919, 'line': ' }\n'}], 'added': [{'line_no': 104, 'char_start': 2925, 'char_end': 2954, 'line': ' int xd_size = 1;\n'}, {'line_no': 118, 'char_start': 3441, 'char_end': 3487, 'line': ' xd_size += len + 1 + len/255;\n'}, {'line_no': 121, 'char_start': 3502, 'char_end': 3563, 'line': ' ret = ff_alloc_extradata(st->codecpar, xd_size);\n'}, {'line_no': 130, 'char_start': 3803, 'char_end': 3858, 'line': ' av_assert0(delta <= xd_size - offset);\n'}, {'line_no': 141, 'char_start': 4213, 'char_end': 4274, 'line': ' av_assert0(data_len[j] <= xd_size - offset);\n'}]}","{'deleted': [{'char_start': 2951, 'char_end': 2952, 'chars': '0'}, {'char_start': 3539, 'char_end': 3544, 'chars': '64 + '}, {'char_start': 3551, 'char_end': 3567, 'chars': ' + xd_size / 255'}, {'char_start': 3826, 'char_end': 3829, 'chars': 'if '}, {'char_start': 3836, 'char_end': 3837, 'chars': '>'}, {'char_start': 3839, 'char_end': 3842, 'chars': 'ata'}, {'char_start': 3843, 'char_end': 3844, 'chars': 'l'}, {'char_start': 3845, 'char_end': 3870, 'chars': 'n[j]) {\n '}, {'char_start': 3872, 'char_end': 3874, 'chars': ' r'}, {'char_start': 3876, 'char_end': 3899, 'chars': 'urn AVERROR_INVALIDDATA'}, {'char_start': 3900, 'char_end': 3918, 'chars': '\n }'}], 'added': [{'char_start': 2951, 'char_end': 2952, 'chars': '1'}, {'char_start': 3471, 'char_end': 3485, 'chars': ' + 1 + len/255'}, {'char_start': 3819, 'char_end': 3829, 'chars': 'av_assert0'}, {'char_start': 3836, 'char_end': 3838, 'chars': '<='}, {'char_start': 3839, 'char_end': 3840, 'chars': 'x'}, {'char_start': 3842, 'char_end': 3845, 'chars': 'siz'}, {'char_start': 3847, 'char_end': 3848, 'chars': '-'}, {'char_start': 3849, 'char_end': 3853, 'chars': 'offs'}, {'char_start': 3855, 'char_end': 3856, 'chars': ')'}, {'char_start': 4212, 'char_end': 4273, 'chars': '\n av_assert0(data_len[j] <= xd_size - offset);'}]}",github.com/FFmpeg/FFmpeg/commit/27a99e2c7d450fef15594671eef4465c8a166bd7,libavformat/vividas.c,cwe-787,1338 cwe-089,karma_sub,"def karma_sub(name): karma = karma_ask(name) db = db_connect() cursor = db.cursor() if karma is None: try: cursor.execute(''' INSERT INTO people(name,karma,shame) VALUES('{}',-1,0) '''.format(name)) db.commit() logger.debug('Inserted into karmadb -1 karma for {}'.format(name)) db.close() return -1 except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise else: karma = karma - 1 try: cursor.execute(''' UPDATE people SET karma = {0} WHERE name = '{1}' '''.format(karma, name)) db.commit() logger.debug('Inserted into karmadb -1 karma for {}'.format(name)) db.close() return karma except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","def karma_sub(name): karma = karma_ask(name) db = db_connect() cursor = db.cursor() if karma is None: try: cursor.execute(''' INSERT INTO people(name,karma,shame) VALUES(%(name)s,-1,0) ''', (name, )) db.commit() logger.debug('Inserted into karmadb -1 karma for {}'.format(name)) db.close() return -1 except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise else: karma = karma - 1 try: cursor.execute(''' UPDATE people SET karma = %(karma)s WHERE name = %(name)s ''', ( karma, name, )) db.commit() logger.debug('Inserted into karmadb -1 karma for {}'.format(name)) db.close() return karma except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","{'deleted': [{'line_no': 8, 'char_start': 162, 'char_end': 233, 'line': "" INSERT INTO people(name,karma,shame) VALUES('{}',-1,0)\n""}, {'line_no': 9, 'char_start': 233, 'char_end': 267, 'line': "" '''.format(name))\n""}, {'line_no': 22, 'char_start': 615, 'char_end': 680, 'line': "" UPDATE people SET karma = {0} WHERE name = '{1}'\n""}, {'line_no': 23, 'char_start': 680, 'char_end': 721, 'line': "" '''.format(karma, name))\n""}], 'added': [{'line_no': 8, 'char_start': 162, 'char_end': 237, 'line': ' INSERT INTO people(name,karma,shame) VALUES(%(name)s,-1,0)\n'}, {'line_no': 9, 'char_start': 237, 'char_end': 268, 'line': "" ''', (name, ))\n""}, {'line_no': 22, 'char_start': 616, 'char_end': 690, 'line': ' UPDATE people SET karma = %(karma)s WHERE name = %(name)s\n'}, {'line_no': 23, 'char_start': 690, 'char_end': 713, 'line': "" ''', (\n""}, {'line_no': 24, 'char_start': 713, 'char_end': 736, 'line': ' karma,\n'}, {'line_no': 25, 'char_start': 736, 'char_end': 758, 'line': ' name,\n'}, {'line_no': 26, 'char_start': 758, 'char_end': 773, 'line': ' ))\n'}]}","{'deleted': [{'char_start': 222, 'char_end': 226, 'chars': ""'{}'""}, {'char_start': 252, 'char_end': 259, 'chars': '.format'}, {'char_start': 657, 'char_end': 660, 'chars': '{0}'}, {'char_start': 674, 'char_end': 679, 'chars': ""'{1}'""}, {'char_start': 699, 'char_end': 706, 'chars': '.format'}], 'added': [{'char_start': 222, 'char_end': 230, 'chars': '%(name)s'}, {'char_start': 256, 'char_end': 258, 'chars': ', '}, {'char_start': 263, 'char_end': 265, 'chars': ', '}, {'char_start': 658, 'char_end': 667, 'chars': '%(karma)s'}, {'char_start': 681, 'char_end': 689, 'chars': '%(name)s'}, {'char_start': 709, 'char_end': 711, 'chars': ', '}, {'char_start': 712, 'char_end': 729, 'chars': '\n '}, {'char_start': 735, 'char_end': 751, 'chars': '\n '}, {'char_start': 756, 'char_end': 770, 'chars': ',\n '}]}",github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a,KarmaBoi/dbopts.py,cwe-089,208 cwe-190,hfs_cat_traverse,"hfs_cat_traverse(HFS_INFO * hfs, TSK_HFS_BTREE_CB a_cb, void *ptr) { TSK_FS_INFO *fs = &(hfs->fs_info); uint32_t cur_node; /* node id of the current node */ char *node; uint16_t nodesize; uint8_t is_done = 0; tsk_error_reset(); nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) return 1; /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: "" ""empty extents btree\n""); free(node); return 1; } if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: starting at "" ""root node %"" PRIu32 ""; nodesize = %"" PRIu16 ""\n"", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; // sanity check if (cur_node > tsk_getu32(fs->endian, hfs->catalog_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: Node %d too large for file"", cur_node); free(node); return 1; } // read the current node cur_off = cur_node * nodesize; cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 (""hfs_cat_traverse: Error reading node %d at offset %"" PRIuOFF, cur_node, cur_off); free(node); return 1; } // process the header / descriptor if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: Node size %d is too small to be valid"", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: node %"" PRIu32 "" @ %"" PRIu64 "" has %"" PRIu16 "" records\n"", cur_node, cur_off, num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr(""hfs_cat_traverse: zero records in node %"" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; uint16_t keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: length of key %d in index node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: record %"" PRIu16 "" ; keylen %"" PRIu16 "" (%"" PRIu32 "")\n"", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ /* save the info from this record unless it is too big */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 (""hfs_cat_traverse: Callback returned error""); free(node); return 1; } // record the closest entry else if ((retval == HFS_BTREE_CB_IDX_LT) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->catalog_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } if (retval == HFS_BTREE_CB_IDX_EQGT) { // move down to the next node break; } } // check if we found a relevant node if (next_node == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: did not find any keys in index node %d"", cur_node); is_done = 1; break; } // TODO: Handle multinode loops if (next_node == cur_node) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: node %d references itself as next node"", cur_node); is_done = 1; break; } cur_node = next_node; } /* With a leaf, we look for the specific record. */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; uint16_t keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: record %"" PRIu16 ""; keylen %"" PRIu16 "" (%"" PRIu32 "")\n"", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ // rec_cnid = tsk_getu32(fs->endian, key->file_id); retval = a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_LEAF_STOP) { is_done = 1; break; } else if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 (""hfs_cat_traverse: Callback returned error""); free(node); return 1; } } // move right to the next node if we got this far if (is_done == 0) { cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; } if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: moving forward to next leaf""); } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr(""hfs_cat_traverse: btree node %"" PRIu32 "" (%"" PRIu64 "") is neither index nor leaf (%"" PRIu8 "")"", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; }","hfs_cat_traverse(HFS_INFO * hfs, TSK_HFS_BTREE_CB a_cb, void *ptr) { TSK_FS_INFO *fs = &(hfs->fs_info); uint32_t cur_node; /* node id of the current node */ char *node; uint16_t nodesize; uint8_t is_done = 0; tsk_error_reset(); nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) return 1; /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: "" ""empty extents btree\n""); free(node); return 1; } if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: starting at "" ""root node %"" PRIu32 ""; nodesize = %"" PRIu16 ""\n"", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; // sanity check if (cur_node > tsk_getu32(fs->endian, hfs->catalog_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: Node %d too large for file"", cur_node); free(node); return 1; } // read the current node cur_off = cur_node * nodesize; cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 (""hfs_cat_traverse: Error reading node %d at offset %"" PRIuOFF, cur_node, cur_off); free(node); return 1; } // process the header / descriptor if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: Node size %d is too small to be valid"", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: node %"" PRIu32 "" @ %"" PRIu64 "" has %"" PRIu16 "" records\n"", cur_node, cur_off, num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr(""hfs_cat_traverse: zero records in node %"" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: length of key %d in index node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: record %"" PRIu16 "" ; keylen %"" PRIu16 "" (%"" PRIu32 "")\n"", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ /* save the info from this record unless it is too big */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 (""hfs_cat_traverse: Callback returned error""); free(node); return 1; } // record the closest entry else if ((retval == HFS_BTREE_CB_IDX_LT) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->catalog_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } if (retval == HFS_BTREE_CB_IDX_EQGT) { // move down to the next node break; } } // check if we found a relevant node if (next_node == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: did not find any keys in index node %d"", cur_node); is_done = 1; break; } // TODO: Handle multinode loops if (next_node == cur_node) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: node %d references itself as next node"", cur_node); is_done = 1; break; } cur_node = next_node; } /* With a leaf, we look for the specific record. */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr (""hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %"" PRIu16 "")"", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: record %"" PRIu16 ""; keylen %"" PRIu16 "" (%"" PRIu32 "")\n"", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ // rec_cnid = tsk_getu32(fs->endian, key->file_id); retval = a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_LEAF_STOP) { is_done = 1; break; } else if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 (""hfs_cat_traverse: Callback returned error""); free(node); return 1; } } // move right to the next node if we got this far if (is_done == 0) { cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; } if (tsk_verbose) tsk_fprintf(stderr, ""hfs_cat_traverse: moving forward to next leaf""); } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr(""hfs_cat_traverse: btree node %"" PRIu32 "" (%"" PRIu64 "") is neither index nor leaf (%"" PRIu8 "")"", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; }","{'deleted': [{'line_no': 105, 'char_start': 3527, 'char_end': 3560, 'line': ' uint16_t keylen;\n'}, {'line_no': 210, 'char_start': 7854, 'char_end': 7887, 'line': ' uint16_t keylen;\n'}], 'added': [{'line_no': 105, 'char_start': 3527, 'char_end': 3555, 'line': ' int keylen;\n'}, {'line_no': 210, 'char_start': 7849, 'char_end': 7877, 'line': ' int keylen;\n'}]}","{'deleted': [{'char_start': 3543, 'char_end': 3544, 'chars': 'u'}, {'char_start': 3546, 'char_end': 3550, 'chars': 't16_'}, {'char_start': 7870, 'char_end': 7871, 'chars': 'u'}, {'char_start': 7873, 'char_end': 7877, 'chars': 't16_'}], 'added': []}",github.com/sleuthkit/sleuthkit/commit/114cd3d0aac8bd1aeaf4b33840feb0163d342d5b,tsk/fs/hfs.c,cwe-190,2579 cwe-089,add_day_data_row," def add_day_data_row(self, ts, data, prev_etotal): if data['power'] > 0: inv_serial = data['source']['serial_id'] query = ''' INSERT INTO DayData ( TimeStamp, Serial, Power, TotalYield ) VALUES ( %s, %s, %s, %s ); ''' % (ts, inv_serial, data['power'], prev_etotal + data['energy']) self.c.execute(query)"," def add_day_data_row(self, ts, data, prev_etotal): if data['power'] > 0: inv_serial = data['source']['serial_id'] query = ''' INSERT INTO DayData ( TimeStamp, Serial, Power, TotalYield ) VALUES ( ?, ?, ?, ? ); ''' self.c.execute(query, (ts, inv_serial, data['power'], prev_etotal + data['energy']))","{'deleted': [{'line_no': 13, 'char_start': 340, 'char_end': 363, 'line': ' %s,\n'}, {'line_no': 14, 'char_start': 363, 'char_end': 386, 'line': ' %s,\n'}, {'line_no': 15, 'char_start': 386, 'char_end': 409, 'line': ' %s,\n'}, {'line_no': 16, 'char_start': 409, 'char_end': 431, 'line': ' %s\n'}, {'line_no': 18, 'char_start': 449, 'char_end': 530, 'line': "" ''' % (ts, inv_serial, data['power'], prev_etotal + data['energy'])\n""}, {'line_no': 19, 'char_start': 530, 'char_end': 563, 'line': ' self.c.execute(query)\n'}], 'added': [{'line_no': 13, 'char_start': 340, 'char_end': 362, 'line': ' ?,\n'}, {'line_no': 14, 'char_start': 362, 'char_end': 384, 'line': ' ?,\n'}, {'line_no': 15, 'char_start': 384, 'char_end': 406, 'line': ' ?,\n'}, {'line_no': 16, 'char_start': 406, 'char_end': 427, 'line': ' ?\n'}, {'line_no': 18, 'char_start': 445, 'char_end': 461, 'line': "" '''\n""}, {'line_no': 19, 'char_start': 461, 'char_end': 558, 'line': "" self.c.execute(query, (ts, inv_serial, data['power'], prev_etotal + data['energy']))\n""}]}","{'deleted': [{'char_start': 359, 'char_end': 361, 'chars': '%s'}, {'char_start': 382, 'char_end': 384, 'chars': '%s'}, {'char_start': 405, 'char_end': 407, 'chars': '%s'}, {'char_start': 428, 'char_end': 430, 'chars': '%s'}, {'char_start': 465, 'char_end': 466, 'chars': '%'}, {'char_start': 529, 'char_end': 562, 'chars': '\n self.c.execute(query'}], 'added': [{'char_start': 359, 'char_end': 360, 'chars': '?'}, {'char_start': 381, 'char_end': 382, 'chars': '?'}, {'char_start': 403, 'char_end': 404, 'chars': '?'}, {'char_start': 425, 'char_end': 426, 'chars': '?'}, {'char_start': 460, 'char_end': 468, 'chars': '\n '}, {'char_start': 469, 'char_end': 494, 'chars': ' self.c.execute(query,'}]}",github.com/philipptrenz/s0-bridge/commit/269b48caa05377b7c58c3e6d1622a4429cb5ba65,util/database.py,cwe-089,112 cwe-089,check_and_update_ranks," def check_and_update_ranks(self, scene): # There are 2 cases here: # 1) Ranks have never been calculated for this scene before # - This means we need to calculate what the ranks were every month of this scenes history # - We should only do this if ranks don't already exist for this scene # 2) Ranks have been calculated for this scene before # - We already have bulk ranks. We should check if it has been more than 1 month since we last # calculated ranks. If so, calculate again with the brackets that have come out this month LOG.info('About to check if ranks need updating for {}'.format(scene)) # First, do we have any ranks for this scene already? sql = 'select count(*) from ranks where scene=""{}"";'.format(scene) res = self.db.exec(sql) count = res[0][0] n = 5 if (scene == 'pro' or scene == 'pro_wiiu') else constants.TOURNAMENTS_PER_RANK if count == 0: LOG.info('Detected that we need to bulk update ranks for {}'.format(scene)) # Alright, we have nothing. Bulk update ranks first_month = bracket_utils.get_first_month(self.db, scene) last_month = bracket_utils.get_last_month(self.db, scene) # Iterate through all tournaments going month by month, and calculate ranks months = bracket_utils.iter_months(first_month, last_month, include_first=False, include_last=True) for month in months: urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n) self.process_ranks(scene, urls, month) else: # Get the date of the last time we calculated ranks sql = ""select date from ranks where scene='{}' order by date desc limit 1;"".format(scene) res = self.db.exec(sql) last_rankings_date = res[0][0] # Check to see if it's been more than 1 month since we last calculated ranks more_than_one_month = bracket_utils.has_month_passed(last_rankings_date) if more_than_one_month: # Get only the last n tournaments, so it doesn't take too long to process today = datetime.datetime.today().strftime('%Y-%m-%d') msg = 'Detected that we need up update monthly ranks for {}, on {}'.format(scene, today) LOG.info(msg) # We should only ever calculate ranks on the 1st. If today is not the first, log error if not today.split('-')[-1] == '1': LOG.exc('We are calculating ranks today, {}, but it isnt the first'.format(today)) months = bracket_utils.iter_months(last_rankings_date, today, include_first=False, include_last=True) for month in months: # Make sure that we actually have matches during this month # Say we are trying to calculate ranks for 2018-05-01, the player would need to have matches during 2018-04-01, 2018-04-30 prev_date = bracket_utils.get_previous_month(month) brackets_during_month = bracket_utils.get_tournaments_during_month(self.db, scene, prev_date) if len(brackets_during_month) > 0: tweet('Calculating {} ranks for {}'.format(month, scene)) urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n) self.process_ranks(scene, urls, month) else: LOG.info('It has not yet been 1 month since we calculated ranks for {}. Skipping'.format(scene))"," def check_and_update_ranks(self, scene): # There are 2 cases here: # 1) Ranks have never been calculated for this scene before # - This means we need to calculate what the ranks were every month of this scenes history # - We should only do this if ranks don't already exist for this scene # 2) Ranks have been calculated for this scene before # - We already have bulk ranks. We should check if it has been more than 1 month since we last # calculated ranks. If so, calculate again with the brackets that have come out this month LOG.info('About to check if ranks need updating for {}'.format(scene)) # First, do we have any ranks for this scene already? sql = 'select count(*) from ranks where scene=""{scene}"";' args = {'scene': scene} res = self.db.exec(sql, args) count = res[0][0] n = 5 if (scene == 'pro' or scene == 'pro_wiiu') else constants.TOURNAMENTS_PER_RANK if count == 0: LOG.info('Detected that we need to bulk update ranks for {}'.format(scene)) # Alright, we have nothing. Bulk update ranks first_month = bracket_utils.get_first_month(self.db, scene) last_month = bracket_utils.get_last_month(self.db, scene) # Iterate through all tournaments going month by month, and calculate ranks months = bracket_utils.iter_months(first_month, last_month, include_first=False, include_last=True) for month in months: urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n) self.process_ranks(scene, urls, month) else: # Get the date of the last time we calculated ranks sql = ""select date from ranks where scene='{scene}' order by date desc limit 1;"" args = {'scene': scene} res = self.db.exec(sql, args) last_rankings_date = res[0][0] # Check to see if it's been more than 1 month since we last calculated ranks more_than_one_month = bracket_utils.has_month_passed(last_rankings_date) if more_than_one_month: # Get only the last n tournaments, so it doesn't take too long to process today = datetime.datetime.today().strftime('%Y-%m-%d') msg = 'Detected that we need up update monthly ranks for {}, on {}'.format(scene, today) LOG.info(msg) # We should only ever calculate ranks on the 1st. If today is not the first, log error if not today.split('-')[-1] == '1': LOG.exc('We are calculating ranks today, {}, but it isnt the first'.format(today)) months = bracket_utils.iter_months(last_rankings_date, today, include_first=False, include_last=True) for month in months: # Make sure that we actually have matches during this month # Say we are trying to calculate ranks for 2018-05-01, the player would need to have matches during 2018-04-01, 2018-04-30 prev_date = bracket_utils.get_previous_month(month) brackets_during_month = bracket_utils.get_tournaments_during_month(self.db, scene, prev_date) if len(brackets_during_month) > 0: tweet('Calculating {} ranks for {}'.format(month, scene)) urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n) self.process_ranks(scene, urls, month) else: LOG.info('It has not yet been 1 month since we calculated ranks for {}. Skipping'.format(scene))","{'deleted': [{'line_no': 12, 'char_start': 763, 'char_end': 838, 'line': ' sql = \'select count(*) from ranks where scene=""{}"";\'.format(scene)\n'}, {'line_no': 13, 'char_start': 838, 'char_end': 870, 'line': ' res = self.db.exec(sql)\n'}, {'line_no': 31, 'char_start': 1777, 'char_end': 1879, 'line': ' sql = ""select date from ranks where scene=\'{}\' order by date desc limit 1;"".format(scene)\n'}, {'line_no': 32, 'char_start': 1879, 'char_end': 1915, 'line': ' res = self.db.exec(sql)\n'}], 'added': [{'line_no': 12, 'char_start': 763, 'char_end': 829, 'line': ' sql = \'select count(*) from ranks where scene=""{scene}"";\'\n'}, {'line_no': 13, 'char_start': 829, 'char_end': 861, 'line': "" args = {'scene': scene}\n""}, {'line_no': 14, 'char_start': 861, 'char_end': 899, 'line': ' res = self.db.exec(sql, args)\n'}, {'line_no': 32, 'char_start': 1806, 'char_end': 1899, 'line': ' sql = ""select date from ranks where scene=\'{scene}\' order by date desc limit 1;""\n'}, {'line_no': 33, 'char_start': 1899, 'char_end': 1935, 'line': "" args = {'scene': scene}\n""}, {'line_no': 34, 'char_start': 1935, 'char_end': 1977, 'line': ' res = self.db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 823, 'char_end': 826, 'chars': '.fo'}, {'char_start': 827, 'char_end': 831, 'chars': 'mat('}, {'char_start': 836, 'char_end': 837, 'chars': ')'}, {'char_start': 1864, 'char_end': 1867, 'chars': '.fo'}, {'char_start': 1868, 'char_end': 1872, 'chars': 'mat('}, {'char_start': 1877, 'char_end': 1878, 'chars': ')'}], 'added': [{'char_start': 819, 'char_end': 824, 'chars': 'scene'}, {'char_start': 828, 'char_end': 837, 'chars': '\n '}, {'char_start': 838, 'char_end': 846, 'chars': ""rgs = {'""}, {'char_start': 851, 'char_end': 860, 'chars': ""': scene}""}, {'char_start': 891, 'char_end': 897, 'chars': ', args'}, {'char_start': 1862, 'char_end': 1867, 'chars': 'scene'}, {'char_start': 1898, 'char_end': 1911, 'chars': '\n '}, {'char_start': 1912, 'char_end': 1920, 'chars': ""rgs = {'""}, {'char_start': 1925, 'char_end': 1934, 'chars': ""': scene}""}, {'char_start': 1969, 'char_end': 1975, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,process_data.py,cwe-089,814 cwe-089,clean_cache," def clean_cache(self, limit): """""" Method that remove several User objects from cache - the least active users :param limit: number of the users that the method should remove from cache :return: None """""" log.info('Figuring out the least active users...') # Select users that the least active recently user_ids = tuple(self.users.keys()) query = ('SELECT chat_id ' 'FROM photo_queries_table2 ' f'WHERE chat_id in {user_ids} ' 'GROUP BY chat_id ' 'ORDER BY MAX(time) ' f'LIMIT {limit}') try: cursor = db.execute_query(query) except DatabaseConnectionError: log.error(""Can't figure out the least active users..."") return if not cursor.rowcount: log.warning(""There are no users in the db"") return # Make list out of tuple of tuples that is returned by MySQL least_active_users = [chat_id[0] for chat_id in cursor.fetchall()] log.info('Removing %d least active users from cache...', limit) num_deleted_entries = 0 for entry in least_active_users: log.debug('Deleting %s...', entry) deleted_entry = self.users.pop(entry, None) if deleted_entry: num_deleted_entries += 1 log.debug(""%d users were removed from cache."", num_deleted_entries)"," def clean_cache(self, limit): """""" Method that remove several User objects from cache - the least active users :param limit: number of the users that the method should remove from cache :return: None """""" log.info('Figuring out the least active users...') # Select users that the least active recently user_ids = tuple(self.users.keys()) query = ('SELECT chat_id ' 'FROM photo_queries_table2 ' f'WHERE chat_id in {user_ids} ' 'GROUP BY chat_id ' 'ORDER BY MAX(time) ' f'LIMIT %s') parameters = limit, try: cursor = db.execute_query(query, parameters) except DatabaseConnectionError: log.error(""Can't figure out the least active users..."") return if not cursor.rowcount: log.warning(""There are no users in the db"") return # Make list out of tuple of tuples that is returned by MySQL least_active_users = [chat_id[0] for chat_id in cursor.fetchall()] log.info('Removing %d least active users from cache...', limit) num_deleted_entries = 0 for entry in least_active_users: log.debug('Deleting %s...', entry) deleted_entry = self.users.pop(entry, None) if deleted_entry: num_deleted_entries += 1 log.debug(""%d users were removed from cache."", num_deleted_entries)","{'deleted': [{'line_no': 18, 'char_start': 628, 'char_end': 663, 'line': "" f'LIMIT {limit}')\n""}, {'line_no': 21, 'char_start': 677, 'char_end': 722, 'line': ' cursor = db.execute_query(query)\n'}], 'added': [{'line_no': 18, 'char_start': 628, 'char_end': 658, 'line': "" f'LIMIT %s')\n""}, {'line_no': 19, 'char_start': 658, 'char_end': 659, 'line': '\n'}, {'line_no': 20, 'char_start': 659, 'char_end': 687, 'line': ' parameters = limit,\n'}, {'line_no': 23, 'char_start': 701, 'char_end': 758, 'line': ' cursor = db.execute_query(query, parameters)\n'}]}","{'deleted': [{'char_start': 653, 'char_end': 654, 'chars': '{'}, {'char_start': 659, 'char_end': 662, 'chars': ""}')""}], 'added': [{'char_start': 653, 'char_end': 680, 'chars': ""%s')\n\n parameters = ""}, {'char_start': 685, 'char_end': 686, 'chars': ','}, {'char_start': 744, 'char_end': 756, 'chars': ', parameters'}]}",github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a,photogpsbot/users.py,cwe-089,303 cwe-022,imap_hcache_open,"header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path) { struct ImapMbox mx; struct Url url; char cachepath[PATH_MAX]; char mbox[PATH_MAX]; if (path) imap_cachepath(idata, path, mbox, sizeof(mbox)); else { if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0) return NULL; imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox)); FREE(&mx.mbox); } mutt_account_tourl(&idata->conn->account, &url); url.path = mbox; url_tostring(&url, cachepath, sizeof(cachepath), U_PATH); return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer); }","header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path) { struct ImapMbox mx; struct Url url; char cachepath[PATH_MAX]; char mbox[PATH_MAX]; if (path) imap_cachepath(idata, path, mbox, sizeof(mbox)); else { if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0) return NULL; imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox)); FREE(&mx.mbox); } if (strstr(mbox, ""/../"") || (strcmp(mbox, "".."") == 0) || (strncmp(mbox, ""../"", 3) == 0)) return NULL; size_t len = strlen(mbox); if ((len > 3) && (strcmp(mbox + len - 3, ""/.."") == 0)) return NULL; mutt_account_tourl(&idata->conn->account, &url); url.path = mbox; url_tostring(&url, cachepath, sizeof(cachepath), U_PATH); return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer); }","{'deleted': [], 'added': [{'line_no': 19, 'char_start': 413, 'char_end': 504, 'line': ' if (strstr(mbox, ""/../"") || (strcmp(mbox, "".."") == 0) || (strncmp(mbox, ""../"", 3) == 0))\n'}, {'line_no': 20, 'char_start': 504, 'char_end': 521, 'line': ' return NULL;\n'}, {'line_no': 21, 'char_start': 521, 'char_end': 550, 'line': ' size_t len = strlen(mbox);\n'}, {'line_no': 22, 'char_start': 550, 'char_end': 607, 'line': ' if ((len > 3) && (strcmp(mbox + len - 3, ""/.."") == 0))\n'}, {'line_no': 23, 'char_start': 607, 'char_end': 624, 'line': ' return NULL;\n'}, {'line_no': 24, 'char_start': 624, 'char_end': 625, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 415, 'char_end': 627, 'chars': '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 '}]}",github.com/neomutt/neomutt/commit/57971dba06346b2d7179294f4528b8d4427a7c5d,imap/util.c,cwe-022,198 cwe-125,enc_untrusted_recvfrom,"ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { int klinux_flags = TokLinuxRecvSendFlag(flags); if (klinux_flags == 0 && flags != 0) { errno = EINVAL; return -1; } MessageWriter input; input.Push(sockfd); input.Push(len); input.Push(klinux_flags); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kRecvFromHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_recvfrom"", 4); int result = output.next(); int klinux_errno = output.next(); // recvfrom() returns -1 on failure, with errno set to indicate the cause // of the error. if (result == -1) { errno = FromkLinuxErrorNumber(klinux_errno); return result; } auto buffer_received = output.next(); memcpy(buf, buffer_received.data(), std::min(len, buffer_received.size())); // If |src_addr| is not NULL, and the underlying protocol provides the source // address, this source address is filled in. When |src_addr| is NULL, nothing // is filled in; in this case, |addrlen| is not used, and should also be NULL. if (src_addr != nullptr && addrlen != nullptr) { auto klinux_sockaddr_buf = output.next(); const struct klinux_sockaddr *klinux_addr = klinux_sockaddr_buf.As(); FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr, addrlen, TrustedPrimitives::BestEffortAbort); } return result; }","ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { int klinux_flags = TokLinuxRecvSendFlag(flags); if (klinux_flags == 0 && flags != 0) { errno = EINVAL; return -1; } MessageWriter input; input.Push(sockfd); input.Push(len); input.Push(klinux_flags); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kRecvFromHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_recvfrom"", 4); int result = output.next(); int klinux_errno = output.next(); // recvfrom() returns -1 on failure, with errno set to indicate the cause // of the error. if (result == -1) { errno = FromkLinuxErrorNumber(klinux_errno); return result; } if (result > len) { ::asylo::primitives::TrustedPrimitives::BestEffortAbort( ""enc_untrusted_recvfrom: result exceeds requested""); } auto buffer_received = output.next(); memcpy(buf, buffer_received.data(), std::min(len, buffer_received.size())); // If |src_addr| is not NULL, and the underlying protocol provides the source // address, this source address is filled in. When |src_addr| is NULL, nothing // is filled in; in this case, |addrlen| is not used, and should also be NULL. if (src_addr != nullptr && addrlen != nullptr) { auto klinux_sockaddr_buf = output.next(); const struct klinux_sockaddr *klinux_addr = klinux_sockaddr_buf.As(); FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr, addrlen, TrustedPrimitives::BestEffortAbort); } return result; }","{'deleted': [], 'added': [{'line_no': 27, 'char_start': 873, 'char_end': 895, 'line': ' if (result > len) {\n'}, {'line_no': 28, 'char_start': 895, 'char_end': 956, 'line': ' ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n'}, {'line_no': 29, 'char_start': 956, 'char_end': 1017, 'line': ' ""enc_untrusted_recvfrom: result exceeds requested"");\n'}, {'line_no': 30, 'char_start': 1017, 'char_end': 1021, 'line': ' }\n'}, {'line_no': 31, 'char_start': 1021, 'char_end': 1022, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 875, 'char_end': 1024, 'chars': 'if (result > len) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n ""enc_untrusted_recvfrom: result exceeds requested"");\n }\n\n '}]}",github.com/google/asylo/commit/6e158d558abd3c29a0208e30c97c9a8c5bd4230f,asylo/platform/host_call/trusted/host_calls.cc,cwe-125,413 cwe-416,xc2028_set_config,"static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg) { struct xc2028_data *priv = fe->tuner_priv; struct xc2028_ctrl *p = priv_cfg; int rc = 0; tuner_dbg(""%s called\n"", __func__); mutex_lock(&priv->lock); /* * Copy the config data. * For the firmware name, keep a local copy of the string, * in order to avoid troubles during device release. */ kfree(priv->ctrl.fname); memcpy(&priv->ctrl, p, sizeof(priv->ctrl)); if (p->fname) { priv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL); if (priv->ctrl.fname == NULL) rc = -ENOMEM; } /* * If firmware name changed, frees firmware. As free_firmware will * reset the status to NO_FIRMWARE, this forces a new request_firmware */ if (!firmware_name[0] && p->fname && priv->fname && strcmp(p->fname, priv->fname)) free_firmware(priv); if (priv->ctrl.max_len < 9) priv->ctrl.max_len = 13; if (priv->state == XC2028_NO_FIRMWARE) { if (!firmware_name[0]) priv->fname = priv->ctrl.fname; else priv->fname = firmware_name; rc = request_firmware_nowait(THIS_MODULE, 1, priv->fname, priv->i2c_props.adap->dev.parent, GFP_KERNEL, fe, load_firmware_cb); if (rc < 0) { tuner_err(""Failed to request firmware %s\n"", priv->fname); priv->state = XC2028_NODEV; } else priv->state = XC2028_WAITING_FIRMWARE; } mutex_unlock(&priv->lock); return rc; }","static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg) { struct xc2028_data *priv = fe->tuner_priv; struct xc2028_ctrl *p = priv_cfg; int rc = 0; tuner_dbg(""%s called\n"", __func__); mutex_lock(&priv->lock); /* * Copy the config data. * For the firmware name, keep a local copy of the string, * in order to avoid troubles during device release. */ kfree(priv->ctrl.fname); priv->ctrl.fname = NULL; memcpy(&priv->ctrl, p, sizeof(priv->ctrl)); if (p->fname) { priv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL); if (priv->ctrl.fname == NULL) return -ENOMEM; } /* * If firmware name changed, frees firmware. As free_firmware will * reset the status to NO_FIRMWARE, this forces a new request_firmware */ if (!firmware_name[0] && p->fname && priv->fname && strcmp(p->fname, priv->fname)) free_firmware(priv); if (priv->ctrl.max_len < 9) priv->ctrl.max_len = 13; if (priv->state == XC2028_NO_FIRMWARE) { if (!firmware_name[0]) priv->fname = priv->ctrl.fname; else priv->fname = firmware_name; rc = request_firmware_nowait(THIS_MODULE, 1, priv->fname, priv->i2c_props.adap->dev.parent, GFP_KERNEL, fe, load_firmware_cb); if (rc < 0) { tuner_err(""Failed to request firmware %s\n"", priv->fname); priv->state = XC2028_NODEV; } else priv->state = XC2028_WAITING_FIRMWARE; } mutex_unlock(&priv->lock); return rc; }","{'deleted': [{'line_no': 21, 'char_start': 572, 'char_end': 589, 'line': '\t\t\trc = -ENOMEM;\n'}], 'added': [{'line_no': 17, 'char_start': 426, 'char_end': 452, 'line': '\tpriv->ctrl.fname = NULL;\n'}, {'line_no': 22, 'char_start': 598, 'char_end': 617, 'line': '\t\t\treturn -ENOMEM;\n'}]}","{'deleted': [{'char_start': 576, 'char_end': 579, 'chars': 'c ='}], 'added': [{'char_start': 427, 'char_end': 453, 'chars': 'priv->ctrl.fname = NULL;\n\t'}, {'char_start': 602, 'char_end': 607, 'chars': 'eturn'}]}",github.com/torvalds/linux/commit/8dfbcc4351a0b6d2f2d77f367552f48ffefafe18,drivers/media/tuners/tuner-xc2028.c,cwe-416,432 cwe-089,get_mapped_projects," @staticmethod def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO: """""" Get all projects a user has mapped on """""" # This query looks scary, but we're really just creating an outer join between the query that gets the # counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to # handle cases where users have only validated tasks on a project, or only mapped on a project. sql = '''SELECT p.id, p.status, p.default_locale, c.mapped, c.validated, st_asgeojson(p.centroid) FROM projects p, (SELECT coalesce(v.project_id, m.project_id) project_id, coalesce(v.validated, 0) validated, coalesce(m.mapped, 0) mapped FROM (SELECT t.project_id, count (t.validated_by) validated FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0}) AND t.validated_by = {0} GROUP BY t.project_id, t.validated_by) v FULL OUTER JOIN (SELECT t.project_id, count(t.mapped_by) mapped FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0}) AND t.mapped_by = {0} GROUP BY t.project_id, t.mapped_by) m ON v.project_id = m.project_id) c WHERE p.id = c.project_id ORDER BY p.id DESC'''.format(user_id) results = db.engine.execute(sql) if results.rowcount == 0: raise NotFound() mapped_projects_dto = UserMappedProjectsDTO() for row in results: mapped_project = MappedProject() mapped_project.project_id = row[0] mapped_project.status = ProjectStatus(row[1]).name mapped_project.tasks_mapped = row[3] mapped_project.tasks_validated = row[4] mapped_project.centroid = geojson.loads(row[5]) project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2]) mapped_project.name = project_info.name mapped_projects_dto.mapped_projects.append(mapped_project) return mapped_projects_dto"," @staticmethod def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO: """""" Get all projects a user has mapped on """""" # This query looks scary, but we're really just creating an outer join between the query that gets the # counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to # handle cases where users have only validated tasks on a project, or only mapped on a project. sql = '''SELECT p.id, p.status, p.default_locale, c.mapped, c.validated, st_asgeojson(p.centroid) FROM projects p, (SELECT coalesce(v.project_id, m.project_id) project_id, coalesce(v.validated, 0) validated, coalesce(m.mapped, 0) mapped FROM (SELECT t.project_id, count (t.validated_by) validated FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id) AND t.validated_by = :user_id GROUP BY t.project_id, t.validated_by) v FULL OUTER JOIN (SELECT t.project_id, count(t.mapped_by) mapped FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id) AND t.mapped_by = :user_id GROUP BY t.project_id, t.mapped_by) m ON v.project_id = m.project_id) c WHERE p.id = c.project_id ORDER BY p.id DESC''' results = db.engine.execute(text(sql), user_id=user_id) if results.rowcount == 0: raise NotFound() mapped_projects_dto = UserMappedProjectsDTO() for row in results: mapped_project = MappedProject() mapped_project.project_id = row[0] mapped_project.status = ProjectStatus(row[1]).name mapped_project.tasks_mapped = row[3] mapped_project.tasks_validated = row[4] mapped_project.centroid = geojson.loads(row[5]) project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2]) mapped_project.name = project_info.name mapped_projects_dto.mapped_projects.append(mapped_project) return mapped_projects_dto","{'deleted': [{'line_no': 21, 'char_start': 1137, 'char_end': 1251, 'line': ' WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})\n'}, {'line_no': 22, 'char_start': 1251, 'char_end': 1311, 'line': ' AND t.validated_by = {0}\n'}, {'line_no': 28, 'char_start': 1570, 'char_end': 1677, 'line': ' WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})\n'}, {'line_no': 29, 'char_start': 1677, 'char_end': 1727, 'line': ' AND t.mapped_by = {0}\n'}, {'line_no': 32, 'char_start': 1850, 'char_end': 1933, 'line': "" WHERE p.id = c.project_id ORDER BY p.id DESC'''.format(user_id)\n""}, {'line_no': 34, 'char_start': 1934, 'char_end': 1975, 'line': ' results = db.engine.execute(sql)\n'}], 'added': [{'line_no': 21, 'char_start': 1137, 'char_end': 1256, 'line': ' WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)\n'}, {'line_no': 22, 'char_start': 1256, 'char_end': 1321, 'line': ' AND t.validated_by = :user_id\n'}, {'line_no': 28, 'char_start': 1580, 'char_end': 1692, 'line': ' WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)\n'}, {'line_no': 29, 'char_start': 1692, 'char_end': 1747, 'line': ' AND t.mapped_by = :user_id\n'}, {'line_no': 32, 'char_start': 1870, 'char_end': 1937, 'line': "" WHERE p.id = c.project_id ORDER BY p.id DESC'''\n""}, {'line_no': 34, 'char_start': 1938, 'char_end': 2002, 'line': ' results = db.engine.execute(text(sql), user_id=user_id)\n'}]}","{'deleted': [{'char_start': 1246, 'char_end': 1249, 'chars': '{0}'}, {'char_start': 1307, 'char_end': 1310, 'chars': '{0}'}, {'char_start': 1672, 'char_end': 1675, 'chars': '{0}'}, {'char_start': 1723, 'char_end': 1726, 'chars': '{0}'}, {'char_start': 1916, 'char_end': 1932, 'chars': '.format(user_id)'}], 'added': [{'char_start': 1246, 'char_end': 1254, 'chars': ':user_id'}, {'char_start': 1312, 'char_end': 1320, 'chars': ':user_id'}, {'char_start': 1682, 'char_end': 1690, 'chars': ':user_id'}, {'char_start': 1738, 'char_end': 1746, 'chars': ':user_id'}, {'char_start': 1974, 'char_end': 1979, 'chars': 'text('}, {'char_start': 1982, 'char_end': 2000, 'chars': '), user_id=user_id'}]}",github.com/hotosm/tasking-manager/commit/dee040a2d22b3c4d5e38e2dbf8c6b651ad4c241a,server/models/postgis/user.py,cwe-089,509 cwe-125,ssl_parse_server_psk_hint,"static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message "" ""(psk_identity_hint length)"" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message "" ""(psk_identity_hint length)"" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); }","static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message "" ""(psk_identity_hint length)"" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) > end - len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad server key exchange message "" ""(psk_identity_hint length)"" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); }","{'deleted': [{'line_no': 23, 'char_start': 646, 'char_end': 673, 'line': ' if( (*p) + len > end )\n'}], 'added': [{'line_no': 23, 'char_start': 646, 'char_end': 673, 'line': ' if( (*p) > end - len )\n'}]}","{'deleted': [{'char_start': 659, 'char_end': 660, 'chars': '+'}, {'char_start': 661, 'char_end': 662, 'chars': 'l'}, {'char_start': 665, 'char_end': 666, 'chars': '>'}, {'char_start': 669, 'char_end': 670, 'chars': 'd'}], 'added': [{'char_start': 659, 'char_end': 660, 'chars': '>'}, {'char_start': 663, 'char_end': 664, 'chars': 'd'}, {'char_start': 665, 'char_end': 666, 'chars': '-'}, {'char_start': 667, 'char_end': 668, 'chars': 'l'}]}",github.com/ARMmbed/mbedtls/commit/5224a7544c95552553e2e6be0b4a789956a6464e,library/ssl_cli.c,cwe-125,292 cwe-476,mailimf_group_parse,"static int mailimf_group_parse(const char * message, size_t length, size_t * indx, struct mailimf_group ** result) { size_t cur_token; char * display_name; struct mailimf_mailbox_list * mailbox_list; struct mailimf_group * group; int r; int res; cur_token = * indx; mailbox_list = NULL; r = mailimf_display_name_parse(message, length, &cur_token, &display_name); if (r != MAILIMF_NO_ERROR) { res = r; goto err; } r = mailimf_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_display_name; } r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list); switch (r) { case MAILIMF_NO_ERROR: break; case MAILIMF_ERROR_PARSE: r = mailimf_cfws_parse(message, length, &cur_token); if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) { res = r; goto free_display_name; } break; default: res = r; goto free_display_name; } r = mailimf_semi_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_mailbox_list; } group = mailimf_group_new(display_name, mailbox_list); if (group == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_mailbox_list; } * indx = cur_token; * result = group; return MAILIMF_NO_ERROR; free_mailbox_list: if (mailbox_list != NULL) { mailimf_mailbox_list_free(mailbox_list); } free_display_name: mailimf_display_name_free(display_name); err: return res; }","static int mailimf_group_parse(const char * message, size_t length, size_t * indx, struct mailimf_group ** result) { size_t cur_token; char * display_name; struct mailimf_mailbox_list * mailbox_list; struct mailimf_group * group; int r; int res; clist * list; cur_token = * indx; mailbox_list = NULL; r = mailimf_display_name_parse(message, length, &cur_token, &display_name); if (r != MAILIMF_NO_ERROR) { res = r; goto err; } r = mailimf_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_display_name; } r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list); switch (r) { case MAILIMF_NO_ERROR: break; case MAILIMF_ERROR_PARSE: r = mailimf_cfws_parse(message, length, &cur_token); if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) { res = r; goto free_display_name; } list = clist_new(); if (list == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_display_name; } mailbox_list = mailimf_mailbox_list_new(list); if (mailbox_list == NULL) { res = MAILIMF_ERROR_MEMORY; clist_free(list); goto free_display_name; } break; default: res = r; goto free_display_name; } r = mailimf_semi_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_mailbox_list; } group = mailimf_group_new(display_name, mailbox_list); if (group == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_mailbox_list; } * indx = cur_token; * result = group; return MAILIMF_NO_ERROR; free_mailbox_list: if (mailbox_list != NULL) { mailimf_mailbox_list_free(mailbox_list); } free_display_name: mailimf_display_name_free(display_name); err: return res; }","{'deleted': [], 'added': [{'line_no': 11, 'char_start': 278, 'char_end': 294, 'line': ' clist * list;\n'}, {'line_no': 39, 'char_start': 946, 'char_end': 970, 'line': ' list = clist_new();\n'}, {'line_no': 40, 'char_start': 970, 'char_end': 994, 'line': ' if (list == NULL) {\n'}, {'line_no': 41, 'char_start': 994, 'char_end': 1028, 'line': ' res = MAILIMF_ERROR_MEMORY;\n'}, {'line_no': 42, 'char_start': 1028, 'char_end': 1058, 'line': ' goto free_display_name;\n'}, {'line_no': 43, 'char_start': 1058, 'char_end': 1064, 'line': ' }\n'}, {'line_no': 44, 'char_start': 1064, 'char_end': 1115, 'line': ' mailbox_list = mailimf_mailbox_list_new(list);\n'}, {'line_no': 45, 'char_start': 1115, 'char_end': 1147, 'line': ' if (mailbox_list == NULL) {\n'}, {'line_no': 46, 'char_start': 1147, 'char_end': 1181, 'line': ' res = MAILIMF_ERROR_MEMORY;\n'}, {'line_no': 47, 'char_start': 1181, 'char_end': 1205, 'line': ' clist_free(list);\n'}, {'line_no': 48, 'char_start': 1205, 'char_end': 1235, 'line': ' goto free_display_name;\n'}, {'line_no': 49, 'char_start': 1235, 'char_end': 1241, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 278, 'char_end': 294, 'chars': ' clist * list;\n'}, {'char_start': 908, 'char_end': 1203, 'chars': ';\n goto free_display_name;\n }\n list = clist_new();\n if (list == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n goto free_display_name;\n }\n mailbox_list = mailimf_mailbox_list_new(list);\n if (mailbox_list == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n clist_free(list)'}]}",github.com/dinhviethoa/libetpan/commit/1fe8fbc032ccda1db9af66d93016b49c16c1f22d,src/low-level/imf/mailimf.c,cwe-476,445 cwe-089,search_films,"@app.route('/movies/search', methods=['GET', 'POST']) def search_films(): form = SearchForm() if not form.validate_on_submit(): return render_template('search.html', title='Search for films', form=form) search_terms = form.data['term'].split(' ') search_string = ' & '.join(search_terms) cur.execute(f""SELECT * FROM film where fulltext @@ to_tsquery('{search_string}')"") res = cur.fetchall() return render_template('search_results.html', title='Home', res=len(res))","@app.route('/movies/search', methods=['GET', 'POST']) def search_films(): form = SearchForm() if not form.validate_on_submit(): return render_template('search.html', title='Search for films', form=form) search_terms = form.data['term'].split(' ') search_string = ' & '.join(search_terms) cur.execute(""SELECT * FROM film where fulltext @@ to_tsquery(%s)"", (search_string, )) res = cur.fetchall() return render_template('search_results.html', title='Home', res=len(res))","{'deleted': [{'line_no': 8, 'char_start': 312, 'char_end': 399, 'line': ' cur.execute(f""SELECT * FROM film where fulltext @@ to_tsquery(\'{search_string}\')"")\n'}], 'added': [{'line_no': 8, 'char_start': 312, 'char_end': 402, 'line': ' cur.execute(""SELECT * FROM film where fulltext @@ to_tsquery(%s)"", (search_string, ))\n'}]}","{'deleted': [{'char_start': 328, 'char_end': 329, 'chars': 'f'}, {'char_start': 378, 'char_end': 380, 'chars': ""'{""}, {'char_start': 393, 'char_end': 395, 'chars': ""}'""}, {'char_start': 396, 'char_end': 397, 'chars': '""'}], 'added': [{'char_start': 377, 'char_end': 384, 'chars': '%s)"", ('}, {'char_start': 397, 'char_end': 399, 'chars': ', '}]}",github.com/Elbertbiggs360/dvdrental/commit/ad144ae2a08a332498d0831bc255170d57ba754b,app.py,cwe-089,116 cwe-078,_set_qos_rule," def _set_qos_rule(self, qos, vvs_name): max_io = self._get_qos_value(qos, 'maxIOPS') max_bw = self._get_qos_value(qos, 'maxBWS') cli_qos_string = """" if max_io is not None: cli_qos_string += ('-io %s ' % max_io) if max_bw is not None: cli_qos_string += ('-bw %sM ' % max_bw) self._cli_run('setqos %svvset:%s' % (cli_qos_string, vvs_name), None)"," def _set_qos_rule(self, qos, vvs_name): max_io = self._get_qos_value(qos, 'maxIOPS') max_bw = self._get_qos_value(qos, 'maxBWS') cli_qos_string = """" if max_io is not None: cli_qos_string += ('-io %s ' % max_io) if max_bw is not None: cli_qos_string += ('-bw %sM ' % max_bw) self._cli_run(['setqos', '%svvset:%s' % (cli_qos_string, vvs_name)])","{'deleted': [{'line_no': 9, 'char_start': 342, 'char_end': 386, 'line': "" self._cli_run('setqos %svvset:%s' %\n""}, {'line_no': 10, 'char_start': 386, 'char_end': 441, 'line': ' (cli_qos_string, vvs_name), None)\n'}], 'added': [{'line_no': 9, 'char_start': 342, 'char_end': 418, 'line': "" self._cli_run(['setqos', '%svvset:%s' % (cli_qos_string, vvs_name)])\n""}]}","{'deleted': [{'char_start': 385, 'char_end': 407, 'chars': '\n '}, {'char_start': 434, 'char_end': 440, 'chars': ', None'}], 'added': [{'char_start': 364, 'char_end': 365, 'chars': '['}, {'char_start': 372, 'char_end': 374, 'chars': ""',""}, {'char_start': 375, 'char_end': 376, 'chars': ""'""}, {'char_start': 416, 'char_end': 417, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,129 cwe-089,upsert_mapped_projects," @staticmethod def upsert_mapped_projects(user_id: int, project_id: int): """""" Adds projects to mapped_projects if it doesn't exist """""" sql = ""select * from users where id = {0} and projects_mapped @> '{{{1}}}'"".format(user_id, project_id) result = db.engine.execute(sql) if result.rowcount > 0: return # User has previously mapped this project so return sql = '''update users set projects_mapped = array_append(projects_mapped, {0}) where id = {1}'''.format(project_id, user_id) db.engine.execute(sql)"," @staticmethod def upsert_mapped_projects(user_id: int, project_id: int): """""" Adds projects to mapped_projects if it doesn't exist """""" sql = ""select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'"" result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id) if result.rowcount > 0: return # User has previously mapped this project so return sql = '''update users set projects_mapped = array_append(projects_mapped, :project_id) where id = :user_id''' db.engine.execute(text(sql), project_id=project_id, user_id=user_id)","{'deleted': [{'line_no': 4, 'char_start': 150, 'char_end': 262, 'line': ' sql = ""select * from users where id = {0} and projects_mapped @> \'{{{1}}}\'"".format(user_id, project_id)\n'}, {'line_no': 5, 'char_start': 262, 'char_end': 302, 'line': ' result = db.engine.execute(sql)\n'}, {'line_no': 11, 'char_start': 438, 'char_end': 515, 'line': ' set projects_mapped = array_append(projects_mapped, {0})\n'}, {'line_no': 12, 'char_start': 515, 'char_end': 579, 'line': "" where id = {1}'''.format(project_id, user_id)\n""}, {'line_no': 14, 'char_start': 580, 'char_end': 610, 'line': ' db.engine.execute(sql)\n'}], 'added': [{'line_no': 4, 'char_start': 150, 'char_end': 247, 'line': ' sql = ""select * from users where id = :user_id and projects_mapped @> \'{{:project_id}}\'""\n'}, {'line_no': 5, 'char_start': 247, 'char_end': 333, 'line': ' result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id)\n'}, {'line_no': 11, 'char_start': 469, 'char_end': 554, 'line': ' set projects_mapped = array_append(projects_mapped, :project_id)\n'}, {'line_no': 12, 'char_start': 554, 'char_end': 595, 'line': "" where id = :user_id'''\n""}, {'line_no': 14, 'char_start': 596, 'char_end': 672, 'line': ' db.engine.execute(text(sql), project_id=project_id, user_id=user_id)\n'}]}","{'deleted': [{'char_start': 196, 'char_end': 199, 'chars': '{0}'}, {'char_start': 226, 'char_end': 250, 'chars': '{1}}}\'"".format(user_id, '}, {'char_start': 260, 'char_end': 261, 'chars': ')'}, {'char_start': 510, 'char_end': 513, 'chars': '{0}'}, {'char_start': 544, 'char_end': 570, 'chars': ""{1}'''.format(project_id, ""}, {'char_start': 577, 'char_end': 578, 'chars': ')'}], 'added': [{'char_start': 196, 'char_end': 204, 'chars': ':user_id'}, {'char_start': 231, 'char_end': 232, 'chars': ':'}, {'char_start': 242, 'char_end': 246, 'chars': '}}\'""'}, {'char_start': 282, 'char_end': 287, 'chars': 'text('}, {'char_start': 290, 'char_end': 331, 'chars': '), user_id=user_id, project_id=project_id'}, {'char_start': 541, 'char_end': 552, 'chars': ':project_id'}, {'char_start': 583, 'char_end': 584, 'chars': ':'}, {'char_start': 591, 'char_end': 594, 'chars': ""'''""}, {'char_start': 622, 'char_end': 627, 'chars': 'text('}, {'char_start': 631, 'char_end': 672, 'chars': ', project_id=project_id, user_id=user_id)'}]}",github.com/hotosm/tasking-manager/commit/dee040a2d22b3c4d5e38e2dbf8c6b651ad4c241a,server/models/postgis/user.py,cwe-089,138 cwe-089,get_previous_yields," def get_previous_yields(self, inverter_serial): query = ''' SELECT TimeStamp, EToday, ETotal FROM Inverters WHERE Serial = '%s' ''' % (inverter_serial) self.c.execute(query) data = self.c.fetchone() return data[0], data[1], data[2]"," def get_previous_yields(self, inverter_serial): query = ''' SELECT TimeStamp, EToday, ETotal FROM Inverters WHERE Serial=? ''' self.c.execute(query, (inverter_serial,)) data = self.c.fetchone() return data[0], data[1], data[2]","{'deleted': [{'line_no': 5, 'char_start': 142, 'char_end': 173, 'line': "" WHERE Serial = '%s'\n""}, {'line_no': 6, 'char_start': 173, 'char_end': 205, 'line': "" ''' % (inverter_serial)\n""}, {'line_no': 7, 'char_start': 205, 'char_end': 235, 'line': ' self.c.execute(query)\n'}], 'added': [{'line_no': 5, 'char_start': 142, 'char_end': 168, 'line': ' WHERE Serial=?\n'}, {'line_no': 6, 'char_start': 168, 'char_end': 180, 'line': "" '''\n""}, {'line_no': 7, 'char_start': 180, 'char_end': 230, 'line': ' self.c.execute(query, (inverter_serial,))\n'}]}","{'deleted': [{'char_start': 165, 'char_end': 166, 'chars': ' '}, {'char_start': 167, 'char_end': 172, 'chars': "" '%s'""}, {'char_start': 184, 'char_end': 204, 'chars': ' % (inverter_serial)'}], 'added': [{'char_start': 166, 'char_end': 167, 'chars': '?'}, {'char_start': 208, 'char_end': 228, 'chars': ', (inverter_serial,)'}]}",github.com/philipptrenz/s0-bridge/commit/269b48caa05377b7c58c3e6d1622a4429cb5ba65,util/database.py,cwe-089,75 cwe-079,save," def save(self): # copy the user's input from plain text to description to be processed self.description = self.description_plain_text if CE.settings.auto_cross_reference: self.auto_cross_ref() else: self.find_tag() self.slug = slugify(self.title) super().save()"," def save(self): # copy the user's input from plain text to description to be processed # uses bleach to remove potentially harmful HTML code self.description = bleach.clean(str(self.description_plain_text), tags=CE.settings.bleach_allowed, strip=True) if CE.settings.auto_cross_reference: self.auto_cross_ref() else: self.find_tag() self.slug = slugify(self.title) super().save()","{'deleted': [{'line_no': 3, 'char_start': 99, 'char_end': 154, 'line': ' self.description = self.description_plain_text\n'}], 'added': [{'line_no': 4, 'char_start': 161, 'char_end': 235, 'line': ' self.description = bleach.clean(str(self.description_plain_text),\n'}, {'line_no': 5, 'char_start': 235, 'char_end': 308, 'line': ' tags=CE.settings.bleach_allowed,\n'}, {'line_no': 6, 'char_start': 308, 'char_end': 360, 'line': ' strip=True)\n'}]}","{'deleted': [], 'added': [{'char_start': 107, 'char_end': 169, 'chars': '# uses bleach to remove potentially harmful HTML code\n '}, {'char_start': 188, 'char_end': 205, 'chars': 'bleach.clean(str('}, {'char_start': 232, 'char_end': 359, 'chars': '),\n tags=CE.settings.bleach_allowed,\n strip=True)'}]}",github.com/stevetasticsteve/CLA_Hub/commit/a06d85cd0b0964f8469e5c4bc9a6c132aa0b4c37,CE/models.py,cwe-079,66 cwe-089,shame_add,"def shame_add(name): shame = shame_ask(name) db = db_connect() cursor = db.cursor() if shame is None: try: cursor.execute(''' INSERT INTO people(name,karma,shame) VALUES('{}',0,1) '''.format(name)) db.commit() logger.debug('Inserted into karmadb 1 shame for {}'.format(name)) db.close() return 1 except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise else: shame = shame + 1 try: cursor.execute(''' UPDATE people SET shame = {0} WHERE name = '{1}' '''.format(shame, name)) db.commit() logger.debug('Inserted into karmadb {} shame for {}'.format( shame, name)) db.close() return shame except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","def shame_add(name): shame = shame_ask(name) db = db_connect() cursor = db.cursor() if shame is None: try: cursor.execute(''' INSERT INTO people(name,karma,shame) VALUES(%(name)s,0,1) ''', (name, )) db.commit() logger.debug('Inserted into karmadb 1 shame for {}'.format(name)) db.close() return 1 except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise else: shame = shame + 1 try: cursor.execute(''' UPDATE people SET shame = %(karma)s WHERE name = %(name)s ''' ( shame, name, )) db.commit() logger.debug('Inserted into karmadb {} shame for {}'.format( shame, name)) db.close() return shame except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","{'deleted': [{'line_no': 8, 'char_start': 162, 'char_end': 232, 'line': "" INSERT INTO people(name,karma,shame) VALUES('{}',0,1)\n""}, {'line_no': 9, 'char_start': 232, 'char_end': 266, 'line': "" '''.format(name))\n""}, {'line_no': 22, 'char_start': 612, 'char_end': 677, 'line': "" UPDATE people SET shame = {0} WHERE name = '{1}'\n""}, {'line_no': 23, 'char_start': 677, 'char_end': 718, 'line': "" '''.format(shame, name))\n""}], 'added': [{'line_no': 8, 'char_start': 162, 'char_end': 236, 'line': ' INSERT INTO people(name,karma,shame) VALUES(%(name)s,0,1)\n'}, {'line_no': 9, 'char_start': 236, 'char_end': 267, 'line': "" ''', (name, ))\n""}, {'line_no': 22, 'char_start': 613, 'char_end': 687, 'line': ' UPDATE people SET shame = %(karma)s WHERE name = %(name)s\n'}, {'line_no': 23, 'char_start': 687, 'char_end': 709, 'line': "" ''' (\n""}, {'line_no': 24, 'char_start': 709, 'char_end': 732, 'line': ' shame,\n'}, {'line_no': 25, 'char_start': 732, 'char_end': 754, 'line': ' name,\n'}, {'line_no': 26, 'char_start': 754, 'char_end': 769, 'line': ' ))\n'}]}","{'deleted': [{'char_start': 222, 'char_end': 226, 'chars': ""'{}'""}, {'char_start': 251, 'char_end': 258, 'chars': '.format'}, {'char_start': 654, 'char_end': 657, 'chars': '{0}'}, {'char_start': 671, 'char_end': 676, 'chars': ""'{1}'""}, {'char_start': 696, 'char_end': 703, 'chars': '.format'}], 'added': [{'char_start': 222, 'char_end': 230, 'chars': '%(name)s'}, {'char_start': 255, 'char_end': 257, 'chars': ', '}, {'char_start': 262, 'char_end': 264, 'chars': ', '}, {'char_start': 655, 'char_end': 664, 'chars': '%(karma)s'}, {'char_start': 678, 'char_end': 686, 'chars': '%(name)s'}, {'char_start': 706, 'char_end': 707, 'chars': ' '}, {'char_start': 708, 'char_end': 725, 'chars': '\n '}, {'char_start': 731, 'char_end': 747, 'chars': '\n '}, {'char_start': 752, 'char_end': 766, 'chars': ',\n '}]}",github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a,KarmaBoi/dbopts.py,cwe-089,210 cwe-078,_make_fc_map," def _make_fc_map(self, source, target, full_copy): copyflag = '' if full_copy else '-copyrate 0' fc_map_cli_cmd = ('svctask mkfcmap -source %(src)s -target %(tgt)s ' '-autodelete %(copyflag)s' % {'src': source, 'tgt': target, 'copyflag': copyflag}) out, err = self._run_ssh(fc_map_cli_cmd) self._driver_assert( len(out.strip()), _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) # Ensure that the output is as expected match_obj = re.search('FlashCopy Mapping, id \[([0-9]+)\], ' 'successfully created', out) # Make sure we got a ""successfully created"" message with vdisk id self._driver_assert( match_obj is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) try: fc_map_id = match_obj.group(1) self._driver_assert( fc_map_id is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) except IndexError: self._driver_assert( False, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) return fc_map_id"," def _make_fc_map(self, source, target, full_copy): fc_map_cli_cmd = ['svctask', 'mkfcmap', '-source', source, '-target', target, '-autodelete'] if not full_copy: fc_map_cli_cmd.extend(['-copyrate', '0']) out, err = self._run_ssh(fc_map_cli_cmd) self._driver_assert( len(out.strip()), _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) # Ensure that the output is as expected match_obj = re.search('FlashCopy Mapping, id \[([0-9]+)\], ' 'successfully created', out) # Make sure we got a ""successfully created"" message with vdisk id self._driver_assert( match_obj is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find success message in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) try: fc_map_id = match_obj.group(1) self._driver_assert( fc_map_id is not None, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) except IndexError: self._driver_assert( False, _('create FC mapping from %(source)s to %(target)s - ' 'did not find mapping id in CLI output.\n' ' stdout: %(out)s\n stderr: %(err)s\n') % {'source': source, 'target': target, 'out': str(out), 'err': str(err)}) return fc_map_id","{'deleted': [{'line_no': 2, 'char_start': 55, 'char_end': 109, 'line': "" copyflag = '' if full_copy else '-copyrate 0'\n""}, {'line_no': 3, 'char_start': 109, 'char_end': 186, 'line': "" fc_map_cli_cmd = ('svctask mkfcmap -source %(src)s -target %(tgt)s '\n""}, {'line_no': 4, 'char_start': 186, 'char_end': 241, 'line': "" '-autodelete %(copyflag)s' %\n""}, {'line_no': 5, 'char_start': 241, 'char_end': 283, 'line': "" {'src': source,\n""}, {'line_no': 6, 'char_start': 283, 'char_end': 325, 'line': "" 'tgt': target,\n""}, {'line_no': 7, 'char_start': 325, 'char_end': 375, 'line': "" 'copyflag': copyflag})\n""}], 'added': [{'line_no': 2, 'char_start': 55, 'char_end': 133, 'line': "" fc_map_cli_cmd = ['svctask', 'mkfcmap', '-source', source, '-target',\n""}, {'line_no': 3, 'char_start': 133, 'char_end': 182, 'line': "" target, '-autodelete']\n""}, {'line_no': 4, 'char_start': 182, 'char_end': 208, 'line': ' if not full_copy:\n'}, {'line_no': 5, 'char_start': 208, 'char_end': 262, 'line': "" fc_map_cli_cmd.extend(['-copyrate', '0'])\n""}]}","{'deleted': [{'char_start': 63, 'char_end': 117, 'chars': ""copyflag = '' if full_copy else '-copyrate 0'\n ""}, {'char_start': 134, 'char_end': 135, 'chars': '('}, {'char_start': 160, 'char_end': 162, 'chars': '%('}, {'char_start': 165, 'char_end': 167, 'chars': ')s'}, {'char_start': 175, 'char_end': 184, 'chars': ' %(tgt)s '}, {'char_start': 224, 'char_end': 237, 'chars': ' %(copyflag)s'}, {'char_start': 238, 'char_end': 240, 'chars': ' %'}, {'char_start': 241, 'char_end': 242, 'chars': ' '}, {'char_start': 252, 'char_end': 271, 'chars': "" {'sr""}, {'char_start': 272, 'char_end': 273, 'chars': ""'""}, {'char_start': 274, 'char_end': 282, 'chars': ' source,'}, {'char_start': 295, 'char_end': 318, 'chars': "" 'tgt': t""}, {'char_start': 319, 'char_end': 321, 'chars': 'rg'}, {'char_start': 323, 'char_end': 352, 'chars': ',\n '}, {'char_start': 357, 'char_end': 359, 'chars': 'fl'}, {'char_start': 360, 'char_end': 361, 'chars': 'g'}, {'char_start': 362, 'char_end': 363, 'chars': ':'}, {'char_start': 364, 'char_end': 373, 'chars': 'copyflag}'}], 'added': [{'char_start': 80, 'char_end': 81, 'chars': '['}, {'char_start': 89, 'char_end': 91, 'chars': ""',""}, {'char_start': 92, 'char_end': 93, 'chars': ""'""}, {'char_start': 100, 'char_end': 102, 'chars': ""',""}, {'char_start': 103, 'char_end': 104, 'chars': ""'""}, {'char_start': 111, 'char_end': 113, 'chars': ""',""}, {'char_start': 115, 'char_end': 117, 'chars': 'ou'}, {'char_start': 119, 'char_end': 121, 'chars': 'e,'}, {'char_start': 122, 'char_end': 123, 'chars': ""'""}, {'char_start': 131, 'char_end': 132, 'chars': ','}, {'char_start': 159, 'char_end': 167, 'chars': 'target, '}, {'char_start': 180, 'char_end': 181, 'chars': ']'}, {'char_start': 190, 'char_end': 192, 'chars': 'if'}, {'char_start': 193, 'char_end': 196, 'chars': 'not'}, {'char_start': 197, 'char_end': 198, 'chars': 'f'}, {'char_start': 199, 'char_end': 202, 'chars': 'll_'}, {'char_start': 203, 'char_end': 207, 'chars': 'opy:'}, {'char_start': 220, 'char_end': 224, 'chars': 'fc_m'}, {'char_start': 225, 'char_end': 235, 'chars': 'p_cli_cmd.'}, {'char_start': 236, 'char_end': 237, 'chars': 'x'}, {'char_start': 238, 'char_end': 243, 'chars': 'end(['}, {'char_start': 244, 'char_end': 245, 'chars': '-'}, {'char_start': 249, 'char_end': 250, 'chars': 'r'}, {'char_start': 251, 'char_end': 253, 'chars': 'te'}, {'char_start': 254, 'char_end': 255, 'chars': ','}, {'char_start': 256, 'char_end': 260, 'chars': ""'0']""}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,507 cwe-022,nntp_hcache_namer,"static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { return snprintf(dest, destlen, ""%s.hcache"", path); }","static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { int count = snprintf(dest, destlen, ""%s.hcache"", path); /* Strip out any directories in the path */ char *first = strchr(dest, '/'); char *last = strrchr(dest, '/'); if (first && last && (last > first)) { memmove(first, last, strlen(last) + 1); count -= (last - first); } return count; }","{'deleted': [{'line_no': 3, 'char_start': 77, 'char_end': 130, 'line': ' return snprintf(dest, destlen, ""%s.hcache"", path);\n'}], 'added': [{'line_no': 3, 'char_start': 77, 'char_end': 135, 'line': ' int count = snprintf(dest, destlen, ""%s.hcache"", path);\n'}, {'line_no': 4, 'char_start': 135, 'char_end': 136, 'line': '\n'}, {'line_no': 5, 'char_start': 136, 'char_end': 182, 'line': ' /* Strip out any directories in the path */\n'}, {'line_no': 6, 'char_start': 182, 'char_end': 217, 'line': "" char *first = strchr(dest, '/');\n""}, {'line_no': 7, 'char_start': 217, 'char_end': 252, 'line': "" char *last = strrchr(dest, '/');\n""}, {'line_no': 8, 'char_start': 252, 'char_end': 291, 'line': ' if (first && last && (last > first))\n'}, {'line_no': 9, 'char_start': 291, 'char_end': 295, 'line': ' {\n'}, {'line_no': 10, 'char_start': 295, 'char_end': 339, 'line': ' memmove(first, last, strlen(last) + 1);\n'}, {'line_no': 11, 'char_start': 339, 'char_end': 368, 'line': ' count -= (last - first);\n'}, {'line_no': 12, 'char_start': 368, 'char_end': 372, 'line': ' }\n'}, {'line_no': 13, 'char_start': 372, 'char_end': 373, 'line': '\n'}, {'line_no': 14, 'char_start': 373, 'char_end': 389, 'line': ' return count;\n'}]}","{'deleted': [{'char_start': 79, 'char_end': 81, 'chars': 're'}, {'char_start': 83, 'char_end': 84, 'chars': 'r'}], 'added': [{'char_start': 79, 'char_end': 81, 'chars': 'in'}, {'char_start': 82, 'char_end': 85, 'chars': ' co'}, {'char_start': 87, 'char_end': 90, 'chars': 't ='}, {'char_start': 133, 'char_end': 387, 'chars': "";\n\n /* Strip out any directories in the path */\n char *first = strchr(dest, '/');\n char *last = strrchr(dest, '/');\n if (first && last && (last > first))\n {\n memmove(first, last, strlen(last) + 1);\n count -= (last - first);\n }\n\n return count""}]}",github.com/neomutt/neomutt/commit/9bfab35522301794483f8f9ed60820bdec9be59e,newsrc.c,cwe-022,39 cwe-416,do_mq_notify,"static int do_mq_notify(mqd_t mqdes, const struct sigevent *notification) { int ret; struct fd f; struct sock *sock; struct inode *inode; struct mqueue_inode_info *info; struct sk_buff *nc; audit_mq_notify(mqdes, notification); nc = NULL; sock = NULL; if (notification != NULL) { if (unlikely(notification->sigev_notify != SIGEV_NONE && notification->sigev_notify != SIGEV_SIGNAL && notification->sigev_notify != SIGEV_THREAD)) return -EINVAL; if (notification->sigev_notify == SIGEV_SIGNAL && !valid_signal(notification->sigev_signo)) { return -EINVAL; } if (notification->sigev_notify == SIGEV_THREAD) { long timeo; /* create the notify skb */ nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL); if (!nc) { ret = -ENOMEM; goto out; } if (copy_from_user(nc->data, notification->sigev_value.sival_ptr, NOTIFY_COOKIE_LEN)) { ret = -EFAULT; goto out; } /* TODO: add a header? */ skb_put(nc, NOTIFY_COOKIE_LEN); /* and attach it to the socket */ retry: f = fdget(notification->sigev_signo); if (!f.file) { ret = -EBADF; goto out; } sock = netlink_getsockbyfilp(f.file); fdput(f); if (IS_ERR(sock)) { ret = PTR_ERR(sock); sock = NULL; goto out; } timeo = MAX_SCHEDULE_TIMEOUT; ret = netlink_attachskb(sock, nc, &timeo, NULL); if (ret == 1) goto retry; if (ret) { sock = NULL; nc = NULL; goto out; } } } f = fdget(mqdes); if (!f.file) { ret = -EBADF; goto out; } inode = file_inode(f.file); if (unlikely(f.file->f_op != &mqueue_file_operations)) { ret = -EBADF; goto out_fput; } info = MQUEUE_I(inode); ret = 0; spin_lock(&info->lock); if (notification == NULL) { if (info->notify_owner == task_tgid(current)) { remove_notification(info); inode->i_atime = inode->i_ctime = current_time(inode); } } else if (info->notify_owner != NULL) { ret = -EBUSY; } else { switch (notification->sigev_notify) { case SIGEV_NONE: info->notify.sigev_notify = SIGEV_NONE; break; case SIGEV_THREAD: info->notify_sock = sock; info->notify_cookie = nc; sock = NULL; nc = NULL; info->notify.sigev_notify = SIGEV_THREAD; break; case SIGEV_SIGNAL: info->notify.sigev_signo = notification->sigev_signo; info->notify.sigev_value = notification->sigev_value; info->notify.sigev_notify = SIGEV_SIGNAL; break; } info->notify_owner = get_pid(task_tgid(current)); info->notify_user_ns = get_user_ns(current_user_ns()); inode->i_atime = inode->i_ctime = current_time(inode); } spin_unlock(&info->lock); out_fput: fdput(f); out: if (sock) netlink_detachskb(sock, nc); else if (nc) dev_kfree_skb(nc); return ret; }","static int do_mq_notify(mqd_t mqdes, const struct sigevent *notification) { int ret; struct fd f; struct sock *sock; struct inode *inode; struct mqueue_inode_info *info; struct sk_buff *nc; audit_mq_notify(mqdes, notification); nc = NULL; sock = NULL; if (notification != NULL) { if (unlikely(notification->sigev_notify != SIGEV_NONE && notification->sigev_notify != SIGEV_SIGNAL && notification->sigev_notify != SIGEV_THREAD)) return -EINVAL; if (notification->sigev_notify == SIGEV_SIGNAL && !valid_signal(notification->sigev_signo)) { return -EINVAL; } if (notification->sigev_notify == SIGEV_THREAD) { long timeo; /* create the notify skb */ nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL); if (!nc) { ret = -ENOMEM; goto out; } if (copy_from_user(nc->data, notification->sigev_value.sival_ptr, NOTIFY_COOKIE_LEN)) { ret = -EFAULT; goto out; } /* TODO: add a header? */ skb_put(nc, NOTIFY_COOKIE_LEN); /* and attach it to the socket */ retry: f = fdget(notification->sigev_signo); if (!f.file) { ret = -EBADF; goto out; } sock = netlink_getsockbyfilp(f.file); fdput(f); if (IS_ERR(sock)) { ret = PTR_ERR(sock); sock = NULL; goto out; } timeo = MAX_SCHEDULE_TIMEOUT; ret = netlink_attachskb(sock, nc, &timeo, NULL); if (ret == 1) { sock = NULL; goto retry; } if (ret) { sock = NULL; nc = NULL; goto out; } } } f = fdget(mqdes); if (!f.file) { ret = -EBADF; goto out; } inode = file_inode(f.file); if (unlikely(f.file->f_op != &mqueue_file_operations)) { ret = -EBADF; goto out_fput; } info = MQUEUE_I(inode); ret = 0; spin_lock(&info->lock); if (notification == NULL) { if (info->notify_owner == task_tgid(current)) { remove_notification(info); inode->i_atime = inode->i_ctime = current_time(inode); } } else if (info->notify_owner != NULL) { ret = -EBUSY; } else { switch (notification->sigev_notify) { case SIGEV_NONE: info->notify.sigev_notify = SIGEV_NONE; break; case SIGEV_THREAD: info->notify_sock = sock; info->notify_cookie = nc; sock = NULL; nc = NULL; info->notify.sigev_notify = SIGEV_THREAD; break; case SIGEV_SIGNAL: info->notify.sigev_signo = notification->sigev_signo; info->notify.sigev_value = notification->sigev_value; info->notify.sigev_notify = SIGEV_SIGNAL; break; } info->notify_owner = get_pid(task_tgid(current)); info->notify_user_ns = get_user_ns(current_user_ns()); inode->i_atime = inode->i_ctime = current_time(inode); } spin_unlock(&info->lock); out_fput: fdput(f); out: if (sock) netlink_detachskb(sock, nc); else if (nc) dev_kfree_skb(nc); return ret; }","{'deleted': [{'line_no': 58, 'char_start': 1368, 'char_end': 1385, 'line': '\t\t\tif (ret == 1)\n'}], 'added': [{'line_no': 58, 'char_start': 1368, 'char_end': 1387, 'line': '\t\t\tif (ret == 1) {\n'}, {'line_no': 59, 'char_start': 1387, 'char_end': 1404, 'line': '\t\t\t\tsock = NULL;\n'}, {'line_no': 61, 'char_start': 1420, 'char_end': 1425, 'line': '\t\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 1384, 'char_end': 1403, 'chars': ' {\n\t\t\t\tsock = NULL;'}, {'char_start': 1419, 'char_end': 1424, 'chars': '\n\t\t\t}'}]}",github.com/torvalds/linux/commit/f991af3daabaecff34684fd51fac80319d1baad1,ipc/mqueue.c,cwe-416,815 cwe-078,install,"def install(filename, target): '''Run a package's installer script against the given target directory.''' print(' Unpacking %s...' % filename) os.system('tar xf ' + filename) basename = filename.split('.tar')[0] print(' Installing %s...' % basename) install_opts = '--prefix=${PWD}/%s --disable-ldconfig' % target os.system('%s/install.sh %s' % (basename, install_opts)) print(' Cleaning %s...' % basename) os.system('rm -rf %s' % basename)","def install(filename, target): '''Run a package's installer script against the given target directory.''' print(' Unpacking %s...' % filename) subprocess.check_call(['tar', 'xf', filename]) basename = filename.split('.tar')[0] print(' Installing %s...' % basename) install_cmd = [os.path.join(basename, 'install.sh')] install_cmd += ['--prefix=' + os.path.abspath(target)] install_cmd += ['--disable-ldconfig'] subprocess.check_call(install_cmd) print(' Cleaning %s...' % basename) subprocess.check_call(['rm', '-rf', basename])","{'deleted': [{'line_no': 4, 'char_start': 147, 'char_end': 181, 'line': "" os.system('tar xf ' + filename)\n""}, {'line_no': 7, 'char_start': 260, 'char_end': 326, 'line': "" install_opts = '--prefix=${PWD}/%s --disable-ldconfig' % target\n""}, {'line_no': 8, 'char_start': 326, 'char_end': 385, 'line': "" os.system('%s/install.sh %s' % (basename, install_opts))\n""}, {'line_no': 10, 'char_start': 423, 'char_end': 458, 'line': "" os.system('rm -rf %s' % basename)\n""}], 'added': [{'line_no': 4, 'char_start': 147, 'char_end': 196, 'line': "" subprocess.check_call(['tar', 'xf', filename])\n""}, {'line_no': 7, 'char_start': 275, 'char_end': 330, 'line': "" install_cmd = [os.path.join(basename, 'install.sh')]\n""}, {'line_no': 8, 'char_start': 330, 'char_end': 387, 'line': "" install_cmd += ['--prefix=' + os.path.abspath(target)]\n""}, {'line_no': 9, 'char_start': 387, 'char_end': 427, 'line': "" install_cmd += ['--disable-ldconfig']\n""}, {'line_no': 10, 'char_start': 427, 'char_end': 464, 'line': ' subprocess.check_call(install_cmd)\n'}, {'line_no': 12, 'char_start': 502, 'char_end': 550, 'line': "" subprocess.check_call(['rm', '-rf', basename])\n""}]}","{'deleted': [{'char_start': 149, 'char_end': 150, 'chars': 'o'}, {'char_start': 151, 'char_end': 152, 'chars': '.'}, {'char_start': 153, 'char_end': 154, 'chars': 'y'}, {'char_start': 155, 'char_end': 156, 'chars': 't'}, {'char_start': 157, 'char_end': 158, 'chars': 'm'}, {'char_start': 166, 'char_end': 167, 'chars': ' '}, {'char_start': 168, 'char_end': 170, 'chars': ' +'}, {'char_start': 287, 'char_end': 295, 'chars': '${PWD}/%'}, {'char_start': 317, 'char_end': 318, 'chars': '%'}, {'char_start': 319, 'char_end': 321, 'chars': 'ta'}, {'char_start': 322, 'char_end': 328, 'chars': 'get\n '}, {'char_start': 329, 'char_end': 335, 'chars': 's.syst'}, {'char_start': 336, 'char_end': 340, 'chars': ""m('%""}, {'char_start': 341, 'char_end': 344, 'chars': '/in'}, {'char_start': 345, 'char_end': 349, 'chars': 'tall'}, {'char_start': 350, 'char_end': 351, 'chars': 's'}, {'char_start': 352, 'char_end': 363, 'chars': "" %s' % (bas""}, {'char_start': 364, 'char_end': 365, 'chars': 'n'}, {'char_start': 366, 'char_end': 370, 'chars': 'me, '}, {'char_start': 378, 'char_end': 383, 'chars': 'opts)'}, {'char_start': 426, 'char_end': 428, 'chars': 's.'}, {'char_start': 429, 'char_end': 430, 'chars': 'y'}, {'char_start': 431, 'char_end': 432, 'chars': 't'}, {'char_start': 433, 'char_end': 434, 'chars': 'm'}, {'char_start': 442, 'char_end': 445, 'chars': ' %s'}, {'char_start': 446, 'char_end': 448, 'chars': ' %'}], 'added': [{'char_start': 149, 'char_end': 154, 'chars': 'subpr'}, {'char_start': 155, 'char_end': 158, 'chars': 'ces'}, {'char_start': 160, 'char_end': 162, 'chars': 'ch'}, {'char_start': 163, 'char_end': 170, 'chars': 'ck_call'}, {'char_start': 171, 'char_end': 172, 'chars': '['}, {'char_start': 176, 'char_end': 178, 'chars': ""',""}, {'char_start': 179, 'char_end': 180, 'chars': ""'""}, {'char_start': 183, 'char_end': 184, 'chars': ','}, {'char_start': 193, 'char_end': 194, 'chars': ']'}, {'char_start': 285, 'char_end': 292, 'chars': 'cmd = ['}, {'char_start': 293, 'char_end': 295, 'chars': 's.'}, {'char_start': 296, 'char_end': 297, 'chars': 'a'}, {'char_start': 298, 'char_end': 307, 'chars': 'h.join(ba'}, {'char_start': 308, 'char_end': 314, 'chars': 'ename,'}, {'char_start': 315, 'char_end': 345, 'chars': ""'install.sh')]\n install_cmd +""}, {'char_start': 347, 'char_end': 348, 'chars': '['}, {'char_start': 358, 'char_end': 391, 'chars': ""' + os.path.abspath(target)]\n in""}, {'char_start': 392, 'char_end': 400, 'chars': 'tall_cmd'}, {'char_start': 401, 'char_end': 406, 'chars': ""+= ['""}, {'char_start': 425, 'char_end': 427, 'chars': ']\n'}, {'char_start': 429, 'char_end': 433, 'chars': 'subp'}, {'char_start': 435, 'char_end': 438, 'chars': 'ces'}, {'char_start': 440, 'char_end': 442, 'chars': 'ch'}, {'char_start': 443, 'char_end': 447, 'chars': 'ck_c'}, {'char_start': 459, 'char_end': 462, 'chars': 'cmd'}, {'char_start': 504, 'char_end': 509, 'chars': 'subpr'}, {'char_start': 510, 'char_end': 512, 'chars': 'ce'}, {'char_start': 514, 'char_end': 517, 'chars': '.ch'}, {'char_start': 518, 'char_end': 525, 'chars': 'ck_call'}, {'char_start': 526, 'char_end': 527, 'chars': '['}, {'char_start': 530, 'char_end': 532, 'chars': ""',""}, {'char_start': 533, 'char_end': 534, 'chars': ""'""}, {'char_start': 538, 'char_end': 539, 'chars': ','}, {'char_start': 548, 'char_end': 549, 'chars': ']'}]}",github.com/rillian/rust-build/commit/b8af51e5811fcb35eff9e1e3e91c98490e7a7dcb,repack_rust.py,cwe-078,121 cwe-089,update_user,"def update_user(username, chat_id, last_update): conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\users\\"" + username + '.db') conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\cf.db') settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") cursor = conn.cursor() cursor2 = conn2.cursor() cursor_settings = settings.cursor() cursor_settings.execute(""select last_problem from users where chat_id = '"" + str(chat_id) + ""'"") update_eq = cursor_settings.fetchone() cursor_settings.execute(""select * from last_update_problemset"") update_base = cursor_settings.fetchone() last_problem = update_base[0] if update_eq[0] != update_base[0]: cursor2.execute(""SELECT * FROM problems"") x = cursor2.fetchone() while x != None: cursor.execute(""select * from result where problem = '"" + str(x[0]) + ""' and diff = '"" + str(x[1]) + ""'"") x2 = cursor.fetchone() if x2 == None: cursor.execute(""insert into result values (?, ?, ? )"", (x[0], x[1], ""NULL"")) last_problem = x x = cursor2.fetchone() conn2.close() settings.close() if len(last_problem) == 2: last_problem = last_problem[0] + last_problem[1] url = 'http://codeforces.com/submissions/' + username r = requests.get(url) max_page = 1 soup = BeautifulSoup(r.text, ""lxml"") for link in soup.find_all(attrs={""class"": ""page-index""}): s = link.find('a') s2 = s.get(""href"").split('/') max_page = max(max_page, int(s2[4])) v = False r = requests.get('http://codeforces.com/submissions/' + username + '/page/0') soup = BeautifulSoup(r.text, ""lxml"") last_try_new = soup.find(attrs={""class"": ""status-small""}) last_try_new = str(last_try_new).split() last_try_new = str(last_try_new[2]) + str(last_try_new[3]) for i in range(1, max_page + 1): r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i)) soup = BeautifulSoup(r.text, ""lxml"") count = 0 j = 0 ver = soup.find_all(attrs={""class"": ""submissionVerdictWrapper""}) last_try = soup.find_all(attrs={""class"": ""status-small""}) for link in soup.find_all('a'): last_try_date = str(last_try[j]).split() last_try_date = str(last_try_date[2]) + str(last_try_date[3]) if last_try_date == last_update: v = True break s = link.get('href') if s != None and s.find('/problemset') != -1: s = s.split('/') if len(s) == 5: s2 = str(ver[count]).split() s2 = s2[5].split('\""') count += 1 j += 1 cursor.execute(""select * from result where problem = '"" + s[3] + ""'and diff = '"" + s[4] + ""'"") x = cursor.fetchone() if s2[1] == 'OK' and x != None: cursor.execute( ""update result set verdict = '"" + s2[1] + ""' where problem = '"" + s[3] + ""' and diff = '"" + s[4] + ""'"") if x[2] != 'OK': cursor.execute( ""update result set verdict = '"" + s2[1] + ""' where problem = '"" + s[3] + ""' and diff = '"" + s[4] + ""'"") if v: break conn.commit() conn.close() settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") conn = settings.cursor() conn.execute(""update users set username = '"" + str(username) + ""' where chat_id = '"" + str(chat_id) + ""'"") conn.execute(""update users set last_update = '"" + str(last_try_new) + ""' where chat_id = '"" + str(chat_id) + ""'"") conn.execute(""update users set last_problem = '"" + str(last_problem) + ""' where chat_id = '"" + str(chat_id) + ""'"") settings.commit() settings.close()","def update_user(username, chat_id, last_update): conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\users\\"" + username + '.db') conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\cf.db') settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") cursor = conn.cursor() cursor2 = conn2.cursor() cursor_settings = settings.cursor() cursor_settings.execute(""select last_problem from users where chat_id = ?"", (str(chat_id), )) update_eq = cursor_settings.fetchone() cursor_settings.execute(""select * from last_update_problemset"") update_base = cursor_settings.fetchone() last_problem = update_base[0] if update_eq[0] != update_base[0]: cursor2.execute(""SELECT * FROM problems"") x = cursor2.fetchone() while x != None: cursor.execute(""select * from result where problem = ? and diff = ?"", (str(x[0]), str(x[1]))) x2 = cursor.fetchone() if x2 == None: cursor.execute(""insert into result values (?, ?, ? )"", (x[0], x[1], ""NULL"")) last_problem = x x = cursor2.fetchone() conn2.close() settings.close() if len(last_problem) == 2: last_problem = last_problem[0] + last_problem[1] url = 'http://codeforces.com/submissions/' + username r = requests.get(url) max_page = 1 soup = BeautifulSoup(r.text, ""lxml"") for link in soup.find_all(attrs={""class"": ""page-index""}): s = link.find('a') s2 = s.get(""href"").split('/') max_page = max(max_page, int(s2[4])) v = False r = requests.get('http://codeforces.com/submissions/' + username + '/page/0') soup = BeautifulSoup(r.text, ""lxml"") last_try_new = soup.find(attrs={""class"": ""status-small""}) last_try_new = str(last_try_new).split() last_try_new = str(last_try_new[2]) + str(last_try_new[3]) for i in range(1, max_page + 1): r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i)) soup = BeautifulSoup(r.text, ""lxml"") count = 0 j = 0 ver = soup.find_all(attrs={""class"": ""submissionVerdictWrapper""}) last_try = soup.find_all(attrs={""class"": ""status-small""}) for link in soup.find_all('a'): last_try_date = str(last_try[j]).split() last_try_date = str(last_try_date[2]) + str(last_try_date[3]) if last_try_date == last_update: v = True break s = link.get('href') if s != None and s.find('/problemset') != -1: s = s.split('/') if len(s) == 5: s2 = str(ver[count]).split() s2 = s2[5].split('\""') count += 1 j += 1 cursor.execute(""select * from result where problem = ? and diff = ?"", (s[3], s[4])) x = cursor.fetchone() if s2[1] == 'OK' and x != None: cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4])) if x[2] != 'OK': cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4])) if v: break conn.commit() conn.close() settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") conn = settings.cursor() conn.execute(""update users set username = ? where chat_id = ?"", (str(username), str(chat_id))) conn.execute(""update users set last_update = ? where chat_id = ?"", (str(last_try_new), str(chat_id))) conn.execute(""update users set last_problem = ? where chat_id = ?"", (str(last_problem), str(chat_id))) settings.commit() settings.close()","{'deleted': [{'line_no': 8, 'char_start': 426, 'char_end': 527, 'line': ' cursor_settings.execute(""select last_problem from users where chat_id = \'"" + str(chat_id) + ""\'"")\n'}, {'line_no': 17, 'char_start': 862, 'char_end': 980, 'line': ' cursor.execute(""select * from result where problem = \'"" + str(x[0]) + ""\' and diff = \'"" + str(x[1]) + ""\'"")\n'}, {'line_no': 65, 'char_start': 2870, 'char_end': 2985, 'line': ' cursor.execute(""select * from result where problem = \'"" + s[3] + ""\'and diff = \'"" + s[4] + ""\'"")\n'}, {'line_no': 68, 'char_start': 3079, 'char_end': 3119, 'line': ' cursor.execute(\n'}, {'line_no': 69, 'char_start': 3119, 'char_end': 3239, 'line': ' ""update result set verdict = \'"" + s2[1] + ""\' where problem = \'"" + s[3] + ""\' and diff = \'"" +\n'}, {'line_no': 70, 'char_start': 3239, 'char_end': 3279, 'line': ' s[4] + ""\'"")\n'}, {'line_no': 72, 'char_start': 3316, 'char_end': 3356, 'line': ' cursor.execute(\n'}, {'line_no': 73, 'char_start': 3356, 'char_end': 3476, 'line': ' ""update result set verdict = \'"" + s2[1] + ""\' where problem = \'"" + s[3] + ""\' and diff = \'"" +\n'}, {'line_no': 74, 'char_start': 3476, 'char_end': 3516, 'line': ' s[4] + ""\'"")\n'}, {'line_no': 83, 'char_start': 3707, 'char_end': 3818, 'line': ' conn.execute(""update users set username = \'"" + str(username) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}, {'line_no': 84, 'char_start': 3818, 'char_end': 3936, 'line': ' conn.execute(""update users set last_update = \'"" + str(last_try_new) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}, {'line_no': 85, 'char_start': 3936, 'char_end': 4055, 'line': ' conn.execute(""update users set last_problem = \'"" + str(last_problem) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}], 'added': [{'line_no': 8, 'char_start': 426, 'char_end': 524, 'line': ' cursor_settings.execute(""select last_problem from users where chat_id = ?"", (str(chat_id), ))\n'}, {'line_no': 17, 'char_start': 859, 'char_end': 965, 'line': ' cursor.execute(""select * from result where problem = ? and diff = ?"", (str(x[0]), str(x[1])))\n'}, {'line_no': 65, 'char_start': 2855, 'char_end': 2959, 'line': ' cursor.execute(""select * from result where problem = ? and diff = ?"", (s[3], s[4]))\n'}, {'line_no': 68, 'char_start': 3053, 'char_end': 3177, 'line': ' cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4]))\n'}, {'line_no': 70, 'char_start': 3214, 'char_end': 3338, 'line': ' cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4]))\n'}, {'line_no': 79, 'char_start': 3529, 'char_end': 3628, 'line': ' conn.execute(""update users set username = ? where chat_id = ?"", (str(username), str(chat_id)))\n'}, {'line_no': 80, 'char_start': 3628, 'char_end': 3734, 'line': ' conn.execute(""update users set last_update = ? where chat_id = ?"", (str(last_try_new), str(chat_id)))\n'}, {'line_no': 81, 'char_start': 3734, 'char_end': 3841, 'line': ' conn.execute(""update users set last_problem = ? where chat_id = ?"", (str(last_problem), str(chat_id)))\n'}]}","{'deleted': [{'char_start': 502, 'char_end': 503, 'chars': ""'""}, {'char_start': 504, 'char_end': 506, 'chars': ' +'}, {'char_start': 519, 'char_end': 521, 'chars': ' +'}, {'char_start': 522, 'char_end': 525, 'chars': '""\'""'}, {'char_start': 927, 'char_end': 946, 'chars': '\'"" + str(x[0]) + ""\''}, {'char_start': 958, 'char_end': 959, 'chars': ""'""}, {'char_start': 961, 'char_end': 962, 'chars': '+'}, {'char_start': 972, 'char_end': 978, 'chars': ' + ""\'""'}, {'char_start': 2943, 'char_end': 2954, 'chars': '\'"" + s[3] +'}, {'char_start': 2955, 'char_end': 2957, 'chars': '""\''}, {'char_start': 2968, 'char_end': 2969, 'chars': ""'""}, {'char_start': 2971, 'char_end': 2972, 'chars': '+'}, {'char_start': 2977, 'char_end': 2983, 'chars': ' + ""\'""'}, {'char_start': 3118, 'char_end': 3147, 'chars': '\n '}, {'char_start': 3176, 'char_end': 3191, 'chars': '\'"" + s2[1] + ""\''}, {'char_start': 3208, 'char_end': 3222, 'chars': '\'"" + s[3] + ""\''}, {'char_start': 3234, 'char_end': 3235, 'chars': ""'""}, {'char_start': 3236, 'char_end': 3258, 'chars': ' +\n '}, {'char_start': 3260, 'char_end': 3266, 'chars': ' '}, {'char_start': 3271, 'char_end': 3277, 'chars': ' + ""\'""'}, {'char_start': 3355, 'char_end': 3384, 'chars': '\n '}, {'char_start': 3413, 'char_end': 3428, 'chars': '\'"" + s2[1] + ""\''}, {'char_start': 3445, 'char_end': 3459, 'chars': '\'"" + s[3] + ""\''}, {'char_start': 3471, 'char_end': 3472, 'chars': ""'""}, {'char_start': 3473, 'char_end': 3494, 'chars': ' +\n '}, {'char_start': 3495, 'char_end': 3496, 'chars': ' '}, {'char_start': 3497, 'char_end': 3503, 'chars': ' '}, {'char_start': 3508, 'char_end': 3514, 'chars': ' + ""\'""'}, {'char_start': 3753, 'char_end': 3776, 'chars': '\'"" + str(username) + ""\''}, {'char_start': 3793, 'char_end': 3794, 'chars': ""'""}, {'char_start': 3796, 'char_end': 3797, 'chars': '+'}, {'char_start': 3810, 'char_end': 3816, 'chars': ' + ""\'""'}, {'char_start': 3867, 'char_end': 3868, 'chars': ""'""}, {'char_start': 3869, 'char_end': 3871, 'chars': ' +'}, {'char_start': 3889, 'char_end': 3915, 'chars': ' + ""\' where chat_id = \'"" +'}, {'char_start': 3928, 'char_end': 3934, 'chars': ' + ""\'""'}, {'char_start': 3986, 'char_end': 4013, 'chars': '\'"" + str(last_problem) + ""\''}, {'char_start': 4030, 'char_end': 4031, 'chars': ""'""}, {'char_start': 4033, 'char_end': 4034, 'chars': '+'}, {'char_start': 4047, 'char_end': 4053, 'chars': ' + ""\'""'}], 'added': [{'char_start': 502, 'char_end': 503, 'chars': '?'}, {'char_start': 504, 'char_end': 505, 'chars': ','}, {'char_start': 506, 'char_end': 507, 'chars': '('}, {'char_start': 519, 'char_end': 520, 'chars': ','}, {'char_start': 521, 'char_end': 522, 'chars': ')'}, {'char_start': 924, 'char_end': 925, 'chars': '?'}, {'char_start': 937, 'char_end': 938, 'chars': '?'}, {'char_start': 939, 'char_end': 940, 'chars': ','}, {'char_start': 941, 'char_end': 952, 'chars': '(str(x[0]),'}, {'char_start': 962, 'char_end': 963, 'chars': ')'}, {'char_start': 2928, 'char_end': 2929, 'chars': '?'}, {'char_start': 2941, 'char_end': 2942, 'chars': '?'}, {'char_start': 2943, 'char_end': 2944, 'chars': ','}, {'char_start': 2945, 'char_end': 2951, 'chars': '(s[3],'}, {'char_start': 2956, 'char_end': 2957, 'chars': ')'}, {'char_start': 3121, 'char_end': 3122, 'chars': '?'}, {'char_start': 3139, 'char_end': 3140, 'chars': '?'}, {'char_start': 3152, 'char_end': 3153, 'chars': '?'}, {'char_start': 3154, 'char_end': 3155, 'chars': ','}, {'char_start': 3156, 'char_end': 3163, 'chars': '(s2[1],'}, {'char_start': 3164, 'char_end': 3169, 'chars': 's[3],'}, {'char_start': 3174, 'char_end': 3175, 'chars': ')'}, {'char_start': 3282, 'char_end': 3283, 'chars': '?'}, {'char_start': 3300, 'char_end': 3301, 'chars': '?'}, {'char_start': 3313, 'char_end': 3314, 'chars': '?'}, {'char_start': 3315, 'char_end': 3316, 'chars': ','}, {'char_start': 3317, 'char_end': 3324, 'chars': '(s2[1],'}, {'char_start': 3325, 'char_end': 3330, 'chars': 's[3],'}, {'char_start': 3335, 'char_end': 3336, 'chars': ')'}, {'char_start': 3575, 'char_end': 3576, 'chars': '?'}, {'char_start': 3593, 'char_end': 3594, 'chars': '?'}, {'char_start': 3595, 'char_end': 3596, 'chars': ','}, {'char_start': 3597, 'char_end': 3612, 'chars': '(str(username),'}, {'char_start': 3625, 'char_end': 3626, 'chars': ')'}, {'char_start': 3677, 'char_end': 3678, 'chars': '?'}, {'char_start': 3695, 'char_end': 3696, 'chars': '?'}, {'char_start': 3697, 'char_end': 3698, 'chars': ','}, {'char_start': 3699, 'char_end': 3718, 'chars': '(str(last_try_new),'}, {'char_start': 3731, 'char_end': 3732, 'chars': ')'}, {'char_start': 3784, 'char_end': 3801, 'chars': '? where chat_id ='}, {'char_start': 3802, 'char_end': 3805, 'chars': '?"",'}, {'char_start': 3806, 'char_end': 3807, 'chars': '('}, {'char_start': 3824, 'char_end': 3825, 'chars': ','}, {'char_start': 3838, 'char_end': 3839, 'chars': ')'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bases/update.py,cwe-089,1005 cwe-787,yaffsfs_istat," yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { TSK_FS_META *fs_meta; TSK_FS_FILE *fs_file; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; char ls[12]; YAFFSFS_PRINT_ADDR print; char timeBuf[32]; YaffsCacheObject * obj = NULL; YaffsCacheVersion * version = NULL; YaffsHeader * header = NULL; yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { return 1; } fs_meta = fs_file->meta; tsk_fprintf(hFile, ""inode: %"" PRIuINUM ""\n"", inum); tsk_fprintf(hFile, ""%sAllocated\n"", (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? """" : ""Not ""); if (fs_meta->link) tsk_fprintf(hFile, ""symbolic link to: %s\n"", fs_meta->link); tsk_fprintf(hFile, ""uid / gid: %"" PRIuUID "" / %"" PRIuGID ""\n"", fs_meta->uid, fs_meta->gid); tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls)); tsk_fprintf(hFile, ""mode: %s\n"", ls); tsk_fprintf(hFile, ""size: %"" PRIdOFF ""\n"", fs_meta->size); tsk_fprintf(hFile, ""num of links: %d\n"", fs_meta->nlink); if(version != NULL){ yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset); if(header != NULL){ tsk_fprintf(hFile, ""Name: %s\n"", header->name); } } if (sec_skew != 0) { tsk_fprintf(hFile, ""\nAdjusted Inode Times:\n""); fs_meta->mtime -= sec_skew; fs_meta->atime -= sec_skew; fs_meta->ctime -= sec_skew; tsk_fprintf(hFile, ""Accessed:\t%s\n"", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, ""File Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, ""Inode Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); fs_meta->mtime += sec_skew; fs_meta->atime += sec_skew; fs_meta->ctime += sec_skew; tsk_fprintf(hFile, ""\nOriginal Inode Times:\n""); } else { tsk_fprintf(hFile, ""\nInode Times:\n""); } tsk_fprintf(hFile, ""Accessed:\t%s\n"", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, ""File Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, ""Inode Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); if(version != NULL){ tsk_fprintf(hFile, ""\nHeader Chunk:\n""); tsk_fprintf(hFile, ""%"" PRIuDADDR ""\n"", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size))); } if (numblock > 0) { TSK_OFF_T lower_size = numblock * fs->block_size; fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size); } tsk_fprintf(hFile, ""\nData Chunks:\n""); if (flags & TSK_FS_ISTAT_RUNLIST){ const TSK_FS_ATTR *fs_attr_default = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_DEFAULT, 0, 0); if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) { if (tsk_fs_attr_print(fs_attr_default, hFile)) { tsk_fprintf(hFile, ""\nError creating run lists ""); tsk_error_print(hFile); tsk_error_reset(); } } } else { print.idx = 0; print.hFile = hFile; if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY, (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) { tsk_fprintf(hFile, ""\nError reading file: ""); tsk_error_print(hFile); tsk_error_reset(); } else if (print.idx != 0) { tsk_fprintf(hFile, ""\n""); } } tsk_fs_file_close(fs_file); return 0; }"," yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { TSK_FS_META *fs_meta; TSK_FS_FILE *fs_file; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; char ls[12]; YAFFSFS_PRINT_ADDR print; char timeBuf[128]; YaffsCacheObject * obj = NULL; YaffsCacheVersion * version = NULL; YaffsHeader * header = NULL; yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { return 1; } fs_meta = fs_file->meta; tsk_fprintf(hFile, ""inode: %"" PRIuINUM ""\n"", inum); tsk_fprintf(hFile, ""%sAllocated\n"", (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? """" : ""Not ""); if (fs_meta->link) tsk_fprintf(hFile, ""symbolic link to: %s\n"", fs_meta->link); tsk_fprintf(hFile, ""uid / gid: %"" PRIuUID "" / %"" PRIuGID ""\n"", fs_meta->uid, fs_meta->gid); tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls)); tsk_fprintf(hFile, ""mode: %s\n"", ls); tsk_fprintf(hFile, ""size: %"" PRIdOFF ""\n"", fs_meta->size); tsk_fprintf(hFile, ""num of links: %d\n"", fs_meta->nlink); if(version != NULL){ yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset); if(header != NULL){ tsk_fprintf(hFile, ""Name: %s\n"", header->name); } } if (sec_skew != 0) { tsk_fprintf(hFile, ""\nAdjusted Inode Times:\n""); fs_meta->mtime -= sec_skew; fs_meta->atime -= sec_skew; fs_meta->ctime -= sec_skew; tsk_fprintf(hFile, ""Accessed:\t%s\n"", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, ""File Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, ""Inode Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); fs_meta->mtime += sec_skew; fs_meta->atime += sec_skew; fs_meta->ctime += sec_skew; tsk_fprintf(hFile, ""\nOriginal Inode Times:\n""); } else { tsk_fprintf(hFile, ""\nInode Times:\n""); } tsk_fprintf(hFile, ""Accessed:\t%s\n"", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, ""File Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, ""Inode Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); if(version != NULL){ tsk_fprintf(hFile, ""\nHeader Chunk:\n""); tsk_fprintf(hFile, ""%"" PRIuDADDR ""\n"", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size))); } if (numblock > 0) { TSK_OFF_T lower_size = numblock * fs->block_size; fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size); } tsk_fprintf(hFile, ""\nData Chunks:\n""); if (flags & TSK_FS_ISTAT_RUNLIST){ const TSK_FS_ATTR *fs_attr_default = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_DEFAULT, 0, 0); if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) { if (tsk_fs_attr_print(fs_attr_default, hFile)) { tsk_fprintf(hFile, ""\nError creating run lists ""); tsk_error_print(hFile); tsk_error_reset(); } } } else { print.idx = 0; print.hFile = hFile; if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY, (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) { tsk_fprintf(hFile, ""\nError reading file: ""); tsk_error_print(hFile); tsk_error_reset(); } else if (print.idx != 0) { tsk_fprintf(hFile, ""\n""); } } tsk_fs_file_close(fs_file); return 0; }","{'deleted': [{'line_no': 9, 'char_start': 285, 'char_end': 307, 'line': ' char timeBuf[32];\n'}], 'added': [{'line_no': 9, 'char_start': 285, 'char_end': 308, 'line': ' char timeBuf[128];\n'}]}","{'deleted': [{'char_start': 302, 'char_end': 303, 'chars': '3'}], 'added': [{'char_start': 302, 'char_end': 303, 'chars': '1'}, {'char_start': 304, 'char_end': 305, 'chars': '8'}]}",github.com/sleuthkit/sleuthkit/commit/459ae818fc8dae717549810150de4d191ce158f1,tsk/fs/yaffs.cpp,cwe-787,1179 cwe-089,add_movie,"@app.route('/movies/add', methods=['GET', 'POST']) def add_movie(): form = MovieForm() if not form.validate_on_submit(): return render_template('new_movie.html', title='Add New Movie', form=form) lang_id = add_language(form.data['language']) movie = { 'title': '', 'description': '', 'release_year': 0, 'rental_duration': 0, 'rental_rate': 0.00, 'length': 0, 'replacement_cost': 0.00 } for k, v in movie.items(): movie[k] = form.data[k] movie['language_id'] = movie.get('language_id', lang_id) cur.execute( """""" INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost) VALUES ('{}', '{}', {}, {}, {}, {}, {}, {}) """""".format(*[v for k, v in movie.items()]) ) try: cur.execute(f""SELECT * FROM film where fulltext @@ to_tsquery('Dark Knight')"") res = cur.fetchall() conn.commit() return redirect(url_for('movies')) except Exception as e: return redirect(url_for('index'))","@app.route('/movies/add', methods=['GET', 'POST']) def add_movie(): form = MovieForm() if not form.validate_on_submit(): return render_template('new_movie.html', title='Add New Movie', form=form) lang_id = add_language(form.data['language']) movie = { 'title': '', 'description': '', 'release_year': 0, 'rental_duration': 0, 'rental_rate': 0.00, 'length': 0, 'replacement_cost': 0.00 } for k, v in movie.items(): movie[k] = form.data[k] movie['language_id'] = movie.get('language_id', lang_id) cur.execute( """""" INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) """""", [(v, ) for k, v in movie.items()] ) try: cur.execute(""SELECT * FROM film where fulltext @@ to_tsquery(%s)"", (movie['title'], )) res = cur.fetchall() conn.commit() return redirect(url_for('movies')) except Exception as e: return redirect(url_for('index'))","{'deleted': [{'line_no': 22, 'char_start': 784, 'char_end': 836, 'line': "" VALUES ('{}', '{}', {}, {}, {}, {}, {}, {})\n""}, {'line_no': 23, 'char_start': 836, 'char_end': 887, 'line': ' """""".format(*[v for k, v in movie.items()])\n'}, {'line_no': 26, 'char_start': 902, 'char_end': 989, 'line': ' cur.execute(f""SELECT * FROM film where fulltext @@ to_tsquery(\'Dark Knight\')"")\n'}], 'added': [{'line_no': 22, 'char_start': 784, 'char_end': 832, 'line': ' VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\n'}, {'line_no': 23, 'char_start': 832, 'char_end': 879, 'line': ' """""", [(v, ) for k, v in movie.items()]\n'}, {'line_no': 26, 'char_start': 894, 'char_end': 989, 'line': ' cur.execute(""SELECT * FROM film where fulltext @@ to_tsquery(%s)"", (movie[\'title\'], ))\n'}]}","{'deleted': [{'char_start': 800, 'char_end': 804, 'chars': ""'{}'""}, {'char_start': 806, 'char_end': 810, 'chars': ""'{}'""}, {'char_start': 812, 'char_end': 814, 'chars': '{}'}, {'char_start': 816, 'char_end': 818, 'chars': '{}'}, {'char_start': 820, 'char_end': 822, 'chars': '{}'}, {'char_start': 824, 'char_end': 826, 'chars': '{}'}, {'char_start': 828, 'char_end': 830, 'chars': '{}'}, {'char_start': 832, 'char_end': 834, 'chars': '{}'}, {'char_start': 847, 'char_end': 856, 'chars': '.format(*'}, {'char_start': 885, 'char_end': 886, 'chars': ')'}, {'char_start': 922, 'char_end': 923, 'chars': 'f'}, {'char_start': 973, 'char_end': 980, 'chars': 'Dark Kn'}, {'char_start': 981, 'char_end': 983, 'chars': 'gh'}, {'char_start': 986, 'char_end': 987, 'chars': '""'}], 'added': [{'char_start': 800, 'char_end': 802, 'chars': '%s'}, {'char_start': 804, 'char_end': 806, 'chars': '%s'}, {'char_start': 808, 'char_end': 810, 'chars': '%s'}, {'char_start': 812, 'char_end': 814, 'chars': '%s'}, {'char_start': 816, 'char_end': 818, 'chars': '%s'}, {'char_start': 820, 'char_end': 822, 'chars': '%s'}, {'char_start': 824, 'char_end': 826, 'chars': '%s'}, {'char_start': 828, 'char_end': 830, 'chars': '%s'}, {'char_start': 843, 'char_end': 846, 'chars': ', ['}, {'char_start': 848, 'char_end': 851, 'chars': ', )'}, {'char_start': 963, 'char_end': 968, 'chars': '%s)"",'}, {'char_start': 969, 'char_end': 978, 'chars': ""(movie['t""}, {'char_start': 980, 'char_end': 982, 'chars': 'le'}, {'char_start': 983, 'char_end': 986, 'chars': '], '}]}",github.com/Elbertbiggs360/dvdrental/commit/ad144ae2a08a332498d0831bc255170d57ba754b,app.py,cwe-089,273 cwe-089,can_user_pass_that_amount_of_money," def can_user_pass_that_amount_of_money(self, user_id, money): self.cursor.execute(""SELECT count(id) FROM kickstarter.users where id = %s and money >= %s"" % (user_id, money)) return self.cursor.fetchall()[0][0]"," def can_user_pass_that_amount_of_money(self, user_id, money): self.cursor.execute(""SELECT count(id) FROM kickstarter.users where id = %s and money >= %s"", (user_id, money)) return self.cursor.fetchall()[0][0]","{'deleted': [{'line_no': 2, 'char_start': 66, 'char_end': 186, 'line': ' self.cursor.execute(""SELECT count(id) FROM kickstarter.users where id = %s and money >= %s"" % (user_id, money))\n'}], 'added': [{'line_no': 2, 'char_start': 66, 'char_end': 185, 'line': ' self.cursor.execute(""SELECT count(id) FROM kickstarter.users where id = %s and money >= %s"", (user_id, money))\n'}]}","{'deleted': [{'char_start': 165, 'char_end': 167, 'chars': ' %'}], 'added': [{'char_start': 165, 'char_end': 166, 'chars': ','}]}",github.com/JLucka/kickstarter-dev/commit/e2ffa062697e060fdfbd2eccbb89a8c53a569e0b,backend/transactions/TransactionConnector.py,cwe-089,57 cwe-089,delete_playlists_videos,"def delete_playlists_videos(playlist_id, db): db.execute(""DELETE FROM video where playlist_id={playlist_id};"".format( playlist_id=playlist_id))","def delete_playlists_videos(playlist_id, db): db.execute(""DELETE FROM video where playlist_id=%s;"", (playlist_id,))","{'deleted': [{'line_no': 2, 'char_start': 46, 'char_end': 122, 'line': ' db.execute(""DELETE FROM video where playlist_id={playlist_id};"".format(\n'}, {'line_no': 3, 'char_start': 122, 'char_end': 155, 'line': ' playlist_id=playlist_id))\n'}], 'added': [{'line_no': 2, 'char_start': 46, 'char_end': 119, 'line': ' db.execute(""DELETE FROM video where playlist_id=%s;"", (playlist_id,))\n'}]}","{'deleted': [{'char_start': 98, 'char_end': 105, 'chars': '{playli'}, {'char_start': 106, 'char_end': 111, 'chars': 't_id}'}, {'char_start': 113, 'char_end': 127, 'chars': '.format(\n '}, {'char_start': 128, 'char_end': 142, 'chars': ' playlist_id='}], 'added': [{'char_start': 98, 'char_end': 99, 'chars': '%'}, {'char_start': 102, 'char_end': 104, 'chars': ', '}, {'char_start': 116, 'char_end': 117, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,video/video_repository.py,cwe-089,35 cwe-089,getGameID,"def getGameID(ID): db.execute(""SELECT * FROM games WHERE ID = %i"" % ID) ID = db.fetchone() return ID","def getGameID(ID): db.execute(""SELECT * FROM games WHERE ID = ?"", ID) ID = db.fetchone() return ID","{'deleted': [{'line_no': 2, 'char_start': 19, 'char_end': 73, 'line': '\tdb.execute(""SELECT * FROM games WHERE ID = %i"" % ID)\n'}], 'added': [{'line_no': 2, 'char_start': 19, 'char_end': 71, 'line': '\tdb.execute(""SELECT * FROM games WHERE ID = ?"", ID)\n'}]}","{'deleted': [{'char_start': 63, 'char_end': 65, 'chars': '%i'}, {'char_start': 66, 'char_end': 68, 'chars': ' %'}], 'added': [{'char_start': 63, 'char_end': 64, 'chars': '?'}, {'char_start': 65, 'char_end': 66, 'chars': ','}]}",github.com/iScrE4m/XLeague/commit/59cab6e5fd8bd5e47f2418a7c71cb1d4e3cad0d2,plugins/database.py,cwe-089,29 cwe-079,mode_init," def mode_init(self, request): """""" This is called by render_POST when the client requests an init mode operation (at startup) Args: request (Request): Incoming request. """""" csessid = request.args.get('csessid')[0] remote_addr = request.getClientIP() host_string = ""%s (%s:%s)"" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port) sess = AjaxWebClientSession() sess.client = self sess.init_session(""ajax/comet"", remote_addr, self.sessionhandler) sess.csessid = csessid csession = _CLIENT_SESSIONS(session_key=sess.csessid) uid = csession and csession.get(""webclient_authenticated_uid"", False) if uid: # the client session is already logged in sess.uid = uid sess.logged_in = True sess.sessionhandler.connect(sess) self.last_alive[csessid] = (time.time(), False) if not self.keep_alive: # the keepalive is not running; start it. self.keep_alive = LoopingCall(self._keepalive) self.keep_alive.start(_KEEPALIVE, now=False) return jsonify({'msg': host_string, 'csessid': csessid})"," def mode_init(self, request): """""" This is called by render_POST when the client requests an init mode operation (at startup) Args: request (Request): Incoming request. """""" csessid = cgi.escape(request.args['csessid'][0]) remote_addr = request.getClientIP() host_string = ""%s (%s:%s)"" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port) sess = AjaxWebClientSession() sess.client = self sess.init_session(""ajax/comet"", remote_addr, self.sessionhandler) sess.csessid = csessid csession = _CLIENT_SESSIONS(session_key=sess.csessid) uid = csession and csession.get(""webclient_authenticated_uid"", False) if uid: # the client session is already logged in sess.uid = uid sess.logged_in = True sess.sessionhandler.connect(sess) self.last_alive[csessid] = (time.time(), False) if not self.keep_alive: # the keepalive is not running; start it. self.keep_alive = LoopingCall(self._keepalive) self.keep_alive.start(_KEEPALIVE, now=False) return jsonify({'msg': host_string, 'csessid': csessid})","{'deleted': [{'line_no': 10, 'char_start': 230, 'char_end': 279, 'line': "" csessid = request.args.get('csessid')[0]\n""}], 'added': [{'line_no': 10, 'char_start': 230, 'char_end': 287, 'line': "" csessid = cgi.escape(request.args['csessid'][0])\n""}]}","{'deleted': [{'char_start': 260, 'char_end': 265, 'chars': '.get('}, {'char_start': 274, 'char_end': 275, 'chars': ')'}], 'added': [{'char_start': 248, 'char_end': 259, 'chars': 'cgi.escape('}, {'char_start': 271, 'char_end': 272, 'chars': '['}, {'char_start': 281, 'char_end': 282, 'chars': ']'}, {'char_start': 285, 'char_end': 286, 'chars': ')'}]}",github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93,evennia/server/portal/webclient_ajax.py,cwe-079,278 cwe-089,getGameCountInSeriesSoFar,"def getGameCountInSeriesSoFar(submission): database = sqlite3.connect('database.db') cursor = database.cursor() return cursor.execute(""SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = '"" + getTitle(submission) + ""' AND Date <= '"" + getSubmissionDateFromDatabase(submission) + ""'"").fetchone()[0] database.close()","def getGameCountInSeriesSoFar(submission): database = sqlite3.connect('database.db') cursor = database.cursor() return cursor.execute(""SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = ? AND Date <= ?"", [getTitle(submission), getSubmissionDateFromDatabase(submission)]).fetchone()[0] database.close()","{'deleted': [{'line_no': 4, 'char_start': 120, 'char_end': 317, 'line': ' return cursor.execute(""SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = \'"" + getTitle(submission) + ""\' AND Date <= \'"" + getSubmissionDateFromDatabase(submission) + ""\'"").fetchone()[0]\n'}], 'added': [{'line_no': 4, 'char_start': 120, 'char_end': 305, 'line': ' return cursor.execute(""SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = ? AND Date <= ?"", [getTitle(submission), getSubmissionDateFromDatabase(submission)]).fetchone()[0]\n'}]}","{'deleted': [{'char_start': 206, 'char_end': 208, 'chars': '\'""'}, {'char_start': 209, 'char_end': 210, 'chars': '+'}, {'char_start': 231, 'char_end': 253, 'chars': ' + ""\' AND Date <= \'"" +'}, {'char_start': 295, 'char_end': 301, 'chars': ' + ""\'""'}], 'added': [{'char_start': 206, 'char_end': 207, 'chars': '?'}, {'char_start': 208, 'char_end': 211, 'chars': 'AND'}, {'char_start': 212, 'char_end': 225, 'chars': 'Date <= ?"", ['}, {'char_start': 245, 'char_end': 246, 'chars': ','}, {'char_start': 288, 'char_end': 289, 'chars': ']'}]}",github.com/LiquidFun/Reddit-GeoGuessr-Tracking-Bot/commit/0cad2d52e24b05da32789fbc8face7a9999a71f9,CheckAndPostForSeriesSubmissions.py,cwe-089,76 cwe-089,get_requested_day," def get_requested_day(self, date): data = dict() day_start, day_end = self.get_epoch_day(date) 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)} query = ''' SELECT TimeStamp, SUM(Power) AS Power FROM DayData WHERE TimeStamp BETWEEN %s AND %s GROUP BY TimeStamp; ''' data['data'] = list() for row in self.c.execute(query % (day_start, day_end)): data['data'].append({ 'time': row[0], 'power': row[1] }) if self.get_datetime(date).date() == datetime.today().date(): query = ''' SELECT SUM(EToday) as EToday FROM Inverters; ''' else: query = ''' SELECT SUM(DayYield) AS Power FROM MonthData WHERE TimeStamp BETWEEN %s AND %s GROUP BY TimeStamp ''' % (day_start, day_end) self.c.execute(query) row = self.c.fetchone() if row and row[0]: data['total'] = row[0] else: data['total'] = 0 query = ''' SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp ); ''' self.c.execute(query) first_data, last_data = self.c.fetchone() if (first_data): data['hasPrevious'] = (first_data < day_start) else: data['hasPrevious'] = False if (last_data): data['hasNext'] = (last_data > day_end) else: data['hasNext'] = False #print(json.dumps(data, indent=4)) return data"," def get_requested_day(self, date): data = dict() day_start, day_end = self.get_epoch_day(date) 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)} query = ''' SELECT TimeStamp, SUM(Power) AS Power FROM DayData WHERE TimeStamp BETWEEN ? AND ? GROUP BY TimeStamp; ''' data['data'] = list() for row in self.c.execute(query, (day_start, day_end)): data['data'].append({ 'time': row[0], 'power': row[1] }) if self.get_datetime(date).date() == datetime.today().date(): query = ''' SELECT SUM(EToday) as EToday FROM Inverters; ''' self.c.execute(query) else: query = ''' SELECT SUM(DayYield) AS Power FROM MonthData WHERE TimeStamp BETWEEN ? AND ? GROUP BY TimeStamp; ''' self.c.execute(query, (day_start, day_end)) row = self.c.fetchone() if row and row[0]: data['total'] = row[0] else: data['total'] = 0 query = ''' SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp ); ''' self.c.execute(query) first_data, last_data = self.c.fetchone() if (first_data): data['hasPrevious'] = (first_data < day_start) else: data['hasPrevious'] = False if (last_data): data['hasNext'] = (last_data > day_end) else: data['hasNext'] = False #print(json.dumps(data, indent=4)) return data","{'deleted': [{'line_no': 11, 'char_start': 379, 'char_end': 426, 'line': ' WHERE TimeStamp BETWEEN %s AND %s \n'}, {'line_no': 16, 'char_start': 501, 'char_end': 566, 'line': ' for row in self.c.execute(query % (day_start, day_end)):\n'}, {'line_no': 29, 'char_start': 945, 'char_end': 995, 'line': ' WHERE TimeStamp BETWEEN %s AND %s\n'}, {'line_no': 30, 'char_start': 995, 'char_end': 1030, 'line': ' GROUP BY TimeStamp\n'}, {'line_no': 31, 'char_start': 1030, 'char_end': 1073, 'line': "" ''' % (day_start, day_end)\n""}, {'line_no': 32, 'char_start': 1073, 'char_end': 1103, 'line': ' self.c.execute(query)\n'}], 'added': [{'line_no': 11, 'char_start': 379, 'char_end': 423, 'line': ' WHERE TimeStamp BETWEEN ? AND ?\n'}, {'line_no': 16, 'char_start': 498, 'char_end': 562, 'line': ' for row in self.c.execute(query, (day_start, day_end)):\n'}, {'line_no': 25, 'char_start': 824, 'char_end': 858, 'line': ' self.c.execute(query)\n'}, {'line_no': 30, 'char_start': 975, 'char_end': 1023, 'line': ' WHERE TimeStamp BETWEEN ? AND ?\n'}, {'line_no': 31, 'char_start': 1023, 'char_end': 1059, 'line': ' GROUP BY TimeStamp;\n'}, {'line_no': 32, 'char_start': 1059, 'char_end': 1079, 'line': "" '''\n""}, {'line_no': 33, 'char_start': 1079, 'char_end': 1135, 'line': ' self.c.execute(query, (day_start, day_end))\n'}, {'line_no': 34, 'char_start': 1135, 'char_end': 1136, 'line': '\n'}]}","{'deleted': [{'char_start': 415, 'char_end': 417, 'chars': '%s'}, {'char_start': 422, 'char_end': 425, 'chars': '%s '}, {'char_start': 540, 'char_end': 542, 'chars': ' %'}, {'char_start': 985, 'char_end': 987, 'chars': '%s'}, {'char_start': 992, 'char_end': 994, 'chars': '%s'}, {'char_start': 1050, 'char_end': 1051, 'chars': '%'}, {'char_start': 1052, 'char_end': 1063, 'chars': '(day_start,'}, {'char_start': 1064, 'char_end': 1073, 'chars': 'day_end)\n'}], 'added': [{'char_start': 415, 'char_end': 416, 'chars': '?'}, {'char_start': 421, 'char_end': 422, 'chars': '?'}, {'char_start': 537, 'char_end': 538, 'chars': ','}, {'char_start': 824, 'char_end': 858, 'chars': ' self.c.execute(query)\n'}, {'char_start': 1015, 'char_end': 1016, 'chars': '?'}, {'char_start': 1021, 'char_end': 1022, 'chars': '?'}, {'char_start': 1057, 'char_end': 1058, 'chars': ';'}, {'char_start': 1078, 'char_end': 1079, 'chars': '\n'}, {'char_start': 1082, 'char_end': 1083, 'chars': ' '}, {'char_start': 1111, 'char_end': 1132, 'chars': ', (day_start, day_end'}, {'char_start': 1133, 'char_end': 1135, 'chars': ')\n'}]}",github.com/philipptrenz/sunportal/commit/7eef493a168ed4e6731ff800713bfb8aee99a506,util/database.py,cwe-089,408 cwe-476,flattenSubquery,"static int flattenSubquery( Parse *pParse, /* Parsing context */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ int isAgg /* True if outer SELECT uses aggregate functions */ ){ const char *zSavedAuthContext = pParse->zAuthContext; Select *pParent; /* Current UNION ALL term of the other query */ Select *pSub; /* The inner query or ""subquery"" */ Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ int iParent; /* VDBE cursor number of the pSub result set temp table */ int iNewParent = -1;/* Replacement table for iParent */ int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ sqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ assert( p!=0 ); assert( p->pPrior==0 ); if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFromnSrc ); pSubitem = &pSrc->a[iFrom]; iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); #ifndef SQLITE_OMIT_WINDOWFUNC if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ #endif pSubSrc = pSub->pSrc; assert( pSubSrc ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET ** because they could be computed at compile-time. But when LIMIT and OFFSET ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ return 0; /* Restriction (15) */ } if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ return 0; /* Restrictions (8)(9) */ } if( p->pOrderBy && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ return 0; /* Restriction (21) */ } if( pSub->selFlags & (SF_Recursive) ){ return 0; /* Restrictions (22) */ } /* ** If the subquery is the right operand of a LEFT JOIN, then the ** subquery may not be a join itself (3a). Example of why this is not ** allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) JOIN t3 ** ** which is not at all the same thing. ** ** If the subquery is the right operand of a LEFT JOIN, then the outer ** query cannot be an aggregate. (3c) This is an artifact of the way ** aggregates are processed - there is no mechanism to determine if ** the LEFT JOIN table should be all-NULL. ** ** See also tickets #306, #350, and #3300. */ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ isLeftJoin = 1; if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){ /* (3a) (3c) (3b) */ return 0; } } #ifdef SQLITE_EXTRA_IFNULLROW else if( iFrom>0 && !isAgg ){ /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for ** every reference to any result column from subquery in a join, even ** though they are not necessary. This will stress-test the OP_IfNullRow ** opcode. */ isLeftJoin = -1; } #endif /* Restriction (17): If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if( pSub->pPrior ){ if( pSub->pOrderBy ){ return 0; /* Restriction (20) */ } if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ return 0; /* (17d1), (17d2), or (17d3) */ } for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); assert( pSub->pSrc!=0 ); assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ || pSub1->pSrc->nSrc<1 /* (17c) */ ){ return 0; } testcase( pSub1->pSrc->nSrc>1 ); } /* Restriction (18). */ if( p->pOrderBy ){ int ii; for(ii=0; iipOrderBy->nExpr; ii++){ if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; } } } /* Ex-restriction (23): ** The only way that the recursive part of a CTE can contain a compound ** subquery is for the subquery to be one term of a join. But if the ** subquery is a join, then the flattening has already been stopped by ** restriction (17d3) */ assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); /***** If we reach this point, flattening is permitted. *****/ SELECTTRACE(1,pParse,p,(""flatten %u.%p from term %d\n"", pSub->selId, pSub, iFrom)); /* Authorize the subquery */ pParse->zAuthContext = pSubitem->zName; TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); testcase( i==SQLITE_DENY ); pParse->zAuthContext = zSavedAuthContext; /* If the sub-query is a compound SELECT statement, then (by restrictions ** 17 and 18 above) it must be a UNION ALL and the parent query must ** be of the form: ** ** SELECT FROM () ** ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or ** OFFSET clauses and joins them to the left-hand-side of the original ** using UNION ALL operators. In this case N is the number of simple ** select statements in the compound sub-query. ** ** Example: ** ** SELECT a+1 FROM ( ** SELECT x FROM tab ** UNION ALL ** SELECT y FROM tab ** UNION ALL ** SELECT abs(z*2) FROM tab2 ** ) WHERE a!=5 ORDER BY 1 ** ** Transformed into: ** ** SELECT x+1 FROM tab WHERE x+1!=5 ** UNION ALL ** SELECT y+1 FROM tab WHERE y+1!=5 ** UNION ALL ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 ** ORDER BY 1 ** ** We call this the ""compound-subquery flattening"". */ for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ Select *pNew; ExprList *pOrderBy = p->pOrderBy; Expr *pLimit = p->pLimit; Select *pPrior = p->pPrior; p->pOrderBy = 0; p->pSrc = 0; p->pPrior = 0; p->pLimit = 0; pNew = sqlite3SelectDup(db, p, 0); p->pLimit = pLimit; p->pOrderBy = pOrderBy; p->pSrc = pSrc; p->op = TK_ALL; if( pNew==0 ){ p->pPrior = pPrior; }else{ pNew->pPrior = pPrior; if( pPrior ) pPrior->pNext = pNew; pNew->pNext = p; p->pPrior = pNew; SELECTTRACE(2,pParse,p,(""compound-subquery flattener"" "" creates %u as peer\n"",pNew->selId)); } if( db->mallocFailed ) return 1; } /* Begin flattening the iFrom-th entry of the FROM clause ** in the outer query. */ pSub = pSub1 = pSubitem->pSelect; /* Delete the transient table structure associated with the ** subquery */ sqlite3DbFree(db, pSubitem->zDatabase); sqlite3DbFree(db, pSubitem->zName); sqlite3DbFree(db, pSubitem->zAlias); pSubitem->zDatabase = 0; pSubitem->zName = 0; pSubitem->zAlias = 0; pSubitem->pSelect = 0; /* Defer deleting the Table object associated with the ** subquery until code generation is ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** ** pSubitem->pTab is always non-NULL by test restrictions and tests above. */ if( ALWAYS(pSubitem->pTab!=0) ){ Table *pTabToDel = pSubitem->pTab; if( pTabToDel->nTabRef==1 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pTabToDel->pNextZombie = pToplevel->pZombieTab; pToplevel->pZombieTab = pTabToDel; }else{ pTabToDel->nTabRef--; } pSubitem->pTab = 0; } /* The following loop runs once for each term in a compound-subquery ** flattening (as described above). If we are doing a different kind ** of flattening - a flattening other than a compound-subquery flattening - ** then this loop only runs once. ** ** This loop moves all of the FROM elements of the subquery into the ** the FROM clause of the outer query. Before doing this, remember ** the cursor number for the original outer query FROM element in ** iParent. The iParent cursor will never be used. Subsequent code ** will scan expressions looking for iParent references and replace ** those references with expressions that resolve to the subquery FROM ** elements we are now copying in. */ for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; u8 jointype = 0; assert( pSub!=0 ); pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ if( pSrc ){ assert( pParent==p ); /* First time through the loop */ jointype = pSubitem->fg.jointype; }else{ assert( pParent!=p ); /* 2nd and subsequent times through the loop */ pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements ** of the subquery. ** ** Example: ** ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; ** ** The outer query has 3 slots in its FROM clause. One slot of the ** outer query (the middle slot) is used by the subquery. The next ** block of code will expand the outer query FROM clause to 4 slots. ** The middle slot is expanded to two slots in order to make space ** for the two elements in the FROM clause of the subquery. */ if( nSubSrc>1 ){ pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for(i=0; ia[i+iFrom].pUsing); assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); pSrc->a[i+iFrom] = pSubSrc->a[i]; iNewParent = pSubSrc->a[i].iCursor; memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].fg.jointype = jointype; /* Now begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: ** ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ** \ \_____________ subquery __________/ / ** \_____________________ outer query ______________________________/ ** ** We look at every expression in the outer query and every place we see ** ""a"" we substitute ""x*3"" and every place we see ""b"" we substitute ""y+10"". */ if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th ** expression returned by SELECT statement pSub. Since these values ** do not necessarily correspond to columns in SELECT statement pParent, ** zero them before transfering the ORDER BY clause. ** ** Not doing this may cause an error if a subsequent call to this ** function attempts to flatten a compound sub-query into pParent ** (the only way this can happen is if the compound sub-query is ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ ExprList *pOrderBy = pSub->pOrderBy; for(i=0; inExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } assert( pParent->pOrderBy==0 ); pParent->pOrderBy = pOrderBy; pSub->pOrderBy = 0; } pWhere = pSub->pWhere; pSub->pWhere = 0; if( isLeftJoin>0 ){ sqlite3SetJoinExpr(pWhere, iNewParent); } pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere); if( db->mallocFailed==0 ){ SubstContext x; x.pParse = pParse; x.iTable = iParent; x.iNewTable = iNewParent; x.isLeftJoin = isLeftJoin; x.pEList = pSub->pEList; substSelect(&x, pParent, 0); } /* The flattened query is a compound if either the inner or the ** outer query is a compound. */ pParent->selFlags |= pSub->selFlags & SF_Compound; assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ** ** One is tempted to try to add a and b to combine the limits. But this ** does not work if either limit is negative. */ if( pSub->pLimit ){ pParent->pLimit = pSub->pLimit; pSub->pLimit = 0; } } /* Finially, delete what is left of the subquery and return ** success. */ sqlite3SelectDelete(db, pSub1); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,(""After flattening:\n"")); sqlite3TreeViewSelect(0, p, 0); } #endif return 1; }","static int flattenSubquery( Parse *pParse, /* Parsing context */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ int isAgg /* True if outer SELECT uses aggregate functions */ ){ const char *zSavedAuthContext = pParse->zAuthContext; Select *pParent; /* Current UNION ALL term of the other query */ Select *pSub; /* The inner query or ""subquery"" */ Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ int iParent; /* VDBE cursor number of the pSub result set temp table */ int iNewParent = -1;/* Replacement table for iParent */ int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ sqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ assert( p!=0 ); assert( p->pPrior==0 ); if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFromnSrc ); pSubitem = &pSrc->a[iFrom]; iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); #ifndef SQLITE_OMIT_WINDOWFUNC if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ #endif pSubSrc = pSub->pSrc; assert( pSubSrc ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET ** because they could be computed at compile-time. But when LIMIT and OFFSET ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ return 0; /* Restriction (15) */ } if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ return 0; /* Restrictions (8)(9) */ } if( p->pOrderBy && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ return 0; /* Restriction (21) */ } if( pSub->selFlags & (SF_Recursive) ){ return 0; /* Restrictions (22) */ } /* ** If the subquery is the right operand of a LEFT JOIN, then the ** subquery may not be a join itself (3a). Example of why this is not ** allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) JOIN t3 ** ** which is not at all the same thing. ** ** If the subquery is the right operand of a LEFT JOIN, then the outer ** query cannot be an aggregate. (3c) This is an artifact of the way ** aggregates are processed - there is no mechanism to determine if ** the LEFT JOIN table should be all-NULL. ** ** See also tickets #306, #350, and #3300. */ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ isLeftJoin = 1; if( pSubSrc->nSrc>1 /* (3a) */ || isAgg /* (3b) */ || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */ || (p->selFlags & SF_Distinct)!=0 /* (3d) */ ){ return 0; } } #ifdef SQLITE_EXTRA_IFNULLROW else if( iFrom>0 && !isAgg ){ /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for ** every reference to any result column from subquery in a join, even ** though they are not necessary. This will stress-test the OP_IfNullRow ** opcode. */ isLeftJoin = -1; } #endif /* Restriction (17): If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if( pSub->pPrior ){ if( pSub->pOrderBy ){ return 0; /* Restriction (20) */ } if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ return 0; /* (17d1), (17d2), or (17d3) */ } for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); assert( pSub->pSrc!=0 ); assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ || pSub1->pSrc->nSrc<1 /* (17c) */ ){ return 0; } testcase( pSub1->pSrc->nSrc>1 ); } /* Restriction (18). */ if( p->pOrderBy ){ int ii; for(ii=0; iipOrderBy->nExpr; ii++){ if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; } } } /* Ex-restriction (23): ** The only way that the recursive part of a CTE can contain a compound ** subquery is for the subquery to be one term of a join. But if the ** subquery is a join, then the flattening has already been stopped by ** restriction (17d3) */ assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); /***** If we reach this point, flattening is permitted. *****/ SELECTTRACE(1,pParse,p,(""flatten %u.%p from term %d\n"", pSub->selId, pSub, iFrom)); /* Authorize the subquery */ pParse->zAuthContext = pSubitem->zName; TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); testcase( i==SQLITE_DENY ); pParse->zAuthContext = zSavedAuthContext; /* If the sub-query is a compound SELECT statement, then (by restrictions ** 17 and 18 above) it must be a UNION ALL and the parent query must ** be of the form: ** ** SELECT FROM () ** ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or ** OFFSET clauses and joins them to the left-hand-side of the original ** using UNION ALL operators. In this case N is the number of simple ** select statements in the compound sub-query. ** ** Example: ** ** SELECT a+1 FROM ( ** SELECT x FROM tab ** UNION ALL ** SELECT y FROM tab ** UNION ALL ** SELECT abs(z*2) FROM tab2 ** ) WHERE a!=5 ORDER BY 1 ** ** Transformed into: ** ** SELECT x+1 FROM tab WHERE x+1!=5 ** UNION ALL ** SELECT y+1 FROM tab WHERE y+1!=5 ** UNION ALL ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 ** ORDER BY 1 ** ** We call this the ""compound-subquery flattening"". */ for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ Select *pNew; ExprList *pOrderBy = p->pOrderBy; Expr *pLimit = p->pLimit; Select *pPrior = p->pPrior; p->pOrderBy = 0; p->pSrc = 0; p->pPrior = 0; p->pLimit = 0; pNew = sqlite3SelectDup(db, p, 0); p->pLimit = pLimit; p->pOrderBy = pOrderBy; p->pSrc = pSrc; p->op = TK_ALL; if( pNew==0 ){ p->pPrior = pPrior; }else{ pNew->pPrior = pPrior; if( pPrior ) pPrior->pNext = pNew; pNew->pNext = p; p->pPrior = pNew; SELECTTRACE(2,pParse,p,(""compound-subquery flattener"" "" creates %u as peer\n"",pNew->selId)); } if( db->mallocFailed ) return 1; } /* Begin flattening the iFrom-th entry of the FROM clause ** in the outer query. */ pSub = pSub1 = pSubitem->pSelect; /* Delete the transient table structure associated with the ** subquery */ sqlite3DbFree(db, pSubitem->zDatabase); sqlite3DbFree(db, pSubitem->zName); sqlite3DbFree(db, pSubitem->zAlias); pSubitem->zDatabase = 0; pSubitem->zName = 0; pSubitem->zAlias = 0; pSubitem->pSelect = 0; /* Defer deleting the Table object associated with the ** subquery until code generation is ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** ** pSubitem->pTab is always non-NULL by test restrictions and tests above. */ if( ALWAYS(pSubitem->pTab!=0) ){ Table *pTabToDel = pSubitem->pTab; if( pTabToDel->nTabRef==1 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pTabToDel->pNextZombie = pToplevel->pZombieTab; pToplevel->pZombieTab = pTabToDel; }else{ pTabToDel->nTabRef--; } pSubitem->pTab = 0; } /* The following loop runs once for each term in a compound-subquery ** flattening (as described above). If we are doing a different kind ** of flattening - a flattening other than a compound-subquery flattening - ** then this loop only runs once. ** ** This loop moves all of the FROM elements of the subquery into the ** the FROM clause of the outer query. Before doing this, remember ** the cursor number for the original outer query FROM element in ** iParent. The iParent cursor will never be used. Subsequent code ** will scan expressions looking for iParent references and replace ** those references with expressions that resolve to the subquery FROM ** elements we are now copying in. */ for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; u8 jointype = 0; assert( pSub!=0 ); pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ if( pSrc ){ assert( pParent==p ); /* First time through the loop */ jointype = pSubitem->fg.jointype; }else{ assert( pParent!=p ); /* 2nd and subsequent times through the loop */ pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements ** of the subquery. ** ** Example: ** ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; ** ** The outer query has 3 slots in its FROM clause. One slot of the ** outer query (the middle slot) is used by the subquery. The next ** block of code will expand the outer query FROM clause to 4 slots. ** The middle slot is expanded to two slots in order to make space ** for the two elements in the FROM clause of the subquery. */ if( nSubSrc>1 ){ pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for(i=0; ia[i+iFrom].pUsing); assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); pSrc->a[i+iFrom] = pSubSrc->a[i]; iNewParent = pSubSrc->a[i].iCursor; memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].fg.jointype = jointype; /* Now begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: ** ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ** \ \_____________ subquery __________/ / ** \_____________________ outer query ______________________________/ ** ** We look at every expression in the outer query and every place we see ** ""a"" we substitute ""x*3"" and every place we see ""b"" we substitute ""y+10"". */ if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th ** expression returned by SELECT statement pSub. Since these values ** do not necessarily correspond to columns in SELECT statement pParent, ** zero them before transfering the ORDER BY clause. ** ** Not doing this may cause an error if a subsequent call to this ** function attempts to flatten a compound sub-query into pParent ** (the only way this can happen is if the compound sub-query is ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ ExprList *pOrderBy = pSub->pOrderBy; for(i=0; inExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } assert( pParent->pOrderBy==0 ); pParent->pOrderBy = pOrderBy; pSub->pOrderBy = 0; } pWhere = pSub->pWhere; pSub->pWhere = 0; if( isLeftJoin>0 ){ sqlite3SetJoinExpr(pWhere, iNewParent); } pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere); if( db->mallocFailed==0 ){ SubstContext x; x.pParse = pParse; x.iTable = iParent; x.iNewTable = iNewParent; x.isLeftJoin = isLeftJoin; x.pEList = pSub->pEList; substSelect(&x, pParent, 0); } /* The flattened query is a compound if either the inner or the ** outer query is a compound. */ pParent->selFlags |= pSub->selFlags & SF_Compound; assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ** ** One is tempted to try to add a and b to combine the limits. But this ** does not work if either limit is negative. */ if( pSub->pLimit ){ pParent->pLimit = pSub->pLimit; pSub->pLimit = 0; } } /* Finially, delete what is left of the subquery and return ** success. */ sqlite3SelectDelete(db, pSub1); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,(""After flattening:\n"")); sqlite3TreeViewSelect(0, p, 0); } #endif return 1; }","{'deleted': [{'line_no': 88, 'char_start': 3695, 'char_end': 3764, 'line': ' if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){\n'}, {'line_no': 89, 'char_start': 3764, 'char_end': 3808, 'line': ' /* (3a) (3c) (3b) */\n'}], 'added': [{'line_no': 88, 'char_start': 3695, 'char_end': 3748, 'line': ' if( pSubSrc->nSrc>1 /* (3a) */\n'}, {'line_no': 89, 'char_start': 3748, 'char_end': 3801, 'line': ' || isAgg /* (3b) */\n'}, {'line_no': 90, 'char_start': 3801, 'char_end': 3854, 'line': ' || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */\n'}, {'line_no': 91, 'char_start': 3854, 'char_end': 3907, 'line': ' || (p->selFlags & SF_Distinct)!=0 /* (3d) */\n'}, {'line_no': 92, 'char_start': 3907, 'char_end': 3914, 'line': ' ){\n'}]}","{'deleted': [{'char_start': 3761, 'char_end': 3766, 'chars': '){\n '}, {'char_start': 3772, 'char_end': 3773, 'chars': ' '}, {'char_start': 3776, 'char_end': 3777, 'chars': 'a'}, {'char_start': 3793, 'char_end': 3794, 'chars': 'c'}, {'char_start': 3800, 'char_end': 3803, 'chars': '(3b'}, {'char_start': 3804, 'char_end': 3807, 'chars': ' */'}], 'added': [{'char_start': 3719, 'char_end': 3753, 'chars': ' /* (3a) */\n '}, {'char_start': 3762, 'char_end': 3806, 'chars': ' /* (3b) */\n '}, {'char_start': 3848, 'char_end': 3849, 'chars': 'c'}, {'char_start': 3851, 'char_end': 3854, 'chars': '*/\n'}, {'char_start': 3859, 'char_end': 3861, 'chars': '||'}, {'char_start': 3862, 'char_end': 3874, 'chars': '(p->selFlags'}, {'char_start': 3875, 'char_end': 3876, 'chars': '&'}, {'char_start': 3877, 'char_end': 3886, 'chars': 'SF_Distin'}, {'char_start': 3887, 'char_end': 3888, 'chars': 't'}, {'char_start': 3889, 'char_end': 3892, 'chars': '!=0'}, {'char_start': 3896, 'char_end': 3898, 'chars': '/*'}, {'char_start': 3901, 'char_end': 3902, 'chars': 'd'}, {'char_start': 3906, 'char_end': 3913, 'chars': '\n ){'}]}",github.com/sqlite/sqlite/commit/396afe6f6aa90a31303c183e11b2b2d4b7956b35,src/select.c,cwe-476,4366 cwe-078,__getattr__.adb_call," def adb_call(*args): clean_name = name.replace('_', '-') arg_str = ' '.join(str(elem) for elem in args) return self._exec_adb_cmd(clean_name, arg_str)"," def adb_call(args=None, shell=False): """"""Wrapper for an ADB command. Args: args: string or list of strings, arguments to the adb command. See subprocess.Proc() documentation. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Proc() docs. Returns: The output of the adb command run if exit code is 0. """""" args = args or '' clean_name = name.replace('_', '-') return self._exec_adb_cmd(clean_name, args, shell=shell)","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 29, 'line': ' def adb_call(*args):\n'}, {'line_no': 3, 'char_start': 77, 'char_end': 136, 'line': "" arg_str = ' '.join(str(elem) for elem in args)\n""}, {'line_no': 4, 'char_start': 136, 'char_end': 194, 'line': ' return self._exec_adb_cmd(clean_name, arg_str)\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 46, 'line': ' def adb_call(args=None, shell=False):\n'}, {'line_no': 2, 'char_start': 46, 'char_end': 89, 'line': ' """"""Wrapper for an ADB command.\n'}, {'line_no': 3, 'char_start': 89, 'char_end': 90, 'line': '\n'}, {'line_no': 4, 'char_start': 90, 'char_end': 108, 'line': ' Args:\n'}, {'line_no': 5, 'char_start': 108, 'char_end': 187, 'line': ' args: string or list of strings, arguments to the adb command.\n'}, {'line_no': 6, 'char_start': 187, 'char_end': 244, 'line': ' See subprocess.Proc() documentation.\n'}, {'line_no': 7, 'char_start': 244, 'char_end': 324, 'line': ' shell: bool, True to run this command through the system shell,\n'}, {'line_no': 8, 'char_start': 324, 'char_end': 401, 'line': ' False to invoke it directly. See subprocess.Proc() docs.\n'}, {'line_no': 9, 'char_start': 401, 'char_end': 402, 'line': '\n'}, {'line_no': 10, 'char_start': 402, 'char_end': 423, 'line': ' Returns:\n'}, {'line_no': 11, 'char_start': 423, 'char_end': 492, 'line': ' The output of the adb command run if exit code is 0.\n'}, {'line_no': 12, 'char_start': 492, 'char_end': 508, 'line': ' """"""\n'}, {'line_no': 13, 'char_start': 508, 'char_end': 538, 'line': "" args = args or ''\n""}, {'line_no': 15, 'char_start': 586, 'char_end': 654, 'line': ' return self._exec_adb_cmd(clean_name, args, shell=shell)\n'}]}","{'deleted': [{'char_start': 21, 'char_end': 22, 'chars': '*'}, {'char_start': 42, 'char_end': 44, 'chars': 'le'}, {'char_start': 46, 'char_end': 47, 'chars': '_'}, {'char_start': 52, 'char_end': 53, 'chars': '='}, {'char_start': 54, 'char_end': 55, 'chars': 'n'}, {'char_start': 58, 'char_end': 60, 'chars': '.r'}, {'char_start': 62, 'char_end': 64, 'chars': 'la'}, {'char_start': 67, 'char_end': 71, 'chars': ""'_',""}, {'char_start': 72, 'char_end': 76, 'chars': ""'-')""}, {'char_start': 92, 'char_end': 93, 'chars': '_'}, {'char_start': 95, 'char_end': 96, 'chars': 'r'}, {'char_start': 97, 'char_end': 98, 'chars': '='}, {'char_start': 99, 'char_end': 100, 'chars': ""'""}, {'char_start': 101, 'char_end': 104, 'chars': ""'.j""}, {'char_start': 107, 'char_end': 109, 'chars': '(s'}, {'char_start': 111, 'char_end': 112, 'chars': '('}, {'char_start': 115, 'char_end': 116, 'chars': 'm'}, {'char_start': 123, 'char_end': 124, 'chars': 'l'}, {'char_start': 125, 'char_end': 126, 'chars': 'm'}, {'char_start': 128, 'char_end': 129, 'chars': 'n'}, {'char_start': 189, 'char_end': 190, 'chars': '_'}, {'char_start': 191, 'char_end': 193, 'chars': 'tr'}], 'added': [{'char_start': 25, 'char_end': 43, 'chars': '=None, shell=False'}, {'char_start': 58, 'char_end': 66, 'chars': '""""""Wrapp'}, {'char_start': 67, 'char_end': 73, 'chars': 'r for '}, {'char_start': 75, 'char_end': 85, 'chars': ' ADB comma'}, {'char_start': 86, 'char_end': 124, 'chars': 'd.\n\n Args:\n '}, {'char_start': 125, 'char_end': 144, 'chars': 'rgs: string or list'}, {'char_start': 145, 'char_end': 147, 'chars': 'of'}, {'char_start': 148, 'char_end': 152, 'chars': 'stri'}, {'char_start': 153, 'char_end': 157, 'chars': 'gs, '}, {'char_start': 158, 'char_end': 161, 'chars': 'rgu'}, {'char_start': 163, 'char_end': 185, 'chars': 'nts to the adb command'}, {'char_start': 186, 'char_end': 208, 'chars': '\n S'}, {'char_start': 209, 'char_end': 214, 'chars': 'e sub'}, {'char_start': 215, 'char_end': 217, 'chars': 'ro'}, {'char_start': 219, 'char_end': 226, 'chars': 'ss.Proc'}, {'char_start': 227, 'char_end': 228, 'chars': ')'}, {'char_start': 229, 'char_end': 243, 'chars': 'documentation.'}, {'char_start': 244, 'char_end': 249, 'chars': ' '}, {'char_start': 260, 'char_end': 284, 'chars': 'shell: bool, True to run'}, {'char_start': 285, 'char_end': 294, 'chars': 'this comm'}, {'char_start': 295, 'char_end': 300, 'chars': 'nd th'}, {'char_start': 301, 'char_end': 303, 'chars': 'ou'}, {'char_start': 304, 'char_end': 312, 'chars': 'h the sy'}, {'char_start': 314, 'char_end': 339, 'chars': 'em shell,\n '}, {'char_start': 342, 'char_end': 351, 'chars': ' False t'}, {'char_start': 352, 'char_end': 353, 'chars': ' '}, {'char_start': 355, 'char_end': 361, 'chars': 'voke i'}, {'char_start': 362, 'char_end': 365, 'chars': ' di'}, {'char_start': 367, 'char_end': 369, 'chars': 'ct'}, {'char_start': 370, 'char_end': 374, 'chars': 'y. S'}, {'char_start': 375, 'char_end': 393, 'chars': 'e subprocess.Proc('}, {'char_start': 395, 'char_end': 396, 'chars': 'd'}, {'char_start': 397, 'char_end': 418, 'chars': 'cs.\n\n Retu'}, {'char_start': 419, 'char_end': 426, 'chars': 'ns:\n '}, {'char_start': 427, 'char_end': 441, 'chars': ' Th'}, {'char_start': 442, 'char_end': 455, 'chars': ' output of th'}, {'char_start': 456, 'char_end': 463, 'chars': ' adb co'}, {'char_start': 464, 'char_end': 472, 'chars': 'mand run'}, {'char_start': 474, 'char_end': 519, 'chars': 'f exit code is 0.\n """"""\n '}, {'char_start': 524, 'char_end': 584, 'chars': "" = args or ''\n clean_name = name.replace('_', '-'""}, {'char_start': 639, 'char_end': 648, 'chars': 's, shell='}, {'char_start': 649, 'char_end': 653, 'chars': 'hell'}]}",github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee,mobly/controllers/android_device_lib/adb.py,cwe-078,44 cwe-125,S_grok_bslash_N,"S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state, regnode ** node_p, UV * code_point_p, int * cp_count, I32 * flagp, const bool strict, const U32 depth ) { /* This routine teases apart the various meanings of \N and returns * accordingly. The input parameters constrain which meaning(s) is/are valid * in the current context. * * Exactly one of and must be non-NULL. * * If is not NULL, the context is expecting the result to be a * single code point. If this \N instance turns out to a single code point, * the function returns TRUE and sets *code_point_p to that code point. * * If is not NULL, the context is expecting the result to be one of * the things representable by a regnode. If this \N instance turns out to be * one such, the function generates the regnode, returns TRUE and sets *node_p * to point to that regnode. * * If this instance of \N isn't legal in any context, this function will * generate a fatal error and not return. * * On input, RExC_parse should point to the first char following the \N at the * time of the call. On successful return, RExC_parse will have been updated * to point to just after the sequence identified by this routine. Also * *flagp has been updated as needed. * * When there is some problem with the current context and this \N instance, * the function returns FALSE, without advancing RExC_parse, nor setting * *node_p, nor *code_point_p, nor *flagp. * * If is not NULL, the caller wants to know the length (in code * points) that this \N sequence matches. This is set even if the function * returns FALSE, as detailed below. * * There are 5 possibilities here, as detailed in the next 5 paragraphs. * * Probably the most common case is for the \N to specify a single code point. * *cp_count will be set to 1, and *code_point_p will be set to that code * point. * * Another possibility is for the input to be an empty \N{}, which for * backwards compatibility we accept. *cp_count will be set to 0. *node_p * will be set to a generated NOTHING node. * * Still another possibility is for the \N to mean [^\n]. *cp_count will be * set to 0. *node_p will be set to a generated REG_ANY node. * * The fourth possibility is that \N resolves to a sequence of more than one * code points. *cp_count will be set to the number of code points in the * sequence. *node_p * will be set to a generated node returned by this * function calling S_reg(). * * The final possibility is that it is premature to be calling this function; * that pass1 needs to be restarted. This can happen when this changes from * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The * latter occurs only when the fourth possibility would otherwise be in * effect, and is because one of those code points requires the pattern to be * recompiled as UTF-8. The function returns FALSE, and sets the * RESTART_PASS1 and NEED_UTF8 flags in *flagp, as appropriate. When this * happens, the caller needs to desist from continuing parsing, and return * this information to its caller. This is not set for when there is only one * code point, as this can be called as part of an ANYOF node, and they can * store above-Latin1 code points without the pattern having to be in UTF-8. * * For non-single-quoted regexes, the tokenizer has resolved character and * sequence names inside \N{...} into their Unicode values, normalizing the * result into what we should see here: '\N{U+c1.c2...}', where c1... are the * hex-represented code points in the sequence. This is done there because * the names can vary based on what charnames pragma is in scope at the time, * so we need a way to take a snapshot of what they resolve to at the time of * the original parse. [perl #56444]. * * That parsing is skipped for single-quoted regexes, so we may here get * '\N{NAME}'. This is a fatal error. These names have to be resolved by the * parser. But if the single-quoted regex is something like '\N{U+41}', that * is legal and handled here. The code point is Unicode, and has to be * translated into the native character set for non-ASCII platforms. */ char * endbrace; /* points to '}' following the name */ char *endchar; /* Points to '.' or '}' ending cur char in the input stream */ char* p = RExC_parse; /* Temporary */ GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_GROK_BSLASH_N; GET_RE_DEBUG_FLAGS; assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */ assert(! (node_p && cp_count)); /* At most 1 should be set */ if (cp_count) { /* Initialize return for the most common case */ *cp_count = 1; } /* The [^\n] meaning of \N ignores spaces and comments under the /x * modifier. The other meanings do not, so use a temporary until we find * out which we are being called with */ skip_to_be_ignored_text(pRExC_state, &p, FALSE /* Don't force to /x */ ); /* Disambiguate between \N meaning a named character versus \N meaning * [^\n]. The latter is assumed when the {...} following the \N is a legal * quantifier, or there is no '{' at all */ if (*p != '{' || regcurly(p)) { RExC_parse = p; if (cp_count) { *cp_count = -1; } if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state, REG_ANY); *flagp |= HASWIDTH|SIMPLE; MARK_NAUGHTY(1); Set_Node_Length(*node_p, 1); /* MJD */ return TRUE; } /* Here, we have decided it should be a named character or sequence */ /* The test above made sure that the next real character is a '{', but * under the /x modifier, it could be separated by space (or a comment and * \n) and this is not allowed (for consistency with \x{...} and the * tokenizer handling of \N{NAME}). */ if (*RExC_parse != '{') { vFAIL(""Missing braces on \\N{}""); } RExC_parse++; /* Skip past the '{' */ endbrace = strchr(RExC_parse, '}'); if (! endbrace) { /* no trailing brace */ vFAIL2(""Missing right brace on \\%c{}"", 'N'); } else if (!( endbrace == RExC_parse /* nothing between the {} */ || memBEGINs(RExC_parse, /* U+ (bad hex is checked below for a better error msg) */ (STRLEN) (RExC_end - RExC_parse), ""U+""))) { RExC_parse = endbrace; /* position msg's '<--HERE' */ vFAIL(""\\N{NAME} must be resolved by the lexer""); } REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode semantics */ if (endbrace == RExC_parse) { /* empty: \N{} */ if (strict) { RExC_parse++; /* Position after the ""}"" */ vFAIL(""Zero length \\N{}""); } if (cp_count) { *cp_count = 0; } nextchar(pRExC_state); if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state,NOTHING); return TRUE; } RExC_parse += 2; /* Skip past the 'U+' */ /* Because toke.c has generated a special construct for us guaranteed not * to have NULs, we can use a str function */ endchar = RExC_parse + strcspn(RExC_parse, "".}""); /* Code points are separated by dots. If none, there is only one code * point, and is terminated by the brace */ if (endchar >= endbrace) { STRLEN length_of_hex; I32 grok_hex_flags; /* Here, exactly one code point. If that isn't what is wanted, fail */ if (! code_point_p) { RExC_parse = p; return FALSE; } /* Convert code point from hex */ length_of_hex = (STRLEN)(endchar - RExC_parse); grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES | PERL_SCAN_DISALLOW_PREFIX /* No errors in the first pass (See [perl * #122671].) We let the code below find the * errors when there are multiple chars. */ | ((SIZE_ONLY) ? PERL_SCAN_SILENT_ILLDIGIT : 0); /* This routine is the one place where both single- and double-quotish * \N{U+xxxx} are evaluated. The value is a Unicode code point which * must be converted to native. */ *code_point_p = UNI_TO_NATIVE(grok_hex(RExC_parse, &length_of_hex, &grok_hex_flags, NULL)); /* The tokenizer should have guaranteed validity, but it's possible to * bypass it by using single quoting, so check. Don't do the check * here when there are multiple chars; we do it below anyway. */ if (length_of_hex == 0 || length_of_hex != (STRLEN)(endchar - RExC_parse) ) { RExC_parse += length_of_hex; /* Includes all the valid */ RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */ ? UTF8SKIP(RExC_parse) : 1; /* Guard against malformed utf8 */ if (RExC_parse >= endchar) { RExC_parse = endchar; } vFAIL(""Invalid hexadecimal number in \\N{U+...}""); } RExC_parse = endbrace + 1; return TRUE; } else { /* Is a multiple character sequence */ SV * substitute_parse; STRLEN len; char *orig_end = RExC_end; char *save_start = RExC_start; I32 flags; /* Count the code points, if desired, in the sequence */ if (cp_count) { *cp_count = 0; while (RExC_parse < endbrace) { /* Point to the beginning of the next character in the sequence. */ RExC_parse = endchar + 1; endchar = RExC_parse + strcspn(RExC_parse, "".}""); (*cp_count)++; } } /* Fail if caller doesn't want to handle a multi-code-point sequence. * But don't backup up the pointer if the caller wants to know how many * code points there are (they can then handle things) */ if (! node_p) { if (! cp_count) { RExC_parse = p; } return FALSE; } /* What is done here is to convert this to a sub-pattern of the form * \x{char1}\x{char2}... and then call reg recursively to parse it * (enclosing in ""(?: ... )"" ). That way, it retains its atomicness, * while not having to worry about special handling that some code * points may have. */ substitute_parse = newSVpvs(""?:""); while (RExC_parse < endbrace) { /* Convert to notation the rest of the code understands */ sv_catpv(substitute_parse, ""\\x{""); sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse); sv_catpv(substitute_parse, ""}""); /* Point to the beginning of the next character in the sequence. */ RExC_parse = endchar + 1; endchar = RExC_parse + strcspn(RExC_parse, "".}""); } sv_catpv(substitute_parse, "")""); len = SvCUR(substitute_parse); /* Don't allow empty number */ if (len < (STRLEN) 8) { RExC_parse = endbrace; vFAIL(""Invalid hexadecimal number in \\N{U+...}""); } RExC_parse = RExC_start = RExC_adjusted_start = SvPV_nolen(substitute_parse); RExC_end = RExC_parse + len; /* The values are Unicode, and therefore not subject to recoding, but * have to be converted to native on a non-Unicode (meaning non-ASCII) * platform. */ #ifdef EBCDIC RExC_recode_x_to_native = 1; #endif *node_p = reg(pRExC_state, 1, &flags, depth+1); /* Restore the saved values */ RExC_start = RExC_adjusted_start = save_start; RExC_parse = endbrace; RExC_end = orig_end; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif SvREFCNT_dec_NN(substitute_parse); if (! *node_p) { if (flags & (RESTART_PASS1|NEED_UTF8)) { *flagp = flags & (RESTART_PASS1|NEED_UTF8); return FALSE; } FAIL2(""panic: reg returned NULL to grok_bslash_N, flags=%#"" UVxf, (UV) flags); } *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED); nextchar(pRExC_state); return TRUE; } }","S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state, regnode ** node_p, UV * code_point_p, int * cp_count, I32 * flagp, const bool strict, const U32 depth ) { /* This routine teases apart the various meanings of \N and returns * accordingly. The input parameters constrain which meaning(s) is/are valid * in the current context. * * Exactly one of and must be non-NULL. * * If is not NULL, the context is expecting the result to be a * single code point. If this \N instance turns out to a single code point, * the function returns TRUE and sets *code_point_p to that code point. * * If is not NULL, the context is expecting the result to be one of * the things representable by a regnode. If this \N instance turns out to be * one such, the function generates the regnode, returns TRUE and sets *node_p * to point to that regnode. * * If this instance of \N isn't legal in any context, this function will * generate a fatal error and not return. * * On input, RExC_parse should point to the first char following the \N at the * time of the call. On successful return, RExC_parse will have been updated * to point to just after the sequence identified by this routine. Also * *flagp has been updated as needed. * * When there is some problem with the current context and this \N instance, * the function returns FALSE, without advancing RExC_parse, nor setting * *node_p, nor *code_point_p, nor *flagp. * * If is not NULL, the caller wants to know the length (in code * points) that this \N sequence matches. This is set even if the function * returns FALSE, as detailed below. * * There are 5 possibilities here, as detailed in the next 5 paragraphs. * * Probably the most common case is for the \N to specify a single code point. * *cp_count will be set to 1, and *code_point_p will be set to that code * point. * * Another possibility is for the input to be an empty \N{}, which for * backwards compatibility we accept. *cp_count will be set to 0. *node_p * will be set to a generated NOTHING node. * * Still another possibility is for the \N to mean [^\n]. *cp_count will be * set to 0. *node_p will be set to a generated REG_ANY node. * * The fourth possibility is that \N resolves to a sequence of more than one * code points. *cp_count will be set to the number of code points in the * sequence. *node_p * will be set to a generated node returned by this * function calling S_reg(). * * The final possibility is that it is premature to be calling this function; * that pass1 needs to be restarted. This can happen when this changes from * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The * latter occurs only when the fourth possibility would otherwise be in * effect, and is because one of those code points requires the pattern to be * recompiled as UTF-8. The function returns FALSE, and sets the * RESTART_PASS1 and NEED_UTF8 flags in *flagp, as appropriate. When this * happens, the caller needs to desist from continuing parsing, and return * this information to its caller. This is not set for when there is only one * code point, as this can be called as part of an ANYOF node, and they can * store above-Latin1 code points without the pattern having to be in UTF-8. * * For non-single-quoted regexes, the tokenizer has resolved character and * sequence names inside \N{...} into their Unicode values, normalizing the * result into what we should see here: '\N{U+c1.c2...}', where c1... are the * hex-represented code points in the sequence. This is done there because * the names can vary based on what charnames pragma is in scope at the time, * so we need a way to take a snapshot of what they resolve to at the time of * the original parse. [perl #56444]. * * That parsing is skipped for single-quoted regexes, so we may here get * '\N{NAME}'. This is a fatal error. These names have to be resolved by the * parser. But if the single-quoted regex is something like '\N{U+41}', that * is legal and handled here. The code point is Unicode, and has to be * translated into the native character set for non-ASCII platforms. */ char * endbrace; /* points to '}' following the name */ char *endchar; /* Points to '.' or '}' ending cur char in the input stream */ char* p = RExC_parse; /* Temporary */ GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_GROK_BSLASH_N; GET_RE_DEBUG_FLAGS; assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */ assert(! (node_p && cp_count)); /* At most 1 should be set */ if (cp_count) { /* Initialize return for the most common case */ *cp_count = 1; } /* The [^\n] meaning of \N ignores spaces and comments under the /x * modifier. The other meanings do not, so use a temporary until we find * out which we are being called with */ skip_to_be_ignored_text(pRExC_state, &p, FALSE /* Don't force to /x */ ); /* Disambiguate between \N meaning a named character versus \N meaning * [^\n]. The latter is assumed when the {...} following the \N is a legal * quantifier, or there is no '{' at all */ if (*p != '{' || regcurly(p)) { RExC_parse = p; if (cp_count) { *cp_count = -1; } if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state, REG_ANY); *flagp |= HASWIDTH|SIMPLE; MARK_NAUGHTY(1); Set_Node_Length(*node_p, 1); /* MJD */ return TRUE; } /* Here, we have decided it should be a named character or sequence */ /* The test above made sure that the next real character is a '{', but * under the /x modifier, it could be separated by space (or a comment and * \n) and this is not allowed (for consistency with \x{...} and the * tokenizer handling of \N{NAME}). */ if (*RExC_parse != '{') { vFAIL(""Missing braces on \\N{}""); } RExC_parse++; /* Skip past the '{' */ endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (! endbrace) { /* no trailing brace */ vFAIL2(""Missing right brace on \\%c{}"", 'N'); } else if (!( endbrace == RExC_parse /* nothing between the {} */ || memBEGINs(RExC_parse, /* U+ (bad hex is checked below for a better error msg) */ (STRLEN) (RExC_end - RExC_parse), ""U+""))) { RExC_parse = endbrace; /* position msg's '<--HERE' */ vFAIL(""\\N{NAME} must be resolved by the lexer""); } REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode semantics */ if (endbrace == RExC_parse) { /* empty: \N{} */ if (strict) { RExC_parse++; /* Position after the ""}"" */ vFAIL(""Zero length \\N{}""); } if (cp_count) { *cp_count = 0; } nextchar(pRExC_state); if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state,NOTHING); return TRUE; } RExC_parse += 2; /* Skip past the 'U+' */ /* Because toke.c has generated a special construct for us guaranteed not * to have NULs, we can use a str function */ endchar = RExC_parse + strcspn(RExC_parse, "".}""); /* Code points are separated by dots. If none, there is only one code * point, and is terminated by the brace */ if (endchar >= endbrace) { STRLEN length_of_hex; I32 grok_hex_flags; /* Here, exactly one code point. If that isn't what is wanted, fail */ if (! code_point_p) { RExC_parse = p; return FALSE; } /* Convert code point from hex */ length_of_hex = (STRLEN)(endchar - RExC_parse); grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES | PERL_SCAN_DISALLOW_PREFIX /* No errors in the first pass (See [perl * #122671].) We let the code below find the * errors when there are multiple chars. */ | ((SIZE_ONLY) ? PERL_SCAN_SILENT_ILLDIGIT : 0); /* This routine is the one place where both single- and double-quotish * \N{U+xxxx} are evaluated. The value is a Unicode code point which * must be converted to native. */ *code_point_p = UNI_TO_NATIVE(grok_hex(RExC_parse, &length_of_hex, &grok_hex_flags, NULL)); /* The tokenizer should have guaranteed validity, but it's possible to * bypass it by using single quoting, so check. Don't do the check * here when there are multiple chars; we do it below anyway. */ if (length_of_hex == 0 || length_of_hex != (STRLEN)(endchar - RExC_parse) ) { RExC_parse += length_of_hex; /* Includes all the valid */ RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */ ? UTF8SKIP(RExC_parse) : 1; /* Guard against malformed utf8 */ if (RExC_parse >= endchar) { RExC_parse = endchar; } vFAIL(""Invalid hexadecimal number in \\N{U+...}""); } RExC_parse = endbrace + 1; return TRUE; } else { /* Is a multiple character sequence */ SV * substitute_parse; STRLEN len; char *orig_end = RExC_end; char *save_start = RExC_start; I32 flags; /* Count the code points, if desired, in the sequence */ if (cp_count) { *cp_count = 0; while (RExC_parse < endbrace) { /* Point to the beginning of the next character in the sequence. */ RExC_parse = endchar + 1; endchar = RExC_parse + strcspn(RExC_parse, "".}""); (*cp_count)++; } } /* Fail if caller doesn't want to handle a multi-code-point sequence. * But don't backup up the pointer if the caller wants to know how many * code points there are (they can then handle things) */ if (! node_p) { if (! cp_count) { RExC_parse = p; } return FALSE; } /* What is done here is to convert this to a sub-pattern of the form * \x{char1}\x{char2}... and then call reg recursively to parse it * (enclosing in ""(?: ... )"" ). That way, it retains its atomicness, * while not having to worry about special handling that some code * points may have. */ substitute_parse = newSVpvs(""?:""); while (RExC_parse < endbrace) { /* Convert to notation the rest of the code understands */ sv_catpv(substitute_parse, ""\\x{""); sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse); sv_catpv(substitute_parse, ""}""); /* Point to the beginning of the next character in the sequence. */ RExC_parse = endchar + 1; endchar = RExC_parse + strcspn(RExC_parse, "".}""); } sv_catpv(substitute_parse, "")""); len = SvCUR(substitute_parse); /* Don't allow empty number */ if (len < (STRLEN) 8) { RExC_parse = endbrace; vFAIL(""Invalid hexadecimal number in \\N{U+...}""); } RExC_parse = RExC_start = RExC_adjusted_start = SvPV_nolen(substitute_parse); RExC_end = RExC_parse + len; /* The values are Unicode, and therefore not subject to recoding, but * have to be converted to native on a non-Unicode (meaning non-ASCII) * platform. */ #ifdef EBCDIC RExC_recode_x_to_native = 1; #endif *node_p = reg(pRExC_state, 1, &flags, depth+1); /* Restore the saved values */ RExC_start = RExC_adjusted_start = save_start; RExC_parse = endbrace; RExC_end = orig_end; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif SvREFCNT_dec_NN(substitute_parse); if (! *node_p) { if (flags & (RESTART_PASS1|NEED_UTF8)) { *flagp = flags & (RESTART_PASS1|NEED_UTF8); return FALSE; } FAIL2(""panic: reg returned NULL to grok_bslash_N, flags=%#"" UVxf, (UV) flags); } *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED); nextchar(pRExC_state); return TRUE; } }","{'deleted': [{'line_no': 142, 'char_start': 6253, 'char_end': 6293, 'line': "" endbrace = strchr(RExC_parse, '}');\n""}], 'added': [{'line_no': 142, 'char_start': 6253, 'char_end': 6325, 'line': "" endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);\n""}]}","{'deleted': [{'char_start': 6268, 'char_end': 6270, 'chars': 'st'}], 'added': [{'char_start': 6268, 'char_end': 6272, 'chars': '(cha'}, {'char_start': 6273, 'char_end': 6280, 'chars': ' *) mem'}, {'char_start': 6299, 'char_end': 6322, 'chars': ', RExC_end - RExC_parse'}]}",github.com/Perl/perl5/commit/43b2f4ef399e2fd7240b4eeb0658686ad95f8e62,regcomp.c,cwe-125,3302 cwe-476,assoc_array_insert_into_terminal_node,"static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0; struct assoc_array_node *node, *new_n0, *new_n1, *side; struct assoc_array_ptr *ptr; unsigned long dissimilarity, base_seg, blank; size_t keylen; bool have_meta; int level, diff; int slot, next_slot, free_slot, i, j; node = result->terminal_node.node; level = result->terminal_node.level; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; pr_devel(""-->%s()\n"", __func__); /* We arrived at a node which doesn't have an onward node or shortcut * pointer that we have to follow. This means that (a) the leaf we * want must go here (either by insertion or replacement) or (b) we * need to split this node and insert in one of the fragments. */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's * a matching one we should replace in place. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (!ptr) { free_slot = i; continue; } if (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) { pr_devel(""replace in slot %d\n"", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; pr_devel(""<--%s() = ok [replace]\n"", __func__); return true; } } /* If there is a free slot in this node then we can just insert the * leaf here. */ if (free_slot >= 0) { pr_devel(""insert in free slot %d\n"", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; pr_devel(""<--%s() = ok [insert]\n"", __func__); return true; } /* The node has no spare slots - so we're either going to have to split * it or insert another node before it. * * Whatever, we're going to need at least two new nodes - so allocate * those now. We may also need a new shortcut, but we deal with that * when we need it. */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n1) return false; edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); /* We need to find out how similar the leaves are. */ pr_devel(""no spare slots\n""); have_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { edit->segment_cache[i] = 0xff; have_meta = true; continue; } base_seg = ops->get_object_key_chunk( assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } if (have_meta) { pr_devel(""have meta\n""); goto split_node; } /* The node contains only leaves */ dissimilarity = 0; base_seg = edit->segment_cache[0]; for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) dissimilarity |= edit->segment_cache[i] ^ base_seg; pr_devel(""only leaves; dissimilarity=%lx\n"", dissimilarity); if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { /* The old leaves all cluster in the same slot. We will need * to insert a shortcut if the new node wants to cluster with them. */ if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) goto all_leaves_cluster_together; /* Otherwise we can just insert a new node ahead of the old * one. */ goto present_leaves_cluster_but_not_new_leaf; } split_node: pr_devel(""split node\n""); /* We need to split the current node; we know that the node doesn't * simply contain a full set of leaves that cluster together (it * contains meta pointers and/or non-clustering leaves). * * We need to expel at least two leaves out of a set consisting of the * leaves in the node and the new leaf. * * We need a new node (n0) to replace the current one and a new node to * take the expelled nodes (n1). */ edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ do_split_node: pr_devel(""do_split_node\n""); new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->nr_leaves_on_branch = 0; /* Begin by finding two matching leaves. There have to be at least two * that match - even if there are meta pointers - because any leaf that * would match a slot with a meta pointer in it must be somewhere * behind that meta pointer and cannot be here. Further, given N * remaining leaf slots, we now have N+1 leaves to go in them. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { slot = edit->segment_cache[i]; if (slot != 0xff) for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) if (edit->segment_cache[j] == slot) goto found_slot_for_multiple_occupancy; } found_slot_for_multiple_occupancy: pr_devel(""same slot: %x %x [%02x]\n"", i, j, slot); BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); new_n1->parent_slot = slot; /* Metadata pointers cannot change slot */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) if (assoc_array_ptr_is_meta(node->slots[i])) new_n0->slots[i] = node->slots[i]; else new_n0->slots[i] = NULL; BUG_ON(new_n0->slots[slot] != NULL); new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); /* Filter the leaf pointers between the new nodes */ free_slot = -1; next_slot = 0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (assoc_array_ptr_is_meta(node->slots[i])) continue; if (edit->segment_cache[i] == slot) { new_n1->slots[next_slot++] = node->slots[i]; new_n1->nr_leaves_on_branch++; } else { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); new_n0->slots[free_slot] = node->slots[i]; } } pr_devel(""filtered: f=%x n=%x\n"", free_slot, next_slot); if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); edit->leaf_p = &new_n0->slots[free_slot]; edit->adjust_count_on = new_n0; } else { edit->leaf_p = &new_n1->slots[next_slot++]; edit->adjust_count_on = new_n1; } BUG_ON(next_slot <= 1); edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (edit->segment_cache[i] == 0xff) { ptr = node->slots[i]; BUG_ON(assoc_array_ptr_is_leaf(ptr)); if (assoc_array_ptr_is_node(ptr)) { side = assoc_array_ptr_to_node(ptr); edit->set_backpointers[i] = &side->back_pointer; } else { shortcut = assoc_array_ptr_to_shortcut(ptr); edit->set_backpointers[i] = &shortcut->back_pointer; } } } ptr = node->back_pointer; if (!ptr) edit->set[0].ptr = &edit->array->root; else if (assoc_array_ptr_is_node(ptr)) edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; else edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel(""<--%s() = ok [split node]\n"", __func__); return true; present_leaves_cluster_but_not_new_leaf: /* All the old leaves cluster in the same slot, but the new leaf wants * to go into a different slot, so we create a new node to hold the new * leaf and a pointer to a new node holding all the old leaves. */ pr_devel(""present leaves cluster but not new leaf\n""); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = edit->segment_cache[0]; new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch; edit->adjust_count_on = new_n0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) new_n1->slots[i] = node->slots[i]; new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0); edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]]; edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot]; edit->set[0].to = assoc_array_node_to_ptr(new_n0); edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel(""<--%s() = ok [insert node before]\n"", __func__); return true; all_leaves_cluster_together: /* All the leaves, new and old, want to cluster together in this node * in the same slot, so we have to replace this node with a shortcut to * skip over the identical parts of the key and then place a pair of * nodes, one inside the other, at the end of the shortcut and * distribute the keys between them. * * Firstly we need to work out where the leaves start diverging as a * bit position into their keys so that we know how big the shortcut * needs to be. * * We only need to make a single pass of N of the N+1 leaves because if * any keys differ between themselves at bit X then at least one of * them must also differ with the base key at bit X or before. */ pr_devel(""all leaves cluster together\n""); diff = INT_MAX; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), index_key); if (x < diff) { BUG_ON(x < 0); diff = x; } } BUG_ON(diff == INT_MAX); BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel(""skip_to_level = %d [diff %d]\n"", level, diff); BUG_ON(level <= 0); for (i = 0; i < keylen; i++) new_s0->index_key[i] = ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel(""blank off [%zu] %d: %lx\n"", keylen - 1, level, blank); new_s0->index_key[keylen - 1] &= ~blank; /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; goto do_split_node; }","static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0; struct assoc_array_node *node, *new_n0, *new_n1, *side; struct assoc_array_ptr *ptr; unsigned long dissimilarity, base_seg, blank; size_t keylen; bool have_meta; int level, diff; int slot, next_slot, free_slot, i, j; node = result->terminal_node.node; level = result->terminal_node.level; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; pr_devel(""-->%s()\n"", __func__); /* We arrived at a node which doesn't have an onward node or shortcut * pointer that we have to follow. This means that (a) the leaf we * want must go here (either by insertion or replacement) or (b) we * need to split this node and insert in one of the fragments. */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's * a matching one we should replace in place. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (!ptr) { free_slot = i; continue; } if (assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) { pr_devel(""replace in slot %d\n"", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; pr_devel(""<--%s() = ok [replace]\n"", __func__); return true; } } /* If there is a free slot in this node then we can just insert the * leaf here. */ if (free_slot >= 0) { pr_devel(""insert in free slot %d\n"", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; pr_devel(""<--%s() = ok [insert]\n"", __func__); return true; } /* The node has no spare slots - so we're either going to have to split * it or insert another node before it. * * Whatever, we're going to need at least two new nodes - so allocate * those now. We may also need a new shortcut, but we deal with that * when we need it. */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n1) return false; edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); /* We need to find out how similar the leaves are. */ pr_devel(""no spare slots\n""); have_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { edit->segment_cache[i] = 0xff; have_meta = true; continue; } base_seg = ops->get_object_key_chunk( assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } if (have_meta) { pr_devel(""have meta\n""); goto split_node; } /* The node contains only leaves */ dissimilarity = 0; base_seg = edit->segment_cache[0]; for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) dissimilarity |= edit->segment_cache[i] ^ base_seg; pr_devel(""only leaves; dissimilarity=%lx\n"", dissimilarity); if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { /* The old leaves all cluster in the same slot. We will need * to insert a shortcut if the new node wants to cluster with them. */ if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) goto all_leaves_cluster_together; /* Otherwise we can just insert a new node ahead of the old * one. */ goto present_leaves_cluster_but_not_new_leaf; } split_node: pr_devel(""split node\n""); /* We need to split the current node; we know that the node doesn't * simply contain a full set of leaves that cluster together (it * contains meta pointers and/or non-clustering leaves). * * We need to expel at least two leaves out of a set consisting of the * leaves in the node and the new leaf. * * We need a new node (n0) to replace the current one and a new node to * take the expelled nodes (n1). */ edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ do_split_node: pr_devel(""do_split_node\n""); new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->nr_leaves_on_branch = 0; /* Begin by finding two matching leaves. There have to be at least two * that match - even if there are meta pointers - because any leaf that * would match a slot with a meta pointer in it must be somewhere * behind that meta pointer and cannot be here. Further, given N * remaining leaf slots, we now have N+1 leaves to go in them. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { slot = edit->segment_cache[i]; if (slot != 0xff) for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) if (edit->segment_cache[j] == slot) goto found_slot_for_multiple_occupancy; } found_slot_for_multiple_occupancy: pr_devel(""same slot: %x %x [%02x]\n"", i, j, slot); BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); new_n1->parent_slot = slot; /* Metadata pointers cannot change slot */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) if (assoc_array_ptr_is_meta(node->slots[i])) new_n0->slots[i] = node->slots[i]; else new_n0->slots[i] = NULL; BUG_ON(new_n0->slots[slot] != NULL); new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); /* Filter the leaf pointers between the new nodes */ free_slot = -1; next_slot = 0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (assoc_array_ptr_is_meta(node->slots[i])) continue; if (edit->segment_cache[i] == slot) { new_n1->slots[next_slot++] = node->slots[i]; new_n1->nr_leaves_on_branch++; } else { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); new_n0->slots[free_slot] = node->slots[i]; } } pr_devel(""filtered: f=%x n=%x\n"", free_slot, next_slot); if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); edit->leaf_p = &new_n0->slots[free_slot]; edit->adjust_count_on = new_n0; } else { edit->leaf_p = &new_n1->slots[next_slot++]; edit->adjust_count_on = new_n1; } BUG_ON(next_slot <= 1); edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (edit->segment_cache[i] == 0xff) { ptr = node->slots[i]; BUG_ON(assoc_array_ptr_is_leaf(ptr)); if (assoc_array_ptr_is_node(ptr)) { side = assoc_array_ptr_to_node(ptr); edit->set_backpointers[i] = &side->back_pointer; } else { shortcut = assoc_array_ptr_to_shortcut(ptr); edit->set_backpointers[i] = &shortcut->back_pointer; } } } ptr = node->back_pointer; if (!ptr) edit->set[0].ptr = &edit->array->root; else if (assoc_array_ptr_is_node(ptr)) edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; else edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel(""<--%s() = ok [split node]\n"", __func__); return true; present_leaves_cluster_but_not_new_leaf: /* All the old leaves cluster in the same slot, but the new leaf wants * to go into a different slot, so we create a new node to hold the new * leaf and a pointer to a new node holding all the old leaves. */ pr_devel(""present leaves cluster but not new leaf\n""); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = edit->segment_cache[0]; new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch; edit->adjust_count_on = new_n0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) new_n1->slots[i] = node->slots[i]; new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0); edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]]; edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot]; edit->set[0].to = assoc_array_node_to_ptr(new_n0); edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel(""<--%s() = ok [insert node before]\n"", __func__); return true; all_leaves_cluster_together: /* All the leaves, new and old, want to cluster together in this node * in the same slot, so we have to replace this node with a shortcut to * skip over the identical parts of the key and then place a pair of * nodes, one inside the other, at the end of the shortcut and * distribute the keys between them. * * Firstly we need to work out where the leaves start diverging as a * bit position into their keys so that we know how big the shortcut * needs to be. * * We only need to make a single pass of N of the N+1 leaves because if * any keys differ between themselves at bit X then at least one of * them must also differ with the base key at bit X or before. */ pr_devel(""all leaves cluster together\n""); diff = INT_MAX; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), index_key); if (x < diff) { BUG_ON(x < 0); diff = x; } } BUG_ON(diff == INT_MAX); BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel(""skip_to_level = %d [diff %d]\n"", level, diff); BUG_ON(level <= 0); for (i = 0; i < keylen; i++) new_s0->index_key[i] = ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel(""blank off [%zu] %d: %lx\n"", keylen - 1, level, blank); new_s0->index_key[keylen - 1] &= ~blank; /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; goto do_split_node; }","{'deleted': [{'line_no': 37, 'char_start': 1199, 'char_end': 1269, 'line': '\t\tif (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) {\n'}], 'added': [{'line_no': 37, 'char_start': 1199, 'char_end': 1237, 'line': '\t\tif (assoc_array_ptr_is_leaf(ptr) &&\n'}, {'line_no': 38, 'char_start': 1237, 'char_end': 1293, 'line': '\t\t ops->compare_object(assoc_array_ptr_to_leaf(ptr),\n'}, {'line_no': 39, 'char_start': 1293, 'char_end': 1312, 'line': '\t\t\t\t\tindex_key)) {\n'}]}","{'deleted': [{'char_start': 1254, 'char_end': 1255, 'chars': ' '}], 'added': [{'char_start': 1205, 'char_end': 1243, 'chars': 'assoc_array_ptr_is_leaf(ptr) &&\n\t\t '}, {'char_start': 1292, 'char_end': 1298, 'chars': '\n\t\t\t\t\t'}]}",github.com/torvalds/linux/commit/8d4a2ec1e0b41b0cf9a0c5cd4511da7f8e4f3de2,lib/assoc_array.c,cwe-476,3307 cwe-078,populate_custom_grains_and_pillar,"def populate_custom_grains_and_pillar(): ''' Populate local salt-minion grains and pillar fields values as specified in config file. For example: custom_grains_pillar: grains: - selinux: selinux:enabled - release: osrelease pillar: - ntpserver: network_services:ntpserver Note that the core grains are already included in hubble grains -- this is only necessary for custom grains and pillar data. ''' log.debug('Fetching custom grains and pillar details') grains = {} salt.modules.config.__opts__ = __opts__ custom_grains = __salt__['config.get']('custom_grains_pillar:grains', []) for grain in custom_grains: for key in grain: if _valid_command(grain[key]): value = __salt__['cmd.run']('salt-call grains.get {0}'.format(grain[key])).split('\n')[1].strip() grains[key] = value custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', []) for pillar in custom_pillar: for key in pillar: if _valid_command(pillar[key]): value = __salt__['cmd.run']('salt-call pillar.get {0}'.format(pillar[key])).split('\n')[1].strip() grains[key] = value log.debug('Done with fetching custom grains and pillar details') return grains","def populate_custom_grains_and_pillar(): ''' Populate local salt-minion grains and pillar fields values as specified in config file. For example: custom_grains_pillar: grains: - selinux: selinux:enabled - release: osrelease pillar: - ntpserver: network_services:ntpserver Note that the core grains are already included in hubble grains -- this is only necessary for custom grains and pillar data. ''' log.debug('Fetching custom grains and pillar details') grains = {} salt.modules.config.__opts__ = __opts__ custom_grains = __salt__['config.get']('custom_grains_pillar:grains', []) for grain in custom_grains: for key in grain: value = __salt__['cmd.run'](['salt-call', 'grains.get', grain[key]]).split('\n')[1].strip() grains[key] = value custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', []) for pillar in custom_pillar: for key in pillar: value = __salt__['cmd.run'](['salt-call', 'pillar.get', pillar[key]]).split('\n')[1].strip() grains[key] = value log.debug('Done with fetching custom grains and pillar details') return grains","{'deleted': [{'line_no': 24, 'char_start': 751, 'char_end': 794, 'line': ' if _valid_command(grain[key]):\n'}, {'line_no': 25, 'char_start': 794, 'char_end': 908, 'line': "" value = __salt__['cmd.run']('salt-call grains.get {0}'.format(grain[key])).split('\\n')[1].strip()\n""}, {'line_no': 26, 'char_start': 908, 'char_end': 944, 'line': ' grains[key] = value\n'}, {'line_no': 30, 'char_start': 1082, 'char_end': 1126, 'line': ' if _valid_command(pillar[key]):\n'}, {'line_no': 31, 'char_start': 1126, 'char_end': 1241, 'line': "" value = __salt__['cmd.run']('salt-call pillar.get {0}'.format(pillar[key])).split('\\n')[1].strip()\n""}, {'line_no': 32, 'char_start': 1241, 'char_end': 1277, 'line': ' grains[key] = value\n'}], 'added': [{'line_no': 24, 'char_start': 751, 'char_end': 855, 'line': "" value = __salt__['cmd.run'](['salt-call', 'grains.get', grain[key]]).split('\\n')[1].strip()\n""}, {'line_no': 25, 'char_start': 855, 'char_end': 887, 'line': ' grains[key] = value\n'}, {'line_no': 29, 'char_start': 1025, 'char_end': 1130, 'line': "" value = __salt__['cmd.run'](['salt-call', 'pillar.get', pillar[key]]).split('\\n')[1].strip()\n""}, {'line_no': 30, 'char_start': 1130, 'char_end': 1162, 'line': ' grains[key] = value\n'}]}","{'deleted': [{'char_start': 763, 'char_end': 810, 'chars': 'if _valid_command(grain[key]):\n '}, {'char_start': 860, 'char_end': 872, 'chars': ""{0}'.format(""}, {'char_start': 882, 'char_end': 883, 'chars': ')'}, {'char_start': 908, 'char_end': 912, 'chars': ' '}, {'char_start': 1094, 'char_end': 1142, 'chars': 'if _valid_command(pillar[key]):\n '}, {'char_start': 1192, 'char_end': 1204, 'chars': ""{0}'.format(""}, {'char_start': 1215, 'char_end': 1216, 'chars': ')'}, {'char_start': 1241, 'char_end': 1245, 'chars': ' '}], 'added': [{'char_start': 791, 'char_end': 792, 'chars': '['}, {'char_start': 802, 'char_end': 804, 'chars': ""',""}, {'char_start': 805, 'char_end': 806, 'chars': ""'""}, {'char_start': 817, 'char_end': 819, 'chars': ', '}, {'char_start': 829, 'char_end': 830, 'chars': ']'}, {'char_start': 1065, 'char_end': 1066, 'chars': '['}, {'char_start': 1076, 'char_end': 1078, 'chars': ""',""}, {'char_start': 1079, 'char_end': 1080, 'chars': ""'""}, {'char_start': 1091, 'char_end': 1093, 'chars': ', '}, {'char_start': 1104, 'char_end': 1105, 'chars': ']'}]}",github.com/hubblestack/hubble/commit/d9ca4a93ea5aabb1298c5b3dbfb23e94203428b9,hubblestack/extmods/grains/custom_grains_pillar.py,cwe-078,323 cwe-190,WriteBMPImage,"static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { BMPInfo bmp_info; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MagickOffsetType scene; MemoryInfo *pixel_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, type; ssize_t y; unsigned char *bmp_data, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); type=4; if (LocaleCompare(image_info->magick,""BMP2"") == 0) type=2; else if (LocaleCompare(image_info->magick,""BMP3"") == 0) type=3; option=GetImageOption(image_info,""bmp:format""); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Format=%s"",option); if (LocaleCompare(option,""bmp2"") == 0) type=2; if (LocaleCompare(option,""bmp3"") == 0) type=3; if (LocaleCompare(option,""bmp4"") == 0) type=4; } scene=0; do { /* Initialize BMP raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass,exception); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass,exception); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait)) { option=GetImageOption(image_info,""bmp3:alpha""); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,""icc""); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size, sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { ssize_t offset; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } offset=(ssize_t) (image->columns+7)/8; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t byte, nibble; ssize_t offset; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(image,p) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } p+=GetPixelChannels(image); } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } offset=(ssize_t) (image->columns+1)/2; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); p+=GetPixelChannels(image); } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Writing BMP version %.20g datastream"",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Storage class=DirectClass""); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Storage class=PseudoClass""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Image depth=%.20g"",(double) image->depth); if (image->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Matte=True""); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Matte=MagickFalse""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" BMP bits_per_pixel=%.20g"",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=BI_RGB""); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=BI_RLE8""); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=BI_BITFIELDS""); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=UNKNOWN (%lu)"",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Number_colors=unspecified""); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Number_colors=%lu"",bmp_info.number_colors); } (void) WriteBlob(image,2,(unsigned char *) ""BM""); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */ (void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */ (void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */ (void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */ (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */ (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */ (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Colormap: %.20g entries"",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Pixels: %lu bytes"",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }","static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { BMPInfo bmp_info; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MagickOffsetType scene; MemoryInfo *pixel_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, type; ssize_t y; unsigned char *bmp_data, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); type=4; if (LocaleCompare(image_info->magick,""BMP2"") == 0) type=2; else if (LocaleCompare(image_info->magick,""BMP3"") == 0) type=3; option=GetImageOption(image_info,""bmp:format""); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Format=%s"",option); if (LocaleCompare(option,""bmp2"") == 0) type=2; if (LocaleCompare(option,""bmp3"") == 0) type=3; if (LocaleCompare(option,""bmp4"") == 0) type=4; } scene=0; do { /* Initialize BMP raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass,exception); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass,exception); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait)) { option=GetImageOption(image_info,""bmp3:alpha""); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,""icc""); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } if ((image->columns != (signed int) image->columns) || (image->rows != (signed int) image->rows)) ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned long) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size, sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { ssize_t offset; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } offset=(ssize_t) (image->columns+7)/8; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t byte, nibble; ssize_t offset; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(image,p) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } p+=GetPixelChannels(image); } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } offset=(ssize_t) (image->columns+1)/2; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); p+=GetPixelChannels(image); } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Writing BMP version %.20g datastream"",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Storage class=DirectClass""); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Storage class=PseudoClass""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Image depth=%.20g"",(double) image->depth); if (image->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Matte=True""); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Matte=MagickFalse""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" BMP bits_per_pixel=%.20g"",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=BI_RGB""); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=BI_RLE8""); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=BI_BITFIELDS""); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Compression=UNKNOWN (%lu)"",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Number_colors=unspecified""); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Number_colors=%lu"",bmp_info.number_colors); } (void) WriteBlob(image,2,(unsigned char *) ""BM""); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */ (void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */ (void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */ (void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */ (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */ (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */ (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Colormap: %.20g entries"",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Pixels: %lu bytes"",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }","{'deleted': [{'line_no': 178, 'char_start': 5036, 'char_end': 5105, 'line': ' bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows);\n'}], 'added': [{'line_no': 175, 'char_start': 4925, 'char_end': 4984, 'line': ' if ((image->columns != (signed int) image->columns) ||\n'}, {'line_no': 176, 'char_start': 4984, 'char_end': 5035, 'line': ' (image->rows != (signed int) image->rows))\n'}, {'line_no': 177, 'char_start': 5035, 'char_end': 5103, 'line': ' ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit"");\n'}, {'line_no': 181, 'char_start': 5214, 'char_end': 5284, 'line': ' bmp_info.image_size=(unsigned long) (bytes_per_line*image->rows);\n'}]}","{'deleted': [{'char_start': 4970, 'char_end': 4970, 'chars': ''}, {'char_start': 5070, 'char_end': 5071, 'chars': 'i'}, {'char_start': 5072, 'char_end': 5073, 'chars': 't'}], 'added': [{'char_start': 4929, 'char_end': 5107, 'chars': 'if ((image->columns != (signed int) image->columns) ||\n (image->rows != (signed int) image->rows))\n ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit"");\n '}, {'char_start': 5248, 'char_end': 5250, 'chars': 'lo'}, {'char_start': 5251, 'char_end': 5252, 'chars': 'g'}]}",github.com/ImageMagick/ImageMagick/commit/4cc6ec8a4197d4c008577127736bf7985d632323,coders/bmp.c,cwe-190,5673 cwe-089,process_vote,"def process_vote(target,action,chan,mask,db,notice,conn): if ' ' in target: notice('Invalid nick') return try: votes2kick = database.get(db,'channels','votekick','chan',chan) except: votes2kick = 10 try: votes2ban = database.get(db,'channels','voteban','chan',chan) except: votes2ban = 10 if len(target) is 0: if action is 'kick': notice('Votes required to kick: {}'.format(votes2kick)) elif action is 'ban': notice('Votes required to ban: {}'.format(votes2ban)) return votefinished = False global db_ready if not db_ready: db_init(db) chan = chan.lower() target = target.lower() voter = user.format_hostmask(mask) voters = db.execute(""SELECT voters FROM votes where chan='{}' and action='{}' and target like '{}'"".format(chan,action,target)).fetchone() if conn.nick.lower() in target: return ""I dont think so Tim."" if voters: voters = voters[0] if voter in voters: notice(""You have already voted."") return else: voters = '{} {}'.format(voters,voter).strip() notice(""Thank you for your vote!"") else: voters = voter votecount = len(voters.split(' ')) if 'kick' in action: votemax = int(votes2kick) if votecount >= votemax: votefinished = True conn.send(""KICK {} {} :{}"".format(chan, target, ""You have been voted off the island."")) if 'ban' in action: votemax = int(votes2ban) if votecount >= votemax: votefinished = True conn.send(""MODE {} +b {}"".format(chan, user.get_hostmask(target,db))) conn.send(""KICK {} {} :"".format(chan, target, ""You have been voted off the island."")) if votefinished: db.execute(""DELETE FROM votes where chan='{}' and action='{}' and target like '{}'"".format(chan,action,target)) else: db.execute(""insert or replace into votes(chan, action, target, voters, time) values(?,?,?,?,?)"", (chan, action, target, voters, time.time())) db.commit() return (""Votes to {} {}: {}/{}"".format(action, target, votecount,votemax))","def process_vote(target,action,chan,mask,db,notice,conn): if ' ' in target: notice('Invalid nick') return try: votes2kick = database.get(db,'channels','votekick','chan',chan) except: votes2kick = 10 try: votes2ban = database.get(db,'channels','voteban','chan',chan) except: votes2ban = 10 if len(target) is 0: if action is 'kick': notice('Votes required to kick: {}'.format(votes2kick)) elif action is 'ban': notice('Votes required to ban: {}'.format(votes2ban)) return votefinished = False global db_ready if not db_ready: db_init(db) chan = chan.lower() target = target.lower() voter = user.format_hostmask(mask) voters = db.execute(""SELECT voters FROM votes where chan=? and action=? and target like ?"", chan, action, target).fetchone() if conn.nick.lower() in target: return ""I dont think so Tim."" if voters: voters = voters[0] if voter in voters: notice(""You have already voted."") return else: voters = '{} {}'.format(voters,voter).strip() notice(""Thank you for your vote!"") else: voters = voter votecount = len(voters.split(' ')) if 'kick' in action: votemax = int(votes2kick) if votecount >= votemax: votefinished = True conn.send(""KICK {} {} :{}"".format(chan, target, ""You have been voted off the island."")) if 'ban' in action: votemax = int(votes2ban) if votecount >= votemax: votefinished = True conn.send(""MODE {} +b {}"".format(chan, user.get_hostmask(target,db))) conn.send(""KICK {} {} :"".format(chan, target, ""You have been voted off the island."")) if votefinished: db.execute(""DELETE FROM votes where chan=? and action=? and target like ?"", chan, action, target) else: db.execute(""insert or replace into votes(chan, action, target, voters, time) values(?,?,?,?,?)"", (chan, action, target, voters, time.time())) db.commit() return (""Votes to {} {}: {}/{}"".format(action, target, votecount,votemax))","{'deleted': [{'line_no': 22, 'char_start': 707, 'char_end': 850, 'line': ' voters = db.execute(""SELECT voters FROM votes where chan=\'{}\' and action=\'{}\' and target like \'{}\'"".format(chan,action,target)).fetchone()\n'}, {'line_no': 51, 'char_start': 1781, 'char_end': 1914, 'line': ' if votefinished: db.execute(""DELETE FROM votes where chan=\'{}\' and action=\'{}\' and target like \'{}\'"".format(chan,action,target))\n'}], 'added': [{'line_no': 22, 'char_start': 707, 'char_end': 836, 'line': ' voters = db.execute(""SELECT voters FROM votes where chan=? and action=? and target like ?"", chan, action, target).fetchone()\n'}, {'line_no': 51, 'char_start': 1767, 'char_end': 1886, 'line': ' if votefinished: db.execute(""DELETE FROM votes where chan=? and action=? and target like ?"", chan, action, target)\n'}]}","{'deleted': [{'char_start': 768, 'char_end': 772, 'chars': ""'{}'""}, {'char_start': 784, 'char_end': 788, 'chars': ""'{}'""}, {'char_start': 805, 'char_end': 809, 'chars': ""'{}'""}, {'char_start': 810, 'char_end': 818, 'chars': '.format('}, {'char_start': 836, 'char_end': 837, 'chars': ')'}, {'char_start': 1843, 'char_end': 1847, 'chars': ""'{}'""}, {'char_start': 1859, 'char_end': 1863, 'chars': ""'{}'""}, {'char_start': 1880, 'char_end': 1884, 'chars': ""'{}'""}, {'char_start': 1885, 'char_end': 1893, 'chars': '.format('}, {'char_start': 1911, 'char_end': 1912, 'chars': ')'}], 'added': [{'char_start': 768, 'char_end': 769, 'chars': '?'}, {'char_start': 781, 'char_end': 782, 'chars': '?'}, {'char_start': 799, 'char_end': 800, 'chars': '?'}, {'char_start': 801, 'char_end': 803, 'chars': ', '}, {'char_start': 808, 'char_end': 809, 'chars': ' '}, {'char_start': 816, 'char_end': 817, 'chars': ' '}, {'char_start': 1829, 'char_end': 1830, 'chars': '?'}, {'char_start': 1842, 'char_end': 1843, 'chars': '?'}, {'char_start': 1860, 'char_end': 1861, 'chars': '?'}, {'char_start': 1862, 'char_end': 1864, 'chars': ', '}, {'char_start': 1869, 'char_end': 1870, 'chars': ' '}, {'char_start': 1877, 'char_end': 1878, 'chars': ' '}]}",github.com/gstack/uguubot/commit/700ff40be84be88964e61f8ae780564e5862460d,plugins/vote.py,cwe-089,560 cwe-125,ng_pkt,"static int ng_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ng *pkt; const char *ptr; size_t alloclen; pkt = git__malloc(sizeof(*pkt)); GITERR_CHECK_ALLOC(pkt); pkt->ref = NULL; pkt->type = GIT_PKT_NG; line += 3; /* skip ""ng "" */ if (!(ptr = strchr(line, ' '))) goto out_err; len = ptr - line; GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->ref = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt->ref); memcpy(pkt->ref, line, len); pkt->ref[len] = '\0'; line = ptr + 1; if (!(ptr = strchr(line, '\n'))) goto out_err; len = ptr - line; GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->msg = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt->msg); memcpy(pkt->msg, line, len); pkt->msg[len] = '\0'; *out = (git_pkt *)pkt; return 0; out_err: giterr_set(GITERR_NET, ""invalid packet line""); git__free(pkt->ref); git__free(pkt); return -1; }","static int ng_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ng *pkt; const char *ptr; size_t alloclen; pkt = git__malloc(sizeof(*pkt)); GITERR_CHECK_ALLOC(pkt); pkt->ref = NULL; pkt->type = GIT_PKT_NG; if (len < 3) goto out_err; line += 3; /* skip ""ng "" */ len -= 3; if (!(ptr = memchr(line, ' ', len))) goto out_err; len = ptr - line; GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->ref = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt->ref); memcpy(pkt->ref, line, len); pkt->ref[len] = '\0'; if (len < 1) goto out_err; line = ptr + 1; len -= 1; if (!(ptr = memchr(line, '\n', len))) goto out_err; len = ptr - line; GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->msg = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt->msg); memcpy(pkt->msg, line, len); pkt->msg[len] = '\0'; *out = (git_pkt *)pkt; return 0; out_err: giterr_set(GITERR_NET, ""invalid packet line""); git__free(pkt->ref); git__free(pkt); return -1; }","{'deleted': [{'line_no': 14, 'char_start': 254, 'char_end': 287, 'line': ""\tif (!(ptr = strchr(line, ' ')))\n""}, {'line_no': 26, 'char_start': 505, 'char_end': 539, 'line': ""\tif (!(ptr = strchr(line, '\\n')))\n""}], 'added': [{'line_no': 13, 'char_start': 225, 'char_end': 239, 'line': '\tif (len < 3)\n'}, {'line_no': 14, 'char_start': 239, 'char_end': 255, 'line': '\t\tgoto out_err;\n'}, {'line_no': 16, 'char_start': 284, 'char_end': 295, 'line': '\tlen -= 3;\n'}, {'line_no': 17, 'char_start': 295, 'char_end': 333, 'line': ""\tif (!(ptr = memchr(line, ' ', len)))\n""}, {'line_no': 28, 'char_start': 534, 'char_end': 548, 'line': '\tif (len < 1)\n'}, {'line_no': 29, 'char_start': 548, 'char_end': 564, 'line': '\t\tgoto out_err;\n'}, {'line_no': 31, 'char_start': 581, 'char_end': 592, 'line': '\tlen -= 1;\n'}, {'line_no': 32, 'char_start': 592, 'char_end': 631, 'line': ""\tif (!(ptr = memchr(line, '\\n', len)))\n""}]}","{'deleted': [{'char_start': 267, 'char_end': 270, 'chars': 'str'}, {'char_start': 518, 'char_end': 521, 'chars': 'str'}], 'added': [{'char_start': 226, 'char_end': 256, 'chars': 'if (len < 3)\n\t\tgoto out_err;\n\t'}, {'char_start': 285, 'char_end': 296, 'chars': 'len -= 3;\n\t'}, {'char_start': 308, 'char_end': 311, 'chars': 'mem'}, {'char_start': 324, 'char_end': 329, 'chars': ', len'}, {'char_start': 535, 'char_end': 565, 'chars': 'if (len < 1)\n\t\tgoto out_err;\n\t'}, {'char_start': 582, 'char_end': 593, 'chars': 'len -= 1;\n\t'}, {'char_start': 605, 'char_end': 608, 'chars': 'mem'}, {'char_start': 622, 'char_end': 627, 'chars': ', len'}]}",github.com/libgit2/libgit2/commit/1f9a8510e1d2f20ed7334eeeddb92c4dd8e7c649,src/transports/smart_pkt.c,cwe-125,291 cwe-078,whitelist,"def whitelist(users: str): for user in users.split(): call(WHITELIST_COMMAND_TEMPLATE.format(user))","def whitelist(channel: discord.TextChannel, users: str): for user in users.split(): if not re.match(r'^[A-Za-z0-9_]{3,16}$', user): # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408 await channel.send('\'{}\' is not a valid Minecraft username'.format(user)) else: call(WHITELIST_COMMAND_TEMPLATE.format(user))","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 27, 'line': 'def whitelist(users: str):\n'}, {'line_no': 3, 'char_start': 58, 'char_end': 111, 'line': ' call(WHITELIST_COMMAND_TEMPLATE.format(user))\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 57, 'line': 'def whitelist(channel: discord.TextChannel, users: str):\n'}, {'line_no': 3, 'char_start': 88, 'char_end': 243, 'line': "" if not re.match(r'^[A-Za-z0-9_]{3,16}$', user): # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408\n""}, {'line_no': 4, 'char_start': 243, 'char_end': 331, 'line': "" await channel.send('\\'{}\\' is not a valid Minecraft username'.format(user))\n""}, {'line_no': 5, 'char_start': 331, 'char_end': 345, 'line': ' else:\n'}, {'line_no': 6, 'char_start': 345, 'char_end': 402, 'line': ' call(WHITELIST_COMMAND_TEMPLATE.format(user))\n'}]}","{'deleted': [], 'added': [{'char_start': 14, 'char_end': 44, 'chars': 'channel: discord.TextChannel, '}, {'char_start': 88, 'char_end': 349, 'chars': "" if not re.match(r'^[A-Za-z0-9_]{3,16}$', user): # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408\n await channel.send('\\'{}\\' is not a valid Minecraft username'.format(user))\n else:\n ""}]}",github.com/thomotron/Gatekeep/commit/955660f9b3dc336ab0d5dfb4392b3ab6deac6b25,bot.py,cwe-078,25 cwe-416,HeifContext::interpret_heif_file,"Error HeifContext::interpret_heif_file() { m_all_images.clear(); m_top_level_images.clear(); m_primary_image.reset(); // --- reference all non-hidden images std::vector image_IDs = m_heif_file->get_item_IDs(); bool primary_is_grid = false; for (heif_item_id id : image_IDs) { auto infe_box = m_heif_file->get_infe_box(id); if (!infe_box) { // TODO(farindk): Should we return an error instead of skipping the invalid id? continue; } if (item_type_is_image(infe_box->get_item_type())) { auto image = std::make_shared(this, id); m_all_images.insert(std::make_pair(id, image)); if (!infe_box->is_hidden_item()) { if (id==m_heif_file->get_primary_image_ID()) { image->set_primary(true); m_primary_image = image; primary_is_grid = infe_box->get_item_type() == ""grid""; } m_top_level_images.push_back(image); } } } if (!m_primary_image) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""'pitm' box references a non-existing image""); } // --- remove thumbnails from top-level images and assign to their respective image auto iref_box = m_heif_file->get_iref_box(); if (iref_box) { // m_top_level_images.clear(); for (auto& pair : m_all_images) { auto& image = pair.second; std::vector references = iref_box->get_references_from(image->get_id()); for (const Box_iref::Reference& ref : references) { uint32_t type = ref.header.get_short_type(); if (type==fourcc(""thmb"")) { // --- this is a thumbnail image, attach to the main image std::vector refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, ""Too many thumbnail references""); } image->set_is_thumbnail_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (master_iter == m_all_images.end()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Thumbnail references a non-existing image""); } if (master_iter->second->is_thumbnail()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Thumbnail references another thumbnail""); } if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Recursive thumbnail image detected""); } master_iter->second->add_thumbnail(image); remove_top_level_image(image); } else if (type==fourcc(""auxl"")) { // --- this is an auxiliary image // check whether it is an alpha channel and attach to the main image if yes std::vector properties; Error err = m_heif_file->get_properties(image->get_id(), properties); if (err) { return err; } std::shared_ptr auxC_property; for (const auto& property : properties) { auto auxC = std::dynamic_pointer_cast(property.property); if (auxC) { auxC_property = auxC; } } if (!auxC_property) { std::stringstream sstr; sstr << ""No auxC property for image "" << image->get_id(); return Error(heif_error_Invalid_input, heif_suberror_Auxiliary_image_type_unspecified, sstr.str()); } std::vector refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, ""Too many auxiliary image references""); } // alpha channel if (auxC_property->get_aux_type() == ""urn:mpeg:avc:2015:auxid:1"" || auxC_property->get_aux_type() == ""urn:mpeg:hevc:2015:auxid:1"") { image->set_is_alpha_channel_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Recursive alpha image detected""); } master_iter->second->set_alpha_channel(image); } // depth channel if (auxC_property->get_aux_type() == ""urn:mpeg:hevc:2015:auxid:2"") { image->set_is_depth_channel_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Recursive depth image detected""); } master_iter->second->set_depth_channel(image); auto subtypes = auxC_property->get_subtypes(); std::vector> sei_messages; Error err = decode_hevc_aux_sei_messages(subtypes, sei_messages); for (auto& msg : sei_messages) { auto depth_msg = std::dynamic_pointer_cast(msg); if (depth_msg) { image->set_depth_representation_info(*depth_msg); } } } remove_top_level_image(image); } else { // 'image' is a normal image, keep it as a top-level image } } } } // --- check that HEVC images have an hvcC property for (auto& pair : m_all_images) { auto& image = pair.second; std::shared_ptr infe = m_heif_file->get_infe_box(image->get_id()); if (infe->get_item_type() == ""hvc1"") { auto ipma = m_heif_file->get_ipma_box(); auto ipco = m_heif_file->get_ipco_box(); if (!ipco->get_property_for_item_ID(image->get_id(), ipma, fourcc(""hvcC""))) { return Error(heif_error_Invalid_input, heif_suberror_No_hvcC_box, ""No hvcC property in hvc1 type image""); } } } // --- read through properties for each image and extract image resolutions for (auto& pair : m_all_images) { auto& image = pair.second; std::vector properties; Error err = m_heif_file->get_properties(pair.first, properties); if (err) { return err; } bool ispe_read = false; bool primary_colr_set = false; for (const auto& prop : properties) { auto ispe = std::dynamic_pointer_cast(prop.property); if (ispe) { uint32_t width = ispe->get_width(); uint32_t height = ispe->get_height(); // --- check whether the image size is ""too large"" if (width >= static_cast(MAX_IMAGE_WIDTH) || height >= static_cast(MAX_IMAGE_HEIGHT)) { std::stringstream sstr; sstr << ""Image size "" << width << ""x"" << height << "" exceeds the maximum image size "" << MAX_IMAGE_WIDTH << ""x"" << MAX_IMAGE_HEIGHT << ""\n""; return Error(heif_error_Memory_allocation_error, heif_suberror_Security_limit_exceeded, sstr.str()); } image->set_resolution(width, height); image->set_ispe_resolution(width, height); ispe_read = true; } if (ispe_read) { auto clap = std::dynamic_pointer_cast(prop.property); if (clap) { image->set_resolution( clap->get_width_rounded(), clap->get_height_rounded() ); } auto irot = std::dynamic_pointer_cast(prop.property); if (irot) { if (irot->get_rotation()==90 || irot->get_rotation()==270) { // swap width and height image->set_resolution( image->get_height(), image->get_width() ); } } } auto colr = std::dynamic_pointer_cast(prop.property); if (colr) { auto profile = colr->get_color_profile(); image->set_color_profile(profile); // if this is a grid item we assign the first one's color profile // to the main image which is supposed to be a grid // TODO: this condition is not correct. It would also classify a secondary image as a 'grid item'. // We have to set the grid-image color profile in another way... const bool is_grid_item = !image->is_primary() && !image->is_alpha_channel() && !image->is_depth_channel(); if (primary_is_grid && !primary_colr_set && is_grid_item) { m_primary_image->set_color_profile(profile); primary_colr_set = true; } } } } // --- read metadata and assign to image for (heif_item_id id : image_IDs) { std::string item_type = m_heif_file->get_item_type(id); std::string content_type = m_heif_file->get_content_type(id); if (item_type == ""Exif"" || (item_type==""mime"" && content_type==""application/rdf+xml"")) { std::shared_ptr metadata = std::make_shared(); metadata->item_id = id; metadata->item_type = item_type; metadata->content_type = content_type; Error err = m_heif_file->get_compressed_image_data(id, &(metadata->m_data)); if (err) { return err; } //std::cerr.write((const char*)data.data(), data.size()); // --- assign metadata to the image if (iref_box) { std::vector references = iref_box->get_references_from(id); for (const auto& ref : references) { if (ref.header.get_short_type() == fourcc(""cdsc"")) { std::vector refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, ""Exif data not correctly assigned to image""); } uint32_t exif_image_id = refs[0]; auto img_iter = m_all_images.find(exif_image_id); if (img_iter == m_all_images.end()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Exif data assigned to non-existing image""); } img_iter->second->add_metadata(metadata); } } } } } return Error::Ok; }","Error HeifContext::interpret_heif_file() { m_all_images.clear(); m_top_level_images.clear(); m_primary_image.reset(); // --- reference all non-hidden images std::vector image_IDs = m_heif_file->get_item_IDs(); bool primary_is_grid = false; for (heif_item_id id : image_IDs) { auto infe_box = m_heif_file->get_infe_box(id); if (!infe_box) { // TODO(farindk): Should we return an error instead of skipping the invalid id? continue; } if (item_type_is_image(infe_box->get_item_type())) { auto image = std::make_shared(this, id); m_all_images.insert(std::make_pair(id, image)); if (!infe_box->is_hidden_item()) { if (id==m_heif_file->get_primary_image_ID()) { image->set_primary(true); m_primary_image = image; primary_is_grid = infe_box->get_item_type() == ""grid""; } m_top_level_images.push_back(image); } } } if (!m_primary_image) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""'pitm' box references a non-existing image""); } // --- remove thumbnails from top-level images and assign to their respective image auto iref_box = m_heif_file->get_iref_box(); if (iref_box) { // m_top_level_images.clear(); for (auto& pair : m_all_images) { auto& image = pair.second; std::vector references = iref_box->get_references_from(image->get_id()); for (const Box_iref::Reference& ref : references) { uint32_t type = ref.header.get_short_type(); if (type==fourcc(""thmb"")) { // --- this is a thumbnail image, attach to the main image std::vector refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, ""Too many thumbnail references""); } image->set_is_thumbnail_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (master_iter == m_all_images.end()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Thumbnail references a non-existing image""); } if (master_iter->second->is_thumbnail()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Thumbnail references another thumbnail""); } if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Recursive thumbnail image detected""); } master_iter->second->add_thumbnail(image); remove_top_level_image(image); } else if (type==fourcc(""auxl"")) { // --- this is an auxiliary image // check whether it is an alpha channel and attach to the main image if yes std::vector properties; Error err = m_heif_file->get_properties(image->get_id(), properties); if (err) { return err; } std::shared_ptr auxC_property; for (const auto& property : properties) { auto auxC = std::dynamic_pointer_cast(property.property); if (auxC) { auxC_property = auxC; } } if (!auxC_property) { std::stringstream sstr; sstr << ""No auxC property for image "" << image->get_id(); return Error(heif_error_Invalid_input, heif_suberror_Auxiliary_image_type_unspecified, sstr.str()); } std::vector refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, ""Too many auxiliary image references""); } // alpha channel if (auxC_property->get_aux_type() == ""urn:mpeg:avc:2015:auxid:1"" || auxC_property->get_aux_type() == ""urn:mpeg:hevc:2015:auxid:1"") { image->set_is_alpha_channel_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (master_iter == m_all_images.end()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Non-existing alpha image referenced""); } if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Recursive alpha image detected""); } master_iter->second->set_alpha_channel(image); } // depth channel if (auxC_property->get_aux_type() == ""urn:mpeg:hevc:2015:auxid:2"") { image->set_is_depth_channel_of(refs[0]); auto master_iter = m_all_images.find(refs[0]); if (image.get() == master_iter->second.get()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Recursive depth image detected""); } master_iter->second->set_depth_channel(image); auto subtypes = auxC_property->get_subtypes(); std::vector> sei_messages; Error err = decode_hevc_aux_sei_messages(subtypes, sei_messages); for (auto& msg : sei_messages) { auto depth_msg = std::dynamic_pointer_cast(msg); if (depth_msg) { image->set_depth_representation_info(*depth_msg); } } } remove_top_level_image(image); } else { // 'image' is a normal image, keep it as a top-level image } } } } // --- check that HEVC images have an hvcC property for (auto& pair : m_all_images) { auto& image = pair.second; std::shared_ptr infe = m_heif_file->get_infe_box(image->get_id()); if (infe->get_item_type() == ""hvc1"") { auto ipma = m_heif_file->get_ipma_box(); auto ipco = m_heif_file->get_ipco_box(); if (!ipco->get_property_for_item_ID(image->get_id(), ipma, fourcc(""hvcC""))) { return Error(heif_error_Invalid_input, heif_suberror_No_hvcC_box, ""No hvcC property in hvc1 type image""); } } } // --- read through properties for each image and extract image resolutions for (auto& pair : m_all_images) { auto& image = pair.second; std::vector properties; Error err = m_heif_file->get_properties(pair.first, properties); if (err) { return err; } bool ispe_read = false; bool primary_colr_set = false; for (const auto& prop : properties) { auto ispe = std::dynamic_pointer_cast(prop.property); if (ispe) { uint32_t width = ispe->get_width(); uint32_t height = ispe->get_height(); // --- check whether the image size is ""too large"" if (width >= static_cast(MAX_IMAGE_WIDTH) || height >= static_cast(MAX_IMAGE_HEIGHT)) { std::stringstream sstr; sstr << ""Image size "" << width << ""x"" << height << "" exceeds the maximum image size "" << MAX_IMAGE_WIDTH << ""x"" << MAX_IMAGE_HEIGHT << ""\n""; return Error(heif_error_Memory_allocation_error, heif_suberror_Security_limit_exceeded, sstr.str()); } image->set_resolution(width, height); image->set_ispe_resolution(width, height); ispe_read = true; } if (ispe_read) { auto clap = std::dynamic_pointer_cast(prop.property); if (clap) { image->set_resolution( clap->get_width_rounded(), clap->get_height_rounded() ); } auto irot = std::dynamic_pointer_cast(prop.property); if (irot) { if (irot->get_rotation()==90 || irot->get_rotation()==270) { // swap width and height image->set_resolution( image->get_height(), image->get_width() ); } } } auto colr = std::dynamic_pointer_cast(prop.property); if (colr) { auto profile = colr->get_color_profile(); image->set_color_profile(profile); // if this is a grid item we assign the first one's color profile // to the main image which is supposed to be a grid // TODO: this condition is not correct. It would also classify a secondary image as a 'grid item'. // We have to set the grid-image color profile in another way... const bool is_grid_item = !image->is_primary() && !image->is_alpha_channel() && !image->is_depth_channel(); if (primary_is_grid && !primary_colr_set && is_grid_item) { m_primary_image->set_color_profile(profile); primary_colr_set = true; } } } } // --- read metadata and assign to image for (heif_item_id id : image_IDs) { std::string item_type = m_heif_file->get_item_type(id); std::string content_type = m_heif_file->get_content_type(id); if (item_type == ""Exif"" || (item_type==""mime"" && content_type==""application/rdf+xml"")) { std::shared_ptr metadata = std::make_shared(); metadata->item_id = id; metadata->item_type = item_type; metadata->content_type = content_type; Error err = m_heif_file->get_compressed_image_data(id, &(metadata->m_data)); if (err) { return err; } //std::cerr.write((const char*)data.data(), data.size()); // --- assign metadata to the image if (iref_box) { std::vector references = iref_box->get_references_from(id); for (const auto& ref : references) { if (ref.header.get_short_type() == fourcc(""cdsc"")) { std::vector refs = ref.to_item_ID; if (refs.size() != 1) { return Error(heif_error_Invalid_input, heif_suberror_Unspecified, ""Exif data not correctly assigned to image""); } uint32_t exif_image_id = refs[0]; auto img_iter = m_all_images.find(exif_image_id); if (img_iter == m_all_images.end()) { return Error(heif_error_Invalid_input, heif_suberror_Nonexisting_item_referenced, ""Exif data assigned to non-existing image""); } img_iter->second->add_metadata(metadata); } } } } } return Error::Ok; }","{'deleted': [], 'added': [{'line_no': 134, 'char_start': 4504, 'char_end': 4557, 'line': ' if (master_iter == m_all_images.end()) {\n'}, {'line_no': 135, 'char_start': 4557, 'char_end': 4610, 'line': ' return Error(heif_error_Invalid_input,\n'}, {'line_no': 136, 'char_start': 4610, 'char_end': 4680, 'line': ' heif_suberror_Nonexisting_item_referenced,\n'}, {'line_no': 137, 'char_start': 4680, 'char_end': 4747, 'line': ' ""Non-existing alpha image referenced"");\n'}, {'line_no': 138, 'char_start': 4747, 'char_end': 4761, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 4520, 'char_end': 4777, 'chars': 'master_iter == m_all_images.end()) {\n return Error(heif_error_Invalid_input,\n heif_suberror_Nonexisting_item_referenced,\n ""Non-existing alpha image referenced"");\n }\n if ('}]}",github.com/strukturag/libheif/commit/995a4283d8ed2d0d2c1ceb1a577b993df2f0e014,libheif/heif_context.cc,cwe-416,2572 cwe-022,process,"local void process(char *path) { int method = -1; /* get_header() return value */ size_t len; /* length of base name (minus suffix) */ struct stat st; /* to get file type and mod time */ /* all compressed suffixes for decoding search, in length order */ static char *sufs[] = {"".z"", ""-z"", ""_z"", "".Z"", "".gz"", ""-gz"", "".zz"", ""-zz"", "".zip"", "".ZIP"", "".tgz"", NULL}; /* open input file with name in, descriptor ind -- set name and mtime */ if (path == NULL) { strcpy(g.inf, """"); g.ind = 0; g.name = NULL; g.mtime = g.headis & 2 ? (fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0; len = 0; } else { /* set input file name (already set if recursed here) */ if (path != g.inf) { strncpy(g.inf, path, sizeof(g.inf)); if (g.inf[sizeof(g.inf) - 1]) bail(""name too long: "", path); } len = strlen(g.inf); /* try to stat input file -- if not there and decoding, look for that name with compressed suffixes */ if (lstat(g.inf, &st)) { if (errno == ENOENT && (g.list || g.decode)) { char **try = sufs; do { if (*try == NULL || len + strlen(*try) >= sizeof(g.inf)) break; strcpy(g.inf + len, *try++); errno = 0; } while (lstat(g.inf, &st) && errno == ENOENT); } #ifdef EOVERFLOW if (errno == EOVERFLOW || errno == EFBIG) bail(g.inf, "" too large -- not compiled with large file support""); #endif if (errno) { g.inf[len] = 0; complain(""%s does not exist -- skipping"", g.inf); return; } len = strlen(g.inf); } /* only process regular files, but allow symbolic links if -f, recurse into directory if -r */ if ((st.st_mode & S_IFMT) != S_IFREG && (st.st_mode & S_IFMT) != S_IFLNK && (st.st_mode & S_IFMT) != S_IFDIR) { complain(""%s is a special file or device -- skipping"", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) { complain(""%s is a symbolic link -- skipping"", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) { complain(""%s is a directory -- skipping"", g.inf); return; } /* recurse into directory (assumes Unix) */ if ((st.st_mode & S_IFMT) == S_IFDIR) { char *roll, *item, *cut, *base, *bigger; size_t len, hold; DIR *here; struct dirent *next; /* accumulate list of entries (need to do this, since readdir() behavior not defined if directory modified between calls) */ here = opendir(g.inf); if (here == NULL) return; hold = 512; roll = MALLOC(hold); if (roll == NULL) bail(""not enough memory"", """"); *roll = 0; item = roll; while ((next = readdir(here)) != NULL) { if (next->d_name[0] == 0 || (next->d_name[0] == '.' && (next->d_name[1] == 0 || (next->d_name[1] == '.' && next->d_name[2] == 0)))) continue; len = strlen(next->d_name) + 1; if (item + len + 1 > roll + hold) { do { /* make roll bigger */ hold <<= 1; } while (item + len + 1 > roll + hold); bigger = REALLOC(roll, hold); if (bigger == NULL) { FREE(roll); bail(""not enough memory"", """"); } item = bigger + (item - roll); roll = bigger; } strcpy(item, next->d_name); item += len; *item = 0; } closedir(here); /* run process() for each entry in the directory */ cut = base = g.inf + strlen(g.inf); if (base > g.inf && base[-1] != (unsigned char)'/') { if ((size_t)(base - g.inf) >= sizeof(g.inf)) bail(""path too long"", g.inf); *base++ = '/'; } item = roll; while (*item) { strncpy(base, item, sizeof(g.inf) - (base - g.inf)); if (g.inf[sizeof(g.inf) - 1]) { strcpy(g.inf + (sizeof(g.inf) - 4), ""...""); bail(""path too long: "", g.inf); } process(g.inf); item += strlen(item) + 1; } *cut = 0; /* release list of entries */ FREE(roll); return; } /* don't compress .gz (or provided suffix) files, unless -f */ if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) && strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) { complain(""%s ends with %s -- skipping"", g.inf, g.sufx); return; } /* create output file only if input file has compressed suffix */ if (g.decode == 1 && !g.pipeout && !g.list) { int suf = compressed_suffix(g.inf); if (suf == 0) { complain(""%s does not have compressed suffix -- skipping"", g.inf); return; } len -= suf; } /* open input file */ g.ind = open(g.inf, O_RDONLY, 0); if (g.ind < 0) bail(""read error on "", g.inf); /* prepare gzip header information for compression */ g.name = g.headis & 1 ? justname(g.inf) : NULL; g.mtime = g.headis & 2 ? st.st_mtime : 0; } SET_BINARY_MODE(g.ind); /* if decoding or testing, try to read gzip header */ g.hname = NULL; if (g.decode) { in_init(); method = get_header(1); if (method != 8 && method != 257 && /* gzip -cdf acts like cat on uncompressed input */ !(method == -2 && g.force && g.pipeout && g.decode != 2 && !g.list)) { RELEASE(g.hname); if (g.ind != 0) close(g.ind); if (method != -1) complain(method < 0 ? ""%s is not compressed -- skipping"" : ""%s has unknown compression method -- skipping"", g.inf); return; } /* if requested, test input file (possibly a special list) */ if (g.decode == 2) { if (method == 8) infchk(); else { unlzw(); if (g.list) { g.in_tot -= 3; show_info(method, 0, g.out_tot, 0); } } RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } } /* if requested, just list information about input file */ if (g.list) { list_info(); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* create output file out, descriptor outd */ if (path == NULL || g.pipeout) { /* write to stdout */ g.outf = MALLOC(strlen("""") + 1); if (g.outf == NULL) bail(""not enough memory"", """"); strcpy(g.outf, """"); g.outd = 1; if (!g.decode && !g.force && isatty(g.outd)) bail(""trying to write compressed data to a terminal"", "" (use -f to force)""); } else { char *to, *repl; /* use header name for output when decompressing with -N */ to = g.inf; if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) { to = g.hname; len = strlen(g.hname); } /* replace .tgz with .tar when decoding */ repl = g.decode && strcmp(to + len, "".tgz"") ? """" : "".tar""; /* create output file and open to write */ g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1); if (g.outf == NULL) bail(""not enough memory"", """"); memcpy(g.outf, to, len); strcpy(g.outf + len, g.decode ? repl : g.sufx); g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY | (g.force ? 0 : O_EXCL), 0600); /* if exists and not -f, give user a chance to overwrite */ if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) { int ch, reply; fprintf(stderr, ""%s exists -- overwrite (y/n)? "", g.outf); fflush(stderr); reply = -1; do { ch = getchar(); if (reply < 0 && ch != ' ' && ch != '\t') reply = ch == 'y' || ch == 'Y' ? 1 : 0; } while (ch != EOF && ch != '\n' && ch != '\r'); if (reply == 1) g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY, 0600); } /* if exists and no overwrite, report and go on to next */ if (g.outd < 0 && errno == EEXIST) { complain(""%s exists -- skipping"", g.outf); RELEASE(g.outf); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* if some other error, give up */ if (g.outd < 0) bail(""write error on "", g.outf); } SET_BINARY_MODE(g.outd); RELEASE(g.hname); /* process ind to outd */ if (g.verbosity > 1) fprintf(stderr, ""%s to %s "", g.inf, g.outf); if (g.decode) { if (method == 8) infchk(); else if (method == 257) unlzw(); else cat(); } #ifndef NOTHREAD else if (g.procs > 1) parallel_compress(); #endif else single_compress(0); if (g.verbosity > 1) { putc('\n', stderr); fflush(stderr); } /* finish up, copy attributes, set times, delete original */ if (g.ind != 0) close(g.ind); if (g.outd != 1) { if (close(g.outd)) bail(""write error on "", g.outf); g.outd = -1; /* now prevent deletion on interrupt */ if (g.ind != 0) { copymeta(g.inf, g.outf); if (!g.keep) unlink(g.inf); } if (g.decode && (g.headis & 2) != 0 && g.stamp) touch(g.outf, g.stamp); } RELEASE(g.outf); }","local void process(char *path) { int method = -1; /* get_header() return value */ size_t len; /* length of base name (minus suffix) */ struct stat st; /* to get file type and mod time */ /* all compressed suffixes for decoding search, in length order */ static char *sufs[] = {"".z"", ""-z"", ""_z"", "".Z"", "".gz"", ""-gz"", "".zz"", ""-zz"", "".zip"", "".ZIP"", "".tgz"", NULL}; /* open input file with name in, descriptor ind -- set name and mtime */ if (path == NULL) { strcpy(g.inf, """"); g.ind = 0; g.name = NULL; g.mtime = g.headis & 2 ? (fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0; len = 0; } else { /* set input file name (already set if recursed here) */ if (path != g.inf) { strncpy(g.inf, path, sizeof(g.inf)); if (g.inf[sizeof(g.inf) - 1]) bail(""name too long: "", path); } len = strlen(g.inf); /* try to stat input file -- if not there and decoding, look for that name with compressed suffixes */ if (lstat(g.inf, &st)) { if (errno == ENOENT && (g.list || g.decode)) { char **try = sufs; do { if (*try == NULL || len + strlen(*try) >= sizeof(g.inf)) break; strcpy(g.inf + len, *try++); errno = 0; } while (lstat(g.inf, &st) && errno == ENOENT); } #ifdef EOVERFLOW if (errno == EOVERFLOW || errno == EFBIG) bail(g.inf, "" too large -- not compiled with large file support""); #endif if (errno) { g.inf[len] = 0; complain(""%s does not exist -- skipping"", g.inf); return; } len = strlen(g.inf); } /* only process regular files, but allow symbolic links if -f, recurse into directory if -r */ if ((st.st_mode & S_IFMT) != S_IFREG && (st.st_mode & S_IFMT) != S_IFLNK && (st.st_mode & S_IFMT) != S_IFDIR) { complain(""%s is a special file or device -- skipping"", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) { complain(""%s is a symbolic link -- skipping"", g.inf); return; } if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) { complain(""%s is a directory -- skipping"", g.inf); return; } /* recurse into directory (assumes Unix) */ if ((st.st_mode & S_IFMT) == S_IFDIR) { char *roll, *item, *cut, *base, *bigger; size_t len, hold; DIR *here; struct dirent *next; /* accumulate list of entries (need to do this, since readdir() behavior not defined if directory modified between calls) */ here = opendir(g.inf); if (here == NULL) return; hold = 512; roll = MALLOC(hold); if (roll == NULL) bail(""not enough memory"", """"); *roll = 0; item = roll; while ((next = readdir(here)) != NULL) { if (next->d_name[0] == 0 || (next->d_name[0] == '.' && (next->d_name[1] == 0 || (next->d_name[1] == '.' && next->d_name[2] == 0)))) continue; len = strlen(next->d_name) + 1; if (item + len + 1 > roll + hold) { do { /* make roll bigger */ hold <<= 1; } while (item + len + 1 > roll + hold); bigger = REALLOC(roll, hold); if (bigger == NULL) { FREE(roll); bail(""not enough memory"", """"); } item = bigger + (item - roll); roll = bigger; } strcpy(item, next->d_name); item += len; *item = 0; } closedir(here); /* run process() for each entry in the directory */ cut = base = g.inf + strlen(g.inf); if (base > g.inf && base[-1] != (unsigned char)'/') { if ((size_t)(base - g.inf) >= sizeof(g.inf)) bail(""path too long"", g.inf); *base++ = '/'; } item = roll; while (*item) { strncpy(base, item, sizeof(g.inf) - (base - g.inf)); if (g.inf[sizeof(g.inf) - 1]) { strcpy(g.inf + (sizeof(g.inf) - 4), ""...""); bail(""path too long: "", g.inf); } process(g.inf); item += strlen(item) + 1; } *cut = 0; /* release list of entries */ FREE(roll); return; } /* don't compress .gz (or provided suffix) files, unless -f */ if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) && strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) { complain(""%s ends with %s -- skipping"", g.inf, g.sufx); return; } /* create output file only if input file has compressed suffix */ if (g.decode == 1 && !g.pipeout && !g.list) { int suf = compressed_suffix(g.inf); if (suf == 0) { complain(""%s does not have compressed suffix -- skipping"", g.inf); return; } len -= suf; } /* open input file */ g.ind = open(g.inf, O_RDONLY, 0); if (g.ind < 0) bail(""read error on "", g.inf); /* prepare gzip header information for compression */ g.name = g.headis & 1 ? justname(g.inf) : NULL; g.mtime = g.headis & 2 ? st.st_mtime : 0; } SET_BINARY_MODE(g.ind); /* if decoding or testing, try to read gzip header */ g.hname = NULL; if (g.decode) { in_init(); method = get_header(1); if (method != 8 && method != 257 && /* gzip -cdf acts like cat on uncompressed input */ !(method == -2 && g.force && g.pipeout && g.decode != 2 && !g.list)) { RELEASE(g.hname); if (g.ind != 0) close(g.ind); if (method != -1) complain(method < 0 ? ""%s is not compressed -- skipping"" : ""%s has unknown compression method -- skipping"", g.inf); return; } /* if requested, test input file (possibly a special list) */ if (g.decode == 2) { if (method == 8) infchk(); else { unlzw(); if (g.list) { g.in_tot -= 3; show_info(method, 0, g.out_tot, 0); } } RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } } /* if requested, just list information about input file */ if (g.list) { list_info(); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* create output file out, descriptor outd */ if (path == NULL || g.pipeout) { /* write to stdout */ g.outf = MALLOC(strlen("""") + 1); if (g.outf == NULL) bail(""not enough memory"", """"); strcpy(g.outf, """"); g.outd = 1; if (!g.decode && !g.force && isatty(g.outd)) bail(""trying to write compressed data to a terminal"", "" (use -f to force)""); } else { char *to = g.inf, *sufx = """"; size_t pre = 0; /* select parts of the output file name */ if (g.decode) { /* for -dN or -dNT, use the path from the input file and the name from the header, stripping any path in the header name */ if ((g.headis & 1) != 0 && g.hname != NULL) { pre = justname(g.inf) - g.inf; to = justname(g.hname); len = strlen(to); } /* for -d or -dNn, replace abbreviated suffixes */ else if (strcmp(to + len, "".tgz"") == 0) sufx = "".tar""; } else /* add appropriate suffix when compressing */ sufx = g.sufx; /* create output file and open to write */ g.outf = MALLOC(pre + len + strlen(sufx) + 1); if (g.outf == NULL) bail(""not enough memory"", """"); memcpy(g.outf, g.inf, pre); memcpy(g.outf + pre, to, len); strcpy(g.outf + pre + len, sufx); g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY | (g.force ? 0 : O_EXCL), 0600); /* if exists and not -f, give user a chance to overwrite */ if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) { int ch, reply; fprintf(stderr, ""%s exists -- overwrite (y/n)? "", g.outf); fflush(stderr); reply = -1; do { ch = getchar(); if (reply < 0 && ch != ' ' && ch != '\t') reply = ch == 'y' || ch == 'Y' ? 1 : 0; } while (ch != EOF && ch != '\n' && ch != '\r'); if (reply == 1) g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY, 0600); } /* if exists and no overwrite, report and go on to next */ if (g.outd < 0 && errno == EEXIST) { complain(""%s exists -- skipping"", g.outf); RELEASE(g.outf); RELEASE(g.hname); if (g.ind != 0) close(g.ind); return; } /* if some other error, give up */ if (g.outd < 0) bail(""write error on "", g.outf); } SET_BINARY_MODE(g.outd); RELEASE(g.hname); /* process ind to outd */ if (g.verbosity > 1) fprintf(stderr, ""%s to %s "", g.inf, g.outf); if (g.decode) { if (method == 8) infchk(); else if (method == 257) unlzw(); else cat(); } #ifndef NOTHREAD else if (g.procs > 1) parallel_compress(); #endif else single_compress(0); if (g.verbosity > 1) { putc('\n', stderr); fflush(stderr); } /* finish up, copy attributes, set times, delete original */ if (g.ind != 0) close(g.ind); if (g.outd != 1) { if (close(g.outd)) bail(""write error on "", g.outf); g.outd = -1; /* now prevent deletion on interrupt */ if (g.ind != 0) { copymeta(g.inf, g.outf); if (!g.keep) unlink(g.inf); } if (g.decode && (g.headis & 2) != 0 && g.stamp) touch(g.outf, g.stamp); } RELEASE(g.outf); }","{'deleted': [{'line_no': 224, 'char_start': 8033, 'char_end': 8058, 'line': ' char *to, *repl;\n'}, {'line_no': 225, 'char_start': 8058, 'char_end': 8059, 'line': '\n'}, {'line_no': 226, 'char_start': 8059, 'char_end': 8127, 'line': ' /* use header name for output when decompressing with -N */\n'}, {'line_no': 227, 'char_start': 8127, 'char_end': 8147, 'line': ' to = g.inf;\n'}, {'line_no': 228, 'char_start': 8147, 'char_end': 8213, 'line': ' if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) {\n'}, {'line_no': 229, 'char_start': 8213, 'char_end': 8239, 'line': ' to = g.hname;\n'}, {'line_no': 230, 'char_start': 8239, 'char_end': 8274, 'line': ' len = strlen(g.hname);\n'}, {'line_no': 232, 'char_start': 8284, 'char_end': 8285, 'line': '\n'}, {'line_no': 233, 'char_start': 8285, 'char_end': 8336, 'line': ' /* replace .tgz with .tar when decoding */\n'}, {'line_no': 234, 'char_start': 8336, 'char_end': 8403, 'line': ' repl = g.decode && strcmp(to + len, "".tgz"") ? """" : "".tar"";\n'}, {'line_no': 237, 'char_start': 8455, 'char_end': 8534, 'line': ' g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1);\n'}, {'line_no': 240, 'char_start': 8605, 'char_end': 8638, 'line': ' memcpy(g.outf, to, len);\n'}, {'line_no': 241, 'char_start': 8638, 'char_end': 8694, 'line': ' strcpy(g.outf + len, g.decode ? repl : g.sufx);\n'}, {'line_no': 243, 'char_start': 8755, 'char_end': 8815, 'line': ' (g.force ? 0 : O_EXCL), 0600);\n'}], 'added': [{'line_no': 224, 'char_start': 8033, 'char_end': 8071, 'line': ' char *to = g.inf, *sufx = """";\n'}, {'line_no': 225, 'char_start': 8071, 'char_end': 8095, 'line': ' size_t pre = 0;\n'}, {'line_no': 226, 'char_start': 8095, 'char_end': 8096, 'line': '\n'}, {'line_no': 227, 'char_start': 8096, 'char_end': 8147, 'line': ' /* select parts of the output file name */\n'}, {'line_no': 228, 'char_start': 8147, 'char_end': 8171, 'line': ' if (g.decode) {\n'}, {'line_no': 229, 'char_start': 8171, 'char_end': 8249, 'line': ' /* for -dN or -dNT, use the path from the input file and the name\n'}, {'line_no': 230, 'char_start': 8249, 'char_end': 8322, 'line': ' from the header, stripping any path in the header name */\n'}, {'line_no': 231, 'char_start': 8322, 'char_end': 8380, 'line': ' if ((g.headis & 1) != 0 && g.hname != NULL) {\n'}, {'line_no': 232, 'char_start': 8380, 'char_end': 8427, 'line': ' pre = justname(g.inf) - g.inf;\n'}, {'line_no': 233, 'char_start': 8427, 'char_end': 8467, 'line': ' to = justname(g.hname);\n'}, {'line_no': 234, 'char_start': 8467, 'char_end': 8501, 'line': ' len = strlen(to);\n'}, {'line_no': 235, 'char_start': 8501, 'char_end': 8515, 'line': ' }\n'}, {'line_no': 236, 'char_start': 8515, 'char_end': 8578, 'line': ' /* for -d or -dNn, replace abbreviated suffixes */\n'}, {'line_no': 237, 'char_start': 8578, 'char_end': 8630, 'line': ' else if (strcmp(to + len, "".tgz"") == 0)\n'}, {'line_no': 238, 'char_start': 8630, 'char_end': 8661, 'line': ' sufx = "".tar"";\n'}, {'line_no': 240, 'char_start': 8671, 'char_end': 8684, 'line': ' else\n'}, {'line_no': 241, 'char_start': 8684, 'char_end': 8742, 'line': ' /* add appropriate suffix when compressing */\n'}, {'line_no': 242, 'char_start': 8742, 'char_end': 8769, 'line': ' sufx = g.sufx;\n'}, {'line_no': 245, 'char_start': 8821, 'char_end': 8876, 'line': ' g.outf = MALLOC(pre + len + strlen(sufx) + 1);\n'}, {'line_no': 248, 'char_start': 8947, 'char_end': 8983, 'line': ' memcpy(g.outf, g.inf, pre);\n'}, {'line_no': 249, 'char_start': 8983, 'char_end': 9022, 'line': ' memcpy(g.outf + pre, to, len);\n'}, {'line_no': 250, 'char_start': 9022, 'char_end': 9064, 'line': ' strcpy(g.outf + pre + len, sufx);\n'}, {'line_no': 252, 'char_start': 9125, 'char_end': 9186, 'line': ' (g.force ? 0 : O_EXCL), 0600);\n'}]}","{'deleted': [{'char_start': 8052, 'char_end': 8053, 'chars': 'r'}, {'char_start': 8055, 'char_end': 8056, 'chars': 'l'}, {'char_start': 8070, 'char_end': 8071, 'chars': 'u'}, {'char_start': 8076, 'char_end': 8078, 'chars': 'ad'}, {'char_start': 8079, 'char_end': 8080, 'chars': 'r'}, {'char_start': 8094, 'char_end': 8095, 'chars': 'u'}, {'char_start': 8096, 'char_end': 8098, 'chars': ' w'}, {'char_start': 8099, 'char_end': 8101, 'chars': 'en'}, {'char_start': 8102, 'char_end': 8105, 'chars': 'dec'}, {'char_start': 8107, 'char_end': 8109, 'chars': 'pr'}, {'char_start': 8110, 'char_end': 8112, 'chars': 'ss'}, {'char_start': 8114, 'char_end': 8115, 'chars': 'g'}, {'char_start': 8116, 'char_end': 8117, 'chars': 'w'}, {'char_start': 8120, 'char_end': 8123, 'chars': ' -N'}, {'char_start': 8124, 'char_end': 8126, 'chars': '*/'}, {'char_start': 8135, 'char_end': 8136, 'chars': 't'}, {'char_start': 8138, 'char_end': 8139, 'chars': '='}, {'char_start': 8141, 'char_end': 8142, 'chars': '.'}, {'char_start': 8144, 'char_end': 8146, 'chars': 'f;'}, {'char_start': 8159, 'char_end': 8171, 'chars': 'g.decode && '}, {'char_start': 8264, 'char_end': 8271, 'chars': 'g.hname'}, {'char_start': 8283, 'char_end': 8284, 'chars': '\n'}, {'char_start': 8304, 'char_end': 8316, 'chars': '.tgz with .t'}, {'char_start': 8318, 'char_end': 8321, 'chars': ' wh'}, {'char_start': 8322, 'char_end': 8325, 'chars': 'n d'}, {'char_start': 8326, 'char_end': 8328, 'chars': 'co'}, {'char_start': 8330, 'char_end': 8332, 'chars': 'ng'}, {'char_start': 8344, 'char_end': 8348, 'chars': 'repl'}, {'char_start': 8349, 'char_end': 8350, 'chars': '='}, {'char_start': 8351, 'char_end': 8354, 'chars': 'g.d'}, {'char_start': 8355, 'char_end': 8358, 'chars': 'cod'}, {'char_start': 8360, 'char_end': 8362, 'chars': '&&'}, {'char_start': 8388, 'char_end': 8389, 'chars': '?'}, {'char_start': 8390, 'char_end': 8392, 'chars': '""""'}, {'char_start': 8393, 'char_end': 8394, 'chars': ':'}, {'char_start': 8479, 'char_end': 8480, 'chars': 'l'}, {'char_start': 8481, 'char_end': 8482, 'chars': 'n'}, {'char_start': 8485, 'char_end': 8500, 'chars': '(g.decode ? str'}, {'char_start': 8503, 'char_end': 8509, 'chars': '(repl)'}, {'char_start': 8510, 'char_end': 8511, 'chars': ':'}, {'char_start': 8519, 'char_end': 8521, 'chars': 'g.'}, {'char_start': 8525, 'char_end': 8526, 'chars': ')'}, {'char_start': 8628, 'char_end': 8630, 'chars': 'to'}, {'char_start': 8632, 'char_end': 8633, 'chars': 'l'}, {'char_start': 8634, 'char_end': 8635, 'chars': 'n'}, {'char_start': 8646, 'char_end': 8649, 'chars': 'str'}, {'char_start': 8665, 'char_end': 8666, 'chars': ','}, {'char_start': 8669, 'char_end': 8672, 'chars': 'dec'}, {'char_start': 8673, 'char_end': 8675, 'chars': 'de'}, {'char_start': 8676, 'char_end': 8677, 'chars': '?'}, {'char_start': 8680, 'char_end': 8682, 'chars': 'pl'}, {'char_start': 8683, 'char_end': 8684, 'chars': ':'}, {'char_start': 8685, 'char_end': 8687, 'chars': 'g.'}], 'added': [{'char_start': 8049, 'char_end': 8057, 'chars': ' = g.inf'}, {'char_start': 8060, 'char_end': 8087, 'chars': 'sufx = """";\n size_t p'}, {'char_start': 8089, 'char_end': 8093, 'chars': ' = 0'}, {'char_start': 8109, 'char_end': 8113, 'chars': 'lect'}, {'char_start': 8114, 'char_end': 8124, 'chars': 'parts of t'}, {'char_start': 8126, 'char_end': 8137, 'chars': ' output fil'}, {'char_start': 8144, 'char_end': 8186, 'chars': '*/\n if (g.decode) {\n /* '}, {'char_start': 8190, 'char_end': 8194, 'chars': '-dN '}, {'char_start': 8195, 'char_end': 8203, 'chars': 'r -dNT, '}, {'char_start': 8204, 'char_end': 8207, 'chars': 'se '}, {'char_start': 8208, 'char_end': 8211, 'chars': 'he '}, {'char_start': 8212, 'char_end': 8213, 'chars': 'a'}, {'char_start': 8216, 'char_end': 8218, 'chars': 'fr'}, {'char_start': 8220, 'char_end': 8223, 'chars': ' th'}, {'char_start': 8224, 'char_end': 8225, 'chars': ' '}, {'char_start': 8227, 'char_end': 8230, 'chars': 'put'}, {'char_start': 8231, 'char_end': 8232, 'chars': 'f'}, {'char_start': 8233, 'char_end': 8240, 'chars': 'le and '}, {'char_start': 8242, 'char_end': 8250, 'chars': 'e name\n '}, {'char_start': 8259, 'char_end': 8269, 'chars': ' from '}, {'char_start': 8270, 'char_end': 8272, 'chars': 'he'}, {'char_start': 8273, 'char_end': 8280, 'chars': 'header,'}, {'char_start': 8281, 'char_end': 8289, 'chars': 'strippin'}, {'char_start': 8290, 'char_end': 8300, 'chars': ' any path '}, {'char_start': 8302, 'char_end': 8321, 'chars': ' the header name */'}, {'char_start': 8322, 'char_end': 8326, 'chars': ' '}, {'char_start': 8392, 'char_end': 8443, 'chars': ' pre = justname(g.inf) - g.inf;\n '}, {'char_start': 8448, 'char_end': 8457, 'chars': 'justname('}, {'char_start': 8464, 'char_end': 8465, 'chars': ')'}, {'char_start': 8467, 'char_end': 8471, 'chars': ' '}, {'char_start': 8496, 'char_end': 8498, 'chars': 'to'}, {'char_start': 8509, 'char_end': 8513, 'chars': ' '}, {'char_start': 8515, 'char_end': 8519, 'chars': ' '}, {'char_start': 8530, 'char_end': 8546, 'chars': 'for -d or -dNn, '}, {'char_start': 8555, 'char_end': 8557, 'chars': 'bb'}, {'char_start': 8559, 'char_end': 8563, 'chars': 'viat'}, {'char_start': 8565, 'char_end': 8570, 'chars': ' suff'}, {'char_start': 8571, 'char_end': 8574, 'chars': 'xes'}, {'char_start': 8586, 'char_end': 8588, 'chars': ' '}, {'char_start': 8591, 'char_end': 8593, 'chars': 'ls'}, {'char_start': 8595, 'char_end': 8597, 'chars': 'if'}, {'char_start': 8598, 'char_end': 8599, 'chars': '('}, {'char_start': 8624, 'char_end': 8645, 'chars': '== 0)\n '}, {'char_start': 8646, 'char_end': 8650, 'chars': 'sufx'}, {'char_start': 8651, 'char_end': 8652, 'chars': '='}, {'char_start': 8661, 'char_end': 8769, 'chars': ' }\n else\n /* add appropriate suffix when compressing */\n sufx = g.sufx;\n'}, {'char_start': 8845, 'char_end': 8847, 'chars': 'pr'}, {'char_start': 8855, 'char_end': 8856, 'chars': '+'}, {'char_start': 8970, 'char_end': 8975, 'chars': 'g.inf'}, {'char_start': 8977, 'char_end': 8979, 'chars': 'pr'}, {'char_start': 8991, 'char_end': 8994, 'chars': 'mem'}, {'char_start': 9006, 'char_end': 9015, 'chars': ' pre, to,'}, {'char_start': 9019, 'char_end': 9029, 'chars': ');\n '}, {'char_start': 9030, 'char_end': 9037, 'chars': 'strcpy('}, {'char_start': 9040, 'char_end': 9043, 'chars': 'utf'}, {'char_start': 9044, 'char_end': 9045, 'chars': '+'}, {'char_start': 9046, 'char_end': 9047, 'chars': 'p'}, {'char_start': 9049, 'char_end': 9052, 'chars': ' + '}, {'char_start': 9053, 'char_end': 9056, 'chars': 'en,'}, {'char_start': 9125, 'char_end': 9126, 'chars': ' '}]}",github.com/madler/pigz/commit/fdad1406b3ec809f4954ff7cdf9e99eb18c2458f,pigz.c,cwe-022,2704 cwe-078,main,"def main(): global word print(""Starting script... press 'ctrl+c' in terminal to turn off"") while True: if pyperclip.paste() != word and len(pyperclip.paste().split())<5: word = pyperclip.paste() wordChc=False req = requests.get(""https://api-portal.dictionary.com/dcom/pageData/%s"" % word) wordChcURB = False reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word) try: data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions'] except TypeError: os.system('notify-send ""Cant find |%s| on dictionary.com!""' % word) wordChc = True except KeyError: os.system('notify-send ""Cant find |%s| on dictionary.com!""' % word) wordChc = True if not wordChc: definitions = [] try: for definition in data[:3]: definitions.append(cleanhtml(definition['definition'])) definitions.append(""------------"") os.system('notify-send ""definitions from dictionary.com:[{}\n{}""'\ .format(word+""]\n------------"",'\n'.join(definitions))) except KeyError: os.system('notify-send ""no results in dictionary.com""') try: dataURB = json.loads(reqURB.text)['list'] except TypeError: os.system('notify-send ""Cant find |%s| on urbandictionary.com!""' % word) wordChcURB = True except KeyError: os.system('notify-send ""Cant find |%s| on urbandictionary.com!""' % word) wordChcURB = True if not wordChcURB: definitionsURB = [] for definition in dataURB[:3]: definitionsURB.append(definition['definition']) definitionsURB.append(""------------"") os.system('notify-send ""definitions from urbandictionary.com:[{}\n{}""'\ .format(word+""]\n------------"",'\n'.join(definitionsURB))) os.system('notify-send ""Thank you for using define.py made by kelj0""')","def main(): global word print(""Starting script... press 'ctrl+c' in terminal to turn off"") while True: if pyperclip.paste() != word and len(pyperclip.paste().split())<5: word = pyperclip.paste() wordChc=False req = requests.get(""https://api-portal.dictionary.com/dcom/pageData/%s"" % word) wordChcURB = False reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word) try: data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions'] except TypeError: os.system('notify-send ""Cant find that word on dictionary.com!""') wordChc = True except KeyError: os.system('notify-send ""Cant find that word on dictionary.com!""') wordChc = True if not wordChc: definitions = [] try: for definition in data[:3]: definitions.append(cleanhtml(definition['definition'])) definitions.append(""------------"") os.system('notify-send ""definitions from dictionary.com:\n{}""'.format('\n'.join(definitions))) except KeyError: os.system('notify-send ""no results in dictionary.com""') try: dataURB = json.loads(reqURB.text)['list'] except TypeError: os.system('notify-send ""Cant find that word on urbandictionary.com!""' % word) wordChcURB = True except KeyError: os.system('notify-send ""Cant find that word on urbandictionary.com!""' % word) wordChcURB = True if not wordChcURB: definitionsURB = [] for definition in dataURB[:3]: definitionsURB.append(definition['definition']) definitionsURB.append(""------------"") os.system('notify-send ""definitions from urbandictionary.com:\n{}""'.format('\n'.join(definitionsURB))) os.system('notify-send ""Thank you for using define.py made by kelj0""')","{'deleted': [{'line_no': 14, 'char_start': 630, 'char_end': 714, 'line': ' os.system(\'notify-send ""Cant find |%s| on dictionary.com!""\' % word)\n'}, {'line_no': 17, 'char_start': 774, 'char_end': 858, 'line': ' os.system(\'notify-send ""Cant find |%s| on dictionary.com!""\' % word)\n'}, {'line_no': 26, 'char_start': 1159, 'char_end': 1246, 'line': ' os.system(\'notify-send ""definitions from dictionary.com:[{}\\n{}""\'\\\n'}, {'line_no': 27, 'char_start': 1246, 'char_end': 1322, 'line': ' .format(word+""]\\n------------"",\'\\n\'.join(definitions)))\n'}, {'line_no': 33, 'char_start': 1540, 'char_end': 1629, 'line': ' os.system(\'notify-send ""Cant find |%s| on urbandictionary.com!""\' % word)\n'}, {'line_no': 36, 'char_start': 1692, 'char_end': 1781, 'line': ' os.system(\'notify-send ""Cant find |%s| on urbandictionary.com!""\' % word)\n'}, {'line_no': 44, 'char_start': 2060, 'char_end': 2148, 'line': ' os.system(\'notify-send ""definitions from urbandictionary.com:[{}\\n{}""\'\\\n'}, {'line_no': 45, 'char_start': 2148, 'char_end': 2223, 'line': ' .format(word+""]\\n------------"",\'\\n\'.join(definitionsURB)))\n'}], 'added': [{'line_no': 14, 'char_start': 630, 'char_end': 712, 'line': ' os.system(\'notify-send ""Cant find that word on dictionary.com!""\')\n'}, {'line_no': 17, 'char_start': 772, 'char_end': 854, 'line': ' os.system(\'notify-send ""Cant find that word on dictionary.com!""\')\n'}, {'line_no': 26, 'char_start': 1155, 'char_end': 1270, 'line': ' os.system(\'notify-send ""definitions from dictionary.com:\\n{}""\'.format(\'\\n\'.join(definitions)))\n'}, {'line_no': 32, 'char_start': 1488, 'char_end': 1582, 'line': ' os.system(\'notify-send ""Cant find that word on urbandictionary.com!""\' % word)\n'}, {'line_no': 35, 'char_start': 1645, 'char_end': 1739, 'line': ' os.system(\'notify-send ""Cant find that word on urbandictionary.com!""\' % word)\n'}, {'line_no': 43, 'char_start': 2018, 'char_end': 2137, 'line': ' os.system(\'notify-send ""definitions from urbandictionary.com:\\n{}""\'.format(\'\\n\'.join(definitionsURB)))\n'}]}","{'deleted': [{'char_start': 680, 'char_end': 684, 'chars': '|%s|'}, {'char_start': 705, 'char_end': 712, 'chars': ' % word'}, {'char_start': 824, 'char_end': 828, 'chars': '|%s|'}, {'char_start': 849, 'char_end': 856, 'chars': ' % word'}, {'char_start': 1235, 'char_end': 1238, 'chars': '[{}'}, {'char_start': 1244, 'char_end': 1266, 'chars': '\\\n '}, {'char_start': 1274, 'char_end': 1297, 'chars': 'word+""]\\n------------"",'}, {'char_start': 1590, 'char_end': 1594, 'chars': '|%s|'}, {'char_start': 1742, 'char_end': 1746, 'chars': '|%s|'}, {'char_start': 2137, 'char_end': 2140, 'chars': '[{}'}, {'char_start': 2146, 'char_end': 2164, 'chars': '\\\n '}, {'char_start': 2172, 'char_end': 2195, 'chars': 'word+""]\\n------------"",'}], 'added': [{'char_start': 680, 'char_end': 689, 'chars': 'that word'}, {'char_start': 822, 'char_end': 831, 'chars': 'that word'}, {'char_start': 1538, 'char_end': 1547, 'chars': 'that word'}, {'char_start': 1695, 'char_end': 1704, 'chars': 'that word'}]}",github.com/kelj0/LearningPython/commit/2563088bf44f4d5e7f7d65f3c41f12fdaef4a1e4,SmallProjects/Define/define.py,cwe-078,502 cwe-125,ParseDsdiffHeaderConfig,"int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, ""DSD "", 4)) { error_line (""%s is not a valid .DFF file!"", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line (""%s is not a valid .DFF file (by total size)!"", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line (""file header indicated length = %lld"", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line (""%s is not a valid .DFF file!"", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line (""chunk header indicated length = %lld"", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, ""FVER"", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line (""%s is not a valid .DFF file!"", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, ""L""); if (debug_logging_mode) error_line (""dsdiff file version = 0x%08x"", version); } else if (!strncmp (dff_chunk_header.ckID, ""PROP"", 4)) { char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line (""%s is not a valid .DFF file!"", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line (""%s"", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, ""SND "", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, ""FS "", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, ""L""); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line (""got sample rate of %u Hz"", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, ""CHNL"", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, ""S""); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, ""SLFT"", 4) || !strncmp (cptr, ""MLFT"", 4)) chanMask |= 0x1; else if (!strncmp (cptr, ""SRGT"", 4) || !strncmp (cptr, ""MRGT"", 4)) chanMask |= 0x2; else if (!strncmp (cptr, ""LS "", 4)) chanMask |= 0x10; else if (!strncmp (cptr, ""RS "", 4)) chanMask |= 0x20; else if (!strncmp (cptr, ""C "", 4)) chanMask |= 0x4; else if (!strncmp (cptr, ""LFE "", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line (""undefined channel ID %c%c%c%c"", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line (""%d channels, mask = 0x%08x"", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, ""CMPR"", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, ""DSD "", 4)) { error_line (""DSDIFF files must be uncompressed, not \""%c%c%c%c\""!"", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line (""got PROP/SND chunk type \""%c%c%c%c\"" of %d bytes"", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line (""%s is not a valid .DFF file!"", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line (""this DSDIFF file already has channel order information!""); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line (""got unknown PROP chunk type \""%c%c%c%c\"" of %d bytes"", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, ""DSD "", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line (""extra unknown chunk \""%c%c%c%c\"" of %d bytes"", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line (""setting configuration with %lld samples"", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line (""%s: %s"", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }","int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, ""DSD "", 4)) { error_line (""%s is not a valid .DFF file!"", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line (""%s is not a valid .DFF file (by total size)!"", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line (""file header indicated length = %lld"", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line (""%s is not a valid .DFF file!"", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line (""chunk header indicated length = %lld"", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, ""FVER"", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line (""%s is not a valid .DFF file!"", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, ""L""); if (debug_logging_mode) error_line (""dsdiff file version = 0x%08x"", version); } else if (!strncmp (dff_chunk_header.ckID, ""PROP"", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line (""%s is not a valid .DFF file!"", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line (""got PROP chunk of %d bytes total"", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line (""%s is not a valid .DFF file!"", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line (""%s"", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, ""SND "", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, ""FS "", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, ""L""); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line (""got sample rate of %u Hz"", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, ""CHNL"", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, ""S""); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, ""SLFT"", 4) || !strncmp (cptr, ""MLFT"", 4)) chanMask |= 0x1; else if (!strncmp (cptr, ""SRGT"", 4) || !strncmp (cptr, ""MRGT"", 4)) chanMask |= 0x2; else if (!strncmp (cptr, ""LS "", 4)) chanMask |= 0x10; else if (!strncmp (cptr, ""RS "", 4)) chanMask |= 0x20; else if (!strncmp (cptr, ""C "", 4)) chanMask |= 0x4; else if (!strncmp (cptr, ""LFE "", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line (""undefined channel ID %c%c%c%c"", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line (""%d channels, mask = 0x%08x"", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, ""CMPR"", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, ""DSD "", 4)) { error_line (""DSDIFF files must be uncompressed, not \""%c%c%c%c\""!"", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line (""got PROP/SND chunk type \""%c%c%c%c\"" of %d bytes"", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line (""%s is not a valid .DFF file!"", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line (""this DSDIFF file already has channel order information!""); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line (""got unknown PROP chunk type \""%c%c%c%c\"" of %d bytes"", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, ""DSD "", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line (""extra unknown chunk \""%c%c%c%c\"" of %d bytes"", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line (""%s"", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line (""setting configuration with %lld samples"", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line (""%s: %s"", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }","{'deleted': [{'line_no': 77, 'char_start': 3244, 'char_end': 3322, 'line': ' char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);\n'}], 'added': [{'line_no': 77, 'char_start': 3244, 'char_end': 3274, 'line': ' char *prop_chunk;\n'}, {'line_no': 78, 'char_start': 3274, 'char_end': 3275, 'line': '\n'}, {'line_no': 79, 'char_start': 3275, 'char_end': 3364, 'line': ' if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {\n'}, {'line_no': 80, 'char_start': 3364, 'char_end': 3437, 'line': ' error_line (""%s is not a valid .DFF file!"", infilename);\n'}, {'line_no': 81, 'char_start': 3437, 'char_end': 3480, 'line': ' return WAVPACK_SOFT_ERROR;\n'}, {'line_no': 82, 'char_start': 3480, 'char_end': 3494, 'line': ' }\n'}, {'line_no': 83, 'char_start': 3494, 'char_end': 3495, 'line': '\n'}, {'line_no': 84, 'char_start': 3495, 'char_end': 3531, 'line': ' if (debug_logging_mode)\n'}, {'line_no': 85, 'char_start': 3531, 'char_end': 3631, 'line': ' error_line (""got PROP chunk of %d bytes total"", (int) dff_chunk_header.ckDataSize);\n'}, {'line_no': 86, 'char_start': 3631, 'char_end': 3632, 'line': '\n'}, {'line_no': 87, 'char_start': 3632, 'char_end': 3704, 'line': ' prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);\n'}]}","{'deleted': [], 'added': [{'char_start': 3272, 'char_end': 3654, 'chars': ';\n\n if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {\n error_line (""%s is not a valid .DFF file!"", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n if (debug_logging_mode)\n error_line (""got PROP chunk of %d bytes total"", (int) dff_chunk_header.ckDataSize);\n\n prop_chunk'}]}",github.com/dbry/WavPack/commit/36a24c7881427d2e1e4dc1cef58f19eee0d13aec,cli/dsdiff.c,cwe-125,2437 cwe-476,hi3660_stub_clk_probe,"static int hi3660_stub_clk_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct resource *res; unsigned int i; int ret; /* Use mailbox client without blocking */ stub_clk_chan.cl.dev = dev; stub_clk_chan.cl.tx_done = NULL; stub_clk_chan.cl.tx_block = false; stub_clk_chan.cl.knows_txdone = false; /* Allocate mailbox channel */ stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0); if (IS_ERR(stub_clk_chan.mbox)) return PTR_ERR(stub_clk_chan.mbox); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); freq_reg = devm_ioremap(dev, res->start, resource_size(res)); if (!freq_reg) return -ENOMEM; freq_reg += HI3660_STUB_CLOCK_DATA; for (i = 0; i < HI3660_CLK_STUB_NUM; i++) { ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw); if (ret) return ret; } return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get, hi3660_stub_clks); }","static int hi3660_stub_clk_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct resource *res; unsigned int i; int ret; /* Use mailbox client without blocking */ stub_clk_chan.cl.dev = dev; stub_clk_chan.cl.tx_done = NULL; stub_clk_chan.cl.tx_block = false; stub_clk_chan.cl.knows_txdone = false; /* Allocate mailbox channel */ stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0); if (IS_ERR(stub_clk_chan.mbox)) return PTR_ERR(stub_clk_chan.mbox); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -EINVAL; freq_reg = devm_ioremap(dev, res->start, resource_size(res)); if (!freq_reg) return -ENOMEM; freq_reg += HI3660_STUB_CLOCK_DATA; for (i = 0; i < HI3660_CLK_STUB_NUM; i++) { ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw); if (ret) return ret; } return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get, hi3660_stub_clks); }","{'deleted': [], 'added': [{'line_no': 20, 'char_start': 558, 'char_end': 569, 'line': '\tif (!res)\n'}, {'line_no': 21, 'char_start': 569, 'char_end': 587, 'line': '\t\treturn -EINVAL;\n'}]}","{'deleted': [], 'added': [{'char_start': 559, 'char_end': 588, 'chars': 'if (!res)\n\t\treturn -EINVAL;\n\t'}]}",github.com/torvalds/linux/commit/9903e41ae1f5d50c93f268ca3304d4d7c64b9311,drivers/clk/hisilicon/clk-hi3660-stub.c,cwe-476,288 cwe-022,valid_id,"def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_) except (AttributeError, KeyError, TypeError) as e: return False","def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: if any(x in id_ for x in ('/', '\\', '\0')): return False return bool(clean_path(opts['pki_dir'], id_)) except (AttributeError, KeyError, TypeError): return False","{'deleted': [{'line_no': 6, 'char_start': 88, 'char_end': 160, 'line': "" return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_)\n""}, {'line_no': 7, 'char_start': 160, 'char_end': 215, 'line': ' except (AttributeError, KeyError, TypeError) as e:\n'}], 'added': [{'line_no': 6, 'char_start': 88, 'char_end': 141, 'line': "" if any(x in id_ for x in ('/', '\\\\', '\\0')):\n""}, {'line_no': 7, 'char_start': 141, 'char_end': 166, 'line': ' return False\n'}, {'line_no': 8, 'char_start': 166, 'char_end': 220, 'line': "" return bool(clean_path(opts['pki_dir'], id_))\n""}, {'line_no': 9, 'char_start': 220, 'char_end': 270, 'line': ' except (AttributeError, KeyError, TypeError):\n'}]}","{'deleted': [{'char_start': 141, 'char_end': 159, 'chars': ' and clean_id(id_)'}, {'char_start': 208, 'char_end': 213, 'chars': ' as e'}], 'added': [{'char_start': 96, 'char_end': 174, 'chars': ""if any(x in id_ for x in ('/', '\\\\', '\\0')):\n return False\n ""}]}",github.com/saltstack/salt/commit/80d90307b07b3703428ecbb7c8bb468e28a9ae6d,salt/utils/verify.py,cwe-022,59 cwe-089,incrementOption,"def incrementOption(cursor, poll_name, option): key = poll_name+""-""+option req = ""UPDATE {} SET count=count+1 WHERE name_option = '{}';"".format(CFG(""options_table_name""), key) cursor.execute(req)","def incrementOption(cursor, poll_name, option): key = poll_name+""-""+option req = ""UPDATE {} SET count=count+1 WHERE name_option=?"".format(CFG(""options_table_name"")) cursor.execute(req, (key,))","{'deleted': [{'line_no': 3, 'char_start': 79, 'char_end': 184, 'line': ' req = ""UPDATE {} SET count=count+1 WHERE name_option = \'{}\';"".format(CFG(""options_table_name""), key)\n'}, {'line_no': 4, 'char_start': 184, 'char_end': 207, 'line': ' cursor.execute(req)\n'}], 'added': [{'line_no': 3, 'char_start': 79, 'char_end': 173, 'line': ' req = ""UPDATE {} SET count=count+1 WHERE name_option=?"".format(CFG(""options_table_name""))\n'}, {'line_no': 4, 'char_start': 173, 'char_end': 204, 'line': ' cursor.execute(req, (key,))\n'}]}","{'deleted': [{'char_start': 135, 'char_end': 136, 'chars': ' '}, {'char_start': 137, 'char_end': 143, 'chars': "" '{}';""}, {'char_start': 177, 'char_end': 182, 'chars': ', key'}], 'added': [{'char_start': 136, 'char_end': 137, 'chars': '?'}, {'char_start': 195, 'char_end': 203, 'chars': ', (key,)'}]}",github.com/FAUSheppy/simple-python-poll/commit/186c5ff5cdf58272e253a1bb432419ee50d93109,database.py,cwe-089,52 cwe-078,_get_vvset_from_3par," def _get_vvset_from_3par(self, volume_name): """"""Get Virtual Volume Set from 3PAR. The only way to do this currently is to try and delete the volume to get the error message. NOTE(walter-boring): don't call this unless you know the volume is already in a vvset! """""" cmd = ""removevv -f %s"" % volume_name LOG.debug(""Issuing remove command to find vvset name %s"" % cmd) out = self._cli_run(cmd, None) vvset_name = None if out and len(out) > 1: if out[1].startswith(""Attempt to delete ""): words = out[1].split("" "") vvset_name = words[len(words) - 1] return vvset_name"," def _get_vvset_from_3par(self, volume_name): """"""Get Virtual Volume Set from 3PAR. The only way to do this currently is to try and delete the volume to get the error message. NOTE(walter-boring): don't call this unless you know the volume is already in a vvset! """""" cmd = ['removevv', '-f', volume_name] LOG.debug(""Issuing remove command to find vvset name %s"" % cmd) out = self._cli_run(cmd) vvset_name = None if out and len(out) > 1: if out[1].startswith(""Attempt to delete ""): words = out[1].split("" "") vvset_name = words[len(words) - 1] return vvset_name","{'deleted': [{'line_no': 10, 'char_start': 319, 'char_end': 364, 'line': ' cmd = ""removevv -f %s"" % volume_name\n'}, {'line_no': 12, 'char_start': 436, 'char_end': 475, 'line': ' out = self._cli_run(cmd, None)\n'}], 'added': [{'line_no': 10, 'char_start': 319, 'char_end': 365, 'line': "" cmd = ['removevv', '-f', volume_name]\n""}, {'line_no': 12, 'char_start': 437, 'char_end': 470, 'line': ' out = self._cli_run(cmd)\n'}]}","{'deleted': [{'char_start': 333, 'char_end': 334, 'chars': '""'}, {'char_start': 345, 'char_end': 351, 'chars': ' %s"" %'}, {'char_start': 467, 'char_end': 473, 'chars': ', None'}], 'added': [{'char_start': 333, 'char_end': 335, 'chars': ""['""}, {'char_start': 343, 'char_end': 345, 'chars': ""',""}, {'char_start': 346, 'char_end': 347, 'chars': ""'""}, {'char_start': 349, 'char_end': 351, 'chars': ""',""}, {'char_start': 363, 'char_end': 364, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,181 cwe-125,start_input_ppm,"start_input_ppm(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { ppm_source_ptr source = (ppm_source_ptr)sinfo; int c; unsigned int w, h, maxval; boolean need_iobuffer, use_raw_buffer, need_rescale; if (getc(source->pub.input_file) != 'P') ERREXIT(cinfo, JERR_PPM_NOT); c = getc(source->pub.input_file); /* subformat discriminator character */ /* detect unsupported variants (ie, PBM) before trying to read header */ switch (c) { case '2': /* it's a text-format PGM file */ case '3': /* it's a text-format PPM file */ case '5': /* it's a raw-format PGM file */ case '6': /* it's a raw-format PPM file */ break; default: ERREXIT(cinfo, JERR_PPM_NOT); break; } /* fetch the remaining header info */ w = read_pbm_integer(cinfo, source->pub.input_file, 65535); h = read_pbm_integer(cinfo, source->pub.input_file, 65535); maxval = read_pbm_integer(cinfo, source->pub.input_file, 65535); if (w <= 0 || h <= 0 || maxval <= 0) /* error check */ ERREXIT(cinfo, JERR_PPM_NOT); cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */ cinfo->image_width = (JDIMENSION)w; cinfo->image_height = (JDIMENSION)h; source->maxval = maxval; /* initialize flags to most common settings */ need_iobuffer = TRUE; /* do we need an I/O buffer? */ use_raw_buffer = FALSE; /* do we map input buffer onto I/O buffer? */ need_rescale = TRUE; /* do we need a rescale array? */ switch (c) { case '2': /* it's a text-format PGM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_GRAYSCALE; TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h); if (cinfo->in_color_space == JCS_GRAYSCALE) source->pub.get_pixel_rows = get_text_gray_row; else if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_text_gray_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_text_gray_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); need_iobuffer = FALSE; break; case '3': /* it's a text-format PPM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_RGB; TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h); if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_text_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_text_rgb_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); need_iobuffer = FALSE; break; case '5': /* it's a raw-format PGM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_GRAYSCALE; TRACEMS2(cinfo, 1, JTRC_PGM, w, h); if (maxval > 255) { source->pub.get_pixel_rows = get_word_gray_row; } else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) && cinfo->in_color_space == JCS_GRAYSCALE) { source->pub.get_pixel_rows = get_raw_row; use_raw_buffer = TRUE; need_rescale = FALSE; } else { if (cinfo->in_color_space == JCS_GRAYSCALE) source->pub.get_pixel_rows = get_scaled_gray_row; else if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_gray_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_gray_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); } break; case '6': /* it's a raw-format PPM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_RGB; TRACEMS2(cinfo, 1, JTRC_PPM, w, h); if (maxval > 255) { source->pub.get_pixel_rows = get_word_rgb_row; } else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) && (cinfo->in_color_space == JCS_EXT_RGB #if RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 3 || cinfo->in_color_space == JCS_RGB #endif )) { source->pub.get_pixel_rows = get_raw_row; use_raw_buffer = TRUE; need_rescale = FALSE; } else { if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_rgb_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); } break; } if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_GRAYSCALE) cinfo->input_components = 1; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; /* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */ if (need_iobuffer) { if (c == '6') source->buffer_width = (size_t)w * 3 * ((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR))); else source->buffer_width = (size_t)w * ((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR))); source->iobuffer = (U_CHAR *) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, source->buffer_width); } /* Create compressor input buffer. */ if (use_raw_buffer) { /* For unscaled raw-input case, we can just map it onto the I/O buffer. */ /* Synthesize a JSAMPARRAY pointer structure */ source->pixrow = (JSAMPROW)source->iobuffer; source->pub.buffer = &source->pixrow; source->pub.buffer_height = 1; } else { /* Need to translate anyway, so make a separate sample buffer. */ source->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)w * cinfo->input_components, (JDIMENSION)1); source->pub.buffer_height = 1; } /* Compute the rescaling array if required. */ if (need_rescale) { long val, half_maxval; /* On 16-bit-int machines we have to be careful of maxval = 65535 */ source->rescale = (JSAMPLE *) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, (size_t)(((long)maxval + 1L) * sizeof(JSAMPLE))); half_maxval = maxval / 2; for (val = 0; val <= (long)maxval; val++) { /* The multiplication here must be done in 32 bits to avoid overflow */ source->rescale[val] = (JSAMPLE)((val * MAXJSAMPLE + half_maxval) / maxval); } } }","start_input_ppm(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { ppm_source_ptr source = (ppm_source_ptr)sinfo; int c; unsigned int w, h, maxval; boolean need_iobuffer, use_raw_buffer, need_rescale; if (getc(source->pub.input_file) != 'P') ERREXIT(cinfo, JERR_PPM_NOT); c = getc(source->pub.input_file); /* subformat discriminator character */ /* detect unsupported variants (ie, PBM) before trying to read header */ switch (c) { case '2': /* it's a text-format PGM file */ case '3': /* it's a text-format PPM file */ case '5': /* it's a raw-format PGM file */ case '6': /* it's a raw-format PPM file */ break; default: ERREXIT(cinfo, JERR_PPM_NOT); break; } /* fetch the remaining header info */ w = read_pbm_integer(cinfo, source->pub.input_file, 65535); h = read_pbm_integer(cinfo, source->pub.input_file, 65535); maxval = read_pbm_integer(cinfo, source->pub.input_file, 65535); if (w <= 0 || h <= 0 || maxval <= 0) /* error check */ ERREXIT(cinfo, JERR_PPM_NOT); cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */ cinfo->image_width = (JDIMENSION)w; cinfo->image_height = (JDIMENSION)h; source->maxval = maxval; /* initialize flags to most common settings */ need_iobuffer = TRUE; /* do we need an I/O buffer? */ use_raw_buffer = FALSE; /* do we map input buffer onto I/O buffer? */ need_rescale = TRUE; /* do we need a rescale array? */ switch (c) { case '2': /* it's a text-format PGM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_GRAYSCALE; TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h); if (cinfo->in_color_space == JCS_GRAYSCALE) source->pub.get_pixel_rows = get_text_gray_row; else if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_text_gray_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_text_gray_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); need_iobuffer = FALSE; break; case '3': /* it's a text-format PPM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_RGB; TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h); if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_text_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_text_rgb_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); need_iobuffer = FALSE; break; case '5': /* it's a raw-format PGM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_GRAYSCALE; TRACEMS2(cinfo, 1, JTRC_PGM, w, h); if (maxval > 255) { source->pub.get_pixel_rows = get_word_gray_row; } else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) && cinfo->in_color_space == JCS_GRAYSCALE) { source->pub.get_pixel_rows = get_raw_row; use_raw_buffer = TRUE; need_rescale = FALSE; } else { if (cinfo->in_color_space == JCS_GRAYSCALE) source->pub.get_pixel_rows = get_scaled_gray_row; else if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_gray_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_gray_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); } break; case '6': /* it's a raw-format PPM file */ if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_RGB; TRACEMS2(cinfo, 1, JTRC_PPM, w, h); if (maxval > 255) { source->pub.get_pixel_rows = get_word_rgb_row; } else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) && (cinfo->in_color_space == JCS_EXT_RGB #if RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 3 || cinfo->in_color_space == JCS_RGB #endif )) { source->pub.get_pixel_rows = get_raw_row; use_raw_buffer = TRUE; need_rescale = FALSE; } else { if (IsExtRGB(cinfo->in_color_space)) source->pub.get_pixel_rows = get_rgb_row; else if (cinfo->in_color_space == JCS_CMYK) source->pub.get_pixel_rows = get_rgb_cmyk_row; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); } break; } if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_GRAYSCALE) cinfo->input_components = 1; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; /* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */ if (need_iobuffer) { if (c == '6') source->buffer_width = (size_t)w * 3 * ((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR))); else source->buffer_width = (size_t)w * ((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR))); source->iobuffer = (U_CHAR *) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, source->buffer_width); } /* Create compressor input buffer. */ if (use_raw_buffer) { /* For unscaled raw-input case, we can just map it onto the I/O buffer. */ /* Synthesize a JSAMPARRAY pointer structure */ source->pixrow = (JSAMPROW)source->iobuffer; source->pub.buffer = &source->pixrow; source->pub.buffer_height = 1; } else { /* Need to translate anyway, so make a separate sample buffer. */ source->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)w * cinfo->input_components, (JDIMENSION)1); source->pub.buffer_height = 1; } /* Compute the rescaling array if required. */ if (need_rescale) { long val, half_maxval; /* On 16-bit-int machines we have to be careful of maxval = 65535 */ source->rescale = (JSAMPLE *) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, (size_t)(((long)MAX(maxval, 255) + 1L) * sizeof(JSAMPLE))); half_maxval = maxval / 2; for (val = 0; val <= (long)maxval; val++) { /* The multiplication here must be done in 32 bits to avoid overflow */ source->rescale[val] = (JSAMPLE)((val * MAXJSAMPLE + half_maxval) / maxval); } } }","{'deleted': [{'line_no': 163, 'char_start': 6187, 'char_end': 6252, 'line': ' (size_t)(((long)maxval + 1L) *\n'}], 'added': [{'line_no': 163, 'char_start': 6187, 'char_end': 6262, 'line': ' (size_t)(((long)MAX(maxval, 255) + 1L) *\n'}]}","{'deleted': [], 'added': [{'char_start': 6237, 'char_end': 6241, 'chars': 'MAX('}, {'char_start': 6247, 'char_end': 6253, 'chars': ', 255)'}]}",github.com/libjpeg-turbo/libjpeg-turbo/commit/3de15e0c344d11d4b90f4a47136467053eb2d09a,rdppm.c,cwe-125,1932 cwe-476,fm10k_init_module,"static int __init fm10k_init_module(void) { pr_info(""%s - version %s\n"", fm10k_driver_string, fm10k_driver_version); pr_info(""%s\n"", fm10k_copyright); /* create driver workqueue */ fm10k_workqueue = alloc_workqueue(""%s"", WQ_MEM_RECLAIM, 0, fm10k_driver_name); fm10k_dbg_init(); return fm10k_register_pci_driver(); }","static int __init fm10k_init_module(void) { pr_info(""%s - version %s\n"", fm10k_driver_string, fm10k_driver_version); pr_info(""%s\n"", fm10k_copyright); /* create driver workqueue */ fm10k_workqueue = alloc_workqueue(""%s"", WQ_MEM_RECLAIM, 0, fm10k_driver_name); if (!fm10k_workqueue) return -ENOMEM; fm10k_dbg_init(); return fm10k_register_pci_driver(); }","{'deleted': [], 'added': [{'line_no': 9, 'char_start': 272, 'char_end': 295, 'line': '\tif (!fm10k_workqueue)\n'}, {'line_no': 10, 'char_start': 295, 'char_end': 313, 'line': '\t\treturn -ENOMEM;\n'}]}","{'deleted': [], 'added': [{'char_start': 272, 'char_end': 313, 'chars': '\tif (!fm10k_workqueue)\n\t\treturn -ENOMEM;\n'}]}",github.com/torvalds/linux/commit/01ca667133d019edc9f0a1f70a272447c84ec41f,drivers/net/ethernet/intel/fm10k/fm10k_main.c,cwe-476,106 cwe-416,PHP_FUNCTION,"PHP_FUNCTION(unserialize) { char *buf = NULL; size_t buf_len; const unsigned char *p; php_unserialize_data_t var_hash; zval *options = NULL, *classes = NULL; HashTable *class_hash = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), ""s|a"", &buf, &buf_len, &options) == FAILURE) { RETURN_FALSE; } if (buf_len == 0) { RETURN_FALSE; } p = (const unsigned char*) buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if(options != NULL) { classes = zend_hash_str_find(Z_ARRVAL_P(options), ""allowed_classes"", sizeof(""allowed_classes"")-1); if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) { ALLOC_HASHTABLE(class_hash); zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0); } if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) { zval *entry; zend_string *lcname; ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) { convert_to_string_ex(entry); lcname = zend_string_tolower(Z_STR_P(entry)); zend_hash_add_empty_element(class_hash, lcname); zend_string_release(lcname); } ZEND_HASH_FOREACH_END(); } } if (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } zval_ptr_dtor(return_value); if (!EG(exception)) { php_error_docref(NULL, E_NOTICE, ""Error at offset "" ZEND_LONG_FMT "" of %zd bytes"", (zend_long)((char*)p - buf), buf_len); } RETURN_FALSE; } /* We should keep an reference to return_value to prevent it from being dtor in case nesting calls to unserialize */ var_push_dtor(&var_hash, return_value); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } }","PHP_FUNCTION(unserialize) { char *buf = NULL; size_t buf_len; const unsigned char *p; php_unserialize_data_t var_hash; zval *options = NULL, *classes = NULL; zval *retval; HashTable *class_hash = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), ""s|a"", &buf, &buf_len, &options) == FAILURE) { RETURN_FALSE; } if (buf_len == 0) { RETURN_FALSE; } p = (const unsigned char*) buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if(options != NULL) { classes = zend_hash_str_find(Z_ARRVAL_P(options), ""allowed_classes"", sizeof(""allowed_classes"")-1); if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) { ALLOC_HASHTABLE(class_hash); zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0); } if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) { zval *entry; zend_string *lcname; ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) { convert_to_string_ex(entry); lcname = zend_string_tolower(Z_STR_P(entry)); zend_hash_add_empty_element(class_hash, lcname); zend_string_release(lcname); } ZEND_HASH_FOREACH_END(); } } retval = var_tmp_var(&var_hash); if (!php_var_unserialize_ex(retval, &p, p + buf_len, &var_hash, class_hash)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } if (!EG(exception)) { php_error_docref(NULL, E_NOTICE, ""Error at offset "" ZEND_LONG_FMT "" of %zd bytes"", (zend_long)((char*)p - buf), buf_len); } RETURN_FALSE; } ZVAL_COPY(return_value, retval); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } }","{'deleted': [{'line_no': 39, 'char_start': 1140, 'char_end': 1226, 'line': '\tif (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) {\n'}, {'line_no': 45, 'char_start': 1356, 'char_end': 1387, 'line': '\t\tzval_ptr_dtor(return_value);\n'}, {'line_no': 52, 'char_start': 1563, 'char_end': 1641, 'line': '\t/* We should keep an reference to return_value to prevent it from being dtor\n'}, {'line_no': 53, 'char_start': 1641, 'char_end': 1685, 'line': '\t in case nesting calls to unserialize */\n'}, {'line_no': 54, 'char_start': 1685, 'char_end': 1726, 'line': '\tvar_push_dtor(&var_hash, return_value);\n'}], 'added': [{'line_no': 8, 'char_start': 163, 'char_end': 178, 'line': '\tzval *retval;\n'}, {'line_no': 40, 'char_start': 1155, 'char_end': 1189, 'line': '\tretval = var_tmp_var(&var_hash);\n'}, {'line_no': 41, 'char_start': 1189, 'char_end': 1269, 'line': '\tif (!php_var_unserialize_ex(retval, &p, p + buf_len, &var_hash, class_hash)) {\n'}, {'line_no': 53, 'char_start': 1575, 'char_end': 1576, 'line': '\n'}, {'line_no': 54, 'char_start': 1576, 'char_end': 1610, 'line': '\tZVAL_COPY(return_value, retval);\n'}]}","{'deleted': [{'char_start': 1172, 'char_end': 1176, 'chars': 'urn_'}, {'char_start': 1179, 'char_end': 1181, 'chars': 'ue'}, {'char_start': 1356, 'char_end': 1387, 'chars': '\t\tzval_ptr_dtor(return_value);\n'}, {'char_start': 1564, 'char_end': 1598, 'chars': '/* We should keep an reference to '}, {'char_start': 1610, 'char_end': 1709, 'chars': ' to prevent it from being dtor\n\t in case nesting calls to unserialize */\n\tvar_push_dtor(&var_hash'}, {'char_start': 1714, 'char_end': 1718, 'chars': 'urn_'}, {'char_start': 1721, 'char_end': 1723, 'chars': 'ue'}], 'added': [{'char_start': 164, 'char_end': 179, 'chars': 'zval *retval;\n\t'}, {'char_start': 1156, 'char_end': 1190, 'chars': 'retval = var_tmp_var(&var_hash);\n\t'}, {'char_start': 1575, 'char_end': 1576, 'chars': '\n'}, {'char_start': 1577, 'char_end': 1587, 'chars': 'ZVAL_COPY('}]}",github.com/php/php-src/commit/b2af4e8868726a040234de113436c6e4f6372d17,ext/standard/var.c,cwe-416,526 cwe-125,fpm_log_write,"int fpm_log_write(char *log_format) /* {{{ */ { char *s, *b; char buffer[FPM_LOG_BUFFER+1]; int token, test; size_t len, len2; struct fpm_scoreboard_proc_s proc, *proc_p; struct fpm_scoreboard_s *scoreboard; char tmp[129]; char format[129]; time_t now_epoch; #ifdef HAVE_TIMES clock_t tms_total; #endif if (!log_format && (!fpm_log_format || fpm_log_fd == -1)) { return -1; } if (!log_format) { log_format = fpm_log_format; test = 0; } else { test = 1; } now_epoch = time(NULL); if (!test) { scoreboard = fpm_scoreboard_get(); if (!scoreboard) { zlog(ZLOG_WARNING, ""unable to get scoreboard while preparing the access log""); return -1; } proc_p = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (!proc_p) { zlog(ZLOG_WARNING, ""[pool %s] Unable to acquire shm slot while preparing the access log"", scoreboard->pool); return -1; } proc = *proc_p; fpm_scoreboard_proc_release(proc_p); } token = 0; memset(buffer, '\0', sizeof(buffer)); b = buffer; len = 0; s = log_format; while (*s != '\0') { /* Test is we have place for 1 more char. */ if (len >= FPM_LOG_BUFFER) { zlog(ZLOG_NOTICE, ""the log buffer is full (%d). The access log request has been truncated."", FPM_LOG_BUFFER); len = FPM_LOG_BUFFER; break; } if (!token && *s == '%') { token = 1; memset(format, '\0', sizeof(format)); /* reset format */ s++; continue; } if (token) { token = 0; len2 = 0; switch (*s) { case '%': /* '%' */ *b = '%'; len2 = 1; break; #ifdef HAVE_TIMES case 'C': /* %CPU */ if (format[0] == '\0' || !strcasecmp(format, ""total"")) { if (!test) { tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cutime + proc.last_request_cpu.tms_cstime; } } else if (!strcasecmp(format, ""user"")) { if (!test) { tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_cutime; } } else if (!strcasecmp(format, ""system"")) { if (!test) { tms_total = proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cstime; } } else { zlog(ZLOG_WARNING, ""only 'total', 'user' or 'system' are allowed as a modifier for %%%c ('%s')"", *s, format); return -1; } format[0] = '\0'; if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%.2f"", tms_total / fpm_scoreboard_get_tick() / (proc.cpu_duration.tv_sec + proc.cpu_duration.tv_usec / 1000000.) * 100.); } break; #endif case 'd': /* duration µs */ /* seconds */ if (format[0] == '\0' || !strcasecmp(format, ""seconds"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%.3f"", proc.duration.tv_sec + proc.duration.tv_usec / 1000000.); } /* miliseconds */ } else if (!strcasecmp(format, ""miliseconds"") || !strcasecmp(format, ""mili"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%.3f"", proc.duration.tv_sec * 1000. + proc.duration.tv_usec / 1000.); } /* microseconds */ } else if (!strcasecmp(format, ""microseconds"") || !strcasecmp(format, ""micro"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%lu"", proc.duration.tv_sec * 1000000UL + proc.duration.tv_usec); } } else { zlog(ZLOG_WARNING, ""only 'seconds', 'mili', 'miliseconds', 'micro' or 'microseconds' are allowed as a modifier for %%%c ('%s')"", *s, format); return -1; } format[0] = '\0'; break; case 'e': /* fastcgi env */ if (format[0] == '\0') { zlog(ZLOG_WARNING, ""the name of the environment variable must be set between embraces for %%%c"", *s); return -1; } if (!test) { char *env = fcgi_getenv((fcgi_request*) SG(server_context), format, strlen(format)); len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", env ? env : ""-""); } format[0] = '\0'; break; case 'f': /* script */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", *proc.script_filename ? proc.script_filename : ""-""); } break; case 'l': /* content length */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%zu"", proc.content_length); } break; case 'm': /* method */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", *proc.request_method ? proc.request_method : ""-""); } break; case 'M': /* memory */ /* seconds */ if (format[0] == '\0' || !strcasecmp(format, ""bytes"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%zu"", proc.memory); } /* kilobytes */ } else if (!strcasecmp(format, ""kilobytes"") || !strcasecmp(format, ""kilo"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%lu"", proc.memory / 1024); } /* megabytes */ } else if (!strcasecmp(format, ""megabytes"") || !strcasecmp(format, ""mega"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%lu"", proc.memory / 1024 / 1024); } } else { zlog(ZLOG_WARNING, ""only 'bytes', 'kilo', 'kilobytes', 'mega' or 'megabytes' are allowed as a modifier for %%%c ('%s')"", *s, format); return -1; } format[0] = '\0'; break; case 'n': /* pool name */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", scoreboard->pool[0] ? scoreboard->pool : ""-""); } break; case 'o': /* header output */ if (format[0] == '\0') { zlog(ZLOG_WARNING, ""the name of the header must be set between embraces for %%%c"", *s); return -1; } if (!test) { sapi_header_struct *h; zend_llist_position pos; sapi_headers_struct *sapi_headers = &SG(sapi_headers); size_t format_len = strlen(format); h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos); while (h) { char *header; if (!h->header_len) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } if (!strstr(h->header, format)) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } /* test if enought char after the header name + ': ' */ if (h->header_len <= format_len + 2) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } if (h->header[format_len] != ':' || h->header[format_len + 1] != ' ') { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } header = h->header + format_len + 2; len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", header && *header ? header : ""-""); /* found, done */ break; } if (!len2) { len2 = 1; *b = '-'; } } format[0] = '\0'; break; case 'p': /* PID */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%ld"", (long)getpid()); } break; case 'P': /* PID */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%ld"", (long)getppid()); } break; case 'q': /* query_string */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", proc.query_string); } break; case 'Q': /* '?' */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", *proc.query_string ? ""?"" : """"); } break; case 'r': /* request URI */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", proc.request_uri); } break; case 'R': /* remote IP address */ if (!test) { const char *tmp = fcgi_get_last_client_ip(); len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", tmp ? tmp : ""-""); } break; case 's': /* status */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%d"", SG(sapi_headers).http_response_code); } break; case 'T': case 't': /* time */ if (!test) { time_t *t; if (*s == 't') { t = &proc.accepted_epoch; } else { t = &now_epoch; } if (format[0] == '\0') { strftime(tmp, sizeof(tmp) - 1, ""%d/%b/%Y:%H:%M:%S %z"", localtime(t)); } else { strftime(tmp, sizeof(tmp) - 1, format, localtime(t)); } len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", tmp); } format[0] = '\0'; break; case 'u': /* remote user */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", proc.auth_user); } break; case '{': /* complex var */ token = 1; { char *start; size_t l; start = ++s; while (*s != '\0') { if (*s == '}') { l = s - start; if (l >= sizeof(format) - 1) { l = sizeof(format) - 1; } memcpy(format, start, l); format[l] = '\0'; break; } s++; } if (s[1] == '\0') { zlog(ZLOG_WARNING, ""missing closing embrace in the access.format""); return -1; } } break; default: zlog(ZLOG_WARNING, ""Invalid token in the access.format (%%%c)"", *s); return -1; } if (*s != '}' && format[0] != '\0') { zlog(ZLOG_WARNING, ""embrace is not allowed for modifier %%%c"", *s); return -1; } s++; if (!test) { b += len2; len += len2; } continue; } if (!test) { // push the normal char to the output buffer *b = *s; b++; len++; } s++; } if (!test && strlen(buffer) > 0) { buffer[len] = '\n'; write(fpm_log_fd, buffer, len + 1); } return 0; }","int fpm_log_write(char *log_format) /* {{{ */ { char *s, *b; char buffer[FPM_LOG_BUFFER+1]; int token, test; size_t len, len2; struct fpm_scoreboard_proc_s proc, *proc_p; struct fpm_scoreboard_s *scoreboard; char tmp[129]; char format[129]; time_t now_epoch; #ifdef HAVE_TIMES clock_t tms_total; #endif if (!log_format && (!fpm_log_format || fpm_log_fd == -1)) { return -1; } if (!log_format) { log_format = fpm_log_format; test = 0; } else { test = 1; } now_epoch = time(NULL); if (!test) { scoreboard = fpm_scoreboard_get(); if (!scoreboard) { zlog(ZLOG_WARNING, ""unable to get scoreboard while preparing the access log""); return -1; } proc_p = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (!proc_p) { zlog(ZLOG_WARNING, ""[pool %s] Unable to acquire shm slot while preparing the access log"", scoreboard->pool); return -1; } proc = *proc_p; fpm_scoreboard_proc_release(proc_p); } token = 0; memset(buffer, '\0', sizeof(buffer)); b = buffer; len = 0; s = log_format; while (*s != '\0') { /* Test is we have place for 1 more char. */ if (len >= FPM_LOG_BUFFER) { zlog(ZLOG_NOTICE, ""the log buffer is full (%d). The access log request has been truncated."", FPM_LOG_BUFFER); len = FPM_LOG_BUFFER; break; } if (!token && *s == '%') { token = 1; memset(format, '\0', sizeof(format)); /* reset format */ s++; continue; } if (token) { token = 0; len2 = 0; switch (*s) { case '%': /* '%' */ *b = '%'; len2 = 1; break; #ifdef HAVE_TIMES case 'C': /* %CPU */ if (format[0] == '\0' || !strcasecmp(format, ""total"")) { if (!test) { tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cutime + proc.last_request_cpu.tms_cstime; } } else if (!strcasecmp(format, ""user"")) { if (!test) { tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_cutime; } } else if (!strcasecmp(format, ""system"")) { if (!test) { tms_total = proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cstime; } } else { zlog(ZLOG_WARNING, ""only 'total', 'user' or 'system' are allowed as a modifier for %%%c ('%s')"", *s, format); return -1; } format[0] = '\0'; if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%.2f"", tms_total / fpm_scoreboard_get_tick() / (proc.cpu_duration.tv_sec + proc.cpu_duration.tv_usec / 1000000.) * 100.); } break; #endif case 'd': /* duration µs */ /* seconds */ if (format[0] == '\0' || !strcasecmp(format, ""seconds"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%.3f"", proc.duration.tv_sec + proc.duration.tv_usec / 1000000.); } /* miliseconds */ } else if (!strcasecmp(format, ""miliseconds"") || !strcasecmp(format, ""mili"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%.3f"", proc.duration.tv_sec * 1000. + proc.duration.tv_usec / 1000.); } /* microseconds */ } else if (!strcasecmp(format, ""microseconds"") || !strcasecmp(format, ""micro"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%lu"", proc.duration.tv_sec * 1000000UL + proc.duration.tv_usec); } } else { zlog(ZLOG_WARNING, ""only 'seconds', 'mili', 'miliseconds', 'micro' or 'microseconds' are allowed as a modifier for %%%c ('%s')"", *s, format); return -1; } format[0] = '\0'; break; case 'e': /* fastcgi env */ if (format[0] == '\0') { zlog(ZLOG_WARNING, ""the name of the environment variable must be set between embraces for %%%c"", *s); return -1; } if (!test) { char *env = fcgi_getenv((fcgi_request*) SG(server_context), format, strlen(format)); len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", env ? env : ""-""); } format[0] = '\0'; break; case 'f': /* script */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", *proc.script_filename ? proc.script_filename : ""-""); } break; case 'l': /* content length */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%zu"", proc.content_length); } break; case 'm': /* method */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", *proc.request_method ? proc.request_method : ""-""); } break; case 'M': /* memory */ /* seconds */ if (format[0] == '\0' || !strcasecmp(format, ""bytes"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%zu"", proc.memory); } /* kilobytes */ } else if (!strcasecmp(format, ""kilobytes"") || !strcasecmp(format, ""kilo"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%lu"", proc.memory / 1024); } /* megabytes */ } else if (!strcasecmp(format, ""megabytes"") || !strcasecmp(format, ""mega"")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%lu"", proc.memory / 1024 / 1024); } } else { zlog(ZLOG_WARNING, ""only 'bytes', 'kilo', 'kilobytes', 'mega' or 'megabytes' are allowed as a modifier for %%%c ('%s')"", *s, format); return -1; } format[0] = '\0'; break; case 'n': /* pool name */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", scoreboard->pool[0] ? scoreboard->pool : ""-""); } break; case 'o': /* header output */ if (format[0] == '\0') { zlog(ZLOG_WARNING, ""the name of the header must be set between embraces for %%%c"", *s); return -1; } if (!test) { sapi_header_struct *h; zend_llist_position pos; sapi_headers_struct *sapi_headers = &SG(sapi_headers); size_t format_len = strlen(format); h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos); while (h) { char *header; if (!h->header_len) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } if (!strstr(h->header, format)) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } /* test if enought char after the header name + ': ' */ if (h->header_len <= format_len + 2) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } if (h->header[format_len] != ':' || h->header[format_len + 1] != ' ') { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } header = h->header + format_len + 2; len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", header && *header ? header : ""-""); /* found, done */ break; } if (!len2) { len2 = 1; *b = '-'; } } format[0] = '\0'; break; case 'p': /* PID */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%ld"", (long)getpid()); } break; case 'P': /* PID */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%ld"", (long)getppid()); } break; case 'q': /* query_string */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", proc.query_string); } break; case 'Q': /* '?' */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", *proc.query_string ? ""?"" : """"); } break; case 'r': /* request URI */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", proc.request_uri); } break; case 'R': /* remote IP address */ if (!test) { const char *tmp = fcgi_get_last_client_ip(); len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", tmp ? tmp : ""-""); } break; case 's': /* status */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%d"", SG(sapi_headers).http_response_code); } break; case 'T': case 't': /* time */ if (!test) { time_t *t; if (*s == 't') { t = &proc.accepted_epoch; } else { t = &now_epoch; } if (format[0] == '\0') { strftime(tmp, sizeof(tmp) - 1, ""%d/%b/%Y:%H:%M:%S %z"", localtime(t)); } else { strftime(tmp, sizeof(tmp) - 1, format, localtime(t)); } len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", tmp); } format[0] = '\0'; break; case 'u': /* remote user */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, ""%s"", proc.auth_user); } break; case '{': /* complex var */ token = 1; { char *start; size_t l; start = ++s; while (*s != '\0') { if (*s == '}') { l = s - start; if (l >= sizeof(format) - 1) { l = sizeof(format) - 1; } memcpy(format, start, l); format[l] = '\0'; break; } s++; } if (s[1] == '\0') { zlog(ZLOG_WARNING, ""missing closing embrace in the access.format""); return -1; } } break; default: zlog(ZLOG_WARNING, ""Invalid token in the access.format (%%%c)"", *s); return -1; } if (*s != '}' && format[0] != '\0') { zlog(ZLOG_WARNING, ""embrace is not allowed for modifier %%%c"", *s); return -1; } s++; if (!test) { b += len2; len += len2; } if (len >= FPM_LOG_BUFFER) { zlog(ZLOG_NOTICE, ""the log buffer is full (%d). The access log request has been truncated."", FPM_LOG_BUFFER); len = FPM_LOG_BUFFER; break; } continue; } if (!test) { // push the normal char to the output buffer *b = *s; b++; len++; } s++; } if (!test && strlen(buffer) > 0) { buffer[len] = '\n'; write(fpm_log_fd, buffer, len + 1); } return 0; }","{'deleted': [], 'added': [{'line_no': 352, 'char_start': 9435, 'char_end': 9467, 'line': '\t\t\tif (len >= FPM_LOG_BUFFER) {\n'}, {'line_no': 353, 'char_start': 9467, 'char_end': 9581, 'line': '\t\t\t\tzlog(ZLOG_NOTICE, ""the log buffer is full (%d). The access log request has been truncated."", FPM_LOG_BUFFER);\n'}, {'line_no': 354, 'char_start': 9581, 'char_end': 9607, 'line': '\t\t\t\tlen = FPM_LOG_BUFFER;\n'}, {'line_no': 355, 'char_start': 9607, 'char_end': 9618, 'line': '\t\t\t\tbreak;\n'}, {'line_no': 356, 'char_start': 9618, 'char_end': 9623, 'line': '\t\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 9438, 'char_end': 9626, 'chars': 'if (len >= FPM_LOG_BUFFER) {\n\t\t\t\tzlog(ZLOG_NOTICE, ""the log buffer is full (%d). The access log request has been truncated."", FPM_LOG_BUFFER);\n\t\t\t\tlen = FPM_LOG_BUFFER;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t'}]}",github.com/php/php-src/commit/2721a0148649e07ed74468f097a28899741eb58f,sapi/fpm/fpm/fpm_log.c,cwe-125,2971 cwe-787,mpol_parse_str,"int mpol_parse_str(char *str, struct mempolicy **mpol) { struct mempolicy *new = NULL; unsigned short mode_flags; nodemask_t nodes; char *nodelist = strchr(str, ':'); char *flags = strchr(str, '='); int err = 1, mode; if (flags) *flags++ = '\0'; /* terminate mode string */ if (nodelist) { /* NUL-terminate mode or flags string */ *nodelist++ = '\0'; if (nodelist_parse(nodelist, nodes)) goto out; if (!nodes_subset(nodes, node_states[N_MEMORY])) goto out; } else nodes_clear(nodes); mode = match_string(policy_modes, MPOL_MAX, str); if (mode < 0) goto out; switch (mode) { case MPOL_PREFERRED: /* * Insist on a nodelist of one node only */ if (nodelist) { char *rest = nodelist; while (isdigit(*rest)) rest++; if (*rest) goto out; } break; case MPOL_INTERLEAVE: /* * Default to online nodes with memory if no nodelist */ if (!nodelist) nodes = node_states[N_MEMORY]; break; case MPOL_LOCAL: /* * Don't allow a nodelist; mpol_new() checks flags */ if (nodelist) goto out; mode = MPOL_PREFERRED; break; case MPOL_DEFAULT: /* * Insist on a empty nodelist */ if (!nodelist) err = 0; goto out; case MPOL_BIND: /* * Insist on a nodelist */ if (!nodelist) goto out; } mode_flags = 0; if (flags) { /* * Currently, we only support two mutually exclusive * mode flags. */ if (!strcmp(flags, ""static"")) mode_flags |= MPOL_F_STATIC_NODES; else if (!strcmp(flags, ""relative"")) mode_flags |= MPOL_F_RELATIVE_NODES; else goto out; } new = mpol_new(mode, mode_flags, &nodes); if (IS_ERR(new)) goto out; /* * Save nodes for mpol_to_str() to show the tmpfs mount options * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo. */ if (mode != MPOL_PREFERRED) new->v.nodes = nodes; else if (nodelist) new->v.preferred_node = first_node(nodes); else new->flags |= MPOL_F_LOCAL; /* * Save nodes for contextualization: this will be used to ""clone"" * the mempolicy in a specific context [cpuset] at a later time. */ new->w.user_nodemask = nodes; err = 0; out: /* Restore string for error message */ if (nodelist) *--nodelist = ':'; if (flags) *--flags = '='; if (!err) *mpol = new; return err; }","int mpol_parse_str(char *str, struct mempolicy **mpol) { struct mempolicy *new = NULL; unsigned short mode_flags; nodemask_t nodes; char *nodelist = strchr(str, ':'); char *flags = strchr(str, '='); int err = 1, mode; if (flags) *flags++ = '\0'; /* terminate mode string */ if (nodelist) { /* NUL-terminate mode or flags string */ *nodelist++ = '\0'; if (nodelist_parse(nodelist, nodes)) goto out; if (!nodes_subset(nodes, node_states[N_MEMORY])) goto out; } else nodes_clear(nodes); mode = match_string(policy_modes, MPOL_MAX, str); if (mode < 0) goto out; switch (mode) { case MPOL_PREFERRED: /* * Insist on a nodelist of one node only, although later * we use first_node(nodes) to grab a single node, so here * nodelist (or nodes) cannot be empty. */ if (nodelist) { char *rest = nodelist; while (isdigit(*rest)) rest++; if (*rest) goto out; if (nodes_empty(nodes)) goto out; } break; case MPOL_INTERLEAVE: /* * Default to online nodes with memory if no nodelist */ if (!nodelist) nodes = node_states[N_MEMORY]; break; case MPOL_LOCAL: /* * Don't allow a nodelist; mpol_new() checks flags */ if (nodelist) goto out; mode = MPOL_PREFERRED; break; case MPOL_DEFAULT: /* * Insist on a empty nodelist */ if (!nodelist) err = 0; goto out; case MPOL_BIND: /* * Insist on a nodelist */ if (!nodelist) goto out; } mode_flags = 0; if (flags) { /* * Currently, we only support two mutually exclusive * mode flags. */ if (!strcmp(flags, ""static"")) mode_flags |= MPOL_F_STATIC_NODES; else if (!strcmp(flags, ""relative"")) mode_flags |= MPOL_F_RELATIVE_NODES; else goto out; } new = mpol_new(mode, mode_flags, &nodes); if (IS_ERR(new)) goto out; /* * Save nodes for mpol_to_str() to show the tmpfs mount options * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo. */ if (mode != MPOL_PREFERRED) new->v.nodes = nodes; else if (nodelist) new->v.preferred_node = first_node(nodes); else new->flags |= MPOL_F_LOCAL; /* * Save nodes for contextualization: this will be used to ""clone"" * the mempolicy in a specific context [cpuset] at a later time. */ new->w.user_nodemask = nodes; err = 0; out: /* Restore string for error message */ if (nodelist) *--nodelist = ':'; if (flags) *--flags = '='; if (!err) *mpol = new; return err; }","{'deleted': [{'line_no': 30, 'char_start': 637, 'char_end': 680, 'line': '\t\t * Insist on a nodelist of one node only\n'}], 'added': [{'line_no': 30, 'char_start': 637, 'char_end': 696, 'line': '\t\t * Insist on a nodelist of one node only, although later\n'}, {'line_no': 31, 'char_start': 696, 'char_end': 757, 'line': '\t\t * we use first_node(nodes) to grab a single node, so here\n'}, {'line_no': 32, 'char_start': 757, 'char_end': 799, 'line': '\t\t * nodelist (or nodes) cannot be empty.\n'}, {'line_no': 40, 'char_start': 915, 'char_end': 942, 'line': '\t\t\tif (nodes_empty(nodes))\n'}, {'line_no': 41, 'char_start': 942, 'char_end': 956, 'line': '\t\t\t\tgoto out;\n'}]}","{'deleted': [], 'added': [{'char_start': 679, 'char_end': 798, 'chars': ', although later\n\t\t * we use first_node(nodes) to grab a single node, so here\n\t\t * nodelist (or nodes) cannot be empty.'}, {'char_start': 899, 'char_end': 940, 'chars': ')\n\t\t\t\tgoto out;\n\t\t\tif (nodes_empty(nodes)'}]}",github.com/torvalds/linux/commit/aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd,mm/mempolicy.c,cwe-787,703 cwe-125,ims_pcu_get_cdc_union_desc,"static const struct usb_cdc_union_desc * ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, ""Missing descriptor data\n""); return NULL; } if (!buflen) { dev_err(&intf->dev, ""Zero length descriptor\n""); return NULL; } while (buflen > 0) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, ""Found union header\n""); return union_desc; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, ""Missing CDC union descriptor\n""); return NULL;","static const struct usb_cdc_union_desc * ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, ""Missing descriptor data\n""); return NULL; } if (!buflen) { dev_err(&intf->dev, ""Zero length descriptor\n""); return NULL; } while (buflen >= sizeof(*union_desc)) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bLength > buflen) { dev_err(&intf->dev, ""Too large descriptor\n""); return NULL; } if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, ""Found union header\n""); if (union_desc->bLength >= sizeof(*union_desc)) return union_desc; dev_err(&intf->dev, ""Union descriptor to short (%d vs %zd\n)"", union_desc->bLength, sizeof(*union_desc)); return NULL; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, ""Missing CDC union descriptor\n""); return NULL;","{'deleted': [{'line_no': 18, 'char_start': 398, 'char_end': 420, 'line': '\twhile (buflen > 0) {\n'}, {'line_no': 24, 'char_start': 640, 'char_end': 662, 'line': '\t\t\treturn union_desc;\n'}], 'added': [{'line_no': 18, 'char_start': 398, 'char_end': 439, 'line': '\twhile (buflen >= sizeof(*union_desc)) {\n'}, {'line_no': 21, 'char_start': 489, 'char_end': 527, 'line': '\t\tif (union_desc->bLength > buflen) {\n'}, {'line_no': 22, 'char_start': 527, 'char_end': 577, 'line': '\t\t\tdev_err(&intf->dev, ""Too large descriptor\\n"");\n'}, {'line_no': 23, 'char_start': 577, 'char_end': 593, 'line': '\t\t\treturn NULL;\n'}, {'line_no': 24, 'char_start': 593, 'char_end': 597, 'line': '\t\t}\n'}, {'line_no': 25, 'char_start': 597, 'char_end': 598, 'line': '\n'}, {'line_no': 29, 'char_start': 768, 'char_end': 769, 'line': '\n'}, {'line_no': 30, 'char_start': 769, 'char_end': 820, 'line': '\t\t\tif (union_desc->bLength >= sizeof(*union_desc))\n'}, {'line_no': 31, 'char_start': 820, 'char_end': 843, 'line': '\t\t\t\treturn union_desc;\n'}, {'line_no': 32, 'char_start': 843, 'char_end': 844, 'line': '\n'}, {'line_no': 33, 'char_start': 844, 'char_end': 867, 'line': '\t\t\tdev_err(&intf->dev,\n'}, {'line_no': 34, 'char_start': 867, 'char_end': 914, 'line': '\t\t\t\t""Union descriptor to short (%d vs %zd\\n)"",\n'}, {'line_no': 35, 'char_start': 914, 'char_end': 961, 'line': '\t\t\t\tunion_desc->bLength, sizeof(*union_desc));\n'}, {'line_no': 36, 'char_start': 961, 'char_end': 977, 'line': '\t\t\treturn NULL;\n'}]}","{'deleted': [{'char_start': 415, 'char_end': 416, 'chars': '0'}], 'added': [{'char_start': 414, 'char_end': 415, 'chars': '='}, {'char_start': 416, 'char_end': 435, 'chars': 'sizeof(*union_desc)'}, {'char_start': 489, 'char_end': 598, 'chars': '\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'}, {'char_start': 768, 'char_end': 821, 'chars': '\n\t\t\tif (union_desc->bLength >= sizeof(*union_desc))\n\t'}, {'char_start': 841, 'char_end': 975, 'chars': ';\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'}]}",github.com/torvalds/linux/commit/ea04efee7635c9120d015dcdeeeb6988130cb67a,drivers/input/misc/ims-pcu.c,cwe-125,230 cwe-089,get_old_sourcebyinstitution_number,"def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution): """""" Get all the old sourcebyinstitution number from the SQLite database. """""" query = """""" SELECT titles FROM history WHERE sourcebyinstitution = ""%s"" ORDER BY titles DESC LIMIT 1 """""" % sourcebyinstitution sqlite.execute(query) for record in sqlite: old_sourcebyinstitution_number = record[0] return old_sourcebyinstitution_number","def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution): """""" Get all the old sourcebyinstitution number from the SQLite database. """""" query = """""" SELECT titles FROM history WHERE sourcebyinstitution = ? ORDER BY titles DESC LIMIT 1 """""" sqlite.execute(query, (sourcebyinstitution,)) for record in sqlite: old_sourcebyinstitution_number = record[0] return old_sourcebyinstitution_number","{'deleted': [{'line_no': 11, 'char_start': 261, 'char_end': 300, 'line': ' sourcebyinstitution = ""%s""\n'}, {'line_no': 15, 'char_start': 357, 'char_end': 387, 'line': ' """""" % sourcebyinstitution\n'}, {'line_no': 17, 'char_start': 388, 'char_end': 414, 'line': ' sqlite.execute(query)\n'}], 'added': [{'line_no': 11, 'char_start': 261, 'char_end': 297, 'line': ' sourcebyinstitution = ?\n'}, {'line_no': 15, 'char_start': 354, 'char_end': 362, 'line': ' """"""\n'}, {'line_no': 17, 'char_start': 363, 'char_end': 413, 'line': ' sqlite.execute(query, (sourcebyinstitution,))\n'}]}","{'deleted': [{'char_start': 295, 'char_end': 299, 'chars': '""%s""'}, {'char_start': 364, 'char_end': 386, 'chars': ' % sourcebyinstitution'}], 'added': [{'char_start': 295, 'char_end': 296, 'chars': '?'}, {'char_start': 387, 'char_end': 411, 'chars': ', (sourcebyinstitution,)'}]}",github.com/miku/siskin/commit/7fa398d2fea72bf2e8b4808f75df4b3d35ae959a,bin/solrcheckup.py,cwe-089,109 cwe-416,__ext4_journal_stop,"int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle) { struct super_block *sb; int err; int rc; if (!ext4_handle_valid(handle)) { ext4_put_nojournal(handle); return 0; } if (!handle->h_transaction) { err = jbd2_journal_stop(handle); return handle->h_err ? handle->h_err : err; } sb = handle->h_transaction->t_journal->j_private; err = handle->h_err; rc = jbd2_journal_stop(handle); if (!err) err = rc; if (err) __ext4_std_error(sb, where, line, err); return err; }","int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle) { struct super_block *sb; int err; int rc; if (!ext4_handle_valid(handle)) { ext4_put_nojournal(handle); return 0; } err = handle->h_err; if (!handle->h_transaction) { rc = jbd2_journal_stop(handle); return err ? err : rc; } sb = handle->h_transaction->t_journal->j_private; rc = jbd2_journal_stop(handle); if (!err) err = rc; if (err) __ext4_std_error(sb, where, line, err); return err; }","{'deleted': [{'line_no': 13, 'char_start': 239, 'char_end': 274, 'line': '\t\terr = jbd2_journal_stop(handle);\n'}, {'line_no': 14, 'char_start': 274, 'char_end': 320, 'line': '\t\treturn handle->h_err ? handle->h_err : err;\n'}, {'line_no': 18, 'char_start': 375, 'char_end': 397, 'line': '\terr = handle->h_err;\n'}], 'added': [{'line_no': 12, 'char_start': 208, 'char_end': 230, 'line': '\terr = handle->h_err;\n'}, {'line_no': 14, 'char_start': 261, 'char_end': 295, 'line': '\t\trc = jbd2_journal_stop(handle);\n'}, {'line_no': 15, 'char_start': 295, 'char_end': 320, 'line': '\t\treturn err ? err : rc;\n'}]}","{'deleted': [{'char_start': 241, 'char_end': 242, 'chars': 'e'}, {'char_start': 243, 'char_end': 244, 'chars': 'r'}, {'char_start': 283, 'char_end': 293, 'chars': 'handle->h_'}, {'char_start': 299, 'char_end': 309, 'chars': 'handle->h_'}, {'char_start': 315, 'char_end': 316, 'chars': 'e'}, {'char_start': 317, 'char_end': 318, 'chars': 'r'}, {'char_start': 373, 'char_end': 395, 'chars': ';\n\terr = handle->h_err'}], 'added': [{'char_start': 209, 'char_end': 231, 'chars': 'err = handle->h_err;\n\t'}, {'char_start': 264, 'char_end': 265, 'chars': 'c'}, {'char_start': 317, 'char_end': 318, 'chars': 'c'}]}",github.com/torvalds/linux/commit/6934da9238da947628be83635e365df41064b09b,fs/ext4/ext4_jbd2.c,cwe-416,152 cwe-089,get," def get(self, email): """""" Fetch data for admin with the corresponding email """""" return database_utilities.execute_query(f""""""select * from admins where email = '{email}'"""""")"," def get(self, email): """""" Fetch data for admin with the corresponding email """""" return database_utilities.execute_query(f""""""select * from admins where email = %s"""""", (email, ))","{'deleted': [{'line_no': 3, 'char_start': 92, 'char_end': 192, 'line': ' return database_utilities.execute_query(f""""""select * from admins where email = \'{email}\'"""""")\n'}], 'added': [{'line_no': 3, 'char_start': 92, 'char_end': 196, 'line': ' return database_utilities.execute_query(f""""""select * from admins where email = %s"""""", (email, ))\n'}]}","{'deleted': [{'char_start': 179, 'char_end': 181, 'chars': ""'{""}, {'char_start': 186, 'char_end': 191, 'chars': '}\'""""""'}], 'added': [{'char_start': 179, 'char_end': 187, 'chars': '%s"""""", ('}, {'char_start': 192, 'char_end': 195, 'chars': ', )'}]}",github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485,apis/admins.py,cwe-089,38 cwe-787,add_password,"static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret) { MD5_CTX md5_secret, my_md5; unsigned char misc[AUTH_VECTOR_LEN]; int i; int length = strlen(password); unsigned char hashed[256 + AUTH_PASS_LEN]; /* can't be longer than this */ unsigned char *vector; attribute_t *attr; if (length > MAXPASS) { /* shorten the password for now */ length = MAXPASS; } if (length == 0) { length = AUTH_PASS_LEN; /* 0 maps to 16 */ } if ((length & (AUTH_PASS_LEN - 1)) != 0) { length += (AUTH_PASS_LEN - 1); /* round it up */ length &= ~(AUTH_PASS_LEN - 1); /* chop it off */ } /* 16*N maps to itself */ memset(hashed, 0, length); memcpy(hashed, password, strlen(password)); attr = find_attribute(request, PW_PASSWORD); if (type == PW_PASSWORD) { vector = request->vector; } else { vector = attr->data; /* attr CANNOT be NULL here. */ } /* ************************************************************ */ /* encrypt the password */ /* password : e[0] = p[0] ^ MD5(secret + vector) */ MD5Init(&md5_secret); MD5Update(&md5_secret, (unsigned char *) secret, strlen(secret)); my_md5 = md5_secret; /* so we won't re-do the hash later */ MD5Update(&my_md5, vector, AUTH_VECTOR_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(hashed, misc, AUTH_PASS_LEN); /* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */ for (i = 1; i < (length >> 4); i++) { my_md5 = md5_secret; /* grab old value of the hash */ MD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN); } if (type == PW_OLD_PASSWORD) { attr = find_attribute(request, PW_OLD_PASSWORD); } if (!attr) { add_attribute(request, type, hashed, length); } else { memcpy(attr->data, hashed, length); /* overwrite the packet */ } }","static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret) { MD5_CTX md5_secret, my_md5; unsigned char misc[AUTH_VECTOR_LEN]; int i; int length = strlen(password); unsigned char hashed[256 + AUTH_PASS_LEN]; /* can't be longer than this */ unsigned char *vector; attribute_t *attr; if (length > MAXPASS) { /* shorten the password for now */ length = MAXPASS; } if (length == 0) { length = AUTH_PASS_LEN; /* 0 maps to 16 */ } if ((length & (AUTH_PASS_LEN - 1)) != 0) { length += (AUTH_PASS_LEN - 1); /* round it up */ length &= ~(AUTH_PASS_LEN - 1); /* chop it off */ } /* 16*N maps to itself */ memset(hashed, 0, length); memcpy(hashed, password, length); attr = find_attribute(request, PW_PASSWORD); if (type == PW_PASSWORD) { vector = request->vector; } else { vector = attr->data; /* attr CANNOT be NULL here. */ } /* ************************************************************ */ /* encrypt the password */ /* password : e[0] = p[0] ^ MD5(secret + vector) */ MD5Init(&md5_secret); MD5Update(&md5_secret, (unsigned char *) secret, strlen(secret)); my_md5 = md5_secret; /* so we won't re-do the hash later */ MD5Update(&my_md5, vector, AUTH_VECTOR_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(hashed, misc, AUTH_PASS_LEN); /* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */ for (i = 1; i < (length >> 4); i++) { my_md5 = md5_secret; /* grab old value of the hash */ MD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN); } if (type == PW_OLD_PASSWORD) { attr = find_attribute(request, PW_OLD_PASSWORD); } if (!attr) { add_attribute(request, type, hashed, length); } else { memcpy(attr->data, hashed, length); /* overwrite the packet */ } }","{'deleted': [{'line_no': 23, 'char_start': 698, 'char_end': 743, 'line': '\tmemcpy(hashed, password, strlen(password));\n'}], 'added': [{'line_no': 23, 'char_start': 698, 'char_end': 733, 'line': '\tmemcpy(hashed, password, length);\n'}]}","{'deleted': [{'char_start': 724, 'char_end': 727, 'chars': 'str'}, {'char_start': 730, 'char_end': 740, 'chars': '(password)'}], 'added': [{'char_start': 727, 'char_end': 730, 'chars': 'gth'}]}",github.com/FreeRADIUS/pam_radius/commit/01173ec2426627dbb1e0d96c06c3ffa0b14d36d0,src/pam_radius_auth.c,cwe-787,577 cwe-078,_create_3par_iscsi_host," def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id): """"""Create a 3PAR host. Create a 3PAR host, if there is already a host on the 3par using the same iqn but with a different hostname, return the hostname used by 3PAR. """""" cmd = 'createhost -iscsi -persona %s -domain %s %s %s' % \ (persona_id, domain, hostname, iscsi_iqn) out = self.common._cli_run(cmd, None) if out and len(out) > 1: return self.common.parse_create_host_error(hostname, out) return hostname"," def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id): """"""Create a 3PAR host. Create a 3PAR host, if there is already a host on the 3par using the same iqn but with a different hostname, return the hostname used by 3PAR. """""" cmd = ['createhost', '-iscsi', '-persona', persona_id, '-domain', domain, hostname, iscsi_iqn] out = self.common._cli_run(cmd) if out and len(out) > 1: return self.common.parse_create_host_error(hostname, out) return hostname","{'deleted': [{'line_no': 8, 'char_start': 291, 'char_end': 358, 'line': "" cmd = 'createhost -iscsi -persona %s -domain %s %s %s' % \\\n""}, {'line_no': 9, 'char_start': 358, 'char_end': 414, 'line': ' (persona_id, domain, hostname, iscsi_iqn)\n'}, {'line_no': 10, 'char_start': 414, 'char_end': 460, 'line': ' out = self.common._cli_run(cmd, None)\n'}], 'added': [{'line_no': 8, 'char_start': 291, 'char_end': 365, 'line': "" cmd = ['createhost', '-iscsi', '-persona', persona_id, '-domain',\n""}, {'line_no': 9, 'char_start': 365, 'char_end': 409, 'line': ' domain, hostname, iscsi_iqn]\n'}, {'line_no': 10, 'char_start': 409, 'char_end': 449, 'line': ' out = self.common._cli_run(cmd)\n'}]}","{'deleted': [{'char_start': 333, 'char_end': 334, 'chars': '%'}, {'char_start': 343, 'char_end': 352, 'chars': ' %s %s %s'}, {'char_start': 353, 'char_end': 357, 'chars': ' % \\'}, {'char_start': 372, 'char_end': 384, 'chars': '(persona_id,'}, {'char_start': 412, 'char_end': 413, 'chars': ')'}, {'char_start': 452, 'char_end': 458, 'chars': ', None'}], 'added': [{'char_start': 305, 'char_end': 306, 'chars': '['}, {'char_start': 317, 'char_end': 319, 'chars': ""',""}, {'char_start': 320, 'char_end': 321, 'chars': ""'""}, {'char_start': 327, 'char_end': 329, 'chars': ""',""}, {'char_start': 330, 'char_end': 331, 'chars': ""'""}, {'char_start': 339, 'char_end': 341, 'chars': ""',""}, {'char_start': 342, 'char_end': 345, 'chars': 'per'}, {'char_start': 346, 'char_end': 353, 'chars': 'ona_id,'}, {'char_start': 354, 'char_end': 355, 'chars': ""'""}, {'char_start': 363, 'char_end': 364, 'chars': ','}, {'char_start': 407, 'char_end': 408, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_iscsi.py,cwe-078,155 cwe-022,set_interface_var,"set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, ""w""); if (!fp) { if (name) flog(LOG_ERR, ""failed to set %s (%u) for %s: %s"", name, val, iface, strerror(errno)); return -1; } fprintf(fp, ""%u"", val); fclose(fp); return 0; }","set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; /* No path traversal */ if (strstr(name, "".."") || strchr(name, '/')) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, ""w""); if (!fp) { if (name) flog(LOG_ERR, ""failed to set %s (%u) for %s: %s"", name, val, iface, strerror(errno)); return -1; } fprintf(fp, ""%u"", val); fclose(fp); return 0; }","{'deleted': [], 'added': [{'line_no': 10, 'char_start': 239, 'char_end': 264, 'line': '\t/* No path traversal */\n'}, {'line_no': 11, 'char_start': 264, 'char_end': 310, 'line': '\tif (strstr(name, "".."") || strchr(name, \'/\'))\n'}, {'line_no': 12, 'char_start': 310, 'char_end': 323, 'line': '\t\treturn -1;\n'}, {'line_no': 13, 'char_start': 323, 'char_end': 324, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 240, 'char_end': 325, 'chars': '/* No path traversal */\n\tif (strstr(name, "".."") || strchr(name, \'/\'))\n\t\treturn -1;\n\n\t'}]}",github.com/reubenhwk/radvd/commit/92e22ca23e52066da2258df8c76a2dca8a428bcc,device-linux.c,cwe-022,167 cwe-089,get_task,"@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value) def get_task(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = '"" + str(message.chat.id) + ""'"") name = conn.fetchone() settings.close() if name == None: bot.send_message(message.chat.id, ""You should login before get tasks."") else: bases.update.update_user(name[1], name[0], name[2]) bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1])) set_state(message.chat.id, config.States.S_START.value)","@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value) def get_task(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),)) name = conn.fetchone() settings.close() if name == None: bot.send_message(message.chat.id, ""You should login before get tasks."") else: bases.update.update_user(name[1], name[0], name[2]) bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1])) set_state(message.chat.id, config.States.S_START.value)","{'deleted': [{'line_no': 5, 'char_start': 266, 'char_end': 353, 'line': ' conn.execute(""select * from users where chat_id = \'"" + str(message.chat.id) + ""\'"")\n'}], 'added': [{'line_no': 5, 'char_start': 266, 'char_end': 349, 'line': ' conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),))\n'}]}","{'deleted': [{'char_start': 320, 'char_end': 321, 'chars': ""'""}, {'char_start': 322, 'char_end': 324, 'chars': ' +'}, {'char_start': 345, 'char_end': 351, 'chars': ' + ""\'""'}], 'added': [{'char_start': 320, 'char_end': 321, 'chars': '?'}, {'char_start': 322, 'char_end': 323, 'chars': ','}, {'char_start': 324, 'char_end': 325, 'chars': '('}, {'char_start': 345, 'char_end': 347, 'chars': ',)'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bot.py,cwe-089,168 cwe-079,_keyify,"def _keyify(key): return _key_pattern.sub(' ', key.lower())","def _keyify(key): key = escape(key.lower(), quote=True) return _key_pattern.sub(' ', key)","{'deleted': [{'line_no': 2, 'char_start': 18, 'char_end': 63, 'line': "" return _key_pattern.sub(' ', key.lower())\n""}], 'added': [{'line_no': 2, 'char_start': 18, 'char_end': 60, 'line': ' key = escape(key.lower(), quote=True)\n'}, {'line_no': 3, 'char_start': 60, 'char_end': 97, 'line': "" return _key_pattern.sub(' ', key)\n""}]}","{'deleted': [{'char_start': 54, 'char_end': 62, 'chars': '.lower()'}], 'added': [{'char_start': 22, 'char_end': 64, 'chars': 'key = escape(key.lower(), quote=True)\n '}]}",github.com/lepture/mistune/commit/5f06d724bc05580e7f203db2d4a4905fc1127f98,mistune.py,cwe-079,17 cwe-079,batch_edit_translations,"@login_required(redirect_field_name='', login_url='/403') @require_POST @require_AJAX @transaction.atomic def batch_edit_translations(request): """"""Perform an action on a list of translations. Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view are defined in `models.BatchActionsForm`. """""" form = forms.BatchActionsForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors.as_json()) locale = get_object_or_404(Locale, code=form.cleaned_data['locale']) entities = Entity.objects.filter(pk__in=form.cleaned_data['entities']) if not entities.exists(): return JsonResponse({'count': 0}) # Batch editing is only available to translators. Check if user has # translate permissions for all of the projects in passed entities. # Also make sure projects are not enabled in read-only mode for a locale. projects_pk = entities.values_list('resource__project__pk', flat=True) projects = Project.objects.filter(pk__in=projects_pk.distinct()) for project in projects: if ( not request.user.can_translate(project=project, locale=locale) or readonly_exists(projects, locale) ): return HttpResponseForbidden( ""Forbidden: You don't have permission for batch editing"" ) # Find all impacted active translations, including plural forms. active_translations = Translation.objects.filter( active=True, locale=locale, entity__in=entities, ) # Execute the actual action. action_function = ACTIONS_FN_MAP[form.cleaned_data['action']] action_status = action_function( form, request.user, active_translations, locale, ) if action_status.get('error'): return JsonResponse(action_status) invalid_translation_count = len(action_status.get('invalid_translation_pks', [])) if action_status['count'] == 0: return JsonResponse({ 'count': 0, 'invalid_translation_count': invalid_translation_count, }) update_stats(action_status['translated_resources'], locale) mark_changed_translation(action_status['changed_entities'], locale) # Update latest translation. if action_status['latest_translation_pk']: Translation.objects.get( pk=action_status['latest_translation_pk'] ).update_latest_translation() update_translation_memory( action_status['changed_translation_pks'], project, locale ) return JsonResponse({ 'count': action_status['count'], 'invalid_translation_count': invalid_translation_count, })","@login_required(redirect_field_name='', login_url='/403') @require_POST @require_AJAX @transaction.atomic def batch_edit_translations(request): """"""Perform an action on a list of translations. Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view are defined in `models.BatchActionsForm`. """""" form = forms.BatchActionsForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors.as_json(escape_html=True)) locale = get_object_or_404(Locale, code=form.cleaned_data['locale']) entities = Entity.objects.filter(pk__in=form.cleaned_data['entities']) if not entities.exists(): return JsonResponse({'count': 0}) # Batch editing is only available to translators. Check if user has # translate permissions for all of the projects in passed entities. # Also make sure projects are not enabled in read-only mode for a locale. projects_pk = entities.values_list('resource__project__pk', flat=True) projects = Project.objects.filter(pk__in=projects_pk.distinct()) for project in projects: if ( not request.user.can_translate(project=project, locale=locale) or readonly_exists(projects, locale) ): return HttpResponseForbidden( ""Forbidden: You don't have permission for batch editing"" ) # Find all impacted active translations, including plural forms. active_translations = Translation.objects.filter( active=True, locale=locale, entity__in=entities, ) # Execute the actual action. action_function = ACTIONS_FN_MAP[form.cleaned_data['action']] action_status = action_function( form, request.user, active_translations, locale, ) if action_status.get('error'): return JsonResponse(action_status) invalid_translation_count = len(action_status.get('invalid_translation_pks', [])) if action_status['count'] == 0: return JsonResponse({ 'count': 0, 'invalid_translation_count': invalid_translation_count, }) update_stats(action_status['translated_resources'], locale) mark_changed_translation(action_status['changed_entities'], locale) # Update latest translation. if action_status['latest_translation_pk']: Translation.objects.get( pk=action_status['latest_translation_pk'] ).update_latest_translation() update_translation_memory( action_status['changed_translation_pks'], project, locale ) return JsonResponse({ 'count': action_status['count'], 'invalid_translation_count': invalid_translation_count, })","{'deleted': [{'line_no': 14, 'char_start': 406, 'char_end': 467, 'line': ' return HttpResponseBadRequest(form.errors.as_json())\n'}], 'added': [{'line_no': 14, 'char_start': 406, 'char_end': 483, 'line': ' return HttpResponseBadRequest(form.errors.as_json(escape_html=True))\n'}]}","{'deleted': [], 'added': [{'char_start': 464, 'char_end': 480, 'chars': 'escape_html=True'}]}",github.com/onefork/pontoon-sr/commit/fc07ed9c68e08d41f74c078b4e7727f1a0888be8,pontoon/batch/views.py,cwe-079,536 cwe-089,ranks,"@endpoints.route(""/ranks"") def ranks(): if db == None: init() scene = request.args.get('scene', default='austin') date = request.args.get('date') # If no date was provided, pick the date of the latest tournament if date == None: sql = ""SELECT distinct date FROM ranks WHERE scene='{}' ORDER BY date DESC LIMIT 1;"".format(scene) res = db.exec(sql) date = res[0][0] # Get all the urls that this player has participated in sql = ""SELECT * FROM ranks WHERE scene = '{}' and date='{}'"".format(scene, date) res = db.exec(sql) # Make a dict out of this data # eg {'christmasmike': 50} cur_ranks = {} for r in res: tag = r[1] rank = r[2] cur_ranks[tag] = rank # Now get the ranks from last month, so we know if these players went up or down y, m, d = date.split('-') prev_date = bracket_utils.get_previous_month(date) # Get all the urls that this player has participated in sql = ""SELECT * FROM ranks WHERE scene = '{}' and date='{}'"".format(scene, prev_date) res = db.exec(sql) # Make a dict out of this data # eg {'christmasmike': 50} prev_ranks = {} for r in res: tag = r[1] rank = r[2] prev_ranks[tag] = rank return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)","@endpoints.route(""/ranks"") def ranks(): if db == None: init() scene = request.args.get('scene', default='austin') date = request.args.get('date') # If no date was provided, pick the date of the latest tournament if date == None: sql = ""SELECT distinct date FROM ranks WHERE scene='{scene}' ORDER BY date DESC LIMIT 1;"" args = {'scene': scene} res = db.exec(sql, args) date = res[0][0] # Get all the urls that this player has participated in sql = ""SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'"" args = {'scene': scene, 'date': date} res = db.exec(sql, args) # Make a dict out of this data # eg {'christmasmike': 50} cur_ranks = {} for r in res: tag = r[1] rank = r[2] cur_ranks[tag] = rank # Now get the ranks from last month, so we know if these players went up or down y, m, d = date.split('-') prev_date = bracket_utils.get_previous_month(date) # Get all the urls that this player has participated in sql = ""SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'"" args = {'scene': scene, 'date': prev_date} res = db.exec(sql, args) # Make a dict out of this data # eg {'christmasmike': 50} prev_ranks = {} for r in res: tag = r[1] rank = r[2] prev_ranks[tag] = rank return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)","{'deleted': [{'line_no': 11, 'char_start': 260, 'char_end': 367, 'line': ' sql = ""SELECT distinct date FROM ranks WHERE scene=\'{}\' ORDER BY date DESC LIMIT 1;"".format(scene)\n'}, {'line_no': 12, 'char_start': 367, 'char_end': 394, 'line': ' res = db.exec(sql)\n'}, {'line_no': 16, 'char_start': 480, 'char_end': 565, 'line': ' sql = ""SELECT * FROM ranks WHERE scene = \'{}\' and date=\'{}\'"".format(scene, date)\n'}, {'line_no': 17, 'char_start': 565, 'char_end': 588, 'line': ' res = db.exec(sql)\n'}, {'line_no': 33, 'char_start': 994, 'char_end': 1084, 'line': ' sql = ""SELECT * FROM ranks WHERE scene = \'{}\' and date=\'{}\'"".format(scene, prev_date)\n'}, {'line_no': 34, 'char_start': 1084, 'char_end': 1107, 'line': ' res = db.exec(sql)\n'}], 'added': [{'line_no': 11, 'char_start': 260, 'char_end': 358, 'line': ' sql = ""SELECT distinct date FROM ranks WHERE scene=\'{scene}\' ORDER BY date DESC LIMIT 1;""\n'}, {'line_no': 12, 'char_start': 358, 'char_end': 390, 'line': "" args = {'scene': scene}\n""}, {'line_no': 13, 'char_start': 390, 'char_end': 423, 'line': ' res = db.exec(sql, args)\n'}, {'line_no': 17, 'char_start': 509, 'char_end': 583, 'line': ' sql = ""SELECT * FROM ranks WHERE scene = \'{scene}\' and date=\'{date}\'""\n'}, {'line_no': 18, 'char_start': 583, 'char_end': 625, 'line': "" args = {'scene': scene, 'date': date}\n""}, {'line_no': 19, 'char_start': 625, 'char_end': 654, 'line': ' res = db.exec(sql, args)\n'}, {'line_no': 35, 'char_start': 1060, 'char_end': 1134, 'line': ' sql = ""SELECT * FROM ranks WHERE scene = \'{scene}\' and date=\'{date}\'""\n'}, {'line_no': 36, 'char_start': 1134, 'char_end': 1181, 'line': "" args = {'scene': scene, 'date': prev_date}\n""}, {'line_no': 37, 'char_start': 1181, 'char_end': 1210, 'line': ' res = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 352, 'char_end': 355, 'chars': '.fo'}, {'char_start': 356, 'char_end': 360, 'chars': 'mat('}, {'char_start': 365, 'char_end': 366, 'chars': ')'}, {'char_start': 544, 'char_end': 547, 'chars': '.fo'}, {'char_start': 548, 'char_end': 552, 'chars': 'mat('}, {'char_start': 563, 'char_end': 564, 'chars': ')'}, {'char_start': 1058, 'char_end': 1061, 'chars': '.fo'}, {'char_start': 1062, 'char_end': 1066, 'chars': 'mat('}, {'char_start': 1082, 'char_end': 1083, 'chars': ')'}], 'added': [{'char_start': 321, 'char_end': 326, 'chars': 'scene'}, {'char_start': 357, 'char_end': 366, 'chars': '\n '}, {'char_start': 367, 'char_end': 375, 'chars': ""rgs = {'""}, {'char_start': 380, 'char_end': 389, 'chars': ""': scene}""}, {'char_start': 415, 'char_end': 421, 'chars': ', args'}, {'char_start': 556, 'char_end': 561, 'chars': 'scene'}, {'char_start': 575, 'char_end': 579, 'chars': 'date'}, {'char_start': 582, 'char_end': 587, 'chars': '\n '}, {'char_start': 588, 'char_end': 604, 'chars': ""rgs = {'scene': ""}, {'char_start': 611, 'char_end': 612, 'chars': ""'""}, {'char_start': 616, 'char_end': 624, 'chars': ""': date}""}, {'char_start': 646, 'char_end': 652, 'chars': ', args'}, {'char_start': 1107, 'char_end': 1112, 'chars': 'scene'}, {'char_start': 1126, 'char_end': 1130, 'chars': 'date'}, {'char_start': 1133, 'char_end': 1138, 'chars': '\n '}, {'char_start': 1139, 'char_end': 1155, 'chars': ""rgs = {'scene': ""}, {'char_start': 1162, 'char_end': 1170, 'chars': ""'date': ""}, {'char_start': 1179, 'char_end': 1180, 'chars': '}'}, {'char_start': 1202, 'char_end': 1208, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,endpoints.py,cwe-089,387 cwe-078,_get_iscsi_ip_addrs," def _get_iscsi_ip_addrs(self): generator = self._port_conf_generator('svcinfo lsportip') header = next(generator, None) if not header: return for port_data in generator: try: port_node_id = port_data['node_id'] port_ipv4 = port_data['IP_address'] port_ipv6 = port_data['IP_address_6'] state = port_data['state'] except KeyError: self._handle_keyerror('lsportip', header) if port_node_id in self._storage_nodes and ( state == 'configured' or state == 'online'): node = self._storage_nodes[port_node_id] if len(port_ipv4): node['ipv4'].append(port_ipv4) if len(port_ipv6): node['ipv6'].append(port_ipv6)"," def _get_iscsi_ip_addrs(self): generator = self._port_conf_generator(['svcinfo', 'lsportip']) header = next(generator, None) if not header: return for port_data in generator: try: port_node_id = port_data['node_id'] port_ipv4 = port_data['IP_address'] port_ipv6 = port_data['IP_address_6'] state = port_data['state'] except KeyError: self._handle_keyerror('lsportip', header) if port_node_id in self._storage_nodes and ( state == 'configured' or state == 'online'): node = self._storage_nodes[port_node_id] if len(port_ipv4): node['ipv4'].append(port_ipv4) if len(port_ipv6): node['ipv6'].append(port_ipv6)","{'deleted': [{'line_no': 2, 'char_start': 35, 'char_end': 101, 'line': "" generator = self._port_conf_generator('svcinfo lsportip')\n""}], 'added': [{'line_no': 2, 'char_start': 35, 'char_end': 106, 'line': "" generator = self._port_conf_generator(['svcinfo', 'lsportip'])\n""}]}","{'deleted': [], 'added': [{'char_start': 81, 'char_end': 82, 'chars': '['}, {'char_start': 90, 'char_end': 92, 'chars': ""',""}, {'char_start': 93, 'char_end': 94, 'chars': ""'""}, {'char_start': 103, 'char_end': 104, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,184 cwe-125,HPHP::string_rfind,"int string_rfind(const char *input, int len, const char *s, int s_len, int pos, bool case_sensitive) { assertx(input); assertx(s); if (!s_len || pos < -len || pos > len) { return -1; } void *ptr; if (case_sensitive) { if (pos >= 0) { ptr = bstrrstr(input + pos, len - pos, s, s_len); } else { ptr = bstrrstr(input, len + pos + s_len, s, s_len); } } else { if (pos >= 0) { ptr = bstrrcasestr(input + pos, len - pos, s, s_len); } else { ptr = bstrrcasestr(input, len + pos + s_len, s, s_len); } } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; }","int string_rfind(const char *input, int len, const char *s, int s_len, int pos, bool case_sensitive) { assertx(input); assertx(s); if (!s_len || pos < -len || pos > len) { return -1; } void *ptr; if (case_sensitive) { if (pos >= 0) { ptr = bstrrstr(input + pos, len - pos, s, s_len); } else { ptr = bstrrstr(input, len + std::min(pos + s_len, 0), s, s_len); } } else { if (pos >= 0) { ptr = bstrrcasestr(input + pos, len - pos, s, s_len); } else { ptr = bstrrcasestr(input, len + std::min(pos + s_len, 0), s, s_len); } } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; }","{'deleted': [{'line_no': 13, 'char_start': 340, 'char_end': 398, 'line': ' ptr = bstrrstr(input, len + pos + s_len, s, s_len);\n'}, {'line_no': 19, 'char_start': 508, 'char_end': 570, 'line': ' ptr = bstrrcasestr(input, len + pos + s_len, s, s_len);\n'}], 'added': [{'line_no': 13, 'char_start': 340, 'char_end': 411, 'line': ' ptr = bstrrstr(input, len + std::min(pos + s_len, 0), s, s_len);\n'}, {'line_no': 19, 'char_start': 521, 'char_end': 596, 'line': ' ptr = bstrrcasestr(input, len + std::min(pos + s_len, 0), s, s_len);\n'}]}","{'deleted': [], 'added': [{'char_start': 374, 'char_end': 383, 'chars': 'std::min('}, {'char_start': 394, 'char_end': 398, 'chars': ', 0)'}, {'char_start': 559, 'char_end': 568, 'chars': 'std::min('}, {'char_start': 579, 'char_end': 583, 'chars': ', 0)'}]}",github.com/facebook/hhvm/commit/46003b4ab564b2abcd8470035fc324fe36aa8c75,hphp/runtime/base/zend-string.cpp,cwe-125,223