otr.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. # -*- coding: utf-8 -*-
  2. # otr - WeeChat script for Off-the-Record IRC messaging
  3. #
  4. # DISCLAIMER: To the best of my knowledge this script securely provides OTR
  5. # messaging in WeeChat, but I offer no guarantee. Please report any security
  6. # holes you find.
  7. #
  8. # Copyright (c) 2012 Matthew M. Boedicker <matthewm@boedicker.org>
  9. # Nils Görs <weechatter@arcor.de>
  10. #
  11. # Report issues at https://github.com/mmb/weechat-otr
  12. #
  13. # This program is free software: you can redistribute it and/or modify
  14. # it under the terms of the GNU General Public License as published by
  15. # the Free Software Foundation, either version 3 of the License, or
  16. # (at your option) any later version.
  17. # This program is distributed in the hope that it will be useful,
  18. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. # GNU General Public License for more details.
  21. # You should have received a copy of the GNU General Public License
  22. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. from __future__ import unicode_literals
  24. import collections
  25. import cStringIO
  26. import os
  27. import re
  28. import traceback
  29. import weechat
  30. import potr
  31. SCRIPT_NAME = 'otr'
  32. SCRIPT_DESC = 'Off-the-Record messaging for IRC'
  33. SCRIPT_HELP = """%s
  34. Quick start:
  35. Add an OTR item to the status bar by adding '[otr]' to the config setting
  36. weechat.bar.status.items. This will show you whether your current conversation
  37. is encrypted, authenticated and logged. /set otr.* for OTR status bar
  38. customization options.
  39. Start a private conversation with a friend who has OTR: /query yourpeer hi
  40. In the private chat buffer: /otr start
  41. If you have not authenticated your peer yet, follow the instructions for
  42. authentication.
  43. View OTR policies for your peer: /otr policy
  44. To end your private conversation: /otr finish
  45. """ % SCRIPT_DESC
  46. SCRIPT_AUTHOR = 'Matthew M. Boedicker'
  47. SCRIPT_LICENCE = 'GPL3'
  48. SCRIPT_VERSION = '1.1.0'
  49. OTR_DIR_NAME = 'otr'
  50. OTR_QUERY_RE = re.compile('\?OTR(\?|\??v[a-z\d]*\?)$')
  51. POLICIES = {
  52. 'allow_v2' : 'allow OTR protocol version 2',
  53. 'require_encryption' : 'refuse to send unencrypted messages',
  54. 'send_tag' : 'advertise your OTR capability using the whitespace tag',
  55. }
  56. READ_ONLY_POLICIES = {
  57. 'allow_v1' : False,
  58. }
  59. IRC_PRIVMSG_RE = re.compile(r"""
  60. (
  61. :
  62. (?P<from>
  63. (?P<from_nick>.+?)
  64. !
  65. (?P<from_user>.+?)
  66. @
  67. (?P<from_host>.+?)
  68. )
  69. \ )?
  70. PRIVMSG
  71. \ (?P<to>.+?)
  72. \ :
  73. (?P<text>.+)
  74. """, re.VERBOSE)
  75. potr.proto.TaggedPlaintextOrig = potr.proto.TaggedPlaintext
  76. class WeechatTaggedPlaintext(potr.proto.TaggedPlaintextOrig):
  77. """Patch potr.proto.TaggedPlaintext to not end plaintext tags in a space.
  78. When POTR adds OTR tags to plaintext it puts them at the end of the message.
  79. The tags end in a space which gets stripped off by WeeChat because it
  80. strips trailing spaces from commands. This causes OTR initiation to fail so
  81. the following code adds an extra tab at the end of the plaintext tags if
  82. they end in a space.
  83. """
  84. def __bytes__(self):
  85. # old style because parent class is old style
  86. result = potr.proto.TaggedPlaintextOrig.__bytes__(self).decode('utf-8')
  87. if result.endswith(' '):
  88. result = '%s\t' % result
  89. return result.encode('utf-8')
  90. potr.proto.TaggedPlaintext = WeechatTaggedPlaintext
  91. def command(buf, command_str):
  92. """Wrap weechat.command() with utf-8 encode."""
  93. debug(command_str)
  94. weechat.command(buf, command_str.encode('utf-8'))
  95. def privmsg(server, nick, message):
  96. """Send a private message to a nick."""
  97. for line in message.split('\n'):
  98. command('', '/quote -server %s PRIVMSG %s :%s' % (server, nick, line))
  99. def build_privmsg_in(fromm, to, msg):
  100. """Build an inbound IRC PRIVMSG command."""
  101. return ':%s PRIVMSG %s :%s' % (fromm, to, msg)
  102. def prnt(buf, message):
  103. """Wrap weechat.prnt() with utf-8 encode."""
  104. weechat.prnt(buf, message.encode('utf-8'))
  105. def debug(msg):
  106. """Send a debug message to the WeeChat core buffer."""
  107. debug_option = weechat.config_get(config_prefix('general.debug'))
  108. if weechat.config_boolean(debug_option):
  109. prnt('', ('%s debug\t%s' % (SCRIPT_NAME, unicode(msg))))
  110. def current_user(server_name):
  111. """Get the nick and server of the current user on a server."""
  112. return irc_user(info_get('irc_nick', server_name), server_name)
  113. def irc_user(nick, server):
  114. """Build an IRC user string from a nick and server."""
  115. return '%s@%s' % (nick, server)
  116. def parse_irc_privmsg(message):
  117. """Parse an IRC PRIVMSG command and return a dictionary.
  118. Either the to_channel key or the to_nick key will be set depending on
  119. whether the message is to a nick or a channel. The other will be None.
  120. Example input:
  121. :nick!user@host PRIVMSG #weechat :message here
  122. Output:
  123. {'from': 'nick!user@host',
  124. 'from_nick': 'nick',
  125. 'from_user': 'user',
  126. 'from_host': 'host',
  127. 'to': '#weechat',
  128. 'to_channel': '#weechat',
  129. 'to_nick': None,
  130. 'text': 'message here'}
  131. """
  132. match = IRC_PRIVMSG_RE.match(message)
  133. if match:
  134. result = match.groupdict()
  135. if result['to'].startswith('#'):
  136. result['to_channel'] = result['to']
  137. result['to_nick'] = None
  138. else:
  139. result['to_channel'] = None
  140. result['to_nick'] = result['to']
  141. return result
  142. def has_otr_end(msg):
  143. """Return True if the message is the end of an OTR message."""
  144. return msg.endswith('.') or msg.endswith(',')
  145. def first_instance(objs, klass):
  146. """Return the first object in the list that is an instance of a class."""
  147. for obj in objs:
  148. if isinstance(obj, klass):
  149. return obj
  150. def config_prefix(option):
  151. """Add the config prefix to an option and return the full option name."""
  152. return '%s.%s' % (SCRIPT_NAME, option)
  153. def config_color(option):
  154. """Get the color of a color config option."""
  155. return weechat.color(weechat.config_color(weechat.config_get(
  156. config_prefix('color.%s' % option))))
  157. def config_string(option):
  158. """Get the string value of a config option with utf-8 decode."""
  159. return weechat.config_string(
  160. weechat.config_get(config_prefix(option))).decode('utf-8')
  161. def buffer_get_string(buf, prop):
  162. """Wrap weechat.buffer_get_string() with utf-8 encode/decode."""
  163. return weechat.buffer_get_string(buf, prop.encode('utf-8')).decode('utf-8')
  164. def buffer_is_private(buf):
  165. """Return True if a buffer is private."""
  166. return buffer_get_string(buf, 'localvar_type') == 'private'
  167. def info_get(info_name, arguments):
  168. """Wrap weechat.info_get() with utf-8 encode/decode."""
  169. return weechat.info_get(info_name, arguments.encode('utf-8')).decode(
  170. 'utf-8')
  171. def default_peer_args(args):
  172. """Get the nick and server of a remote peer from command arguments or
  173. the current buffer.
  174. Passed in args are the [nick, server] slice of arguments from a command.
  175. If these are present, return them. If args is empty and the current buffer
  176. is private, return the remote nick and server of the current buffer.
  177. """
  178. result = None, None
  179. if len(args) == 2:
  180. result = tuple(args)
  181. else:
  182. buf = weechat.current_buffer()
  183. if buffer_is_private(buf):
  184. result = (
  185. buffer_get_string(buf, 'localvar_channel'),
  186. buffer_get_string(buf, 'localvar_server'))
  187. return result
  188. class AccountDict(collections.defaultdict):
  189. """Dictionary that adds missing keys as IrcOtrAccount instances."""
  190. def __missing__(self, key):
  191. debug(('add account', key))
  192. self[key] = IrcOtrAccount(key)
  193. return self[key]
  194. class Assembler:
  195. """Reassemble fragmented OTR messages.
  196. This does not deal with OTR fragmentation, which is handled by potr, but
  197. fragmentation of received OTR messages that are too large for IRC.
  198. """
  199. def __init__(self):
  200. self.clear()
  201. def add(self, data):
  202. """Add data to the buffer."""
  203. self.value += data
  204. def clear(self):
  205. """Empty the buffer."""
  206. self.value = ''
  207. def is_done(self):
  208. """Return True if the buffer is a complete message."""
  209. return self.is_query() or \
  210. not self.value.startswith(potr.proto.OTRTAG) or \
  211. has_otr_end(self.value)
  212. def get(self):
  213. """Return the current value of the buffer and empty it."""
  214. result = self.value
  215. self.clear()
  216. return result
  217. def is_query(self):
  218. """Return true if the buffer is an OTR query."""
  219. return OTR_QUERY_RE.match(self.value)
  220. class IrcContext(potr.context.Context):
  221. """Context class for OTR over IRC."""
  222. def __init__(self, account, peername):
  223. super(IrcContext, self).__init__(account, peername)
  224. self.peer_nick, self.peer_server = peername.split('@')
  225. self.in_assembler = Assembler()
  226. self.in_otr_message = False
  227. self.in_smp = False
  228. self.smp_question = False
  229. def policy_config_option(self, policy):
  230. """Get the option name of a policy option for this context."""
  231. return config_prefix('.'.join([
  232. 'policy', self.peer_server, self.user.nick, self.peer_nick,
  233. policy.lower()]))
  234. def getPolicy(self, key):
  235. """Get the value of a policy option for this context."""
  236. key_lower = key.lower()
  237. if key_lower in READ_ONLY_POLICIES:
  238. result = READ_ONLY_POLICIES[key_lower]
  239. else:
  240. option = weechat.config_get(self.policy_config_option(key))
  241. if option == '':
  242. option = weechat.config_get(
  243. config_prefix('policy.default.%s' % key_lower))
  244. result = bool(weechat.config_boolean(option))
  245. debug(('getPolicy', key, result))
  246. return result
  247. def inject(self, msg, appdata=None):
  248. """Send a message to the remote peer."""
  249. if isinstance(msg, potr.proto.OTRMessage):
  250. msg = unicode(msg)
  251. else:
  252. msg = msg.decode('utf-8')
  253. debug(('inject', msg, 'len %d' % len(msg), appdata))
  254. privmsg(self.peer_server, self.peer_nick, msg)
  255. def setState(self, newstate):
  256. """Handle state transition."""
  257. debug(('state', self.state, newstate))
  258. if self.is_encrypted():
  259. if newstate == potr.context.STATE_ENCRYPTED:
  260. self.print_buffer(
  261. 'Private conversation has been refreshed.')
  262. elif newstate == potr.context.STATE_FINISHED:
  263. self.print_buffer(
  264. """%s has ended the private conversation. You should do the same:
  265. /otr finish %s %s
  266. """ % (self.peer, self.peer_nick, self.peer_server))
  267. elif newstate == potr.context.STATE_ENCRYPTED:
  268. # unencrypted => encrypted
  269. trust = self.getCurrentTrust()
  270. if trust is None:
  271. fpr = str(self.getCurrentKey())
  272. self.print_buffer('New fingerprint: %s' % fpr)
  273. self.setCurrentTrust('')
  274. if bool(trust):
  275. self.print_buffer(
  276. 'Authenticated secured OTR conversation started.')
  277. else:
  278. self.print_buffer(
  279. 'Unauthenticated secured OTR conversation started.')
  280. self.print_buffer(self.verify_instructions())
  281. if self.state != potr.context.STATE_PLAINTEXT and \
  282. newstate == potr.context.STATE_PLAINTEXT:
  283. self.print_buffer('Private conversation ended.')
  284. super(IrcContext, self).setState(newstate)
  285. def maxMessageSize(self, appdata=None):
  286. """Return the max message size for this context."""
  287. # remove 'PRIVMSG <nick> :' from max message size
  288. result = self.user.maxMessageSize - 10 - len(self.peer_nick)
  289. debug('max message size %d' % result)
  290. return result
  291. def buffer(self):
  292. """Get the buffer for this context."""
  293. return info_get(
  294. 'irc_buffer', '%s,%s' % (self.peer_server, self.peer_nick))
  295. def print_buffer(self, msg):
  296. """Print a message to the buffer for this context."""
  297. prnt(self.buffer(), '%s\t%s' % (SCRIPT_NAME, msg))
  298. def smp_finish(self, message):
  299. """Reset SMP state and send a message to the user."""
  300. self.in_smp = False
  301. self.smp_question = False
  302. self.user.saveTrusts()
  303. self.print_buffer(message)
  304. def handle_tlvs(self, tlvs):
  305. """Handle SMP states."""
  306. if tlvs:
  307. smp1q = first_instance(tlvs, potr.proto.SMP1QTLV)
  308. smp3 = first_instance(tlvs, potr.proto.SMP3TLV)
  309. smp4 = first_instance(tlvs, potr.proto.SMP4TLV)
  310. if self.in_smp and not self.smpIsValid():
  311. debug('SMP aborted')
  312. self.smp_finish('SMP aborted.')
  313. elif first_instance(tlvs, potr.proto.SMP1TLV):
  314. debug('SMP1')
  315. self.in_smp = True
  316. self.print_buffer(
  317. """Peer has requested SMP verification.
  318. Respond with: /otr smp respond %s %s <secret>""" % (
  319. self.peer_nick, self.peer_server))
  320. elif smp1q:
  321. debug(('SMP1Q', smp1q.msg))
  322. self.in_smp = True
  323. self.smp_question = True
  324. self.print_buffer(
  325. """Peer has requested SMP verification: %s
  326. Respond with: /otr smp respond %s %s <answer>""" % (
  327. smp1q.msg, self.peer_nick, self.peer_server))
  328. elif first_instance(tlvs, potr.proto.SMP2TLV):
  329. debug('SMP2')
  330. self.print_buffer('SMP progressing.')
  331. elif smp3 or smp4:
  332. if smp3:
  333. debug('SMP3')
  334. elif smp4:
  335. debug('SMP4')
  336. if self.smpIsSuccess():
  337. self.smp_finish('SMP verification succeeded.')
  338. if self.smp_question:
  339. self.print_buffer(
  340. """You may want to authenticate your peer by asking your own question:
  341. /otr smp ask %s %s <secret> <question>
  342. """ % (self.peer_nick, self.peer_server))
  343. else:
  344. self.smp_finish('SMP verification failed.')
  345. def verify_instructions(self):
  346. """Generate verification instructions for user."""
  347. return """You can verify that this contact is who they claim to be in one of the following ways:
  348. 1) Verify each other's fingerprints using a secure channel:
  349. Your fingerprint : %(your_fingerprint)s
  350. %(peer)s's fingerprint : %(peer_fingerprint)s
  351. then use the command: /otr trust %(peer_nick)s %(peer_server)s
  352. 2) SMP pre-shared secret that you both know:
  353. /otr smp ask %(peer_nick)s %(peer_server)s <secret>
  354. 3) SMP pre-shared secret that you both know with a question:
  355. /otr smp ask %(peer_nick)s %(peer_server)s <secret> <question>
  356. """ % dict(
  357. your_fingerprint=self.user.getPrivkey(),
  358. peer=self.peer,
  359. peer_fingerprint=potr.human_hash(
  360. self.crypto.theirPubkey.cfingerprint()),
  361. peer_nick=self.peer_nick,
  362. peer_server=self.peer_server,
  363. )
  364. def is_encrypted(self):
  365. """Return True if the conversation with this context's peer is
  366. currently encrypted."""
  367. return self.state == potr.context.STATE_ENCRYPTED
  368. def is_verified(self):
  369. """Return True if this context's peer is verified."""
  370. return bool(self.getCurrentTrust())
  371. def format_policies(self):
  372. """Return current policies for this context formatted as a string for
  373. the user."""
  374. buf = cStringIO.StringIO()
  375. buf.write('Current OTR policies for %s:\n' % self.peer)
  376. for policy, desc in sorted(POLICIES.iteritems()):
  377. buf.write(' %s (%s) : %s\n' % (
  378. policy, desc,
  379. { True : 'on', False : 'off'}[self.getPolicy(policy)]))
  380. buf.write('Change policies with: /otr policy NAME on|off')
  381. return buf.getvalue()
  382. def is_logged(self):
  383. """Return True if conversations with this context's peer are currently
  384. being logged to disk."""
  385. infolist = weechat.infolist_get('logger_buffer', '', '')
  386. buf = self.buffer()
  387. result = False
  388. while weechat.infolist_next(infolist):
  389. if weechat.infolist_pointer(infolist, 'buffer') == buf:
  390. result = bool(weechat.infolist_integer(infolist, 'log_enabled'))
  391. break
  392. weechat.infolist_free(infolist)
  393. return result
  394. class IrcOtrAccount(potr.context.Account):
  395. """Account class for OTR over IRC."""
  396. contextclass = IrcContext
  397. PROTOCOL = 'irc'
  398. MAX_MSG_SIZE = 415
  399. def __init__(self, name):
  400. super(IrcOtrAccount, self).__init__(
  401. name, IrcOtrAccount.PROTOCOL, IrcOtrAccount.MAX_MSG_SIZE)
  402. self.nick, self.server = self.name.split('@')
  403. # IRC messages cannot have newlines, OTR query and "no plugin" text
  404. # need to be one message
  405. self.defaultQuery = self.defaultQuery.replace("\n", ' ')
  406. self.key_file_path = os.path.join(OTR_DIR, '%s.%s' % (name, 'key3'))
  407. self.fpr_file_path = os.path.join(OTR_DIR, '%s.%s' % (name, 'fpr'))
  408. self.load_trusts()
  409. def load_trusts(self):
  410. """Load trust data from the fingerprint file."""
  411. if os.path.exists(self.fpr_file_path):
  412. with open(self.fpr_file_path) as fpr_file:
  413. for line in fpr_file:
  414. debug(('load trust check', line))
  415. context, account, protocol, fpr, trust = \
  416. line[:-1].split('\t')
  417. if account == self.name and \
  418. protocol == IrcOtrAccount.PROTOCOL:
  419. debug(('set trust', context, fpr, trust))
  420. self.setTrust(context, fpr, trust)
  421. def loadPrivkey(self):
  422. """Load key file."""
  423. debug(('load private key', self.key_file_path))
  424. if os.path.exists(self.key_file_path):
  425. with open(self.key_file_path, 'rb') as key_file:
  426. return potr.crypt.PK.parsePrivateKey(key_file.read())[0]
  427. def savePrivkey(self):
  428. """Save key file."""
  429. debug(('save private key', self.key_file_path))
  430. with open(self.key_file_path, 'wb') as key_file:
  431. key_file.write(self.getPrivkey().serializePrivateKey())
  432. def saveTrusts(self):
  433. """Save trusts."""
  434. with open(self.fpr_file_path, 'w') as fpr_file:
  435. for uid, trusts in self.trusts.iteritems():
  436. for fpr, trust in trusts.iteritems():
  437. debug(('trust write', uid, self.name,
  438. IrcOtrAccount.PROTOCOL, fpr, trust))
  439. fpr_file.write('\t'.join(
  440. (uid, self.name, IrcOtrAccount.PROTOCOL, fpr,
  441. trust)))
  442. fpr_file.write('\n')
  443. def end_all_private(self):
  444. """End all currently encrypted conversations."""
  445. for context in self.ctxs.itervalues():
  446. if context.is_encrypted():
  447. context.disconnect()
  448. def message_in_cb(data, modifier, modifier_data, string):
  449. """Incoming message callback"""
  450. debug(('message_in_cb', data, modifier, modifier_data, string))
  451. parsed = parse_irc_privmsg(string.decode('utf-8'))
  452. debug(('parsed message', parsed))
  453. # skip processing messages to public channels
  454. if parsed['to_channel']:
  455. return string
  456. server = modifier_data.decode('utf-8')
  457. from_user = irc_user(parsed['from_nick'], server)
  458. local_user = current_user(server)
  459. context = ACCOUNTS[local_user].getContext(from_user)
  460. context.in_assembler.add(parsed['text'])
  461. result = ''
  462. if context.in_assembler.is_done():
  463. try:
  464. msg, tlvs = context.receiveMessage(context.in_assembler.get())
  465. debug(('receive', msg, tlvs))
  466. if msg:
  467. result = build_privmsg_in(
  468. parsed['from'], parsed['to'], msg.decode('utf-8')).encode(
  469. 'utf-8')
  470. context.handle_tlvs(tlvs)
  471. except potr.context.ErrorReceived, e:
  472. context.print_buffer('Received OTR error: %s' % e.args[0].error)
  473. except potr.context.NotEncryptedError:
  474. context.print_buffer(
  475. 'Received encrypted data but no private session established.')
  476. except potr.context.NotOTRMessage:
  477. result = string
  478. except potr.context.UnencryptedMessage, err:
  479. result = build_privmsg_in(
  480. parsed['from'], parsed['to'],
  481. 'Unencrypted message received: %s' % (
  482. err.args[0])).encode('utf-8')
  483. weechat.bar_item_update(SCRIPT_NAME)
  484. return result
  485. def message_out_cb(data, modifier, modifier_data, string):
  486. """Outgoing message callback."""
  487. result = ''
  488. # If any exception is raised in this function, WeeChat will send the
  489. # outgoing message, which could be something that the user intended to be
  490. # encrypted. This paranoid exception handling ensures that the system
  491. # fails closed and not open.
  492. try:
  493. debug(('message_out_cb', data, modifier, modifier_data, string))
  494. parsed = parse_irc_privmsg(string.decode('utf-8'))
  495. debug(('parsed message', parsed))
  496. # skip processing messages to public channels
  497. if parsed['to_channel']:
  498. return string
  499. server = modifier_data.decode('utf-8')
  500. to_user = irc_user(parsed['to_nick'], server)
  501. local_user = current_user(server)
  502. context = ACCOUNTS[local_user].getContext(to_user)
  503. if parsed['text'].startswith(potr.proto.OTRTAG) and \
  504. not OTR_QUERY_RE.match(parsed['text']):
  505. if not has_otr_end(parsed['text']):
  506. debug('in OTR message')
  507. context.in_otr_message = True
  508. else:
  509. debug('complete OTR message')
  510. result = string
  511. elif context.in_otr_message:
  512. if has_otr_end(parsed['text']):
  513. context.in_otr_message = False
  514. debug('in OTR message end')
  515. result = string
  516. else:
  517. debug(('context send message', parsed['text'], parsed['to_nick'],
  518. server))
  519. try:
  520. ret = context.sendMessage(
  521. potr.context.FRAGMENT_SEND_ALL, parsed['text'].encode(
  522. 'utf-8'))
  523. if ret:
  524. debug(('sendMessage returned', ret))
  525. result = ('PRIVMSG %s :%s' % (
  526. parsed['to_nick'], ret.decode('utf-8'))).encode(
  527. 'utf-8')
  528. except potr.context.NotEncryptedError, err:
  529. if err.args[0] == potr.context.EXC_FINISHED:
  530. context.print_buffer(
  531. """Your message was not sent. End your private conversation:\n/otr finish %s %s""" % (
  532. parsed['to_nick'], server))
  533. else:
  534. raise
  535. weechat.bar_item_update(SCRIPT_NAME)
  536. except:
  537. try:
  538. prnt('', traceback.format_exc())
  539. context.print_buffer(
  540. 'Failed to send message. See core buffer for traceback.')
  541. except:
  542. pass
  543. return result
  544. def shutdown():
  545. """Script unload callback."""
  546. debug('shutdown')
  547. weechat.config_write(CONFIG_FILE)
  548. for account in ACCOUNTS.itervalues():
  549. account.end_all_private()
  550. free_all_config()
  551. weechat.bar_item_remove(OTR_STATUSBAR)
  552. return weechat.WEECHAT_RC_OK
  553. def command_cb(data, buf, args):
  554. """Parse and dispatch WeeChat OTR commands."""
  555. result = weechat.WEECHAT_RC_ERROR
  556. arg_parts = args.split(None, 5)
  557. if len(arg_parts) in (1, 3) and arg_parts[0] == 'start':
  558. nick, server = default_peer_args(arg_parts[1:3])
  559. if nick is not None and server is not None:
  560. context = ACCOUNTS[current_user(server)].getContext(
  561. irc_user(nick, server))
  562. context.print_buffer('Sending OTR query...')
  563. context.print_buffer(
  564. 'To try OTR on all conversations with %s: /otr policy send_tag on' %
  565. context.peer)
  566. privmsg(server, nick, '?OTR?')
  567. result = weechat.WEECHAT_RC_OK
  568. elif len(arg_parts) in (1, 3) and arg_parts[0] == 'finish':
  569. nick, server = default_peer_args(arg_parts[1:3])
  570. if nick is not None and server is not None:
  571. context = ACCOUNTS[current_user(server)].getContext(
  572. irc_user(nick, server))
  573. context.disconnect()
  574. result = weechat.WEECHAT_RC_OK
  575. elif len(arg_parts) in (5, 6) and arg_parts[0] == 'smp':
  576. action = arg_parts[1]
  577. if action == 'respond':
  578. nick, server = arg_parts[2:4]
  579. secret = args.split(None, 4)[-1]
  580. context = ACCOUNTS[current_user(server)].getContext(
  581. irc_user(nick, server))
  582. context.smpGotSecret(secret)
  583. result = weechat.WEECHAT_RC_OK
  584. elif action == 'ask':
  585. nick, server, secret = arg_parts[2:5]
  586. if len(arg_parts) > 5:
  587. question = arg_parts[5]
  588. else:
  589. question = None
  590. context = ACCOUNTS[current_user(server)].getContext(
  591. irc_user(nick, server))
  592. try:
  593. context.smpInit(secret, question)
  594. except potr.context.NotEncryptedError:
  595. context.print_buffer(
  596. 'There is currently no encrypted session with %s.' % \
  597. context.peer)
  598. else:
  599. result = weechat.WEECHAT_RC_OK
  600. elif len(arg_parts) in (1, 3) and arg_parts[0] == 'trust':
  601. nick, server = default_peer_args(arg_parts[1:3])
  602. if nick is not None and server is not None:
  603. context = ACCOUNTS[current_user(server)].getContext(
  604. irc_user(nick, server))
  605. if context.crypto.theirPubkey is not None:
  606. context.setCurrentTrust('verified')
  607. context.print_buffer('%s is now authenticated.' % context.peer)
  608. weechat.bar_item_update(SCRIPT_NAME)
  609. else:
  610. context.print_buffer(
  611. 'No fingerprint for %s. Start an OTR conversation first: /otr start' \
  612. % context.peer)
  613. result = weechat.WEECHAT_RC_OK
  614. elif len(arg_parts) in (1, 3) and arg_parts[0] == 'policy':
  615. if len(arg_parts) == 1:
  616. nick, server = default_peer_args([])
  617. if nick is not None and server is not None:
  618. context = ACCOUNTS[current_user(server)].getContext(
  619. irc_user(nick, server))
  620. context.print_buffer(context.format_policies())
  621. result = weechat.WEECHAT_RC_OK
  622. elif len(arg_parts) == 3 and arg_parts[1].lower() in POLICIES:
  623. nick, server = default_peer_args([])
  624. if nick is not None and server is not None:
  625. context = ACCOUNTS[current_user(server)].getContext(
  626. irc_user(nick, server))
  627. policy_var = context.policy_config_option(arg_parts[1].lower())
  628. command('', '/set %s %s' % (policy_var, arg_parts[2]))
  629. context.print_buffer(context.format_policies())
  630. result = weechat.WEECHAT_RC_OK
  631. return result
  632. def otr_statusbar_cb(data, item, window):
  633. """Update the statusbar."""
  634. if window:
  635. buf = weechat.window_get_pointer(window, 'buffer')
  636. else:
  637. # If the bar item is in a root bar that is not in a window, window
  638. # will be empty.
  639. buf = weechat.current_buffer()
  640. result = ''
  641. if buffer_is_private(buf):
  642. local_user = irc_user(
  643. buffer_get_string(buf, 'localvar_nick'),
  644. buffer_get_string(buf, 'localvar_server'))
  645. remote_user = irc_user(
  646. buffer_get_string(buf, 'localvar_channel'),
  647. buffer_get_string(buf, 'localvar_server'))
  648. context = ACCOUNTS[local_user].getContext(remote_user)
  649. encrypted_str = config_string('look.bar.state.encrypted')
  650. unencrypted_str = config_string('look.bar.state.unencrypted')
  651. authenticated_str = config_string('look.bar.state.authenticated')
  652. unauthenticated_str = config_string('look.bar.state.unauthenticated')
  653. logged_str = config_string('look.bar.state.logged')
  654. notlogged_str = config_string('look.bar.state.notlogged')
  655. bar_parts = []
  656. if context.is_encrypted():
  657. if encrypted_str:
  658. bar_parts.append(''.join([
  659. config_color('status.encrypted'),
  660. encrypted_str,
  661. config_color('status.default')]))
  662. if context.is_verified():
  663. if authenticated_str:
  664. bar_parts.append(''.join([
  665. config_color('status.authenticated'),
  666. authenticated_str,
  667. config_color('status.default')]))
  668. elif unauthenticated_str:
  669. bar_parts.append(''.join([
  670. config_color('status.unauthenticated'),
  671. unauthenticated_str,
  672. config_color('status.default')]))
  673. if context.is_logged():
  674. if logged_str:
  675. bar_parts.append(''.join([
  676. config_color('status.logged'),
  677. logged_str,
  678. config_color('status.default')]))
  679. elif notlogged_str:
  680. bar_parts.append(''.join([
  681. config_color('status.notlogged'),
  682. notlogged_str,
  683. config_color('status.default')]))
  684. elif unencrypted_str:
  685. bar_parts.append(''.join([
  686. config_color('status.unencrypted'),
  687. unencrypted_str,
  688. config_color('status.default')]))
  689. result = config_string('look.bar.state.separator').join(bar_parts)
  690. if result:
  691. result = '%s%s%s' % (
  692. config_color('status.default'),
  693. config_string('look.bar.prefix'), result)
  694. return result
  695. def bar_config_update_cb(data, option):
  696. """Callback for updating the status bar when its config changes."""
  697. weechat.bar_item_update(SCRIPT_NAME)
  698. return weechat.WEECHAT_RC_OK
  699. def policy_completion_cb(data, completion_item, buf, completion):
  700. """Callback for policy tab completion."""
  701. for policy in POLICIES:
  702. weechat.hook_completion_list_add(
  703. completion, policy, 0, weechat.WEECHAT_LIST_POS_SORT)
  704. return weechat.WEECHAT_RC_OK
  705. def policy_create_option_cb(data, config_file, section, name, value):
  706. """Callback for creating a new policy option when the user sets one
  707. that doesn't exist."""
  708. weechat.config_new_option(
  709. config_file, section, name, 'boolean', '', '', 0, 0, value, value, 0,
  710. '', '', '', '', '', '')
  711. return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED
  712. def logger_level_update_cb(data, option, value):
  713. """Callback called when any logger level changes."""
  714. weechat.bar_item_update(SCRIPT_NAME)
  715. return weechat.WEECHAT_RC_OK
  716. def buffer_switch_cb(data, signal, signal_data):
  717. """Callback for buffer switched.
  718. Used for updating the status bar item when it is in a root bar.
  719. """
  720. weechat.bar_item_update(SCRIPT_NAME)
  721. return weechat.WEECHAT_RC_OK
  722. def init_config():
  723. """Set up configuration options and load config file."""
  724. global CONFIG_FILE
  725. CONFIG_FILE = weechat.config_new(SCRIPT_NAME, 'config_reload_cb', '')
  726. global CONFIG_SECTIONS
  727. CONFIG_SECTIONS = {}
  728. CONFIG_SECTIONS['general'] = weechat.config_new_section(
  729. CONFIG_FILE, 'general', 0, 0, '', '', '', '', '', '', '', '', '', '')
  730. for option, typ, desc, default in [
  731. ('debug', 'boolean', 'OTR script debugging', 'off'),
  732. ]:
  733. weechat.config_new_option(
  734. CONFIG_FILE, CONFIG_SECTIONS['general'], option, typ, desc, '', 0,
  735. 0, default, default, 0, '', '', '', '', '', '')
  736. CONFIG_SECTIONS['color'] = weechat.config_new_section(
  737. CONFIG_FILE, 'color', 0, 0, '', '', '', '', '', '', '', '', '', '')
  738. for option, desc, default, update_cb in [
  739. ('status.default', 'status bar default color', 'default',
  740. 'bar_config_update_cb'),
  741. ('status.encrypted', 'status bar encrypted indicator color', 'green',
  742. 'bar_config_update_cb'),
  743. ('status.unencrypted', 'status bar unencrypted indicator color',
  744. 'lightred', 'bar_config_update_cb'),
  745. ('status.authenticated', 'status bar authenticated indicator color',
  746. 'green', 'bar_config_update_cb'),
  747. ('status.unauthenticated', 'status bar unauthenticated indicator color',
  748. 'lightred', 'bar_config_update_cb'),
  749. ('status.logged', 'status bar logged indicator color', 'lightred',
  750. 'bar_config_update_cb'),
  751. ('status.notlogged', 'status bar not logged indicator color',
  752. 'green', 'bar_config_update_cb'),
  753. ]:
  754. weechat.config_new_option(
  755. CONFIG_FILE, CONFIG_SECTIONS['color'], option, 'color', desc, '', 0,
  756. 0, default, default, 0, '', '', update_cb, '', '', '')
  757. CONFIG_SECTIONS['look'] = weechat.config_new_section(
  758. CONFIG_FILE, 'look', 0, 0, '', '', '', '', '', '', '', '', '', '')
  759. for option, desc, default, update_cb in [
  760. ('bar.prefix', 'prefix for OTR status bar item', 'OTR:',
  761. 'bar_config_update_cb'),
  762. ('bar.state.encrypted',
  763. 'shown in status bar when conversation is encrypted', 'SEC',
  764. 'bar_config_update_cb'),
  765. ('bar.state.unencrypted',
  766. 'shown in status bar when conversation is not encrypted', '!SEC',
  767. 'bar_config_update_cb'),
  768. ('bar.state.authenticated',
  769. 'shown in status bar when peer is authenticated', 'AUTH',
  770. 'bar_config_update_cb'),
  771. ('bar.state.unauthenticated',
  772. 'shown in status bar when peer is not authenticated', '!AUTH',
  773. 'bar_config_update_cb'),
  774. ('bar.state.logged',
  775. 'shown in status bar when peer conversation is being logged to disk',
  776. 'LOG',
  777. 'bar_config_update_cb'),
  778. ('bar.state.notlogged',
  779. 'shown in status bar when peer conversation is not being logged to disk',
  780. '!LOG',
  781. 'bar_config_update_cb'),
  782. ('bar.state.separator', 'separator for states in the status bar', ',',
  783. 'bar_config_update_cb'),
  784. ]:
  785. weechat.config_new_option(
  786. CONFIG_FILE, CONFIG_SECTIONS['look'], option, 'string', desc, '',
  787. 0, 0, default, default, 0, '', '', update_cb, '', '', '')
  788. CONFIG_SECTIONS['policy'] = weechat.config_new_section(
  789. CONFIG_FILE, 'policy', 1, 1, '', '', '', '', '', '',
  790. 'policy_create_option_cb', '', '', '')
  791. for option, desc, default in [
  792. ('default.allow_v2', 'default allow OTR v2 policy', 'on'),
  793. ('default.require_encryption', 'default require encryption policy',
  794. 'off'),
  795. ('default.send_tag', 'default send tag policy', 'off'),
  796. ]:
  797. weechat.config_new_option(
  798. CONFIG_FILE, CONFIG_SECTIONS['policy'], option, 'boolean', desc, '',
  799. 0, 0, default, default, 0, '', '', '', '', '', '')
  800. weechat.config_read(CONFIG_FILE)
  801. def config_reload_cb(data, config_file):
  802. """/reload callback to reload config from file."""
  803. free_all_config()
  804. init_config()
  805. return weechat.WEECHAT_CONFIG_READ_OK
  806. def free_all_config():
  807. """Free all config options, sections and config file."""
  808. for section in CONFIG_SECTIONS.itervalues():
  809. weechat.config_section_free_options(section)
  810. weechat.config_section_free(section)
  811. weechat.config_free(CONFIG_FILE)
  812. def create_dir():
  813. """Create the OTR subdirectory in the WeeChat config directory if it does
  814. not exist."""
  815. if not os.path.exists(OTR_DIR):
  816. weechat.mkdir_home(OTR_DIR_NAME, 0700)
  817. if weechat.register(
  818. SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENCE, SCRIPT_DESC,
  819. 'shutdown', ''):
  820. init_config()
  821. OTR_DIR = os.path.join(info_get('weechat_dir', ''), OTR_DIR_NAME)
  822. create_dir()
  823. ACCOUNTS = AccountDict()
  824. weechat.hook_modifier('irc_in_privmsg', 'message_in_cb', '')
  825. weechat.hook_modifier('irc_out_privmsg', 'message_out_cb', '')
  826. weechat.hook_command(
  827. SCRIPT_NAME, SCRIPT_HELP,
  828. 'start [NICK SERVER] || '
  829. 'finish [NICK SERVER] || '
  830. 'smp ask NICK SERVER SECRET [QUESTION] || '
  831. 'smp respond NICK SERVER SECRET || '
  832. 'trust [NICK SERVER] || '
  833. 'policy [POLICY on|off]',
  834. '',
  835. 'start %(nick) %(irc_servers) %-||'
  836. 'finish %(nick) %(irc_servers) %-||'
  837. 'smp ask|respond %(nick) %(irc_servers) %-||'
  838. 'trust %(nick) %(irc_servers) %-||'
  839. 'policy %(otr_policy) on|off %-||',
  840. 'command_cb',
  841. '')
  842. weechat.hook_completion(
  843. 'otr_policy', 'OTR policies', 'policy_completion_cb', '')
  844. weechat.hook_config('logger.level.irc.*', 'logger_level_update_cb', '')
  845. weechat.hook_signal('buffer_switch', 'buffer_switch_cb', '')
  846. OTR_STATUSBAR = weechat.bar_item_new(SCRIPT_NAME, 'otr_statusbar_cb', '')
  847. weechat.bar_item_update(SCRIPT_NAME)