source: otr.c @ fd9fa52

Last change on this file since fd9fa52 was fd9fa52, checked in by Sven Moritz Hallberg <sm@…>, at 2008-02-16T17:17:29Z

indent fingerprints in 'otr info <buddy>'

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