submit.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. # reportbug_submit module - email and GnuPG functions
  2. # Written by Chris Lawrence <lawrencc@debian.org>
  3. # Copyright (C) 1999-2006 Chris Lawrence
  4. # Copyright (C) 2008-2016 Sandro Tosi <morph@debian.org>
  5. #
  6. # This program is freely distributable per the following license:
  7. #
  8. # Permission to use, copy, modify, and distribute this software and its
  9. # documentation for any purpose and without fee is hereby granted,
  10. # provided that the above copyright notice appears in all copies and that
  11. # both that copyright notice and this permission notice appear in
  12. # supporting documentation.
  13. #
  14. # I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
  15. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL I
  16. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  17. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  18. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
  19. # ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  20. # SOFTWARE.
  21. import sys
  22. import os
  23. import re
  24. import commands
  25. from subprocess import Popen, STDOUT, PIPE
  26. import rfc822
  27. import smtplib
  28. import socket
  29. import email
  30. from email.MIMEMultipart import MIMEMultipart
  31. from email.MIMEText import MIMEText
  32. from email.MIMEAudio import MIMEAudio
  33. from email.MIMEImage import MIMEImage
  34. from email.MIMEBase import MIMEBase
  35. from email.MIMEMessage import MIMEMessage
  36. from email.Header import Header, decode_header
  37. import mimetypes
  38. from __init__ import VERSION, VERSION_NUMBER
  39. from tempfiles import TempFile, open_write_safe, tempfile_prefix
  40. from exceptions import (
  41. NoMessage,
  42. )
  43. import ui.text_ui as ui
  44. from utils import get_email_addr
  45. import errno
  46. quietly = False
  47. ascii_range = ''.join([chr(ai) for ai in range(32, 127)])
  48. notascii = re.compile(r'[^' + re.escape(ascii_range) + ']')
  49. notascii2 = re.compile(r'[^' + re.escape(ascii_range) + r'\s]')
  50. # Wrapper for MIMEText
  51. class BetterMIMEText(MIMEText):
  52. def __init__(self, _text, _subtype='plain', _charset=None):
  53. MIMEText.__init__(self, _text, _subtype, 'us-ascii')
  54. # Only set the charset paraemeter to non-ASCII if the body
  55. # includes unprintable characters
  56. if notascii2.search(_text):
  57. self.set_param('charset', _charset)
  58. def encode_if_needed(text, charset, encoding='q'):
  59. needed = False
  60. if notascii.search(text):
  61. # Fall back on something vaguely sensible if there are high chars
  62. # and the encoding is us-ascii
  63. if charset == 'us-ascii':
  64. charset = 'iso-8859-15'
  65. return Header(text, charset)
  66. else:
  67. return Header(text, 'us-ascii')
  68. def rfc2047_encode_address(addr, charset, mua=None):
  69. newlist = []
  70. addresses = rfc822.AddressList(addr).addresslist
  71. for (realname, address) in addresses:
  72. if realname:
  73. newlist.append(email.Utils.formataddr(
  74. (str(rfc2047_encode_header(realname, charset, mua)), address)))
  75. else:
  76. newlist.append(address)
  77. return ', '.join(newlist)
  78. def rfc2047_encode_header(header, charset, mua=None):
  79. if mua:
  80. return header
  81. # print repr(header), repr(charset)
  82. return encode_if_needed(header, charset)
  83. def decode_email_header(header):
  84. # returns a list of 2-items tuples
  85. decoded = decode_header(header)
  86. return ' '.join([x[0] for x in decoded]).strip()
  87. # Cheat for now.
  88. # ewrite() may put stuff on the status bar or in message boxes depending on UI
  89. def ewrite(*args):
  90. return quietly or ui.log_message(*args)
  91. def sign_message(body, fromaddr, package='x', pgp_addr=None, sign='gpg', draftpath=None):
  92. '''Sign message with pgp key.'''
  93. ''' Return: a signed body.
  94. On failure, return None.
  95. kw need to have the following keys
  96. '''
  97. if not pgp_addr:
  98. pgp_addr = get_email_addr(fromaddr)[1]
  99. # Make the unsigned file first
  100. (unsigned, file1) = TempFile(prefix=tempfile_prefix(package, 'unsigned'), dir=draftpath)
  101. unsigned.write(body)
  102. unsigned.close()
  103. # Now make the signed file
  104. (signed, file2) = TempFile(prefix=tempfile_prefix(package, 'signed'), dir=draftpath)
  105. signed.close()
  106. if sign == 'gpg':
  107. os.unlink(file2)
  108. if 'GPG_AGENT_INFO' not in os.environ:
  109. signcmd = "gpg --local-user '%s' --clearsign " % pgp_addr
  110. else:
  111. signcmd = "gpg --local-user '%s' --use-agent --clearsign " % pgp_addr
  112. signcmd += '--output ' + commands.mkarg(file2) + ' ' + commands.mkarg(file1)
  113. else:
  114. signcmd = "pgp -u '%s' -fast" % pgp_addr
  115. signcmd += '<' + commands.mkarg(file1) + ' >' + commands.mkarg(file2)
  116. try:
  117. os.system(signcmd)
  118. x = file(file2, 'r')
  119. signedbody = x.read()
  120. x.close()
  121. if os.path.exists(file1):
  122. os.unlink(file1)
  123. if os.path.exists(file2):
  124. os.unlink(file2)
  125. if not signedbody:
  126. raise NoMessage
  127. body = signedbody
  128. except (NoMessage, IOError, OSError):
  129. fh, tmpfile2 = TempFile(prefix=tempfile_prefix(package), dir=draftpath)
  130. fh.write(body)
  131. fh.close()
  132. ewrite('gpg/pgp failed; input file in %s\n', tmpfile2)
  133. body = None
  134. return body
  135. def mime_attach(body, attachments, charset, body_charset=None):
  136. mimetypes.init()
  137. message = MIMEMultipart('mixed')
  138. bodypart = BetterMIMEText(body, _charset=(body_charset or charset))
  139. bodypart.add_header('Content-Disposition', 'inline')
  140. message.preamble = 'This is a multi-part MIME message sent by reportbug.\n\n'
  141. message.epilogue = ''
  142. message.attach(bodypart)
  143. failed = False
  144. for attachment in attachments:
  145. try:
  146. fp = file(attachment)
  147. fp.close()
  148. except EnvironmentError, x:
  149. ewrite("Warning: opening '%s' failed: %s.\n", attachment,
  150. x.strerror)
  151. failed = True
  152. continue
  153. ctype = None
  154. cset = charset
  155. info = Popen(['file', '--mime', '--brief', attachment],
  156. stdout=PIPE, stderr=STDOUT).communicate()[0]
  157. if info:
  158. match = re.match(r'([^;, ]*)(,[^;]+)?(?:; )?(.*)', info)
  159. if match:
  160. ctype, junk, extras = match.groups()
  161. match = re.search(r'charset=([^,]+|"[^,"]+")', extras)
  162. if match:
  163. cset = match.group(1)
  164. # If we didn't get a real MIME type, fall back
  165. if '/' not in ctype:
  166. ctype = None
  167. # If file doesn't work, try to guess based on the extension
  168. if not ctype:
  169. ctype, encoding = mimetypes.guess_type(
  170. attachment, strict=False)
  171. if not ctype:
  172. ctype = 'application/octet-stream'
  173. maintype, subtype = ctype.split('/', 1)
  174. if maintype == 'text':
  175. fp = file(attachment, 'rU')
  176. part = BetterMIMEText(fp.read(), _subtype=subtype,
  177. _charset=cset)
  178. fp.close()
  179. elif maintype == 'message':
  180. fp = file(attachment, 'rb')
  181. part = MIMEMessage(email.message_from_file(fp),
  182. _subtype=subtype)
  183. fp.close()
  184. elif maintype == 'image':
  185. fp = file(attachment, 'rb')
  186. part = MIMEImage(fp.read(), _subtype=subtype)
  187. fp.close()
  188. elif maintype == 'audio':
  189. fp = file(attachment, 'rb')
  190. part = MIMEAudio(fp.read(), _subtype=subtype)
  191. fp.close()
  192. else:
  193. fp = file(attachment, 'rb')
  194. part = MIMEBase(maintype, subtype)
  195. part.set_payload(fp.read())
  196. fp.close()
  197. email.Encoders.encode_base64(part)
  198. part.add_header('Content-Disposition', 'attachment',
  199. filename=os.path.basename(attachment))
  200. message.attach(part)
  201. return (message, failed)
  202. def send_report(body, attachments, mua, fromaddr, sendto, ccaddr, bccaddr,
  203. headers, package='x', charset="us-ascii", mailing=True,
  204. sysinfo=None,
  205. rtype='debbugs', exinfo=None, replyto=None, printonly=False,
  206. template=False, outfile=None, mta='', kudos=False,
  207. smtptls=False, smtphost='localhost',
  208. smtpuser=None, smtppasswd=None, paranoid=False, draftpath=None,
  209. envelopefrom=None):
  210. '''Send a report.'''
  211. failed = using_sendmail = False
  212. msgname = ''
  213. # Disable smtphost if mua is set
  214. if mua and smtphost:
  215. smtphost = ''
  216. # No, I'm not going to do a full MX lookup on every address... get a
  217. # real MTA!
  218. if kudos and smtphost == 'reportbug.debian.org':
  219. smtphost = 'packages.debian.org'
  220. body_charset = charset
  221. if isinstance(body, unicode):
  222. # Since the body is Unicode, utf-8 seems like a sensible body encoding
  223. # to choose pretty much all the time.
  224. body = body.encode('utf-8', 'replace')
  225. body_charset = 'utf-8'
  226. tfprefix = tempfile_prefix(package)
  227. if attachments and not mua:
  228. (message, failed) = mime_attach(body, attachments, charset, body_charset)
  229. if failed:
  230. ewrite("Error: Message creation failed, not sending\n")
  231. mua = mta = smtphost = None
  232. else:
  233. message = BetterMIMEText(body, _charset=body_charset)
  234. # Standard headers
  235. message['From'] = rfc2047_encode_address(fromaddr, 'utf-8', mua)
  236. message['To'] = rfc2047_encode_address(sendto, charset, mua)
  237. for (header, value) in headers:
  238. if header in ['From', 'To', 'Cc', 'Bcc', 'X-Debbugs-CC', 'Reply-To',
  239. 'Mail-Followup-To']:
  240. message[header] = rfc2047_encode_address(value, charset, mua)
  241. else:
  242. message[header] = rfc2047_encode_header(value, charset, mua)
  243. if ccaddr:
  244. message['Cc'] = rfc2047_encode_address(ccaddr, charset, mua)
  245. if bccaddr:
  246. message['Bcc'] = rfc2047_encode_address(bccaddr, charset, mua)
  247. replyto = os.environ.get("REPLYTO", replyto)
  248. if replyto:
  249. message['Reply-To'] = rfc2047_encode_address(replyto, charset, mua)
  250. if mailing:
  251. message['Message-ID'] = email.Utils.make_msgid('reportbug')
  252. message['X-Mailer'] = VERSION
  253. message['Date'] = email.Utils.formatdate(localtime=True)
  254. elif mua and not (printonly or template):
  255. message['X-Reportbug-Version'] = VERSION_NUMBER
  256. addrs = [str(x) for x in (message.get_all('To', []) +
  257. message.get_all('Cc', []) +
  258. message.get_all('Bcc', []))]
  259. alist = email.Utils.getaddresses(addrs)
  260. cclist = [str(x) for x in message.get_all('X-Debbugs-Cc', [])]
  261. debbugs_cc = email.Utils.getaddresses(cclist)
  262. if cclist:
  263. del message['X-Debbugs-Cc']
  264. addrlist = ', '.join(cclist)
  265. message['X-Debbugs-Cc'] = rfc2047_encode_address(addrlist, charset, mua)
  266. # Drop any Bcc headers from the message to be sent
  267. if not outfile and not mua:
  268. try:
  269. del message['Bcc']
  270. except:
  271. pass
  272. message = message.as_string()
  273. if paranoid and not (template or printonly):
  274. pager = os.environ.get('PAGER', 'sensible-pager')
  275. try:
  276. os.popen(pager, 'w').write(message)
  277. except Exception, e:
  278. # if the PAGER exits before all the text has been sent,
  279. # it'd send a SIGPIPE, so crash only if that's not the case
  280. if e.errno != errno.EPIPE:
  281. raise e
  282. if not ui.yes_no('Does your report seem satisfactory', 'Yes, send it.',
  283. 'No, don\'t send it.'):
  284. smtphost = mta = None
  285. filename = None
  286. if template or printonly:
  287. pipe = sys.stdout
  288. elif mua:
  289. pipe, filename = TempFile(prefix=tfprefix, dir=draftpath)
  290. elif outfile or not ((mta and os.path.exists(mta)) and not smtphost):
  291. # outfile can be None at this point
  292. if outfile:
  293. msgname = os.path.expanduser(outfile)
  294. else:
  295. msgname = '/var/tmp/%s.bug' % package
  296. if os.path.exists(msgname):
  297. try:
  298. os.rename(msgname, msgname + '~')
  299. except OSError:
  300. ewrite('Unable to rename existing %s as %s~\n',
  301. msgname, msgname)
  302. try:
  303. pipe = open_write_safe(msgname, 'w')
  304. except OSError:
  305. # we can't write to the selected file, use a temp file instead
  306. fh, newmsgname = TempFile(prefix=tfprefix, dir=draftpath)
  307. ewrite('Writing to %s failed; '
  308. 'using instead %s\n', msgname, newmsgname)
  309. msgname = newmsgname
  310. # we just need a place where to write() and a file handler
  311. # is here just for that
  312. pipe = fh
  313. elif (mta and os.path.exists(mta)) and not smtphost:
  314. try:
  315. x = os.getcwd()
  316. except OSError:
  317. os.chdir('/')
  318. malist = [commands.mkarg(a[1]) for a in alist]
  319. jalist = ' '.join(malist)
  320. faddr = rfc822.parseaddr(fromaddr)[1]
  321. if envelopefrom:
  322. envfrom = rfc822.parseaddr(envelopefrom)[1]
  323. else:
  324. envfrom = faddr
  325. ewrite("Sending message via %s...\n", mta)
  326. pipe = os.popen('%s -f %s -oi -oem %s' % (
  327. mta, commands.mkarg(envfrom), jalist), 'w')
  328. using_sendmail = True
  329. # saving a backup of the report
  330. backupfh, backupname = TempFile(prefix=tempfile_prefix(package, 'backup'), dir=draftpath)
  331. ewrite('Saving a backup of the report at %s\n', backupname)
  332. backupfh.write(message)
  333. backupfh.close()
  334. if smtphost:
  335. toaddrs = [x[1] for x in alist]
  336. tryagain = True
  337. refused = None
  338. retry = 0
  339. while tryagain:
  340. tryagain = False
  341. ewrite("Connecting to %s via SMTP...\n", smtphost)
  342. try:
  343. conn = None
  344. # if we're using reportbug.debian.org, send mail to
  345. # submit
  346. if smtphost.lower() == 'reportbug.debian.org':
  347. conn = smtplib.SMTP(smtphost, 587)
  348. else:
  349. conn = smtplib.SMTP(smtphost)
  350. response = conn.ehlo()
  351. if not (200 <= response[0] <= 299):
  352. conn.helo()
  353. if smtptls:
  354. conn.starttls()
  355. response = conn.ehlo()
  356. if not (200 <= response[0] <= 299):
  357. conn.helo()
  358. if smtpuser:
  359. if not smtppasswd:
  360. smtppasswd = ui.get_password(
  361. 'Enter SMTP password for %s@%s: ' %
  362. (smtpuser, smtphost))
  363. conn.login(smtpuser, smtppasswd)
  364. refused = conn.sendmail(fromaddr, toaddrs, message)
  365. conn.quit()
  366. except (socket.error, smtplib.SMTPException), x:
  367. # If wrong password, try again...
  368. if isinstance(x, smtplib.SMTPAuthenticationError):
  369. ewrite('SMTP error: authentication failed. Try again.\n')
  370. tryagain = True
  371. smtppasswd = None
  372. retry += 1
  373. if retry <= 2:
  374. continue
  375. else:
  376. tryagain = False
  377. # In case of failure, ask to retry or to save & exit
  378. if ui.yes_no('SMTP send failure: %s. Do you want to retry (or else save the report and exit)?' % x,
  379. 'Yes, please retry.',
  380. 'No, save and exit.'):
  381. tryagain = True
  382. continue
  383. else:
  384. failed = True
  385. fh, msgname = TempFile(prefix=tfprefix, dir=draftpath)
  386. fh.write(message)
  387. fh.close()
  388. ewrite('Wrote bug report to %s\n', msgname)
  389. # Handle when some recipients are refused.
  390. if refused:
  391. for (addr, err) in refused.iteritems():
  392. ewrite('Unable to send report to %s: %d %s\n', addr, err[0],
  393. err[1])
  394. fh, msgname = TempFile(prefix=tfprefix, dir=draftpath)
  395. fh.write(message)
  396. fh.close()
  397. ewrite('Wrote bug report to %s\n', msgname)
  398. else:
  399. try:
  400. pipe.write(message)
  401. pipe.flush()
  402. if msgname:
  403. ewrite("Bug report written as %s\n", msgname)
  404. except IOError:
  405. failed = True
  406. pipe.close()
  407. if failed or (pipe.close() and using_sendmail):
  408. failed = True
  409. fh, msgname = TempFile(prefix=tfprefix, dir=draftpath)
  410. fh.write(message)
  411. fh.close()
  412. ui.long_message('Error: send/write operation failed, bug report '
  413. 'saved to %s\n', msgname)
  414. if mua:
  415. ewrite("Spawning %s...\n", mua.name)
  416. returnvalue = 0
  417. succeeded = False
  418. while not succeeded:
  419. returnvalue = mua.send(filename)
  420. if returnvalue != 0:
  421. ewrite("Mutt users should be aware it is mandatory to edit the draft before sending.\n")
  422. mtitle = 'Report has not been sent yet; what do you want to do now?'
  423. mopts = 'Eq'
  424. moptsdesc = {'e': 'Edit the message.',
  425. 'q': 'Quit reportbug; will save the draft for future use.'}
  426. x = ui.select_options(mtitle, mopts, moptsdesc)
  427. if x == 'q':
  428. failed = True
  429. fh, msgname = TempFile(prefix=tfprefix, dir=draftpath)
  430. fh.write(message)
  431. fh.close()
  432. ewrite('Draft saved into %s\n', msgname)
  433. succeeded = True
  434. else:
  435. succeeded = True
  436. elif not failed and (using_sendmail or smtphost):
  437. if kudos:
  438. ewrite('\nMessage sent to: %s\n', sendto)
  439. else:
  440. ewrite("\nBug report submitted to: %s\n", sendto)
  441. addresses = []
  442. for addr in alist:
  443. if addr[1] != rfc822.parseaddr(sendto)[1]:
  444. addresses.append(addr)
  445. if len(addresses):
  446. ewrite("Copies sent to:\n")
  447. for address in addrs:
  448. ewrite(' %s\n', decode_email_header(address))
  449. if debbugs_cc and rtype == 'debbugs':
  450. ewrite("Copies will be sent after processing to:\n")
  451. for address in cclist:
  452. ewrite(' %s\n', decode_email_header(address))
  453. if not (exinfo or kudos) and rtype == 'debbugs' and sysinfo and 'email' in sysinfo and not failed \
  454. and mailing:
  455. ewrite('\n')
  456. ui.final_message(
  457. """If you want to provide additional information, please wait to
  458. receive the bug tracking number via email; you may then send any extra
  459. information to %s (e.g. %s), where n is the bug number. Normally you
  460. will receive an acknowledgement via email including the bug report number
  461. within an hour; if you haven't received a confirmation, then the bug reporting process failed at some point (reportbug or MTA failure, BTS maintenance, etc.).\n""",
  462. (sysinfo['email'] % 'n'), (sysinfo['email'] % '999999'))
  463. # If we've stored more than one copy of the message, delete the
  464. # one without the SMTP headers.
  465. if filename and os.path.exists(msgname) and os.path.exists(filename):
  466. try:
  467. os.unlink(filename)
  468. except:
  469. pass
  470. if filename and os.path.exists(filename) and not mua:
  471. # Message is misleading if an MUA is used.
  472. ewrite("A copy of the report is stored as: %s\n" % filename)
  473. return