comment_email_milter.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Milter calls methods of your class at milter events.
  4. # Return REJECT,TEMPFAIL,ACCEPT to short circuit processing for a message.
  5. # You can also add/del recipients, replacebody, add/del headers, etc.
  6. from __future__ import print_function, unicode_literals
  7. import base64
  8. import email
  9. import hashlib
  10. import os
  11. import sys
  12. import time
  13. from io import BytesIO
  14. from multiprocessing import Process as Thread, Queue
  15. import Milter
  16. import requests
  17. from Milter.utils import parse_addr
  18. import pagure.config
  19. import pagure.lib
  20. if 'PAGURE_CONFIG' not in os.environ \
  21. and os.path.exists('/etc/pagure/pagure.cfg'):
  22. os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg'
  23. logq = Queue(maxsize=4)
  24. _config = pagure.config.reload_config()
  25. def get_email_body(emailobj):
  26. ''' Return the body of the email, preferably in text.
  27. '''
  28. def _get_body(emailobj):
  29. """ Return the first text/plain body found if the email is multipart
  30. or just the regular payload otherwise.
  31. """
  32. if emailobj.is_multipart():
  33. for payload in emailobj.get_payload():
  34. # If the message comes with a signature it can be that this
  35. # payload itself has multiple parts, so just return the
  36. # first one
  37. if payload.is_multipart():
  38. return _get_body(payload)
  39. body = payload.get_payload()
  40. if payload.get_content_type() == 'text/plain':
  41. return body
  42. else:
  43. return emailobj.get_payload()
  44. body = _get_body(emailobj)
  45. enc = emailobj['Content-Transfer-Encoding']
  46. if enc == 'base64':
  47. body = base64.decodestring(body)
  48. return body
  49. def clean_item(item):
  50. ''' For an item provided as <item> return the content, if there are no
  51. <> then return the string.
  52. '''
  53. if '<' in item:
  54. item = item.split('<')[1]
  55. if '>' in item:
  56. item = item.split('>')[0]
  57. return item
  58. class PagureMilter(Milter.Base):
  59. def __init__(self): # A new instance with each new connection.
  60. self.id = Milter.uniqueID() # Integer incremented with each call.
  61. self.fp = None
  62. def log(self, message):
  63. print(message)
  64. sys.stdout.flush()
  65. def envfrom(self, mailfrom, *str):
  66. self.log("mail from: %s - %s" % (mailfrom, str))
  67. self.fromparms = Milter.dictfromlist(str)
  68. # NOTE: self.fp is only an *internal* copy of message data. You
  69. # must use addheader, chgheader, replacebody to change the message
  70. # on the MTA.
  71. self.fp = BytesIO()
  72. self.canon_from = '@'.join(parse_addr(mailfrom))
  73. from_txt = 'From %s %s\n' % (self.canon_from, time.ctime())
  74. self.fp.write(from_txt.encode('utf-8'))
  75. return Milter.CONTINUE
  76. @Milter.noreply
  77. def header(self, name, hval):
  78. ''' Headers '''
  79. # add header to buffer
  80. header_txt = "%s: %s\n" % (name, hval)
  81. self.fp.write(header_txt.encode('utf-8'))
  82. return Milter.CONTINUE
  83. @Milter.noreply
  84. def eoh(self):
  85. ''' End of Headers '''
  86. self.fp.write(b"\n")
  87. return Milter.CONTINUE
  88. @Milter.noreply
  89. def body(self, chunk):
  90. ''' Body '''
  91. self.fp.write(chunk)
  92. return Milter.CONTINUE
  93. @Milter.noreply
  94. def envrcpt(self, to, *str):
  95. rcptinfo = to, Milter.dictfromlist(str)
  96. print(rcptinfo)
  97. return Milter.CONTINUE
  98. def eom(self):
  99. ''' End of Message '''
  100. self.fp.seek(0)
  101. msg = email.message_from_file(self.fp)
  102. msg_id = msg.get('In-Reply-To', None)
  103. if msg_id is None:
  104. self.log('No In-Reply-To, keep going')
  105. return Milter.CONTINUE
  106. # Ensure we don't get extra lines in the message-id
  107. msg_id = msg_id.split('\n')[0].strip()
  108. self.log('msg-ig %s' % msg_id)
  109. self.log('To %s' % msg['to'])
  110. self.log('Cc %s' % msg.get('cc'))
  111. self.log('From %s' % msg['From'])
  112. # Check the email was sent to the right address
  113. email_address = msg['to']
  114. if 'reply+' in msg.get('cc', ''):
  115. email_address = msg['cc']
  116. if 'reply+' not in email_address:
  117. self.log(
  118. 'No valid recipient email found in To/Cc: %s'
  119. % email_address)
  120. return Milter.CONTINUE
  121. # Ensure the user replied to his/her own notification, not that
  122. # they are trying to forge their ID into someone else's
  123. salt = _config.get('SALT_EMAIL')
  124. from_email = clean_item(msg['From'])
  125. session = pagure.lib.create_session(_config['DB_URL'])
  126. try:
  127. user = pagure.lib.get_user(session, from_email)
  128. except:
  129. self.log(
  130. "Could not find an user in the DB associated with %s" %
  131. from_email)
  132. session.remove()
  133. return Milter.CONTINUE
  134. hashes = []
  135. for email_obj in user.emails:
  136. m = hashlib.sha512('%s%s%s' % (msg_id, salt, email_obj.email))
  137. hashes.append(m.hexdigest())
  138. tohash = email_address.split('@')[0].split('+')[-1]
  139. if tohash not in hashes:
  140. self.log('hash list: %s' % hashes)
  141. self.log('tohash: %s' % tohash)
  142. self.log('Hash does not correspond to the destination')
  143. session.remove()
  144. return Milter.CONTINUE
  145. if msg['From'] and msg['From'] == _config.get('FROM_EMAIL'):
  146. self.log("Let's not process the email we send")
  147. session.remove()
  148. return Milter.CONTINUE
  149. msg_id = clean_item(msg_id)
  150. if msg_id and '-ticket-' in msg_id:
  151. self.log('Processing issue')
  152. session.remove()
  153. return self.handle_ticket_email(msg, msg_id)
  154. elif msg_id and '-pull-request-' in msg_id:
  155. self.log('Processing pull-request')
  156. session.remove()
  157. return self.handle_request_email(msg, msg_id)
  158. else:
  159. self.log('Not a pagure ticket or pull-request email, let it go')
  160. session.remove()
  161. return Milter.CONTINUE
  162. def handle_ticket_email(self, emailobj, msg_id):
  163. ''' Add the email as a comment on a ticket. '''
  164. uid = msg_id.split('-ticket-')[-1].split('@')[0]
  165. parent_id = None
  166. if '-' in uid:
  167. uid, parent_id = uid.rsplit('-', 1)
  168. if '/' in uid:
  169. uid = uid.split('/')[0]
  170. self.log('uid %s' % uid)
  171. self.log('parent_id %s' % parent_id)
  172. data = {
  173. 'objid': uid,
  174. 'comment': get_email_body(emailobj),
  175. 'useremail': clean_item(emailobj['From']),
  176. }
  177. url = _config.get('APP_URL')
  178. if url.endswith('/'):
  179. url = url[:-1]
  180. url = '%s/pv/ticket/comment/' % url
  181. self.log('Calling URL: %s' % url)
  182. req = requests.put(url, data=data)
  183. if req.status_code == 200:
  184. self.log('Comment added')
  185. return Milter.ACCEPT
  186. self.log('Could not add the comment to ticket to pagure')
  187. self.log(req.text)
  188. return Milter.CONTINUE
  189. def handle_request_email(self, emailobj, msg_id):
  190. ''' Add the email as a comment on a request. '''
  191. uid = msg_id.split('-pull-request-')[-1].split('@')[0]
  192. parent_id = None
  193. if '-' in uid:
  194. uid, parent_id = uid.rsplit('-', 1)
  195. if '/' in uid:
  196. uid = uid.split('/')[0]
  197. self.log('uid %s' % uid)
  198. self.log('parent_id %s' % parent_id)
  199. data = {
  200. 'objid': uid,
  201. 'comment': get_email_body(emailobj),
  202. 'useremail': clean_item(emailobj['From']),
  203. }
  204. url = _config.get('APP_URL')
  205. if url.endswith('/'):
  206. url = url[:-1]
  207. url = '%s/pv/pull-request/comment/' % url
  208. self.log('Calling URL: %s' % url)
  209. req = requests.put(url, data=data)
  210. if req.status_code == 200:
  211. self.log('Comment added on PR')
  212. return Milter.ACCEPT
  213. self.log('Could not add the comment to PR to pagure')
  214. self.log(req.text)
  215. return Milter.CONTINUE
  216. def background():
  217. while True:
  218. t = logq.get()
  219. if not t:
  220. break
  221. msg, id, ts = t
  222. print("%s [%d]" % (time.strftime(
  223. '%Y%b%d %H:%M:%S', time.localtime(ts)), id))
  224. # 2005Oct13 02:34:11 [1] msg1 msg2 msg3 ...
  225. for i in msg:
  226. print(i,)
  227. print
  228. def main():
  229. bt = Thread(target=background)
  230. bt.start()
  231. socketname = "/var/run/pagure/paguresock"
  232. timeout = 600
  233. # Register to have the Milter factory create instances of your class:
  234. Milter.factory = PagureMilter
  235. print("%s pagure milter startup" % time.strftime('%Y%b%d %H:%M:%S'))
  236. sys.stdout.flush()
  237. Milter.runmilter("paguremilter", socketname, timeout)
  238. logq.put(None)
  239. bt.join()
  240. print("%s pagure milter shutdown" % time.strftime('%Y%b%d %H:%M:%S'))
  241. if __name__ == "__main__":
  242. main()