source: otr.c @ 2ffc41e

Last change on this file since 2ffc41e was 69ef042, checked in by Sven Moritz Hallberg <pesco@…>, at 2011-05-01T16:22:35Z

add otr reconnect command

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