source: otr.c @ ad2d8bc

Last change on this file since ad2d8bc was ad2d8bc, checked in by Wilmer van der Gaast <wilmer@…>, at 2010-08-25T23:03:11Z

It compiles, including otr.c. Time to hook it up with the rest again.

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