File: otr.py

package info (click to toggle)
weechat-scripts 20120603-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,804 kB
  • sloc: python: 23,181; perl: 16,968; ruby: 1,166; tcl: 199; sh: 8; makefile: 7
file content (1061 lines) | stat: -rw-r--r-- 37,131 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# -*- coding: utf-8 -*-
# otr - WeeChat script for Off-the-Record IRC messaging
#
# DISCLAIMER: To the best of my knowledge this script securely provides OTR
# messaging in WeeChat, but I offer no guarantee. Please report any security
# holes you find.
#
# Copyright (c) 2012 Matthew M. Boedicker <matthewm@boedicker.org>
#                    Nils Görs <weechatter@arcor.de>
#
# Report issues at https://github.com/mmb/weechat-otr
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

import collections
import cStringIO
import os
import re
import traceback

import weechat

import potr

SCRIPT_NAME = 'otr'
SCRIPT_DESC = 'Off-the-Record messaging for IRC'
SCRIPT_HELP = """%s

Quick start:

Add an OTR item to the status bar by adding '[otr]' to the config setting
weechat.bar.status.items. This will show you whether your current conversation
is encrypted, authenticated and logged. /set otr.* for OTR status bar
customization options.

Start a private conversation with a friend who has OTR: /query yourpeer hi

In the private chat buffer: /otr start

If you have not authenticated your peer yet, follow the instructions for
authentication.

View OTR policies for your peer: /otr policy

To end your private conversation: /otr finish
""" % SCRIPT_DESC

SCRIPT_AUTHOR = 'Matthew M. Boedicker'
SCRIPT_LICENCE = 'GPL3'
SCRIPT_VERSION = '1.0.0'

OTR_DIR_NAME = 'otr'

OTR_QUERY_RE = re.compile('\?OTR(\?|\??v[a-z\d]*\?)$')

POLICIES = {
    'allow_v1' : 'allow OTR protocol version 1',
    'allow_v2' : 'allow OTR protocol version 2',
    'require_encryption' : 'refuse to send unencrypted messages',
    'send_tag' : 'advertise your OTR capability using the whitespace tag',
    }

IRC_PRIVMSG_RE = re.compile(r"""
(
    :
    (?P<from>
        (?P<from_nick>.+?)
        !
        (?P<from_user>.+?)
        @
        (?P<from_host>.+?)
    )
\ )?
PRIVMSG
\ (?P<to>.+?)
\ :
(?P<text>.+)
""", re.VERBOSE)

potr.proto.TaggedPlaintextOrig = potr.proto.TaggedPlaintext

class WeechatTaggedPlaintext(potr.proto.TaggedPlaintextOrig):
    """Patch potr.proto.TaggedPlaintext to not end plaintext tags in a space.

    When POTR adds OTR tags to plaintext it puts them at the end of the message.
    The tags end in a space which gets stripped off by WeeChat because it
    strips trailing spaces from commands. This causes OTR initiation to fail so
    the following code adds an extra tab at the end of the plaintext tags if
    they end in a space.
    """

    def __bytes__(self):
        # old style because parent class is old style
        result = potr.proto.TaggedPlaintextOrig.__bytes__(self).decode('utf-8')

        if result.endswith(' '):
            result = '%s\t' % result

        return result.encode('utf-8')

potr.proto.TaggedPlaintext = WeechatTaggedPlaintext

def command(buf, command_str):
    """Wrap weechat.command() with utf-8 encode."""
    debug(command_str)
    weechat.command(buf, command_str.encode('utf-8'))

def privmsg(server, nick, message):
    """Send a private message to a nick."""
    for line in message.split('\n'):
        command('', '/quote -server %s PRIVMSG %s :%s' % (server, nick, line))

def build_privmsg_in(fromm, to, msg):
    """Build an inbound IRC PRIVMSG command."""
    return ':%s PRIVMSG %s :%s' % (fromm, to, msg)

def prnt(buf, message):
    """Wrap weechat.prnt() with utf-8 encode."""
    weechat.prnt(buf, message.encode('utf-8'))

def debug(msg):
    """Send a debug message to the WeeChat core buffer."""
    debug_option = weechat.config_get(config_prefix('general.debug'))

    if weechat.config_boolean(debug_option):
        prnt('', ('%s debug\t%s' % (SCRIPT_NAME, unicode(msg))))

def current_user(server_name):
    """Get the nick and server of the current user on a server."""
    return irc_user(info_get('irc_nick', server_name), server_name)

def irc_user(nick, server):
    """Build an IRC user string from a nick and server."""
    return '%s@%s' % (nick, server)

def parse_irc_privmsg(message):
    """Parse an IRC PRIVMSG command and return a dictionary.

    Either the to_channel key or the to_nick key will be set depending on
    whether the message is to a nick or a channel. The other will be None.

    Example input:

    :nick!user@host PRIVMSG #weechat :message here

    Output:

    {'from': 'nick!user@host',
    'from_nick': 'nick',
    'from_user': 'user',
    'from_host': 'host',
    'to': '#weechat',
    'to_channel': '#weechat',
    'to_nick': None,
    'text': 'message here'}
    """

    match = IRC_PRIVMSG_RE.match(message)
    if match:
        result = match.groupdict()

        if result['to'].startswith('#'):
            result['to_channel'] = result['to']
            result['to_nick'] = None
        else:
            result['to_channel'] = None
            result['to_nick'] = result['to']

        return result

def has_otr_end(msg):
    """Return True if the message is the end of an OTR message."""
    return msg.endswith('.') or msg.endswith(',')

def first_instance(objs, klass):
    """Return the first object in the list that is an instance of a class."""
    for obj in objs:
        if isinstance(obj, klass):
            return obj

def config_prefix(option):
    """Add the config prefix to an option and return the full option name."""
    return '%s.%s' % (SCRIPT_NAME, option)

def config_color(option):
    """Get the color of a color config option."""
    return weechat.color(weechat.config_color(weechat.config_get(
            config_prefix('color.%s' % option))))

def config_string(option):
    """Get the string value of a config option with utf-8 decode."""
    return weechat.config_string(
        weechat.config_get(config_prefix(option))).decode('utf-8')

def buffer_get_string(buf, prop):
    """Wrap weechat.buffer_get_string() with utf-8 encode/decode."""
    return weechat.buffer_get_string(buf, prop.encode('utf-8')).decode('utf-8')

def buffer_is_private(buf):
    """Return True if a buffer is private."""
    return buffer_get_string(buf, 'localvar_type') == 'private'

def info_get(info_name, arguments):
    """Wrap weechat.info_get() with utf-8 encode/decode."""
    return weechat.info_get(info_name, arguments.encode('utf-8')).decode(
        'utf-8')

def default_peer_args(args):
    """Get the nick and server of a remote peer from command arguments or
    the current buffer.

    Passed in args are the [nick, server] slice of arguments from a command.
    If these are present, return them. If args is empty and the current buffer
    is private, return the remote nick and server of the current buffer.
    """
    result = None, None

    if len(args) == 2:
        result = tuple(args)
    else:
        buf = weechat.current_buffer()

        if buffer_is_private(buf):
            result = (
                buffer_get_string(buf, 'localvar_channel'),
                buffer_get_string(buf, 'localvar_server'))

    return result

class AccountDict(collections.defaultdict):
    """Dictionary that adds missing keys as IrcOtrAccount instances."""

    def __missing__(self, key):
        debug(('add account', key))
        self[key] = IrcOtrAccount(key)

        return self[key]

class Assembler:
    """Reassemble fragmented OTR messages.

    This does not deal with OTR fragmentation, which is handled by potr, but
    fragmentation of received OTR messages that are too large for IRC.
    """
    def __init__(self):
        self.clear()

    def add(self, data):
        """Add data to the buffer."""
        self.value += data

    def clear(self):
        """Empty the buffer."""
        self.value = ''

    def is_done(self):
        """Return True if the buffer is a complete message."""
        return self.is_query() or \
            not self.value.startswith(potr.proto.OTRTAG) or \
            has_otr_end(self.value)

    def get(self):
        """Return the current value of the buffer and empty it."""
        result = self.value
        self.clear()

        return result

    def is_query(self):
        """Return true if the buffer is an OTR query."""
        return OTR_QUERY_RE.match(self.value)

class IrcContext(potr.context.Context):
    """Context class for OTR over IRC."""

    def __init__(self, account, peername):
        super(IrcContext, self).__init__(account, peername)

        self.peer_nick, self.peer_server = peername.split('@')
        self.in_assembler = Assembler()
        self.in_otr_message = False
        self.in_smp = False
        self.smp_question = False

    def policy_config_option(self, policy):
        """Get the option name of a policy option for this context."""
        return config_prefix('.'.join([
                    'policy', self.peer_server, self.user.nick, self.peer_nick,
                    policy.lower()]))

    def getPolicy(self, key):
        """Get the value of a policy option for this context."""
        option = weechat.config_get(self.policy_config_option(key))

        if option == '':
            option = weechat.config_get(
                config_prefix('policy.default.%s' % key.lower()))

        result = bool(weechat.config_boolean(option))

        debug(('getPolicy', key, result))

        return result

    def inject(self, msg, appdata=None):
        """Send a message to the remote peer."""
        if isinstance(msg, potr.proto.OTRMessage):
            msg = unicode(msg)
        else:
            msg = msg.decode('utf-8')

        debug(('inject', msg, 'len %d' % len(msg), appdata))

        privmsg(self.peer_server, self.peer_nick, msg)

    def setState(self, newstate):
        """Handle state transition."""
        debug(('state', self.state, newstate))

        if self.is_encrypted():
            if newstate == potr.context.STATE_ENCRYPTED:
                self.print_buffer(
                    'Private conversation has been refreshed.')
            elif newstate == potr.context.STATE_FINISHED:
                self.print_buffer(
                    """%s has ended the private conversation. You should do the same:
/otr finish %s %s
""" % (self.peer, self.peer_nick, self.peer_server))
        elif newstate == potr.context.STATE_ENCRYPTED:
            # unencrypted => encrypted
            trust = self.getCurrentTrust()
            if trust is None:
                fpr = str(self.getCurrentKey())
                self.print_buffer('New fingerprint: %s' % fpr)
                self.setCurrentTrust('')

            if bool(trust):
                self.print_buffer(
                    'Authenticated secured OTR conversation started.')
            else:
                self.print_buffer(
                    'Unauthenticated secured OTR conversation started.')
                self.print_buffer(self.verify_instructions())

        if self.state != potr.context.STATE_PLAINTEXT and \
                newstate == potr.context.STATE_PLAINTEXT:
            self.print_buffer('Private conversation ended.')

        super(IrcContext, self).setState(newstate)

    def maxMessageSize(self, appdata=None):
        """Return the max message size for this context."""
        # remove 'PRIVMSG <nick> :' from max message size
        result = self.user.maxMessageSize - 10 - len(self.peer_nick)
        debug('max message size %d' % result)

        return result

    def buffer(self):
        """Get the buffer for this context."""
        return info_get(
            'irc_buffer', '%s,%s' % (self.peer_server, self.peer_nick))

    def print_buffer(self, msg):
        """Print a message to the buffer for this context."""
        prnt(self.buffer(), '%s\t%s' % (SCRIPT_NAME, msg))

    def smp_finish(self, message):
        """Reset SMP state and send a message to the user."""
        self.in_smp = False
        self.smp_question = False

        self.user.saveTrusts()
        self.print_buffer(message)

    def handle_tlvs(self, tlvs):
        """Handle SMP states."""
        if tlvs:
            smp1q = first_instance(tlvs, potr.proto.SMP1QTLV)
            smp3 = first_instance(tlvs, potr.proto.SMP3TLV)
            smp4 = first_instance(tlvs, potr.proto.SMP4TLV)

            if self.in_smp and not self.smpIsValid():
                debug('SMP aborted')
                self.smp_finish('SMP aborted.')
            elif first_instance(tlvs, potr.proto.SMP1TLV):
                debug('SMP1')
                self.in_smp = True

                self.print_buffer(
                    """Peer has requested SMP verification.
Respond with: /otr smp respond %s %s <secret>""" % (
                        self.peer_nick, self.peer_server))
            elif smp1q:
                debug(('SMP1Q', smp1q.msg))
                self.in_smp = True
                self.smp_question = True

                self.print_buffer(
                    """Peer has requested SMP verification: %s
Respond with: /otr smp respond %s %s <answer>""" % (
                        smp1q.msg, self.peer_nick, self.peer_server))
            elif first_instance(tlvs, potr.proto.SMP2TLV):
                debug('SMP2')
                self.print_buffer('SMP progressing.')
            elif smp3 or smp4:
                if smp3:
                    debug('SMP3')
                elif smp4:
                    debug('SMP4')

                if self.smpIsSuccess():
                    self.smp_finish('SMP verification succeeded.')

                    if self.smp_question:
                        self.print_buffer(
                            """You may want to authenticate your peer by asking your own question:
/otr smp ask %s %s <secret> <question>
""" % (self.peer_nick, self.peer_server))
                else:
                    self.smp_finish('SMP verification failed.')

    def verify_instructions(self):
        """Generate verification instructions for user."""
        return """You can verify that this contact is who they claim to be in one of the following ways:

1) Verify each other's fingerprints using a secure channel:
  Your fingerprint : %(your_fingerprint)s
  %(peer)s's fingerprint : %(peer_fingerprint)s
  then use the command: /otr trust %(peer_nick)s %(peer_server)s

2) SMP pre-shared secret that you both know:
  /otr smp ask %(peer_nick)s %(peer_server)s <secret>

3) SMP pre-shared secret that you both know with a question:
  /otr smp ask %(peer_nick)s %(peer_server)s <secret> <question>
""" % dict(
            your_fingerprint=self.user.getPrivkey(),
            peer=self.peer,
            peer_fingerprint=potr.human_hash(
        self.crypto.theirPubkey.cfingerprint()),
            peer_nick=self.peer_nick,
            peer_server=self.peer_server,
            )

    def is_encrypted(self):
        """Return True if the conversation with this context's peer is
        currently encrypted."""
        return self.state == potr.context.STATE_ENCRYPTED

    def is_verified(self):
        """Return True if this context's peer is verified."""
        return bool(self.getCurrentTrust())

    def format_policies(self):
        """Return current policies for this context formatted as a string for
        the user."""
        buf = cStringIO.StringIO()

        buf.write('Current OTR policies for %s:\n' % self.peer)
        
        for policy, desc in sorted(POLICIES.iteritems()):
            buf.write('  %s (%s) : %s\n' % (
                    policy, desc,
                    { True : 'on', False : 'off'}[self.getPolicy(policy)]))

        buf.write('Change policies with: /otr policy NAME on|off')

        return buf.getvalue()

    def is_logged(self):
        """Return True if conversations with this context's peer are currently
        being logged to disk."""
        infolist = weechat.infolist_get('logger_buffer', '', '')

        buf = self.buffer()

        result = False

        while weechat.infolist_next(infolist):
            if weechat.infolist_pointer(infolist, 'buffer') == buf:
                result = bool(weechat.infolist_integer(infolist, 'log_enabled'))
                break

        weechat.infolist_free(infolist)

        return result

class IrcOtrAccount(potr.context.Account):
    """Account class for OTR over IRC."""

    contextclass = IrcContext

    PROTOCOL = 'irc'
    MAX_MSG_SIZE = 415

    def __init__(self, name):
        super(IrcOtrAccount, self).__init__(
            name, IrcOtrAccount.PROTOCOL, IrcOtrAccount.MAX_MSG_SIZE)

        self.nick, self.server = self.name.split('@')

        # IRC messages cannot have newlines, OTR query and "no plugin" text
        # need to be one message
        self.defaultQuery = self.defaultQuery.replace("\n", ' ')

        self.key_file_path = os.path.join(OTR_DIR, '%s.%s' % (name, 'key3'))
        self.fpr_file_path = os.path.join(OTR_DIR, '%s.%s' % (name, 'fpr'))

        self.load_trusts()

    def load_trusts(self):
        """Load trust data from the fingerprint file."""
        if os.path.exists(self.fpr_file_path):
            with open(self.fpr_file_path) as fpr_file:
                for line in fpr_file:
                    debug(('load trust check', line))

                    context, account, protocol, fpr, trust = \
                        line[:-1].split('\t')

                    if account == self.name and \
                            protocol == IrcOtrAccount.PROTOCOL:
                        debug(('set trust', context, fpr, trust))
                        self.setTrust(context, fpr, trust)

    def loadPrivkey(self):
        """Load key file."""
        debug(('load private key', self.key_file_path))

        if os.path.exists(self.key_file_path):
            with open(self.key_file_path, 'rb') as key_file:
                return potr.crypt.PK.parsePrivateKey(key_file.read())[0]

    def savePrivkey(self):
        """Save key file."""
        debug(('save private key', self.key_file_path))

        with open(self.key_file_path, 'wb') as key_file:
            key_file.write(self.getPrivkey().serializePrivateKey())

    def saveTrusts(self):
        """Save trusts."""
        with open(self.fpr_file_path, 'w') as fpr_file:
            for uid, trusts in self.trusts.iteritems():
                for fpr, trust in trusts.iteritems():
                    debug(('trust write', uid, self.name,
                           IrcOtrAccount.PROTOCOL, fpr, trust))
                    fpr_file.write('\t'.join(
                            (uid, self.name, IrcOtrAccount.PROTOCOL, fpr,
                             trust)))
                    fpr_file.write('\n')

    def end_all_private(self):
        """End all currently encrypted conversations."""
        for context in self.ctxs.itervalues():
            if context.is_encrypted():
                context.disconnect()

def message_in_cb(data, modifier, modifier_data, string):
    """Incoming message callback"""
    debug(('message_in_cb', data, modifier, modifier_data, string))

    parsed = parse_irc_privmsg(string.decode('utf-8'))
    debug(('parsed message', parsed))

    # skip processing messages to public channels
    if parsed['to_channel']:
        return string

    server = modifier_data.decode('utf-8')

    from_user = irc_user(parsed['from_nick'], server)
    local_user = current_user(server)

    context = ACCOUNTS[local_user].getContext(from_user)

    context.in_assembler.add(parsed['text'])

    result = ''

    if context.in_assembler.is_done():
        try:
            msg, tlvs = context.receiveMessage(context.in_assembler.get())

            debug(('receive', msg, tlvs))

            if msg:
                result = build_privmsg_in(
                    parsed['from'], parsed['to'], msg.decode('utf-8')).encode(
                    'utf-8')

            context.handle_tlvs(tlvs)
        except potr.context.ErrorReceived, e:
            context.print_buffer('Received OTR error: %s' % e.args[0].error)
        except potr.context.NotEncryptedError:
            context.print_buffer(
                'Received encrypted data but no private session established.')
        except potr.context.NotOTRMessage:
            result = string
        except potr.context.UnencryptedMessage, err:
            result = build_privmsg_in(
                parsed['from'], parsed['to'],
                'Unencrypted message received: %s' % (
                    err.args[0])).encode('utf-8')

    weechat.bar_item_update(SCRIPT_NAME)

    return result

def message_out_cb(data, modifier, modifier_data, string):
    """Outgoing message callback."""
    result = ''

    # If any exception is raised in this function, WeeChat will send the
    # outgoing message, which could be something that the user intended to be
    # encrypted. This paranoid exception handling ensures that the system
    # fails closed and not open.
    try:
        debug(('message_out_cb', data, modifier, modifier_data, string))

        parsed = parse_irc_privmsg(string.decode('utf-8'))
        debug(('parsed message', parsed))

        # skip processing messages to public channels
        if parsed['to_channel']:
            return string

        server = modifier_data.decode('utf-8')

        to_user = irc_user(parsed['to_nick'], server)
        local_user = current_user(server)

        context = ACCOUNTS[local_user].getContext(to_user)

        if parsed['text'].startswith(potr.proto.OTRTAG) and \
                not OTR_QUERY_RE.match(parsed['text']):
            if not has_otr_end(parsed['text']):
                debug('in OTR message')
                context.in_otr_message = True
            else:
                debug('complete OTR message')
            result = string
        elif context.in_otr_message:
            if has_otr_end(parsed['text']):
                context.in_otr_message = False
                debug('in OTR message end')
            result = string
        else:
            debug(('context send message', parsed['text'], parsed['to_nick'],
                   server))

            try:
                ret = context.sendMessage(
                    potr.context.FRAGMENT_SEND_ALL, parsed['text'].encode(
                        'utf-8'))

                if ret:
                    debug(('sendMessage returned', ret))
                    result = ('PRIVMSG %s :%s' % (
                            parsed['to_nick'], ret.decode('utf-8'))).encode(
                        'utf-8')
            except potr.context.NotEncryptedError, err:
                if err.args[0] == potr.context.EXC_FINISHED:
                    context.print_buffer(
                        """Your message was not sent. End your private conversation:\n/otr finish %s %s""" % (
                            parsed['to_nick'], server))
                else:
                    raise

        weechat.bar_item_update(SCRIPT_NAME)
    except:
        try:
            prnt('', traceback.format_exc())
            context.print_buffer(
                'Failed to send message. See core buffer for traceback.')
        except:
            pass

    return result

def shutdown():
    """Script unload callback."""
    debug('shutdown')

    weechat.config_write(CONFIG_FILE)

    for account in ACCOUNTS.itervalues():
        account.end_all_private()

    free_all_config()

    weechat.bar_item_remove(OTR_STATUSBAR)

    return weechat.WEECHAT_RC_OK

def command_cb(data, buf, args):
    """Parse and dispatch WeeChat OTR commands."""
    result = weechat.WEECHAT_RC_ERROR

    arg_parts = args.split(None, 5)

    if arg_parts[0] == 'start':
        nick, server = default_peer_args(arg_parts[1:3])

        if nick is not None and server is not None:
            context = ACCOUNTS[current_user(server)].getContext(
                irc_user(nick, server))

            context.print_buffer('Sending OTR query...')
            context.print_buffer(
                'To try OTR on all conversations with %s: /otr policy send_tag on' %
                context.peer)

            privmsg(server, nick, '?OTR?')

            result = weechat.WEECHAT_RC_OK
    elif arg_parts[0] == 'finish':
        nick, server = default_peer_args(arg_parts[1:3])

        if nick is not None and server is not None:
            context = ACCOUNTS[current_user(server)].getContext(
                irc_user(nick, server))
            context.disconnect()

            result = weechat.WEECHAT_RC_OK
    elif len(arg_parts) in (5, 6) and arg_parts[0] == 'smp':
        action = arg_parts[1]

        if action == 'respond':
            nick, server = arg_parts[2:4]
            secret = args.split(None, 4)[-1]

            context = ACCOUNTS[current_user(server)].getContext(
                irc_user(nick, server))
            context.smpGotSecret(secret)

            result = weechat.WEECHAT_RC_OK
        elif action == 'ask':
            nick, server, secret = arg_parts[2:5]

            if len(arg_parts) > 5:
                question = arg_parts[5]
            else:
                question = None

            context = ACCOUNTS[current_user(server)].getContext(
                irc_user(nick, server))

            context.smpInit(secret, question)

            result = weechat.WEECHAT_RC_OK
    elif arg_parts[0] == 'trust':
        nick, server = default_peer_args(arg_parts[1:3])

        if nick is not None and server is not None:
            context = ACCOUNTS[current_user(server)].getContext(
                irc_user(nick, server))

            if context.crypto.theirPubkey is not None:
                context.setCurrentTrust('verified')
                context.print_buffer('%s is now authenticated.' % context.peer)

                weechat.bar_item_update(SCRIPT_NAME)
            else:
                context.print_buffer(
                    'No fingerprint for %s. Start an OTR conversation first: /otr start' \
                        % context.peer)

            result = weechat.WEECHAT_RC_OK
    elif arg_parts[0] == 'policy':
        if len(arg_parts) == 1:
            nick, server = default_peer_args([])

            if nick is not None and server is not None:
                context = ACCOUNTS[current_user(server)].getContext(
                    irc_user(nick, server))

                context.print_buffer(context.format_policies())

                result = weechat.WEECHAT_RC_OK
        elif len(arg_parts) == 3 and arg_parts[1].lower() in POLICIES:
            nick, server = default_peer_args([])

            if nick is not None and server is not None:
                context = ACCOUNTS[current_user(server)].getContext(
                    irc_user(nick, server))

                policy_var = context.policy_config_option(arg_parts[1].lower())

                command('', '/set %s %s' % (policy_var, arg_parts[2]))

                context.print_buffer(context.format_policies())
                
                result = weechat.WEECHAT_RC_OK

    return result

def otr_statusbar_cb(data, item, window):
    """Update the statusbar."""
    buf = weechat.window_get_pointer(window, 'buffer')

    result = ''

    if buffer_is_private(buf):
        local_user = irc_user(
            buffer_get_string(buf, 'localvar_nick'),
            buffer_get_string(buf, 'localvar_server'))

        remote_user = irc_user(
            buffer_get_string(buf, 'localvar_channel'),
            buffer_get_string(buf, 'localvar_server'))

        context = ACCOUNTS[local_user].getContext(remote_user)

        encrypted_str = config_string('look.bar.state.encrypted')
        unencrypted_str = config_string('look.bar.state.unencrypted')
        authenticated_str = config_string('look.bar.state.authenticated')
        unauthenticated_str = config_string('look.bar.state.unauthenticated')
        logged_str = config_string('look.bar.state.logged')
        notlogged_str = config_string('look.bar.state.notlogged')

        bar_parts = []

        if context.is_encrypted():
            if encrypted_str:
                bar_parts.append(''.join([
                            config_color('status.encrypted'),
                            encrypted_str,
                            config_color('status.default')]))

            if context.is_verified():
                if authenticated_str:
                    bar_parts.append(''.join([
                                config_color('status.authenticated'),
                                authenticated_str,
                                config_color('status.default')]))
            elif unauthenticated_str:
                bar_parts.append(''.join([
                            config_color('status.unauthenticated'),
                            unauthenticated_str,
                            config_color('status.default')]))

            if context.is_logged():
                if logged_str:
                    bar_parts.append(''.join([
                                config_color('status.logged'),
                                logged_str,
                                config_color('status.default')]))
            elif notlogged_str:
                bar_parts.append(''.join([
                            config_color('status.notlogged'),
                            notlogged_str,
                            config_color('status.default')]))

        elif unencrypted_str:
            bar_parts.append(''.join([
                        config_color('status.unencrypted'),
                        unencrypted_str,
                        config_color('status.default')]))

        result = config_string('look.bar.state.separator').join(bar_parts)

        if result:
            result = '%s%s%s' % (
                config_color('status.default'),
                config_string('look.bar.prefix'), result)

    return result

def bar_config_update_cb(data, option):
    """Callback for updating the status bar when its config changes."""
    weechat.bar_item_update(SCRIPT_NAME)

    return weechat.WEECHAT_RC_OK

def policy_completion_cb(data, completion_item, buf, completion):
    """Callback for policy tab completion."""
    for policy in POLICIES:
        weechat.hook_completion_list_add(
            completion, policy, 0, weechat.WEECHAT_LIST_POS_SORT)

    return weechat.WEECHAT_RC_OK

def policy_create_option_cb(data, config_file, section, name, value):
    """Callback for creating a new policy option when the user sets one
    that doesn't exist."""
    weechat.config_new_option(
        config_file, section, name, 'boolean', '', '', 0, 0, value, value, 0,
        '', '', '', '', '', '')

    return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED

def logger_level_update_cb(data, option, value):
    """Callback called when any logger level changes."""
    weechat.bar_item_update(SCRIPT_NAME)

    return weechat.WEECHAT_RC_OK

def init_config():
    """Set up configuration options and load config file."""
    global CONFIG_FILE
    CONFIG_FILE = weechat.config_new(SCRIPT_NAME, 'config_reload_cb', '')

    global CONFIG_SECTIONS
    CONFIG_SECTIONS = {}

    CONFIG_SECTIONS['general'] = weechat.config_new_section(
        CONFIG_FILE, 'general', 0, 0, '', '', '', '', '', '', '', '', '', '')

    for option, typ, desc, default in [
        ('debug', 'boolean', 'OTR script debugging', 'off'),
        ]:
        weechat.config_new_option(
            CONFIG_FILE, CONFIG_SECTIONS['general'], option, typ, desc, '', 0,
            0, default, default, 0, '', '', '', '', '', '')

    CONFIG_SECTIONS['color'] = weechat.config_new_section(
        CONFIG_FILE, 'color', 0, 0, '', '', '', '', '', '', '', '', '', '')

    for option, desc, default, update_cb in [
        ('status.default', 'status bar default color', 'default',
         'bar_config_update_cb'),
        ('status.encrypted', 'status bar encrypted indicator color', 'green',
         'bar_config_update_cb'),
        ('status.unencrypted', 'status bar unencrypted indicator color',
         'lightred', 'bar_config_update_cb'),
        ('status.authenticated', 'status bar authenticated indicator color',
         'green', 'bar_config_update_cb'),
        ('status.unauthenticated', 'status bar unauthenticated indicator color',
         'lightred', 'bar_config_update_cb'),
        ('status.logged', 'status bar logged indicator color', 'lightred',
         'bar_config_update_cb'),
        ('status.notlogged', 'status bar not logged indicator color',
         'green', 'bar_config_update_cb'),
        ]:
        weechat.config_new_option(
            CONFIG_FILE, CONFIG_SECTIONS['color'], option, 'color', desc, '', 0,
            0, default, default, 0, '', '', update_cb, '', '', '')

    CONFIG_SECTIONS['look'] = weechat.config_new_section(
        CONFIG_FILE, 'look', 0, 0, '', '', '', '', '', '', '', '', '', '')

    for option, desc, default, update_cb in [
        ('bar.prefix', 'prefix for OTR status bar item', 'OTR:',
         'bar_config_update_cb'),
        ('bar.state.encrypted',
         'shown in status bar when conversation is encrypted', 'SEC',
         'bar_config_update_cb'),
        ('bar.state.unencrypted',
         'shown in status bar when conversation is not encrypted', '!SEC',
         'bar_config_update_cb'),
        ('bar.state.authenticated',
         'shown in status bar when peer is authenticated', 'AUTH',
         'bar_config_update_cb'),
        ('bar.state.unauthenticated',
         'shown in status bar when peer is not authenticated', '!AUTH',
         'bar_config_update_cb'),
        ('bar.state.logged',
         'shown in status bar when peer conversation is being logged to disk',
         'LOG',
         'bar_config_update_cb'),
        ('bar.state.notlogged',
         'shown in status bar when peer conversation is not being logged to disk',
         '!LOG',
         'bar_config_update_cb'),
        ('bar.state.separator', 'separator for states in the status bar', ',',
         'bar_config_update_cb'),
        ]:
        weechat.config_new_option(
            CONFIG_FILE, CONFIG_SECTIONS['look'], option, 'string', desc, '',
            0, 0, default, default, 0, '', '', update_cb, '', '', '')

    CONFIG_SECTIONS['policy'] = weechat.config_new_section(
        CONFIG_FILE, 'policy', 1, 1, '', '', '', '', '', '',
        'policy_create_option_cb', '', '', '')

    for option, desc, default in [
        ('default.allow_v1', 'default allow OTR v1 policy', 'off'),
        ('default.allow_v2', 'default allow OTR v2 policy', 'on'),
        ('default.require_encryption', 'default require encryption policy',
         'off'),
        ('default.send_tag', 'default send tag policy', 'off'),
        ]:
        weechat.config_new_option(
            CONFIG_FILE, CONFIG_SECTIONS['policy'], option, 'boolean', desc, '',
            0, 0, default, default, 0, '', '', '', '', '', '')

    weechat.config_read(CONFIG_FILE)

def config_reload_cb(data, config_file):
    """/reload callback to reload config from file."""
    free_all_config()
    init_config()

    return weechat.WEECHAT_CONFIG_READ_OK

def free_all_config():
    """Free all config options, sections and config file."""
    for section in CONFIG_SECTIONS.itervalues():
        weechat.config_section_free_options(section)
        weechat.config_section_free(section)

    weechat.config_free(CONFIG_FILE)

def create_dir():
    """Create the OTR subdirectory in the WeeChat config directory if it does
    not exist."""
    if not os.path.exists(OTR_DIR):
        weechat.mkdir_home(OTR_DIR_NAME, 0700)

if weechat.register(
    SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENCE, SCRIPT_DESC,
    'shutdown', ''):
    init_config()

    OTR_DIR = os.path.join(info_get('weechat_dir', ''), OTR_DIR_NAME)
    create_dir()

    ACCOUNTS = AccountDict()

    weechat.hook_modifier('irc_in_privmsg', 'message_in_cb', '')
    weechat.hook_modifier('irc_out_privmsg', 'message_out_cb', '')

    weechat.hook_command(
        SCRIPT_NAME, SCRIPT_HELP,
        'start [NICK SERVER] || '
        'finish [NICK SERVER] || '
        'smp ask NICK SERVER SECRET [QUESTION] || '
        'smp respond NICK SERVER SECRET || '
        'trust [NICK SERVER] || '
        'policy [POLICY on|off]',
        '',
        'start %(nick) %(irc_servers) %-||'
        'finish %(nick) %(irc_servers) %-||'
        'smp ask|respond %(nick) %(irc_servers) %-||'
        'trust %(nick) %(irc_servers) %-||'
        'policy %(otr_policy) on|off %-||',
        'command_cb',
        '')

    weechat.hook_completion(
        'otr_policy', 'OTR policies', 'policy_completion_cb', '')

    weechat.hook_config('logger.level.irc.*', 'logger_level_update_cb', '')

    OTR_STATUSBAR = weechat.bar_item_new(SCRIPT_NAME, 'otr_statusbar_cb', '')
    weechat.bar_item_update(SCRIPT_NAME)