source: otr.c @ f5c0d8e

Last change on this file since f5c0d8e was 8358691, checked in by Wilmer van der Gaast <wilmer@…>, at 2010-08-31T20:05:36Z

Added root_command_add() and use it to create the "otr" command.

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