deanonymind.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/env python
  2. import optparse
  3. import os
  4. import sys
  5. import zipfile
  6. """
  7. Take a MaxMind GeoLite Country database as input and replace A1 entries
  8. with the country code and name of the preceding entry iff the preceding
  9. (subsequent) entry ends (starts) directly before (after) the A1 entry and
  10. both preceding and subsequent entries contain the same country code.
  11. Then apply manual changes, either replacing A1 entries that could not be
  12. replaced automatically or overriding previously made automatic changes.
  13. """
  14. def main():
  15. options = parse_options()
  16. assignments = read_file(options.in_maxmind)
  17. assignments = apply_automatic_changes(assignments)
  18. write_file(options.out_automatic, assignments)
  19. manual_assignments = read_file(options.in_manual, must_exist=False)
  20. assignments = apply_manual_changes(assignments, manual_assignments)
  21. write_file(options.out_manual, assignments)
  22. write_file(options.out_geoip, assignments, long_format=False)
  23. def parse_options():
  24. parser = optparse.OptionParser()
  25. parser.add_option('-i', action='store', dest='in_maxmind',
  26. default='GeoIPCountryCSV.zip', metavar='FILE',
  27. help='use the specified MaxMind GeoLite Country .zip or .csv '
  28. 'file as input [default: %default]')
  29. parser.add_option('-g', action='store', dest='in_manual',
  30. default='geoip-manual', metavar='FILE',
  31. help='use the specified .csv file for manual changes or to '
  32. 'override automatic changes [default: %default]')
  33. parser.add_option('-a', action='store', dest='out_automatic',
  34. default="AutomaticGeoIPCountryWhois.csv", metavar='FILE',
  35. help='write full input file plus automatic changes to the '
  36. 'specified .csv file [default: %default]')
  37. parser.add_option('-m', action='store', dest='out_manual',
  38. default='ManualGeoIPCountryWhois.csv', metavar='FILE',
  39. help='write full input file plus automatic and manual '
  40. 'changes to the specified .csv file [default: %default]')
  41. parser.add_option('-o', action='store', dest='out_geoip',
  42. default='geoip', metavar='FILE',
  43. help='write full input file plus automatic and manual '
  44. 'changes to the specified .csv file that can be shipped '
  45. 'with tor [default: %default]')
  46. (options, args) = parser.parse_args()
  47. return options
  48. def read_file(path, must_exist=True):
  49. if not os.path.exists(path):
  50. if must_exist:
  51. print 'File %s does not exist. Exiting.' % (path, )
  52. sys.exit(1)
  53. else:
  54. return
  55. if path.endswith('.zip'):
  56. zip_file = zipfile.ZipFile(path)
  57. csv_content = zip_file.read('GeoIPCountryWhois.csv')
  58. zip_file.close()
  59. else:
  60. csv_file = open(path)
  61. csv_content = csv_file.read()
  62. csv_file.close()
  63. assignments = []
  64. for line in csv_content.split('\n'):
  65. stripped_line = line.strip()
  66. if len(stripped_line) > 0 and not stripped_line.startswith('#'):
  67. assignments.append(stripped_line)
  68. return assignments
  69. def apply_automatic_changes(assignments):
  70. print '\nApplying automatic changes...'
  71. result_lines = []
  72. prev_line = None
  73. a1_lines = []
  74. for line in assignments:
  75. if '"A1"' in line:
  76. a1_lines.append(line)
  77. else:
  78. if len(a1_lines) > 0:
  79. new_a1_lines = process_a1_lines(prev_line, a1_lines, line)
  80. for new_a1_line in new_a1_lines:
  81. result_lines.append(new_a1_line)
  82. a1_lines = []
  83. result_lines.append(line)
  84. prev_line = line
  85. if len(a1_lines) > 0:
  86. new_a1_lines = process_a1_lines(prev_line, a1_lines, None)
  87. for new_a1_line in new_a1_lines:
  88. result_lines.append(new_a1_line)
  89. return result_lines
  90. def process_a1_lines(prev_line, a1_lines, next_line):
  91. if not prev_line or not next_line:
  92. return a1_lines # Can't merge first or last line in file.
  93. if len(a1_lines) > 1:
  94. return a1_lines # Can't merge more than 1 line at once.
  95. a1_line = a1_lines[0].strip()
  96. prev_entry = parse_line(prev_line)
  97. a1_entry = parse_line(a1_line)
  98. next_entry = parse_line(next_line)
  99. touches_prev_entry = int(prev_entry['end_num']) + 1 == \
  100. int(a1_entry['start_num'])
  101. touches_next_entry = int(a1_entry['end_num']) + 1 == \
  102. int(next_entry['start_num'])
  103. same_country_code = prev_entry['country_code'] == \
  104. next_entry['country_code']
  105. if touches_prev_entry and touches_next_entry and same_country_code:
  106. new_line = format_line_with_other_country(a1_entry, prev_entry)
  107. print '-%s\n+%s' % (a1_line, new_line, )
  108. return [new_line]
  109. else:
  110. return a1_lines
  111. def parse_line(line):
  112. if not line:
  113. return None
  114. keys = ['start_str', 'end_str', 'start_num', 'end_num',
  115. 'country_code', 'country_name']
  116. stripped_line = line.replace('"', '').strip()
  117. parts = stripped_line.split(',')
  118. entry = dict((k, v) for k, v in zip(keys, parts))
  119. return entry
  120. def format_line_with_other_country(original_entry, other_entry):
  121. return '"%s","%s","%s","%s","%s","%s"' % (original_entry['start_str'],
  122. original_entry['end_str'], original_entry['start_num'],
  123. original_entry['end_num'], other_entry['country_code'],
  124. other_entry['country_name'], )
  125. def apply_manual_changes(assignments, manual_assignments):
  126. if not manual_assignments:
  127. return assignments
  128. print '\nApplying manual changes...'
  129. manual_dict = {}
  130. for line in manual_assignments:
  131. start_num = parse_line(line)['start_num']
  132. if start_num in manual_dict:
  133. print ('Warning: duplicate start number in manual '
  134. 'assignments:\n %s\n %s\nDiscarding first entry.' %
  135. (manual_dict[start_num], line, ))
  136. manual_dict[start_num] = line
  137. result = []
  138. for line in assignments:
  139. entry = parse_line(line)
  140. start_num = entry['start_num']
  141. if start_num in manual_dict:
  142. manual_line = manual_dict[start_num]
  143. manual_entry = parse_line(manual_line)
  144. if entry['start_str'] == manual_entry['start_str'] and \
  145. entry['end_str'] == manual_entry['end_str'] and \
  146. entry['end_num'] == manual_entry['end_num']:
  147. if len(manual_entry['country_code']) != 2:
  148. print '-%s' % (line, ) # only remove, don't replace
  149. else:
  150. new_line = format_line_with_other_country(entry,
  151. manual_entry)
  152. print '-%s\n+%s' % (line, new_line, )
  153. result.append(new_line)
  154. del manual_dict[start_num]
  155. else:
  156. print ('Warning: only partial match between '
  157. 'original/automatically replaced assignment and '
  158. 'manual assignment:\n %s\n %s\nNot applying '
  159. 'manual change.' % (line, manual_line, ))
  160. result.append(line)
  161. else:
  162. result.append(line)
  163. if len(manual_dict) > 0:
  164. print ('Warning: could not apply all manual assignments: %s' %
  165. ('\n '.join(manual_dict.values())), )
  166. return result
  167. def write_file(path, assignments, long_format=True):
  168. if long_format:
  169. output_lines = assignments
  170. else:
  171. output_lines = []
  172. for long_line in assignments:
  173. entry = parse_line(long_line)
  174. short_line = "%s,%s,%s" % (entry['start_num'],
  175. entry['end_num'], entry['country_code'], )
  176. output_lines.append(short_line)
  177. out_file = open(path, 'w')
  178. out_file.write('\n'.join(output_lines))
  179. out_file.close()
  180. if __name__ == '__main__':
  181. main()