source: otr.c @ dc9797f

Last change on this file since dc9797f was dc9797f, checked in by Sven Moritz Hallberg <sm@…>, at 2008-02-16T13:24:44Z

keep track of which keys are queued for generation

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