source: otr.c @ 090c9b7

Last change on this file since 090c9b7 was 090c9b7, checked in by unknown <pesco@…>, at 2013-08-01T20:39:49Z

implement handle_msg_event

  • Property mode set to 100644
File size: 50.7 KB
Line 
1  /********************************************************************\
2  * BitlBee -- An IRC to other IM-networks gateway                     *
3  *                                                                    *
4  * Copyright 2002-2012 Wilmer van der Gaast and others                *
5  \********************************************************************/
6
7/*
8  OTR support (cf. http://www.cypherpunks.ca/otr/)
9 
10  (c) 2008-2011,2013 Sven Moritz Hallberg <pesco@khjk.org>
11  funded by stonedcoder.org
12   
13  files used to store OTR data:
14    <configdir>/<nick>.otr_keys
15    <configdir>/<nick>.otr_fprints
16   
17  top-level todos: (search for TODO for more ;-))
18    integrate otr_load/otr_save with existing storage backends
19    per-account policy settings
20    per-user policy settings
21*/
22
23/*
24  This program is free software; you can redistribute it and/or modify
25  it under the terms of the GNU General Public License as published by
26  the Free Software Foundation; either version 2 of the License, or
27  (at your option) any later version.
28
29  This program is distributed in the hope that it will be useful,
30  but WITHOUT ANY WARRANTY; without even the implied warranty of
31  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32  GNU General Public License for more details.
33
34  You should have received a copy of the GNU General Public License with
35  the Debian GNU/Linux distribution in /usr/share/common-licenses/GPL;
36  if not, write to the Free Software Foundation, Inc., 59 Temple Place,
37  Suite 330, Boston, MA  02111-1307  USA
38*/
39
40#include "bitlbee.h"
41#include "irc.h"
42#include "otr.h"
43#include <sys/types.h>
44#include <sys/wait.h>
45#include <unistd.h>
46#include <assert.h>
47#include <signal.h>
48
49
50/** OTR interface routines for the OtrlMessageAppOps struct: **/
51
52OtrlPolicy op_policy(void *opdata, ConnContext *context);
53
54void op_create_privkey(void *opdata, const char *accountname, const char *protocol);
55
56int op_is_logged_in(void *opdata, const char *accountname, const char *protocol,
57        const char *recipient);
58
59void op_inject_message(void *opdata, const char *accountname, const char *protocol,
60        const char *recipient, const char *message);
61
62void op_new_fingerprint(void *opdata, OtrlUserState us, const char *accountname,
63        const char *protocol, const char *username, unsigned char fingerprint[20]);
64
65void op_write_fingerprints(void *opdata);
66
67void op_gone_secure(void *opdata, ConnContext *context);
68
69void op_gone_insecure(void *opdata, ConnContext *context);
70
71void op_still_secure(void *opdata, ConnContext *context, int is_reply);
72
73void op_log_message(void *opdata, const char *message);
74
75int op_max_message_size(void *opdata, ConnContext *context);
76
77const char *op_account_name(void *opdata, const char *account, const char *protocol);
78
79void op_convert_msg(void *opdata, ConnContext *ctx, OtrlConvertType typ,
80        char **dst, const char *src);
81void op_convert_free(void *opdata, ConnContext *ctx, char *msg);
82
83void op_handle_smp_event(void *opdata, OtrlSMPEvent ev, ConnContext *ctx,
84        unsigned short percent, char *question);
85
86void op_handle_msg_event(void *opdata, OtrlMessageEvent ev, ConnContext *ctx,
87        const char *message, gcry_error_t err);
88
89/** otr sub-command handlers: **/
90
91static void cmd_otr(irc_t *irc, char **args);
92void cmd_otr_connect(irc_t *irc, char **args);
93void cmd_otr_disconnect(irc_t *irc, char **args);
94void cmd_otr_reconnect(irc_t *irc, char **args);
95void cmd_otr_smp(irc_t *irc, char **args);
96void cmd_otr_smpq(irc_t *irc, char **args);
97void cmd_otr_trust(irc_t *irc, char **args);
98void cmd_otr_info(irc_t *irc, char **args);
99void cmd_otr_keygen(irc_t *irc, char **args);
100void cmd_otr_forget(irc_t *irc, char **args);
101
102const command_t otr_commands[] = {
103        { "connect",     1, &cmd_otr_connect,    0 },
104        { "disconnect",  1, &cmd_otr_disconnect, 0 },
105        { "reconnect",   1, &cmd_otr_reconnect,  0 },
106        { "smp",         2, &cmd_otr_smp,        0 },
107        { "smpq",        3, &cmd_otr_smpq,       0 },
108        { "trust",       6, &cmd_otr_trust,      0 },
109        { "info",        0, &cmd_otr_info,       0 },
110        { "keygen",      1, &cmd_otr_keygen,     0 },
111        { "forget",      2, &cmd_otr_forget,     0 },
112        { NULL }
113};
114
115typedef struct {
116        void *fst;
117        void *snd;
118} pair_t;       
119
120static OtrlMessageAppOps otr_ops;   /* collects interface functions required by OTR */
121
122
123/** misc. helpers/subroutines: **/
124
125/* check whether we are already generating a key for a given account */
126int keygen_in_progress(irc_t *irc, const char *handle, const char *protocol);
127
128/* start background process to generate a (new) key for a given account */
129void otr_keygen(irc_t *irc, const char *handle, const char *protocol);
130
131/* main function for the forked keygen slave */
132void keygen_child_main(OtrlUserState us, int infd, int outfd);
133
134/* mainloop handler for when a keygen finishes */
135gboolean keygen_finish_handler(gpointer data, gint fd, b_input_condition cond);
136
137/* copy the contents of file a to file b, overwriting it if it exists */
138void copyfile(const char *a, const char *b);
139
140/* read one line of input from a stream, excluding trailing newline */
141void myfgets(char *s, int size, FILE *stream);
142
143/* some yes/no handlers */
144void yes_keygen(void *data);
145void yes_forget_fingerprint(void *data);
146void yes_forget_context(void *data);
147void yes_forget_key(void *data);
148
149/* helper to make sure accountname and protocol match the incoming "opdata" */
150struct im_connection *check_imc(void *opdata, const char *accountname,
151        const char *protocol);
152
153/* determine the nick for a given handle/protocol pair
154   returns "handle/protocol" if not found */
155const char *peernick(irc_t *irc, const char *handle, const char *protocol);
156
157/* turn a hexadecimal digit into its numerical value */
158int hexval(char a);
159
160/* determine the irc_user_t for a given handle/protocol pair
161   returns NULL if not found */
162irc_user_t *peeruser(irc_t *irc, const char *handle, const char *protocol);
163
164/* show an otr-related message to the user */
165void display_otr_message(void *opdata, ConnContext *ctx, const char *fmt, ...);
166
167/* write an otr-related message to the system log */
168void log_otr_message(void *opdata, const char *fmt, ...);
169
170/* combined handler for the 'otr smp' and 'otr smpq' commands */
171void otr_smp_or_smpq(irc_t *irc, const char *nick, const char *question,
172                const char *secret);
173
174/* update flags within the irc_user structure to reflect OTR status of context */
175void otr_update_uflags(ConnContext *context, irc_user_t *u);
176
177/* update op/voice flag of given user according to encryption state and settings
178   returns 0 if neither op_buddies nor voice_buddies is set to "encrypted",
179   i.e. msgstate should be announced seperately */
180int otr_update_modeflags(irc_t *irc, irc_user_t *u);
181
182/* show general info about the OTR subsystem; called by 'otr info' */
183void show_general_otr_info(irc_t *irc);
184
185/* show info about a given OTR context */
186void show_otr_context_info(irc_t *irc, ConnContext *ctx);
187
188/* show the list of fingerprints associated with a given context */
189void show_fingerprints(irc_t *irc, ConnContext *ctx);
190
191/* find a fingerprint by prefix (given as any number of hex strings) */
192Fingerprint *match_fingerprint(irc_t *irc, ConnContext *ctx, const char **args);
193
194/* find a private key by fingerprint prefix (given as any number of hex strings) */
195OtrlPrivKey *match_privkey(irc_t *irc, const char **args);
196
197/* check whether a string is safe to use in a path component */
198int strsane(const char *s);
199
200/* functions to be called for certain events */
201static const struct irc_plugin otr_plugin;
202
203
204/*** routines declared in otr.h: ***/
205
206#ifdef OTR_BI
207#define init_plugin otr_init
208#endif
209
210void init_plugin(void)
211{
212        OTRL_INIT;
213       
214        /* fill global OtrlMessageAppOps */
215        otr_ops.policy = &op_policy;
216        otr_ops.create_privkey = &op_create_privkey;
217        otr_ops.is_logged_in = &op_is_logged_in;
218        otr_ops.inject_message = &op_inject_message;
219        otr_ops.update_context_list = NULL;
220        otr_ops.new_fingerprint = &op_new_fingerprint;
221        otr_ops.write_fingerprints = &op_write_fingerprints;
222        otr_ops.gone_secure = &op_gone_secure;
223        otr_ops.gone_insecure = &op_gone_insecure;
224        otr_ops.still_secure = &op_still_secure;
225        otr_ops.max_message_size = &op_max_message_size;
226        otr_ops.account_name = &op_account_name;
227        otr_ops.account_name_free = NULL;
228
229        /* stuff added with libotr 4.0.0 */
230        otr_ops.received_symkey = NULL;         /* we don't use the extra key */
231        otr_ops.otr_error_message = NULL;       // TODO?
232        otr_ops.otr_error_message_free = NULL;
233        otr_ops.resent_msg_prefix = NULL;       // don't need?
234        otr_ops.resent_msg_prefix_free = NULL;
235        otr_ops.handle_smp_event = &op_handle_smp_event;
236        otr_ops.handle_msg_event = &op_handle_msg_event;
237        otr_ops.create_instag = NULL;    // XXX
238        otr_ops.convert_msg = &op_convert_msg;
239        otr_ops.convert_free = &op_convert_free;
240        otr_ops.timer_control = NULL;    // XXX call otrl_message_poll reg'ly
241               
242        root_command_add( "otr", 1, cmd_otr, 0 );
243        register_irc_plugin( &otr_plugin );
244}
245
246gboolean otr_irc_new(irc_t *irc)
247{
248        set_t *s;
249        GSList *l;
250       
251        irc->otr = g_new0(otr_t, 1);
252        irc->otr->us = otrl_userstate_create();
253       
254        s = set_add( &irc->b->set, "otr_color_encrypted", "true", set_eval_bool, irc );
255       
256        s = set_add( &irc->b->set, "otr_policy", "opportunistic", set_eval_list, irc );
257        l = g_slist_prepend( NULL, "never" );
258        l = g_slist_prepend( l, "opportunistic" );
259        l = g_slist_prepend( l, "manual" );
260        l = g_slist_prepend( l, "always" );
261        s->eval_data = l;
262
263        s = set_add( &irc->b->set, "otr_does_html", "true", set_eval_bool, irc );
264       
265        return TRUE;
266}
267
268void otr_irc_free(irc_t *irc)
269{
270        otr_t *otr = irc->otr;
271        otrl_userstate_free(otr->us);
272        if(otr->keygen) {
273                kill(otr->keygen, SIGTERM);
274                waitpid(otr->keygen, NULL, 0);
275                /* TODO: remove stale keygen tempfiles */
276        }
277        if(otr->to)
278                fclose(otr->to);
279        if(otr->from)
280                fclose(otr->from);
281        while(otr->todo) {
282                kg_t *p = otr->todo;
283                otr->todo = p->next;
284                g_free(p);
285        }
286        g_free(otr);
287}
288
289void otr_load(irc_t *irc)
290{
291        char s[512];
292        account_t *a;
293        gcry_error_t e;
294        gcry_error_t enoent = gcry_error_from_errno(ENOENT);
295        int kg=0;
296
297        if(strsane(irc->user->nick)) {
298                g_snprintf(s, 511, "%s%s.otr_keys", global.conf->configdir, irc->user->nick);
299                e = otrl_privkey_read(irc->otr->us, s);
300                if(e && e!=enoent) {
301                        irc_rootmsg(irc, "otr load: %s: %s", s, gcry_strerror(e));
302                }
303                g_snprintf(s, 511, "%s%s.otr_fprints", global.conf->configdir, irc->user->nick);
304                e = otrl_privkey_read_fingerprints(irc->otr->us, s, NULL, NULL);
305                if(e && e!=enoent) {
306                        irc_rootmsg(irc, "otr load: %s: %s", s, gcry_strerror(e));
307                }
308        }
309       
310        /* check for otr keys on all accounts */
311        for(a=irc->b->accounts; a; a=a->next) {
312                kg = otr_check_for_key(a) || kg;
313        }
314        if(kg) {
315                irc_rootmsg(irc, "Notice: "
316                        "The accounts above do not have OTR encryption keys associated with them, yet. "
317                        "These keys are now being generated in the background. "
318                        "You will be notified as they are completed. "
319                        "It is not necessary to wait; "
320                        "BitlBee can be used normally during key generation. "
321                        "You may safely ignore this message if you don't know what OTR is. ;)");
322        }
323}
324
325void otr_save(irc_t *irc)
326{
327        char s[512];
328        gcry_error_t e;
329
330        if(strsane(irc->user->nick)) {
331                g_snprintf(s, 511, "%s%s.otr_fprints", global.conf->configdir, irc->user->nick);
332                e = otrl_privkey_write_fingerprints(irc->otr->us, s);
333                if(e) {
334                        irc_rootmsg(irc, "otr save: %s: %s", s, gcry_strerror(e));
335                }
336                chmod(s, 0600);
337        }
338}
339
340void otr_remove(const char *nick)
341{
342        char s[512];
343       
344        if(strsane(nick)) {
345                g_snprintf(s, 511, "%s%s.otr_keys", global.conf->configdir, nick);
346                unlink(s);
347                g_snprintf(s, 511, "%s%s.otr_fprints", global.conf->configdir, nick);
348                unlink(s);
349        }
350}
351
352void otr_rename(const char *onick, const char *nnick)
353{
354        char s[512], t[512];
355       
356        if(strsane(nnick) && strsane(onick)) {
357                g_snprintf(s, 511, "%s%s.otr_keys", global.conf->configdir, onick);
358                g_snprintf(t, 511, "%s%s.otr_keys", global.conf->configdir, nnick);
359                rename(s,t);
360                g_snprintf(s, 511, "%s%s.otr_fprints", global.conf->configdir, onick);
361                g_snprintf(t, 511, "%s%s.otr_fprints", global.conf->configdir, nnick);
362                rename(s,t);
363        }
364}
365
366int otr_check_for_key(account_t *a)
367{
368        irc_t *irc = a->bee->ui_data;
369        OtrlPrivKey *k;
370       
371        /* don't do OTR on certain (not classic IM) protocols, e.g. twitter */
372        if(a->prpl->options & OPT_NOOTR) {
373                return 0;
374        }
375       
376        k = otrl_privkey_find(irc->otr->us, a->user, a->prpl->name);
377        if(k) {
378                irc_rootmsg(irc, "otr: %s/%s ready", a->user, a->prpl->name);
379                return 0;
380        } if(keygen_in_progress(irc, a->user, a->prpl->name)) {
381                irc_rootmsg(irc, "otr: keygen for %s/%s already in progress", a->user, a->prpl->name);
382                return 0;
383        } else {
384                irc_rootmsg(irc, "otr: starting background keygen for %s/%s", a->user, a->prpl->name);
385                otr_keygen(irc, a->user, a->prpl->name);
386                return 1;
387        }
388}
389
390char *otr_filter_msg_in(irc_user_t *iu, char *msg, int flags)
391{
392        int ignore_msg;
393        char *newmsg = NULL;
394        OtrlTLV *tlvs = NULL;
395        irc_t *irc = iu->irc;
396        struct im_connection *ic = iu->bu->ic;
397       
398        /* don't do OTR on certain (not classic IM) protocols, e.g. twitter */
399        if(ic->acc->prpl->options & OPT_NOOTR) {
400                return msg;
401        }
402       
403        ignore_msg = otrl_message_receiving(irc->otr->us, &otr_ops, ic,
404                ic->acc->user, ic->acc->prpl->name, iu->bu->handle, msg, &newmsg,
405                &tlvs, NULL, NULL, NULL);
406
407        if(ignore_msg) {
408                /* this was an internal OTR protocol message */
409                return NULL;
410        } else if(!newmsg) {
411                /* this was a non-OTR message */
412                return msg;
413        } else {
414                /* we're done with the original msg, which will be caller-freed. */
415                return newmsg;
416        }
417}
418
419char *otr_filter_msg_out(irc_user_t *iu, char *msg, int flags)
420{       
421        int st;
422        char *otrmsg = NULL;
423        char *emsg = msg;           /* the message as we hand it to libotr */
424        ConnContext *ctx = NULL;
425        irc_t *irc = iu->irc;
426        struct im_connection *ic = iu->bu->ic;
427        otrl_instag_t instag = OTRL_INSTAG_MASTER; // XXX?
428
429        /* don't do OTR on certain (not classic IM) protocols, e.g. twitter */
430        if(ic->acc->prpl->options & OPT_NOOTR) {
431                return msg;
432        }
433
434        st = otrl_message_sending(irc->otr->us, &otr_ops, ic,
435                ic->acc->user, ic->acc->prpl->name, iu->bu->handle, instag,
436                emsg, NULL, &otrmsg, OTRL_FRAGMENT_SEND_ALL, &ctx, NULL, NULL);
437
438        if(emsg != msg) {
439                g_free(emsg);   /* we're done with this one */
440        }
441        if(otrmsg) {
442                /* Is this ever reached!? */
443                ic->acc->prpl->buddy_msg(ic, iu->bu->handle, otrmsg, 0);
444        }
445        if(st) {
446                /* TODO: Error reporting? */
447        }
448       
449        return NULL;
450}
451
452static const struct irc_plugin otr_plugin =
453{
454        otr_irc_new,
455        otr_irc_free,
456        otr_filter_msg_out,
457        otr_filter_msg_in,
458        otr_load,
459        otr_save,
460        otr_remove,
461};
462
463static void cmd_otr(irc_t *irc, char **args)
464{
465        const command_t *cmd;
466       
467        if(!args[0])
468                return;
469       
470        if(!args[1])
471                return;
472       
473        for(cmd=otr_commands; cmd->command; cmd++) {
474                if(strcmp(cmd->command, args[1]) == 0)
475                        break;
476        }
477       
478        if(!cmd->command) {
479                irc_rootmsg(irc, "%s: unknown subcommand \"%s\", see \x02help otr\x02",
480                        args[0], args[1]);
481                return;
482        }
483       
484        if(!args[cmd->required_parameters+1]) {
485                irc_rootmsg(irc, "%s %s: not enough arguments (%d req.)",
486                        args[0], args[1], cmd->required_parameters);
487                return;
488        }
489       
490        cmd->execute(irc, args+1);
491}
492
493
494/*** OTR "MessageAppOps" callbacks for global.otr_ui: ***/
495
496OtrlPolicy op_policy(void *opdata, ConnContext *context)
497{
498        struct im_connection *ic = check_imc(opdata, context->accountname, context->protocol);
499        irc_t *irc = ic->bee->ui_data;
500        const char *p;
501       
502        /* policy override during keygen: if we're missing the key for context but are currently
503           generating it, then that's as much as we can do. => temporarily return NEVER. */
504        if(keygen_in_progress(irc, context->accountname, context->protocol) &&
505           !otrl_privkey_find(irc->otr->us, context->accountname, context->protocol))
506                return OTRL_POLICY_NEVER;
507
508        p = set_getstr(&ic->bee->set, "otr_policy");
509        if(!strcmp(p, "never"))
510                return OTRL_POLICY_NEVER;
511        if(!strcmp(p, "opportunistic"))
512                return OTRL_POLICY_OPPORTUNISTIC;
513        if(!strcmp(p, "manual"))
514                return OTRL_POLICY_MANUAL;
515        if(!strcmp(p, "always"))
516                return OTRL_POLICY_ALWAYS;
517       
518        return OTRL_POLICY_OPPORTUNISTIC;
519}
520
521void op_create_privkey(void *opdata, const char *accountname,
522        const char *protocol)
523{
524        struct im_connection *ic = check_imc(opdata, accountname, protocol);
525        irc_t *irc = ic->bee->ui_data;
526       
527        /* will fail silently if keygen already in progress */
528        otr_keygen(irc, accountname, protocol);
529}
530
531int op_is_logged_in(void *opdata, const char *accountname,
532        const char *protocol, const char *recipient)
533{
534        struct im_connection *ic = check_imc(opdata, accountname, protocol);
535        bee_user_t *bu;
536
537        /* lookup the irc_user_t for the given recipient */
538        bu = bee_user_by_handle(ic->bee, ic, recipient);
539        if(bu) {
540                if(bu->flags & BEE_USER_ONLINE)
541                        return 1;
542                else
543                        return 0;
544        } else {
545                return -1;
546        }
547}
548
549void op_inject_message(void *opdata, const char *accountname,
550        const char *protocol, const char *recipient, const char *message)
551{
552        struct im_connection *ic = check_imc(opdata, accountname, protocol);
553        irc_t *irc = ic->bee->ui_data;
554
555        if (strcmp(accountname, recipient) == 0) {
556                /* huh? injecting messages to myself? */
557                irc_rootmsg(irc, "note to self: %s", message);
558        } else {
559                /* need to drop some consts here :-( */
560                /* TODO: get flags into op_inject_message?! */
561                ic->acc->prpl->buddy_msg(ic, (char *)recipient, (char *)message, 0);
562                /* ignoring return value :-/ */
563        }
564}
565
566void op_new_fingerprint(void *opdata, OtrlUserState us,
567        const char *accountname, const char *protocol,
568        const char *username, unsigned char fingerprint[20])
569{
570        struct im_connection *ic = check_imc(opdata, accountname, protocol);
571        irc_t *irc = ic->bee->ui_data;
572        irc_user_t *u = peeruser(irc, username, protocol);
573        char hunam[45];         /* anybody looking? ;-) */
574       
575        otrl_privkey_hash_to_human(hunam, fingerprint);
576        if(u) {
577                irc_usernotice(u, "new fingerprint: %s", hunam);
578        } else {
579                /* this case shouldn't normally happen */
580                irc_rootmsg(irc, "new fingerprint for %s/%s: %s",
581                        username, protocol, hunam);
582        }
583}
584
585void op_write_fingerprints(void *opdata)
586{
587        struct im_connection *ic = (struct im_connection *)opdata;
588        irc_t *irc = ic->bee->ui_data;
589
590        otr_save(irc);
591}
592
593void op_gone_secure(void *opdata, ConnContext *context)
594{
595        struct im_connection *ic =
596                check_imc(opdata, context->accountname, context->protocol);
597        irc_user_t *u;
598        irc_t *irc = ic->bee->ui_data;
599
600        u = peeruser(irc, context->username, context->protocol);
601        if(!u) {
602                log_message(LOGLVL_ERROR,
603                        "BUG: otr.c: op_gone_secure: irc_user_t for %s/%s/%s not found!",
604                        context->username, context->protocol, context->accountname);
605                return;
606        }
607       
608        otr_update_uflags(context, u);
609        if(!otr_update_modeflags(irc, u)) {
610                char *trust = u->flags & IRC_USER_OTR_TRUSTED ? "trusted" : "untrusted!";
611                irc_usernotice(u, "conversation is now off the record (%s)", trust);
612        }
613}
614
615void op_gone_insecure(void *opdata, ConnContext *context)
616{
617        struct im_connection *ic =
618                check_imc(opdata, context->accountname, context->protocol);
619        irc_t *irc = ic->bee->ui_data;
620        irc_user_t *u;
621
622        u = peeruser(irc, context->username, context->protocol);
623        if(!u) {
624                log_message(LOGLVL_ERROR,
625                        "BUG: otr.c: op_gone_insecure: irc_user_t for %s/%s/%s not found!",
626                        context->username, context->protocol, context->accountname);
627                return;
628        }
629        otr_update_uflags(context, u);
630        if(!otr_update_modeflags(irc, u))
631                irc_usernotice(u, "conversation is now in cleartext");
632}
633
634void op_still_secure(void *opdata, ConnContext *context, int is_reply)
635{
636        struct im_connection *ic =
637                check_imc(opdata, context->accountname, context->protocol);
638        irc_t *irc = ic->bee->ui_data;
639        irc_user_t *u;
640
641        u = peeruser(irc, context->username, context->protocol);
642        if(!u) {
643                log_message(LOGLVL_ERROR,
644                        "BUG: otr.c: op_still_secure: irc_user_t for %s/%s/%s not found!",
645                        context->username, context->protocol, context->accountname);
646                return;
647        }
648
649        otr_update_uflags(context, u);
650        if(!otr_update_modeflags(irc, u)) {
651                char *trust = u->flags & IRC_USER_OTR_TRUSTED ? "trusted" : "untrusted!";
652                irc_usernotice(u, "otr connection has been refreshed (%s)", trust);
653        }
654}
655
656int op_max_message_size(void *opdata, ConnContext *context)
657{
658        struct im_connection *ic =
659                check_imc(opdata, context->accountname, context->protocol);
660
661        return ic->acc->prpl->mms;
662}
663
664const char *op_account_name(void *opdata, const char *account, const char *protocol)
665{
666        struct im_connection *ic = (struct im_connection *)opdata;
667        irc_t *irc = ic->bee->ui_data;
668
669        return peernick(irc, account, protocol);
670}
671
672void op_convert_msg(void *opdata, ConnContext *ctx, OtrlConvertType typ,
673        char **dst, const char *src)
674{
675        struct im_connection *ic =
676                check_imc(opdata, ctx->accountname, ctx->protocol);
677        irc_t *irc = ic->bee->ui_data;
678        irc_user_t *iu = peeruser(irc, ctx->username, ctx->protocol);
679
680        if(typ == OTRL_CONVERT_RECEIVING) {
681                char *msg = g_strdup(src);
682
683                /* HTML decoding */
684                if(set_getbool(&ic->bee->set, "otr_does_html") &&
685                   !(ic->flags & OPT_DOES_HTML) &&
686                   set_getbool(&ic->bee->set, "strip_html")) {
687                        strip_html(msg);
688                        *dst = msg;
689                }
690
691                /* coloring */
692                if(set_getbool(&ic->bee->set, "otr_color_encrypted")) {
693                        int color;                /* color according to f'print trust */
694                        char *pre="", *sep="";    /* optional parts */
695                        const char *trust = ctx->active_fingerprint->trust;
696
697                        if(trust && trust[0] != '\0')
698                                color=3;   /* green */
699                        else
700                                color=5;   /* red */
701
702                        /* in a query window, keep "/me " uncolored at the beginning */
703                        if(g_strncasecmp(msg, "/me ", 4) == 0
704                           && irc_user_msgdest(iu) == irc->user->nick) {
705                                msg += 4;  /* skip */
706                                pre = "/me ";
707                        }
708
709                        /* comma in first place could mess with the color code */
710                        if(msg[0] == ',') {
711                            /* insert a space between color spec and message */
712                            sep = " ";
713                        }
714
715                        *dst = g_strdup_printf("%s\x03%.2d%s%s\x0F", pre,
716                                color, sep, msg);
717                        g_free(msg);
718                }
719        } else {
720                /* HTML encoding */
721                /* consider OTR plaintext to be HTML if otr_does_html is set */
722                if(ctx && ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED &&
723                   set_getbool(&ic->bee->set, "otr_does_html") &&
724                   (g_strncasecmp(src, "<html>", 6) != 0)) {
725                        *dst = escape_html(src);
726                }
727        }
728}
729
730void op_convert_free(void *opdata, ConnContext *ctx, char *msg)
731{
732        g_free(msg);
733}
734       
735/* Socialist Millionaires' Protocol */
736void op_handle_smp_event(void *opdata, OtrlSMPEvent ev, ConnContext *ctx,
737        unsigned short percent, char *question)
738{
739        struct im_connection *ic =
740                check_imc(opdata, ctx->accountname, ctx->protocol);
741        irc_t *irc = ic->bee->ui_data;
742        OtrlUserState us = irc->otr->us;
743        irc_user_t *u = peeruser(irc, ctx->username, ctx->protocol);
744
745        if(!u) return;
746
747        switch(ev) {
748        case OTRL_SMPEVENT_ASK_FOR_SECRET:
749                irc_rootmsg(irc, "smp: initiated by %s"
750                        " - respond with \x02otr smp %s <secret>\x02",
751                        u->nick, u->nick);
752                break;
753        case OTRL_SMPEVENT_ASK_FOR_ANSWER:
754                irc_rootmsg(irc, "smp: initiated by %s with question: \x02\"%s\"\x02", u->nick,
755                        question);
756                irc_rootmsg(irc, "smp: respond with \x02otr smp %s <answer>\x02",
757                        u->nick);
758                break;
759        case OTRL_SMPEVENT_CHEATED:
760                irc_rootmsg(irc, "smp %s: opponent violated protocol, aborting",
761                        u->nick);
762                otrl_message_abort_smp(us, &otr_ops, u->bu->ic, ctx);
763                otrl_sm_state_free(ctx->smstate);
764                break;
765        case OTRL_SMPEVENT_NONE:
766                break;
767        case OTRL_SMPEVENT_IN_PROGRESS:
768                break;
769        case OTRL_SMPEVENT_SUCCESS:
770                if(ctx->smstate->received_question) {
771                        irc_rootmsg(irc, "smp %s: correct answer, you are trusted",
772                                u->nick);
773                } else {
774                        irc_rootmsg(irc, "smp %s: secrets proved equal, fingerprint trusted",
775                                u->nick);
776                }
777                otrl_sm_state_free(ctx->smstate);
778                break;
779        case OTRL_SMPEVENT_FAILURE:
780                if(ctx->smstate->received_question) {
781                        irc_rootmsg(irc, "smp %s: wrong answer, you are not trusted",
782                                u->nick);
783                } else {
784                        irc_rootmsg(irc, "smp %s: secrets did not match, fingerprint not trusted",
785                                u->nick);
786                }
787                otrl_sm_state_free(ctx->smstate);
788                break;
789        case OTRL_SMPEVENT_ABORT:
790                irc_rootmsg(irc, "smp: received abort from %s", u->nick);
791                otrl_sm_state_free(ctx->smstate);
792                break;
793        case OTRL_SMPEVENT_ERROR:
794                irc_rootmsg(irc, "smp %s: protocol error, aborting",
795                        u->nick);
796                otrl_message_abort_smp(us, &otr_ops, u->bu->ic, ctx);
797                otrl_sm_state_free(ctx->smstate);
798                break;
799        }
800}
801
802void op_handle_msg_event(void *opdata, OtrlMessageEvent ev, ConnContext *ctx,
803        const char *message, gcry_error_t err)
804{
805        switch(ev) {
806        case OTRL_MSGEVENT_ENCRYPTION_REQUIRED:
807                display_otr_message(opdata, ctx,
808                        "policy requires encryption - message not sent");
809                break;
810        case OTRL_MSGEVENT_ENCRYPTION_ERROR:
811                display_otr_message(opdata, ctx,
812                        "error during encryption - message not sent");
813                break;
814        case OTRL_MSGEVENT_CONNECTION_ENDED:
815                display_otr_message(opdata, ctx,
816                        "other end has disconnected OTR - "
817                        "close connection or reconnect!");
818                break;
819        case OTRL_MSGEVENT_SETUP_ERROR:
820                display_otr_message(opdata, ctx,
821                        "OTR connection failed: %s", gcry_strerror(err));
822                break;
823        case OTRL_MSGEVENT_MSG_REFLECTED:
824                display_otr_message(opdata, ctx,
825                        "received our own OTR message (!?)");
826                break;
827        case OTRL_MSGEVENT_MSG_RESENT:
828                display_otr_message(opdata, ctx,
829                        "the previous message was resent");
830                break;
831        case OTRL_MSGEVENT_RCVDMSG_NOT_IN_PRIVATE:
832                display_otr_message(opdata, ctx,
833                        "unexpected encrypted message received");
834                break;
835        case OTRL_MSGEVENT_RCVDMSG_UNREADABLE:
836                display_otr_message(opdata, ctx,
837                        "unreadable encrypted message received");
838                break;
839        case OTRL_MSGEVENT_RCVDMSG_MALFORMED:
840                display_otr_message(opdata, ctx,
841                        "malformed OTR message received");
842                break;
843        case OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR:
844                display_otr_message(opdata, ctx,
845                        "OTR error message received: %s", message);
846                break;
847        case OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED:
848                display_otr_message(opdata, ctx,
849                        "unencrypted message received: %s", message);
850                break;
851        case OTRL_MSGEVENT_RCVDMSG_UNRECOGNIZED:
852                display_otr_message(opdata, ctx,
853                        "unrecognized OTR message received");
854                break;
855        default:
856                /* ignore  XXX log? */
857                break;
858        }
859}
860
861
862
863/*** OTR sub-command handlers ***/
864
865void cmd_otr_reconnect(irc_t *irc, char **args)
866{
867        cmd_otr_disconnect(irc, args);
868        cmd_otr_connect(irc, args);
869}
870
871void cmd_otr_disconnect(irc_t *irc, char **args)
872{
873        irc_user_t *u;
874
875        u = irc_user_by_name(irc, args[1]);
876        if(!u || !u->bu || !u->bu->ic) {
877                irc_rootmsg(irc, "%s: unknown user", args[1]);
878                return;
879        }
880       
881        /* XXX we disconnect all instances; is that what we want? */
882        otrl_message_disconnect_all_instances(irc->otr->us, &otr_ops,
883                u->bu->ic, u->bu->ic->acc->user, u->bu->ic->acc->prpl->name, u->bu->handle);
884       
885        /* for some reason, libotr (4.0.0) doesn't do this itself: */
886        if(!(u->flags & IRC_USER_OTR_ENCRYPTED))
887                return;
888
889        ConnContext *ctx, *p;
890        ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
891                u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);
892        if(!ctx) { /* huh? */
893                u->flags &= ( IRC_USER_OTR_ENCRYPTED | IRC_USER_OTR_TRUSTED );
894                return;
895        }
896
897        for(p=ctx; p && p->m_context == ctx->m_context; p=p->next)
898                op_gone_insecure(u->bu->ic, p);
899}
900
901void cmd_otr_connect(irc_t *irc, char **args)
902{
903        irc_user_t *u;
904
905        u = irc_user_by_name(irc, args[1]);
906        if(!u || !u->bu || !u->bu->ic) {
907                irc_rootmsg(irc, "%s: unknown user", args[1]);
908                return;
909        }
910        if(!(u->bu->flags & BEE_USER_ONLINE)) {
911                irc_rootmsg(irc, "%s is offline", args[1]);
912                return;
913        }
914       
915        bee_user_msg(irc->b, u->bu, "?OTR?v2?", 0);
916}
917
918void cmd_otr_smp(irc_t *irc, char **args)
919{
920        otr_smp_or_smpq(irc, args[1], NULL, args[2]);   /* no question */
921}
922
923void cmd_otr_smpq(irc_t *irc, char **args)
924{
925        otr_smp_or_smpq(irc, args[1], args[2], args[3]);
926}
927
928void cmd_otr_trust(irc_t *irc, char **args)
929{
930        irc_user_t *u;
931        ConnContext *ctx;
932        unsigned char raw[20];
933        Fingerprint *fp;
934        int i,j;
935       
936        u = irc_user_by_name(irc, args[1]);
937        if(!u || !u->bu || !u->bu->ic) {
938                irc_rootmsg(irc, "%s: unknown user", args[1]);
939                return;
940        }
941       
942        ctx = otrl_context_find(irc->otr->us, u->bu->handle,
943                u->bu->ic->acc->user, u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
944        if(!ctx) {
945                irc_rootmsg(irc, "%s: no otr context with user", args[1]);
946                return;
947        }
948       
949        /* convert given fingerprint to raw representation */
950        for(i=0; i<5; i++) {
951                for(j=0; j<4; j++) {
952                        char *p = args[2+i]+(2*j);
953                        char *q = p+1;
954                        int x, y;
955                       
956                        if(!*p || !*q) {
957                                irc_rootmsg(irc, "failed: truncated fingerprint block %d", i+1);
958                                return;
959                        }
960                       
961                        x = hexval(*p);
962                        y = hexval(*q);
963                        if(x<0) {
964                                irc_rootmsg(irc, "failed: %d. hex digit of block %d out of range", 2*j+1, i+1);
965                                return;
966                        }
967                        if(y<0) {
968                                irc_rootmsg(irc, "failed: %d. hex digit of block %d out of range", 2*j+2, i+1);
969                                return;
970                        }
971
972                        raw[i*4+j] = x*16 + y;
973                }
974        }
975        fp = otrl_context_find_fingerprint(ctx, raw, 0, NULL);
976        if(!fp) {
977                irc_rootmsg(irc, "failed: no such fingerprint for %s", args[1]);
978        } else {
979                char *trust = args[7] ? args[7] : "affirmed";
980                otrl_context_set_trust(fp, trust);
981                irc_rootmsg(irc, "fingerprint match, trust set to \"%s\"", trust);
982                if(u->flags & IRC_USER_OTR_ENCRYPTED)
983                        u->flags |= IRC_USER_OTR_TRUSTED;
984                otr_update_modeflags(irc, u);
985        }
986}
987
988void cmd_otr_info(irc_t *irc, char **args)
989{
990        if(!args[1]) {
991                show_general_otr_info(irc);
992        } else {
993                char *arg = g_strdup(args[1]);
994                char *myhandle, *handle=NULL, *protocol;
995                ConnContext *ctx;
996               
997                /* interpret arg as 'user/protocol/account' if possible */
998                protocol = strchr(arg, '/');
999                myhandle = NULL;
1000                if(protocol) {
1001                        *(protocol++) = '\0';
1002                        myhandle = strchr(protocol, '/');
1003                }
1004                if(protocol && myhandle) {
1005                        *(myhandle++) = '\0';
1006                        handle = arg;
1007                        ctx = otrl_context_find(irc->otr->us, handle, myhandle, protocol, 0, OTRL_INSTAG_MASTER, NULL, NULL, NULL);  // XXX
1008                        if(!ctx) {
1009                                irc_rootmsg(irc, "no such context");
1010                                g_free(arg);
1011                                return;
1012                        }
1013                } else {
1014                        irc_user_t *u = irc_user_by_name(irc, args[1]);
1015                        if(!u || !u->bu || !u->bu->ic) {
1016                                irc_rootmsg(irc, "%s: unknown user", args[1]);
1017                                g_free(arg);
1018                                return;
1019                        }
1020                        ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
1021                                u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1022                        if(!ctx) {
1023                                irc_rootmsg(irc, "no otr context with %s", args[1]);
1024                                g_free(arg);
1025                                return;
1026                        }
1027                }
1028       
1029                /* show how we resolved the (nick) argument, if we did */
1030                if(handle!=arg) {
1031                        irc_rootmsg(irc, "%s is %s/%s; we are %s/%s to them", args[1],
1032                                ctx->username, ctx->protocol, ctx->accountname, ctx->protocol);
1033                }
1034                show_otr_context_info(irc, ctx);
1035                g_free(arg);
1036        }
1037}
1038
1039void cmd_otr_keygen(irc_t *irc, char **args)
1040{
1041        int i, n;
1042        account_t *a;
1043       
1044        n = atoi(args[1]);
1045        if(n<0 || (!n && strcmp(args[1], "0"))) {
1046                irc_rootmsg(irc, "%s: invalid account number", args[1]);
1047                return;
1048        }
1049       
1050        a = irc->b->accounts;
1051        for(i=0; i<n && a; i++, a=a->next);
1052        if(!a) {
1053                irc_rootmsg(irc, "%s: no such account", args[1]);
1054                return;
1055        }
1056       
1057        if(keygen_in_progress(irc, a->user, a->prpl->name)) {
1058                irc_rootmsg(irc, "keygen for account %d already in progress", n);
1059                return;
1060        }
1061       
1062        if(otrl_privkey_find(irc->otr->us, a->user, a->prpl->name)) {
1063                char *s = g_strdup_printf("account %d already has a key, replace it?", n);
1064                query_add(irc, NULL, s, yes_keygen, NULL, NULL, a);
1065                g_free(s);
1066        } else {
1067                otr_keygen(irc, a->user, a->prpl->name);
1068        }
1069}
1070
1071void yes_forget_fingerprint(void *data)
1072{
1073        pair_t *p = (pair_t *)data;
1074        irc_t *irc = (irc_t *)p->fst;
1075        Fingerprint *fp = (Fingerprint *)p->snd;
1076
1077        g_free(p);
1078       
1079        if(fp == fp->context->active_fingerprint) {
1080                irc_rootmsg(irc, "that fingerprint is active, terminate otr connection first");
1081                return;
1082        }
1083               
1084        otrl_context_forget_fingerprint(fp, 0);
1085}
1086
1087void yes_forget_context(void *data)
1088{
1089        pair_t *p = (pair_t *)data;
1090        irc_t *irc = (irc_t *)p->fst;
1091        ConnContext *ctx = (ConnContext *)p->snd;
1092
1093        g_free(p);
1094       
1095        if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
1096                irc_rootmsg(irc, "active otr connection with %s, terminate it first",
1097                        peernick(irc, ctx->username, ctx->protocol));
1098                return;
1099        }
1100               
1101        if(ctx->msgstate == OTRL_MSGSTATE_FINISHED)
1102                otrl_context_force_plaintext(ctx);
1103        otrl_context_forget(ctx);
1104}
1105
1106void yes_forget_key(void *data)
1107{
1108        OtrlPrivKey *key = (OtrlPrivKey *)data;
1109       
1110        otrl_privkey_forget(key);
1111        /* Hm, libotr doesn't seem to offer a function for explicitly /writing/
1112           keyfiles. So the key will be back on the next load... */
1113        /* TODO: Actually erase forgotten keys from storage? */
1114}
1115
1116void cmd_otr_forget(irc_t *irc, char **args)
1117{
1118        if(!strcmp(args[1], "fingerprint"))
1119        {
1120                irc_user_t *u;
1121                ConnContext *ctx;
1122                Fingerprint *fp;
1123                char human[54];
1124                char *s;
1125                pair_t *p;
1126               
1127                if(!args[3]) {
1128                        irc_rootmsg(irc, "otr %s %s: not enough arguments (2 req.)", args[0], args[1]);
1129                        return;
1130                }
1131               
1132                /* TODO: allow context specs ("user/proto/account") in 'otr forget fingerprint'? */
1133                u = irc_user_by_name(irc, args[2]);
1134                if(!u || !u->bu || !u->bu->ic) {
1135                        irc_rootmsg(irc, "%s: unknown user", args[2]);
1136                        return;
1137                }
1138               
1139                ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
1140                        u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1141                if(!ctx) {
1142                        irc_rootmsg(irc, "no otr context with %s", args[2]);
1143                        return;
1144                }
1145               
1146                fp = match_fingerprint(irc, ctx, ((const char **)args)+3);
1147                if(!fp) {
1148                        /* match_fingerprint does error messages */
1149                        return;
1150                }
1151               
1152                if(fp == ctx->active_fingerprint) {
1153                        irc_rootmsg(irc, "that fingerprint is active, terminate otr connection first");
1154                        return;
1155                }
1156               
1157                otrl_privkey_hash_to_human(human, fp->fingerprint);
1158                s = g_strdup_printf("about to forget fingerprint %s, are you sure?", human);
1159                p = g_malloc(sizeof(pair_t));
1160                if(!p)
1161                        return;
1162                p->fst = irc;
1163                p->snd = fp;
1164                query_add(irc, NULL, s, yes_forget_fingerprint, NULL, NULL, p);
1165                g_free(s);
1166        }
1167       
1168        else if(!strcmp(args[1], "context"))
1169        {
1170                irc_user_t *u;
1171                ConnContext *ctx;
1172                char *s;
1173                pair_t *p;
1174               
1175                /* TODO: allow context specs ("user/proto/account") in 'otr forget contex'? */
1176                u = irc_user_by_name(irc, args[2]);
1177                if(!u || !u->bu || !u->bu->ic) {
1178                        irc_rootmsg(irc, "%s: unknown user", args[2]);
1179                        return;
1180                }
1181               
1182                ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
1183                        u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1184                if(!ctx) {
1185                        irc_rootmsg(irc, "no otr context with %s", args[2]);
1186                        return;
1187                }
1188               
1189                if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
1190                        irc_rootmsg(irc, "active otr connection with %s, terminate it first", args[2]);
1191                        return;
1192                }
1193               
1194                s = g_strdup_printf("about to forget otr data about %s, are you sure?", args[2]);
1195                p = g_malloc(sizeof(pair_t));
1196                if(!p)
1197                        return;
1198                p->fst = irc;
1199                p->snd = ctx;
1200                query_add(irc, NULL, s, yes_forget_context, NULL, NULL, p);
1201                g_free(s);
1202        }
1203       
1204        else if(!strcmp(args[1], "key"))
1205        {
1206                OtrlPrivKey *key;
1207                char *s;
1208               
1209                key = match_privkey(irc, ((const char **)args)+2);
1210                if(!key) {
1211                        /* match_privkey does error messages */
1212                        return;
1213                }
1214               
1215                s = g_strdup_printf("about to forget the private key for %s/%s, are you sure?",
1216                        key->accountname, key->protocol);
1217                query_add(irc, NULL, s, yes_forget_key, NULL, NULL, key);
1218                g_free(s);
1219        }
1220       
1221        else
1222        {
1223                irc_rootmsg(irc, "otr %s: unknown subcommand \"%s\", see \x02help otr forget\x02",
1224                        args[0], args[1]);
1225        }
1226}
1227
1228
1229/*** local helpers / subroutines: ***/
1230
1231void log_otr_message(void *opdata, const char *fmt, ...)
1232{
1233        va_list va;
1234
1235        va_start(va, fmt);
1236        char *msg = g_strdup_vprintf(fmt, va);
1237        va_end(va);
1238       
1239        log_message(LOGLVL_INFO, "otr: %s", msg);
1240}
1241
1242void display_otr_message(void *opdata, ConnContext *ctx, const char *fmt, ...)
1243{
1244        struct im_connection *ic =
1245                check_imc(opdata, ctx->accountname, ctx->protocol);
1246        irc_t *irc = ic->bee->ui_data;
1247        irc_user_t *u = peeruser(irc, ctx->username, ctx->protocol);
1248        va_list va;
1249
1250        va_start(va, fmt);
1251        char *msg = g_strdup_vprintf(fmt, va);
1252        va_end(va);
1253
1254        if(u) {
1255                /* display as a notice from this particular user */
1256                irc_usernotice(u, "%s", msg);
1257        } else {
1258                irc_rootmsg(irc, "[otr] %s", msg);
1259        }
1260
1261        g_free(msg);
1262}
1263
1264/* combined handler for the 'otr smp' and 'otr smpq' commands */
1265void otr_smp_or_smpq(irc_t *irc, const char *nick, const char *question,
1266                const char *secret)
1267{
1268        irc_user_t *u;
1269        ConnContext *ctx;
1270
1271        u = irc_user_by_name(irc, nick);
1272        if(!u || !u->bu || !u->bu->ic) {
1273                irc_rootmsg(irc, "%s: unknown user", nick);
1274                return;
1275        }
1276        if(!(u->bu->flags & BEE_USER_ONLINE)) {
1277                irc_rootmsg(irc, "%s is offline", nick);
1278                return;
1279        }
1280       
1281        ctx = otrl_context_find(irc->otr->us, u->bu->handle,
1282                u->bu->ic->acc->user, u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1283        if(!ctx || ctx->msgstate != OTRL_MSGSTATE_ENCRYPTED) {
1284                irc_rootmsg(irc, "smp: otr inactive with %s, try \x02otr connect"
1285                                " %s\x02", nick, nick);
1286                return;
1287        }
1288
1289        if(ctx->smstate->nextExpected != OTRL_SMP_EXPECT1) {
1290                log_message(LOGLVL_INFO,
1291                        "SMP already in phase %d, sending abort before reinitiating",
1292                        ctx->smstate->nextExpected+1);
1293                otrl_message_abort_smp(irc->otr->us, &otr_ops, u->bu->ic, ctx);
1294                otrl_sm_state_free(ctx->smstate);
1295        }
1296
1297        if(question) {
1298                /* this was 'otr smpq', just initiate */
1299                irc_rootmsg(irc, "smp: initiating with %s...", u->nick);
1300                otrl_message_initiate_smp_q(irc->otr->us, &otr_ops, u->bu->ic, ctx,
1301                        question, (unsigned char *)secret, strlen(secret));
1302                /* smp is now in EXPECT2 */
1303        } else {
1304                /* this was 'otr smp', initiate or reply */
1305                /* warning: the following assumes that smstates are cleared whenever an SMP
1306                   is completed or aborted! */ 
1307                if(ctx->smstate->secret == NULL) {
1308                        irc_rootmsg(irc, "smp: initiating with %s...", u->nick);
1309                        otrl_message_initiate_smp(irc->otr->us, &otr_ops,
1310                                u->bu->ic, ctx, (unsigned char *)secret, strlen(secret));
1311                        /* smp is now in EXPECT2 */
1312                } else {
1313                        /* if we're still in EXPECT1 but smstate is initialized, we must have
1314                           received the SMP1, so let's issue a response */
1315                        irc_rootmsg(irc, "smp: responding to %s...", u->nick);
1316                        otrl_message_respond_smp(irc->otr->us, &otr_ops,
1317                                u->bu->ic, ctx, (unsigned char *)secret, strlen(secret));
1318                        /* smp is now in EXPECT3 */
1319                }
1320        }
1321}
1322
1323/* helper to assert that account and protocol names given to ops below always
1324   match the im_connection passed through as opdata */
1325struct im_connection *check_imc(void *opdata, const char *accountname,
1326        const char *protocol)
1327{
1328        struct im_connection *ic = (struct im_connection *)opdata;
1329
1330        if (strcmp(accountname, ic->acc->user) != 0) {
1331                log_message(LOGLVL_WARNING,
1332                        "otr: internal account name mismatch: '%s' vs '%s'",
1333                        accountname, ic->acc->user);
1334        }
1335        if (strcmp(protocol, ic->acc->prpl->name) != 0) {
1336                log_message(LOGLVL_WARNING,
1337                        "otr: internal protocol name mismatch: '%s' vs '%s'",
1338                        protocol, ic->acc->prpl->name);
1339        }
1340       
1341        return ic;
1342}
1343
1344irc_user_t *peeruser(irc_t *irc, const char *handle, const char *protocol)
1345{
1346        GSList *l;
1347       
1348        for(l=irc->b->users; l; l = l->next) {
1349                bee_user_t *bu = l->data;
1350                struct prpl *prpl;
1351                if(!bu->ui_data || !bu->ic || !bu->handle)
1352                        continue;
1353                prpl = bu->ic->acc->prpl;
1354                if(strcmp(prpl->name, protocol) == 0
1355                        && prpl->handle_cmp(bu->handle, handle) == 0) {
1356                        return bu->ui_data;
1357                }
1358        }
1359       
1360        return NULL;
1361}
1362
1363int hexval(char a)
1364{
1365        int x=tolower(a);
1366       
1367        if(x>='a' && x<='f')
1368                x = x - 'a' + 10;
1369        else if(x>='0' && x<='9')
1370                x = x - '0';
1371        else
1372                return -1;
1373       
1374        return x;
1375}
1376
1377const char *peernick(irc_t *irc, const char *handle, const char *protocol)
1378{
1379        static char fallback[512];
1380       
1381        irc_user_t *u = peeruser(irc, handle, protocol);
1382        if(u) {
1383                return u->nick;
1384        } else {
1385                g_snprintf(fallback, 511, "%s/%s", handle, protocol);
1386                return fallback;
1387        }
1388}
1389
1390void otr_update_uflags(ConnContext *context, irc_user_t *u)
1391{
1392        const char *trust;
1393
1394        if(context->active_fingerprint) {
1395                u->flags |= IRC_USER_OTR_ENCRYPTED;
1396
1397                trust = context->active_fingerprint->trust;
1398                if(trust && trust[0])
1399                        u->flags |= IRC_USER_OTR_TRUSTED;
1400                else
1401                        u->flags &= ~IRC_USER_OTR_TRUSTED;
1402        } else {
1403                u->flags &= ~IRC_USER_OTR_ENCRYPTED;
1404        }
1405}
1406
1407int otr_update_modeflags(irc_t *irc, irc_user_t *u)
1408{
1409        return 0;
1410}
1411
1412void show_fingerprints(irc_t *irc, ConnContext *ctx)
1413{
1414        char human[45];
1415        Fingerprint *fp;
1416        const char *trust;
1417        int count=0;
1418       
1419        for(fp=&ctx->fingerprint_root; fp; fp=fp->next) {
1420                if(!fp->fingerprint)
1421                        continue;
1422                count++;
1423                otrl_privkey_hash_to_human(human, fp->fingerprint);
1424                if(!fp->trust || fp->trust[0] == '\0') {
1425                        trust="untrusted";
1426                } else {
1427                        trust=fp->trust;
1428                }
1429                if(fp == ctx->active_fingerprint) {
1430                        irc_rootmsg(irc, "    \x02%s (%s)\x02", human, trust);
1431                } else {
1432                        irc_rootmsg(irc, "    %s (%s)", human, trust);
1433                }
1434        }
1435        if(count==0)
1436                irc_rootmsg(irc, "    (none)");
1437}
1438
1439Fingerprint *match_fingerprint(irc_t *irc, ConnContext *ctx, const char **args)
1440{
1441        Fingerprint *fp, *fp2;
1442        char human[45];
1443        char prefix[45], *p;
1444        int n;
1445        int i,j;
1446       
1447        /* assemble the args into a prefix in standard "human" form */
1448        n=0;
1449        p=prefix;
1450        for(i=0; args[i]; i++) {
1451                for(j=0; args[i][j]; j++) {
1452                        char c = toupper(args[i][j]);
1453                       
1454                        if(n>=40) {
1455                                irc_rootmsg(irc, "too many fingerprint digits given, expected at most 40");
1456                                return NULL;
1457                        }
1458                       
1459                        if( (c>='A' && c<='F') || (c>='0' && c<='9') ) {
1460                                *(p++) = c;
1461                        } else {
1462                                irc_rootmsg(irc, "invalid hex digit '%c' in block %d", args[i][j], i+1);
1463                                return NULL;
1464                        }
1465                       
1466                        n++;
1467                        if(n%8 == 0)
1468                                *(p++) = ' ';
1469                }
1470        }
1471        *p = '\0';
1472       
1473        /* find first fingerprint with the given prefix */
1474        n = strlen(prefix);
1475        for(fp=&ctx->fingerprint_root; fp; fp=fp->next) {
1476                if(!fp->fingerprint)
1477                        continue;
1478                otrl_privkey_hash_to_human(human, fp->fingerprint);
1479                if(!strncmp(prefix, human, n))
1480                        break;
1481        }
1482        if(!fp) {
1483                irc_rootmsg(irc, "%s: no match", prefix);
1484                return NULL;
1485        }
1486       
1487        /* make sure the match, if any, is unique */
1488        for(fp2=fp->next; fp2; fp2=fp2->next) {
1489                if(!fp2->fingerprint)
1490                        continue;
1491                otrl_privkey_hash_to_human(human, fp2->fingerprint);
1492                if(!strncmp(prefix, human, n))
1493                        break;
1494        }
1495        if(fp2) {
1496                irc_rootmsg(irc, "%s: multiple matches", prefix);
1497                return NULL;
1498        }
1499       
1500        return fp;
1501}
1502
1503OtrlPrivKey *match_privkey(irc_t *irc, const char **args)
1504{
1505        OtrlPrivKey *k, *k2;
1506        char human[45];
1507        char prefix[45], *p;
1508        int n;
1509        int i,j;
1510       
1511        /* assemble the args into a prefix in standard "human" form */
1512        n=0;
1513        p=prefix;
1514        for(i=0; args[i]; i++) {
1515                for(j=0; args[i][j]; j++) {
1516                        char c = toupper(args[i][j]);
1517                       
1518                        if(n>=40) {
1519                                irc_rootmsg(irc, "too many fingerprint digits given, expected at most 40");
1520                                return NULL;
1521                        }
1522                       
1523                        if( (c>='A' && c<='F') || (c>='0' && c<='9') ) {
1524                                *(p++) = c;
1525                        } else {
1526                                irc_rootmsg(irc, "invalid hex digit '%c' in block %d", args[i][j], i+1);
1527                                return NULL;
1528                        }
1529                       
1530                        n++;
1531                        if(n%8 == 0)
1532                                *(p++) = ' ';
1533                }
1534        }
1535        *p = '\0';
1536       
1537        /* find first key which matches the given prefix */
1538        n = strlen(prefix);
1539        for(k=irc->otr->us->privkey_root; k; k=k->next) {
1540                p = otrl_privkey_fingerprint(irc->otr->us, human, k->accountname, k->protocol);
1541                if(!p) /* gah! :-P */
1542                        continue;
1543                if(!strncmp(prefix, human, n))
1544                        break;
1545        }
1546        if(!k) {
1547                irc_rootmsg(irc, "%s: no match", prefix);
1548                return NULL;
1549        }
1550       
1551        /* make sure the match, if any, is unique */
1552        for(k2=k->next; k2; k2=k2->next) {
1553                p = otrl_privkey_fingerprint(irc->otr->us, human, k2->accountname, k2->protocol);
1554                if(!p) /* gah! :-P */
1555                        continue;
1556                if(!strncmp(prefix, human, n))
1557                        break;
1558        }
1559        if(k2) {
1560                irc_rootmsg(irc, "%s: multiple matches", prefix);
1561                return NULL;
1562        }
1563       
1564        return k;
1565}
1566
1567void show_general_otr_info(irc_t *irc)
1568{
1569        ConnContext *ctx;
1570        OtrlPrivKey *key;
1571        char human[45];
1572        kg_t *kg;
1573
1574        /* list all privkeys (including ones being generated) */
1575        irc_rootmsg(irc, "\x1fprivate keys:\x1f");
1576        for(key=irc->otr->us->privkey_root; key; key=key->next) {
1577                const char *hash;
1578               
1579                switch(key->pubkey_type) {
1580                case OTRL_PUBKEY_TYPE_DSA:
1581                        irc_rootmsg(irc, "  %s/%s - DSA", key->accountname, key->protocol);
1582                        break;
1583                default:
1584                        irc_rootmsg(irc, "  %s/%s - type %d", key->accountname, key->protocol,
1585                                key->pubkey_type);
1586                }
1587
1588                /* No, it doesn't make much sense to search for the privkey again by
1589                   account/protocol, but libotr currently doesn't provide a direct routine
1590                   for hashing a given 'OtrlPrivKey'... */
1591                hash = otrl_privkey_fingerprint(irc->otr->us, human, key->accountname, key->protocol);
1592                if(hash) /* should always succeed */
1593                        irc_rootmsg(irc, "    %s", human);
1594        }
1595        if(irc->otr->sent_accountname) {
1596                irc_rootmsg(irc, "  %s/%s - DSA", irc->otr->sent_accountname,
1597                        irc->otr->sent_protocol);
1598                irc_rootmsg(irc, "    (being generated)");
1599        }
1600        for(kg=irc->otr->todo; kg; kg=kg->next) {
1601                irc_rootmsg(irc, "  %s/%s - DSA", kg->accountname, kg->protocol);
1602                irc_rootmsg(irc, "    (queued)");
1603        }
1604        if(key == irc->otr->us->privkey_root &&
1605           !irc->otr->sent_accountname &&
1606           kg == irc->otr->todo)
1607                irc_rootmsg(irc, "  (none)");
1608
1609        /* list all contexts */
1610        irc_rootmsg(irc, "%s", "");
1611        irc_rootmsg(irc, "\x1f" "connection contexts:\x1f (bold=currently encrypted)");
1612        for(ctx=irc->otr->us->context_root; ctx; ctx=ctx->next) {\
1613                irc_user_t *u;
1614                char *userstring;
1615               
1616                u = peeruser(irc, ctx->username, ctx->protocol);
1617                if(u)
1618                        userstring = g_strdup_printf("%s/%s/%s (%s)",
1619                                ctx->username, ctx->protocol, ctx->accountname, u->nick);
1620                else
1621                        userstring = g_strdup_printf("%s/%s/%s",
1622                                ctx->username, ctx->protocol, ctx->accountname);
1623               
1624                if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
1625                        irc_rootmsg(irc, \x02%s\x02", userstring);
1626                } else {
1627                        irc_rootmsg(irc, "  %s", userstring);
1628                }
1629               
1630                g_free(userstring);
1631        }
1632        if(ctx == irc->otr->us->context_root)
1633                irc_rootmsg(irc, "  (none)");
1634}
1635
1636void show_otr_context_info(irc_t *irc, ConnContext *ctx)
1637{
1638        switch(ctx->otr_offer) {
1639        case OFFER_NOT:
1640                irc_rootmsg(irc, "  otr offer status: none sent");
1641                break;
1642        case OFFER_SENT:
1643                irc_rootmsg(irc, "  otr offer status: awaiting reply");
1644                break;
1645        case OFFER_ACCEPTED:
1646                irc_rootmsg(irc, "  otr offer status: accepted our offer");
1647                break;
1648        case OFFER_REJECTED:
1649                irc_rootmsg(irc, "  otr offer status: ignored our offer");
1650                break;
1651        default:
1652                irc_rootmsg(irc, "  otr offer status: %d", ctx->otr_offer);
1653        }
1654
1655        switch(ctx->msgstate) {
1656        case OTRL_MSGSTATE_PLAINTEXT:
1657                irc_rootmsg(irc, "  connection state: cleartext");
1658                break;
1659        case OTRL_MSGSTATE_ENCRYPTED:
1660                irc_rootmsg(irc, "  connection state: encrypted (v%d)", ctx->protocol_version);
1661                break;
1662        case OTRL_MSGSTATE_FINISHED:
1663                irc_rootmsg(irc, "  connection state: shut down");
1664                break;
1665        default:
1666                irc_rootmsg(irc, "  connection state: %d", ctx->msgstate);
1667        }
1668
1669        irc_rootmsg(irc, "  fingerprints: (bold=active)");     
1670        show_fingerprints(irc, ctx);
1671}
1672
1673int keygen_in_progress(irc_t *irc, const char *handle, const char *protocol)
1674{
1675        kg_t *kg;
1676       
1677        if(!irc->otr->sent_accountname || !irc->otr->sent_protocol)
1678                return 0;
1679
1680        /* are we currently working on this key? */
1681        if(!strcmp(handle, irc->otr->sent_accountname) &&
1682           !strcmp(protocol, irc->otr->sent_protocol))
1683                return 1;
1684       
1685        /* do we have it queued for later? */
1686        for(kg=irc->otr->todo; kg; kg=kg->next) {
1687                if(!strcmp(handle, kg->accountname) &&
1688                   !strcmp(protocol, kg->protocol))
1689                        return 1;
1690        }
1691       
1692        return 0;
1693}
1694
1695void otr_keygen(irc_t *irc, const char *handle, const char *protocol)
1696{
1697        /* do nothing if a key for the requested account is already being generated */
1698        if(keygen_in_progress(irc, handle, protocol))
1699                return;
1700
1701        /* see if we already have a keygen child running. if not, start one and put a
1702           handler on its output. */
1703        if(!irc->otr->keygen || waitpid(irc->otr->keygen, NULL, WNOHANG)) {
1704                pid_t p;
1705                int to[2], from[2];
1706                FILE *tof, *fromf;
1707               
1708                if(pipe(to) < 0 || pipe(from) < 0) {
1709                        irc_rootmsg(irc, "otr keygen: couldn't create pipe: %s", strerror(errno));
1710                        return;
1711                }
1712               
1713                tof = fdopen(to[1], "w");
1714                fromf = fdopen(from[0], "r");
1715                if(!tof || !fromf) {
1716                        irc_rootmsg(irc, "otr keygen: couldn't streamify pipe: %s", strerror(errno));
1717                        return;
1718                }
1719               
1720                p = fork();
1721                if(p<0) {
1722                        irc_rootmsg(irc, "otr keygen: couldn't fork: %s", strerror(errno));
1723                        return;
1724                }
1725               
1726                if(!p) {
1727                        /* child process */
1728                        signal(SIGTERM, exit);
1729                        keygen_child_main(irc->otr->us, to[0], from[1]);
1730                        exit(0);
1731                }
1732               
1733                irc->otr->keygen = p;
1734                irc->otr->to = tof;
1735                irc->otr->from = fromf;
1736                irc->otr->sent_accountname = NULL;
1737                irc->otr->sent_protocol = NULL;
1738                irc->otr->todo = NULL;
1739                b_input_add(from[0], B_EV_IO_READ, keygen_finish_handler, irc);
1740        }
1741       
1742        /* is the keygen slave currently working? */
1743        if(irc->otr->sent_accountname) {
1744                /* enqueue our job for later transmission */
1745                kg_t **kg = &irc->otr->todo;
1746                while(*kg)
1747                        kg=&((*kg)->next);
1748                *kg = g_new0(kg_t, 1);
1749                (*kg)->accountname = g_strdup(handle);
1750                (*kg)->protocol = g_strdup(protocol);
1751        } else {
1752                /* send our job over and remember it */
1753                fprintf(irc->otr->to, "%s\n%s\n", handle, protocol);
1754                fflush(irc->otr->to);
1755                irc->otr->sent_accountname = g_strdup(handle);
1756                irc->otr->sent_protocol = g_strdup(protocol);
1757        }
1758}
1759
1760void keygen_child_main(OtrlUserState us, int infd, int outfd)
1761{
1762        FILE *input, *output;
1763        char filename[128], accountname[512], protocol[512];
1764        gcry_error_t e;
1765        int tempfd;
1766       
1767        input = fdopen(infd, "r");
1768        output = fdopen(outfd, "w");
1769       
1770        while(!feof(input) && !ferror(input) && !feof(output) && !ferror(output)) {
1771                myfgets(accountname, 512, input);
1772                myfgets(protocol, 512, input);
1773               
1774                strncpy(filename, "/tmp/bitlbee-XXXXXX", 128);
1775                tempfd = mkstemp(filename);
1776                close(tempfd);
1777
1778                e = otrl_privkey_generate(us, filename, accountname, protocol);
1779                if(e) {
1780                        fprintf(output, "\n");  /* this means failure */
1781                        fprintf(output, "otr keygen: %s\n", gcry_strerror(e));
1782                        unlink(filename);
1783                } else {
1784                        fprintf(output, "%s\n", filename);
1785                        fprintf(output, "otr keygen for %s/%s complete\n", accountname, protocol);
1786                }
1787                fflush(output);
1788        }
1789       
1790        fclose(input);
1791        fclose(output);
1792}
1793
1794gboolean keygen_finish_handler(gpointer data, gint fd, b_input_condition cond)
1795{
1796        irc_t *irc = (irc_t *)data;
1797        char filename[512], msg[512];
1798
1799        myfgets(filename, 512, irc->otr->from);
1800        myfgets(msg, 512, irc->otr->from);
1801       
1802        irc_rootmsg(irc, "%s", msg);
1803        if(filename[0]) {
1804                if(strsane(irc->user->nick)) {
1805                        char *kf = g_strdup_printf("%s%s.otr_keys", global.conf->configdir, irc->user->nick);
1806                        char *tmp = g_strdup_printf("%s.new", kf);
1807                        copyfile(filename, tmp);
1808                        unlink(filename);
1809                        rename(tmp,kf);
1810                        otrl_privkey_read(irc->otr->us, kf);
1811                        g_free(kf);
1812                        g_free(tmp);
1813                } else {
1814                        otrl_privkey_read(irc->otr->us, filename);
1815                        unlink(filename);
1816                }
1817        }
1818       
1819        /* forget this job */
1820        g_free(irc->otr->sent_accountname);
1821        g_free(irc->otr->sent_protocol);
1822        irc->otr->sent_accountname = NULL;
1823        irc->otr->sent_protocol = NULL;
1824       
1825        /* see if there are any more in the queue */
1826        if(irc->otr->todo) {
1827                kg_t *p = irc->otr->todo;
1828                /* send the next one over */
1829                fprintf(irc->otr->to, "%s\n%s\n", p->accountname, p->protocol);
1830                fflush(irc->otr->to);
1831                irc->otr->sent_accountname = p->accountname;
1832                irc->otr->sent_protocol = p->protocol;
1833                irc->otr->todo = p->next;
1834                g_free(p);
1835                return TRUE;   /* keep watching */
1836        } else {
1837                /* okay, the slave is idle now, so kill him */
1838                fclose(irc->otr->from);
1839                fclose(irc->otr->to);
1840                irc->otr->from = irc->otr->to = NULL;
1841                kill(irc->otr->keygen, SIGTERM);
1842                waitpid(irc->otr->keygen, NULL, 0);
1843                irc->otr->keygen = 0;
1844                return FALSE;  /* unregister ourselves */
1845        }
1846}
1847
1848void copyfile(const char *a, const char *b)
1849{
1850        int fda, fdb;
1851        int n;
1852        char buf[1024];
1853       
1854        fda = open(a, O_RDONLY);
1855        fdb = open(b, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1856       
1857        while((n=read(fda, buf, 1024)) > 0)
1858                write(fdb, buf, n);
1859       
1860        close(fda);
1861        close(fdb);     
1862}
1863
1864void myfgets(char *s, int size, FILE *stream)
1865{
1866        if(!fgets(s, size, stream)) {
1867                s[0] = '\0';
1868        } else {
1869                int n = strlen(s);
1870                if(n>0 && s[n-1] == '\n')
1871                        s[n-1] = '\0';
1872        }
1873}
1874
1875void yes_keygen(void *data)
1876{
1877        account_t *acc = (account_t *)data;
1878        irc_t *irc = acc->bee->ui_data;
1879       
1880        if(keygen_in_progress(irc, acc->user, acc->prpl->name)) {
1881                irc_rootmsg(irc, "keygen for %s/%s already in progress",
1882                        acc->user, acc->prpl->name);
1883        } else {
1884                irc_rootmsg(irc, "starting background keygen for %s/%s",
1885                        acc->user, acc->prpl->name);
1886                irc_rootmsg(irc, "you will be notified when it completes");
1887                otr_keygen(irc, acc->user, acc->prpl->name);
1888        }
1889}
1890
1891/* check whether a string is safe to use in a path component */
1892int strsane(const char *s)
1893{
1894        return strpbrk(s, "/\\") == NULL;
1895}
1896
1897/* vim: set noet ts=4 sw=4: */
Note: See TracBrowser for help on using the repository browser.