comment_email_milter.py 9.0 KB

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