source: otr.c @ 82e8fe8

Last change on this file since 82e8fe8 was 82e8fe8, checked in by Sven Moritz Hallberg <sm@…>, at 2008-02-17T01:50:23Z

free query strings after query_add

  • Property mode set to 100644
File size: 46.2 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(const char *nick, 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                g_free(s);
867        } else {
868                otr_keygen(irc, a->user, a->prpl->name);
869        }
870}
871
872void yes_forget_fingerprint(gpointer w, void *data)
873{
874        irc_t *irc = (irc_t *)w;
875        Fingerprint *fp = (Fingerprint *)data;
876       
877        if(fp == fp->context->active_fingerprint) {
878                irc_usermsg(irc, "that fingerprint is active, terminate otr connection first");
879                return;
880        }
881               
882        otrl_context_forget_fingerprint(fp, 0);
883}
884
885void yes_forget_context(gpointer w, void *data)
886{
887        irc_t *irc = (irc_t *)w;
888        ConnContext *ctx = (ConnContext *)data;
889       
890        if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
891                irc_usermsg(irc, "active otr connection with %s, terminate it first",
892                        peernick(irc, ctx->username, ctx->protocol));
893                return;
894        }
895               
896        if(ctx->msgstate == OTRL_MSGSTATE_FINISHED)
897                otrl_context_force_plaintext(ctx);
898        otrl_context_forget(ctx);
899}
900
901void cmd_otr_forget(irc_t *irc, char **args)
902{
903        if(!strcmp(args[1], "fingerprint"))
904        {
905                user_t *u;
906                ConnContext *ctx;
907                Fingerprint *fp;
908                char human[54];
909                char *s;
910               
911                if(!args[3]) {
912                        irc_usermsg(irc, "otr %s %s: not enough arguments (2 req.)", args[0], args[1]);
913                        return;
914                }
915               
916                /* TODO: allow context specs ("user/proto/account") in 'otr forget fingerprint'? */
917                u = user_find(irc, args[2]);
918                if(!u || !u->ic) {
919                        irc_usermsg(irc, "%s: unknown user", args[2]);
920                        return;
921                }
922               
923                ctx = otrl_context_find(irc->otr->us, u->handle, u->ic->acc->user,
924                        u->ic->acc->prpl->name, 0, NULL, NULL, NULL);
925                if(!ctx) {
926                        irc_usermsg(irc, "no otr context with %s", args[2]);
927                        return;
928                }
929               
930                fp = match_fingerprint(irc, ctx, ((const char **)args)+3);
931                if(!fp) {
932                        /* match_fingerprint does error messages */
933                        return;
934                }
935               
936                if(fp == ctx->active_fingerprint) {
937                        irc_usermsg(irc, "that fingerprint is active, terminate otr connection first");
938                        return;
939                }
940               
941                otrl_privkey_hash_to_human(human, fp->fingerprint);
942                s = g_strdup_printf("about to forget fingerprint %s, are you sure?", human);
943                query_add(irc, NULL, s, yes_forget_fingerprint, NULL, fp);
944                g_free(s);
945        }
946       
947        else if(!strcmp(args[1], "context"))
948        {
949                user_t *u;
950                ConnContext *ctx;
951                char *s;
952               
953                /* TODO: allow context specs ("user/proto/account") in 'otr forget contex'? */
954                u = user_find(irc, args[2]);
955                if(!u || !u->ic) {
956                        irc_usermsg(irc, "%s: unknown user", args[2]);
957                        return;
958                }
959               
960                ctx = otrl_context_find(irc->otr->us, u->handle, u->ic->acc->user,
961                        u->ic->acc->prpl->name, 0, NULL, NULL, NULL);
962                if(!ctx) {
963                        irc_usermsg(irc, "no otr context with %s", args[2]);
964                        return;
965                }
966               
967                if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
968                        irc_usermsg(irc, "active otr connection with %s, terminate it first", args[2]);
969                        return;
970                }
971               
972                s = g_strdup_printf("about to forget otr data about %s, are you sure?", args[2]);
973                query_add(irc, NULL, s, yes_forget_context, NULL, ctx);
974                g_free(s);
975        }
976       
977        else
978        {
979                irc_usermsg(irc, "otr %s: unknown subcommand \"%s\", see \x02help otr forget\x02",
980                        args[0], args[1]);
981        }
982}
983
984
985/*** local helpers / subroutines: ***/
986
987/* Socialist Millionaires' Protocol */
988void otr_handle_smp(struct im_connection *ic, const char *handle, OtrlTLV *tlvs)
989{
990        irc_t *irc = ic->irc;
991        OtrlUserState us = irc->otr->us;
992        OtrlMessageAppOps *ops = &global.otr_ops;
993        OtrlTLV *tlv = NULL;
994        ConnContext *context;
995        NextExpectedSMP nextMsg;
996        user_t *u;
997
998        u = user_findhandle(ic, handle);
999        if(!u) return;
1000        context = otrl_context_find(us, handle,
1001                ic->acc->user, ic->acc->prpl->name, 1, NULL, NULL, NULL);
1002        if(!context) {
1003                /* huh? out of memory or what? */
1004                return;
1005        }
1006        nextMsg = context->smstate->nextExpected;
1007
1008        tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP1);
1009        if (tlv) {
1010                if (nextMsg != OTRL_SMP_EXPECT1) {
1011                        irc_usermsg(irc, "smp %s: spurious SMP1 received, aborting", u->nick);
1012                        otrl_message_abort_smp(us, ops, u->ic, context);
1013                        otrl_sm_state_free(context->smstate);
1014                } else {
1015                        irc_usermsg(irc, "smp: initiated by %s"
1016                                " - respond with \x02otr smp %s <secret>\x02",
1017                                u->nick, u->nick);
1018                        /* smp stays in EXPECT1 until user responds */
1019                }
1020        }
1021        tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP2);
1022        if (tlv) {
1023                if (nextMsg != OTRL_SMP_EXPECT2) {
1024                        irc_usermsg(irc, "smp %s: spurious SMP2 received, aborting", u->nick);
1025                        otrl_message_abort_smp(us, ops, u->ic, context);
1026                        otrl_sm_state_free(context->smstate);
1027                } else {
1028                        /* SMP2 received, otrl_message_receiving will have sent SMP3 */
1029                        context->smstate->nextExpected = OTRL_SMP_EXPECT4;
1030                }
1031        }
1032        tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP3);
1033        if (tlv) {
1034                if (nextMsg != OTRL_SMP_EXPECT3) {
1035                        irc_usermsg(irc, "smp %s: spurious SMP3 received, aborting", u->nick);
1036                        otrl_message_abort_smp(us, ops, u->ic, context);
1037                        otrl_sm_state_free(context->smstate);
1038                } else {
1039                        /* SMP3 received, otrl_message_receiving will have sent SMP4 and set fp trust */
1040                        const char *trust = context->active_fingerprint->trust;
1041                        if(!trust || trust[0]=='\0') {
1042                                irc_usermsg(irc, "smp %s: secrets did not match, fingerprint not trusted",
1043                                        u->nick);
1044                        } else {
1045                                irc_usermsg(irc, "smp %s: secrets proved equal, fingerprint trusted",
1046                                        u->nick);
1047                        }
1048                        otrl_sm_state_free(context->smstate);
1049                        /* smp is in back in EXPECT1 */
1050                }
1051        }
1052        tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP4);
1053        if (tlv) {
1054                if (nextMsg != OTRL_SMP_EXPECT4) {
1055                        irc_usermsg(irc, "smp %s: spurious SMP4 received, aborting", u->nick);
1056                        otrl_message_abort_smp(us, ops, u->ic, context);
1057                        otrl_sm_state_free(context->smstate);
1058                } else {
1059                        /* SMP4 received, otrl_message_receiving will have set fp trust */
1060                        const char *trust = context->active_fingerprint->trust;
1061                        if(!trust || trust[0]=='\0') {
1062                                irc_usermsg(irc, "smp %s: secrets did not match, fingerprint not trusted",
1063                                        u->nick);
1064                        } else {
1065                                irc_usermsg(irc, "smp %s: secrets proved equal, fingerprint trusted",
1066                                        u->nick);
1067                        }
1068                        otrl_sm_state_free(context->smstate);
1069                        /* smp is in back in EXPECT1 */
1070                }
1071        }
1072        tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP_ABORT);
1073        if (tlv) {
1074                irc_usermsg(irc, "smp: received abort from %s", u->nick);
1075                otrl_sm_state_free(context->smstate);
1076                /* smp is in back in EXPECT1 */
1077        }
1078}
1079
1080/* helper to assert that account and protocol names given to ops below always
1081   match the im_connection passed through as opdata */
1082struct im_connection *check_imc(void *opdata, const char *accountname,
1083        const char *protocol)
1084{
1085        struct im_connection *ic = (struct im_connection *)opdata;
1086
1087        if (strcmp(accountname, ic->acc->user) != 0) {
1088                log_message(LOGLVL_WARNING,
1089                        "otr: internal account name mismatch: '%s' vs '%s'",
1090                        accountname, ic->acc->user);
1091        }
1092        if (strcmp(protocol, ic->acc->prpl->name) != 0) {
1093                log_message(LOGLVL_WARNING,
1094                        "otr: internal protocol name mismatch: '%s' vs '%s'",
1095                        protocol, ic->acc->prpl->name);
1096        }
1097       
1098        return ic;
1099}
1100
1101user_t *peeruser(irc_t *irc, const char *handle, const char *protocol)
1102{
1103        user_t *u;
1104       
1105        log_message(LOGLVL_DEBUG, "peeruser '%s' '%s'", handle, protocol);
1106       
1107        for(u=irc->users; u; u=u->next) {
1108                struct prpl *prpl;
1109                if(!u->ic || !u->handle)
1110                        continue;
1111                prpl = u->ic->acc->prpl;
1112                if(strcmp(prpl->name, protocol) == 0
1113                        && prpl->handle_cmp(u->handle, handle) == 0) {
1114                        return u;
1115                }
1116        }
1117       
1118        return NULL;
1119}
1120
1121int hexval(char a)
1122{
1123        int x=tolower(a);
1124       
1125        if(x>='a' && x<='f')
1126                x = x - 'a' + 10;
1127        else if(x>='0' && x<='9')
1128                x = x - '0';
1129        else
1130                return -1;
1131       
1132        return x;
1133}
1134
1135const char *peernick(irc_t *irc, const char *handle, const char *protocol)
1136{
1137        static char fallback[512];
1138       
1139        user_t *u = peeruser(irc, handle, protocol);
1140        if(u) {
1141                return u->nick;
1142        } else {
1143                g_snprintf(fallback, 511, "%s/%s", handle, protocol);
1144                return fallback;
1145        }
1146}
1147
1148int otr_update_modeflags(irc_t *irc, user_t *u)
1149{
1150        char *vb = set_getstr(&irc->set, "voice_buddies");
1151        char *hb = set_getstr(&irc->set, "halfop_buddies");
1152        char *ob = set_getstr(&irc->set, "op_buddies");
1153        int encrypted = u->encrypted;
1154        int trusted = u->encrypted > 1;
1155        char flags[7];
1156        int nflags=0;
1157        char *p = flags;
1158        char *from;
1159        int i;
1160       
1161        if(!strcmp(vb, "encrypted")) {
1162                *(p++) = encrypted ? '+' : '-';
1163                *(p++) = 'v';
1164                nflags++;
1165        } else if(!strcmp(vb, "trusted")) {
1166                *(p++) = trusted ? '+' : '-';
1167                *(p++) = 'v';
1168                nflags++;
1169        }
1170        if(!strcmp(hb, "encrypted")) {
1171                *(p++) = encrypted ? '+' : '-';
1172                *(p++) = 'h';
1173                nflags++;
1174        } else if(!strcmp(hb, "trusted")) {
1175                *(p++) = trusted ? '+' : '-';
1176                *(p++) = 'h';
1177                nflags++;
1178        }
1179        if(!strcmp(ob, "encrypted")) {
1180                *(p++) = encrypted ? '+' : '-';
1181                *(p++) = 'o';
1182                nflags++;
1183        } else if(!strcmp(ob, "trusted")) {
1184                *(p++) = trusted ? '+' : '-';
1185                *(p++) = 'o';
1186                nflags++;
1187        }
1188        *p = '\0';
1189       
1190        p = g_malloc(nflags * (strlen(u->nick)+1) + 1);
1191        *p = '\0';
1192        if(!p)
1193                return 0;
1194        for(i=0; i<nflags; i++) {
1195                strcat(p, " ");
1196                strcat(p, u->nick);
1197        }
1198        if(set_getbool(&irc->set, "simulate_netsplit"))
1199                from = g_strdup(irc->myhost);
1200        else
1201                from = g_strdup_printf("%s!%s@%s", irc->mynick, irc->mynick, irc->myhost);
1202        irc_write(irc, ":%s MODE %s %s%s", from, irc->channel, flags, p);
1203        g_free(from);
1204        g_free(p);
1205               
1206        return 1;
1207}
1208
1209void show_fingerprints(irc_t *irc, ConnContext *ctx)
1210{
1211        char human[45];
1212        Fingerprint *fp;
1213        const char *trust;
1214        int count=0;
1215       
1216        for(fp=&ctx->fingerprint_root; fp; fp=fp->next) {
1217                if(!fp->fingerprint)
1218                        continue;
1219                count++;
1220                otrl_privkey_hash_to_human(human, fp->fingerprint);
1221                if(!fp->trust || fp->trust[0] == '\0') {
1222                        trust="untrusted";
1223                } else {
1224                        trust=fp->trust;
1225                }
1226                if(fp == ctx->active_fingerprint) {
1227                        irc_usermsg(irc, "    \x02%s (%s)\x02", human, trust);
1228                } else {
1229                        irc_usermsg(irc, "    %s (%s)", human, trust);
1230                }
1231        }
1232        if(count==0)
1233                irc_usermsg(irc, "    (none)");
1234}
1235
1236Fingerprint *match_fingerprint(irc_t *irc, ConnContext *ctx, const char **args)
1237{
1238        Fingerprint *fp, *fp2;
1239        char human[45];
1240        char prefix[45], *p;
1241        int n;
1242        int i,j;
1243       
1244        /* assemble the args into a prefix in standard "human" form */
1245        n=0;
1246        p=prefix;
1247        for(i=0; args[i]; i++) {
1248                for(j=0; args[i][j]; j++) {
1249                        char c = toupper(args[i][j]);
1250                       
1251                        if(n>=40) {
1252                                irc_usermsg(irc, "too many fingerprint digits given, expected at most 40");
1253                                return NULL;
1254                        }
1255                       
1256                        if( (c>='A' && c<='F') || (c>='0' && c<='9') ) {
1257                                *(p++) = c;
1258                        } else {
1259                                irc_usermsg(irc, "invalid hex digit '%c' in block %d", args[i][j], i+1);
1260                                return NULL;
1261                        }
1262                       
1263                        n++;
1264                        if(n%8 == 0)
1265                                *(p++) = ' ';
1266                }
1267        }
1268        *p = '\0';
1269        log_message(LOGLVL_DEBUG, "match_fingerprint '%s'", prefix);
1270        log_message(LOGLVL_DEBUG, "n=%d strlen(prefix)=%d", n, strlen(prefix));
1271       
1272        /* find first fingerprint with the given prefix */
1273        n = strlen(prefix);
1274        for(fp=&ctx->fingerprint_root; fp; fp=fp->next) {
1275                if(!fp->fingerprint)
1276                        continue;
1277                otrl_privkey_hash_to_human(human, fp->fingerprint);
1278                if(!strncmp(prefix, human, n))
1279                        break;
1280        }
1281        if(!fp) {
1282                irc_usermsg(irc, "%s: no match", prefix);
1283                return NULL;
1284        }
1285       
1286        /* make sure the match, if any, is unique */
1287        for(fp2=fp->next; fp2; fp2=fp2->next) {
1288                if(!fp2->fingerprint)
1289                        continue;
1290                otrl_privkey_hash_to_human(human, fp2->fingerprint);
1291                if(!strncmp(prefix, human, n))
1292                        break;
1293        }
1294        if(fp2) {
1295                irc_usermsg(irc, "%s: multiple matches", prefix);
1296                return NULL;
1297        }
1298       
1299        return fp;
1300}
1301
1302OtrlPrivKey *match_privkey(irc_t *irc, const char **args)
1303{
1304        OtrlPrivKey *k, *k2;
1305        char human[45];
1306        char prefix[45], *p;
1307        int n;
1308        int i,j;
1309       
1310        /* assemble the args into a prefix in standard "human" form */
1311        n=0;
1312        p=prefix;
1313        for(i=0; args[i]; i++) {
1314                for(j=0; args[i][j]; j++) {
1315                        char c = toupper(args[i][j]);
1316                       
1317                        if(n>=40) {
1318                                irc_usermsg(irc, "too many fingerprint digits given, expected at most 40");
1319                                return NULL;
1320                        }
1321                       
1322                        if( (c>='A' && c<='F') || (c>='0' && c<='9') ) {
1323                                *(p++) = c;
1324                        } else {
1325                                irc_usermsg(irc, "invalid hex digit '%c' in block %d", args[i][j], i+1);
1326                                return NULL;
1327                        }
1328                       
1329                        n++;
1330                        if(n%8 == 0)
1331                                *(p++) = ' ';
1332                }
1333        }
1334        *p = '\0';
1335        log_message(LOGLVL_DEBUG, "match_privkey '%s'", prefix);
1336        log_message(LOGLVL_DEBUG, "n=%d strlen(prefix)=%d", n, strlen(prefix));
1337       
1338        /* find first key which matches the given prefix */
1339        n = strlen(prefix);
1340        for(k=irc->otr->us->privkey_root; k; k=k->next) {
1341                p = otrl_privkey_fingerprint(irc->otr->us, human, k->accountname, k->protocol);
1342                if(!p) /* gah! :-P */
1343                        continue;
1344                if(!strncmp(prefix, human, n))
1345                        break;
1346        }
1347        if(!k) {
1348                irc_usermsg(irc, "%s: no match", prefix);
1349                return NULL;
1350        }
1351       
1352        /* make sure the match, if any, is unique */
1353        for(k2=k->next; k2; k2=k2->next) {
1354                p = otrl_privkey_fingerprint(irc->otr->us, human, k2->accountname, k2->protocol);
1355                if(!p) /* gah! :-P */
1356                        continue;
1357                if(!strncmp(prefix, human, n))
1358                        break;
1359        }
1360        if(k2) {
1361                irc_usermsg(irc, "%s: multiple matches", prefix);
1362                return NULL;
1363        }
1364       
1365        return k;
1366}
1367
1368void show_general_otr_info(irc_t *irc)
1369{
1370        ConnContext *ctx;
1371        OtrlPrivKey *key;
1372        char human[45];
1373        kg_t *kg;
1374
1375        /* list all privkeys (including ones being generated) */
1376        irc_usermsg(irc, "\x1fprivate keys:\x1f");
1377        for(key=irc->otr->us->privkey_root; key; key=key->next) {
1378                const char *hash;
1379               
1380                switch(key->pubkey_type) {
1381                case OTRL_PUBKEY_TYPE_DSA:
1382                        irc_usermsg(irc, "  %s/%s - DSA", key->accountname, key->protocol);
1383                        break;
1384                default:
1385                        irc_usermsg(irc, "  %s/%s - type %d", key->accountname, key->protocol,
1386                                key->pubkey_type);
1387                }
1388
1389                /* No, it doesn't make much sense to search for the privkey again by
1390                   account/protocol, but libotr currently doesn't provide a direct routine
1391                   for hashing a given 'OtrlPrivKey'... */
1392                hash = otrl_privkey_fingerprint(irc->otr->us, human, key->accountname, key->protocol);
1393                if(hash) /* should always succeed */
1394                        irc_usermsg(irc, "    %s", human);
1395        }
1396        if(irc->otr->sent_accountname) {
1397                irc_usermsg(irc, "  %s/%s - DSA", irc->otr->sent_accountname,
1398                        irc->otr->sent_protocol);
1399                irc_usermsg(irc, "    (being generated)");
1400        }
1401        for(kg=irc->otr->todo; kg; kg=kg->next) {
1402                irc_usermsg(irc, "  %s/%s - DSA", kg->accountname, kg->protocol);
1403                irc_usermsg(irc, "    (queued)");
1404        }
1405        if(key == irc->otr->us->privkey_root &&
1406           !irc->otr->sent_accountname &&
1407           kg == irc->otr->todo)
1408                irc_usermsg(irc, "  (none)");
1409
1410        /* list all contexts */
1411        irc_usermsg(irc, "%s", "");
1412        irc_usermsg(irc, "\x1f" "connection contexts:\x1f (bold=currently encrypted)");
1413        for(ctx=irc->otr->us->context_root; ctx; ctx=ctx->next) {\
1414                user_t *u;
1415                char *userstring;
1416               
1417                u = peeruser(irc, ctx->username, ctx->protocol);
1418                if(u)
1419                        userstring = g_strdup_printf("%s/%s/%s (%s)",
1420                                ctx->username, ctx->protocol, ctx->accountname, u->nick);
1421                else
1422                        userstring = g_strdup_printf("%s/%s/%s",
1423                                ctx->username, ctx->protocol, ctx->accountname);
1424               
1425                if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
1426                        irc_usermsg(irc, \x02%s\x02", userstring);
1427                } else {
1428                        irc_usermsg(irc, "  %s", userstring);
1429                }
1430               
1431                g_free(userstring);
1432        }
1433        if(ctx == irc->otr->us->context_root)
1434                irc_usermsg(irc, "  (none)");
1435}
1436
1437void show_otr_context_info(irc_t *irc, ConnContext *ctx)
1438{
1439        switch(ctx->otr_offer) {
1440        case OFFER_NOT:
1441                irc_usermsg(irc, "  otr offer status: none sent");
1442                break;
1443        case OFFER_SENT:
1444                irc_usermsg(irc, "  otr offer status: awaiting reply");
1445                break;
1446        case OFFER_ACCEPTED:
1447                irc_usermsg(irc, "  otr offer status: accepted our offer");
1448                break;
1449        case OFFER_REJECTED:
1450                irc_usermsg(irc, "  otr offer status: ignored our offer");
1451                break;
1452        default:
1453                irc_usermsg(irc, "  otr offer status: %d", ctx->otr_offer);
1454        }
1455
1456        switch(ctx->msgstate) {
1457        case OTRL_MSGSTATE_PLAINTEXT:
1458                irc_usermsg(irc, "  connection state: cleartext");
1459                break;
1460        case OTRL_MSGSTATE_ENCRYPTED:
1461                irc_usermsg(irc, "  connection state: encrypted (v%d)", ctx->protocol_version);
1462                break;
1463        case OTRL_MSGSTATE_FINISHED:
1464                irc_usermsg(irc, "  connection state: shut down");
1465                break;
1466        default:
1467                irc_usermsg(irc, "  connection state: %d", ctx->msgstate);
1468        }
1469
1470        irc_usermsg(irc, "  fingerprints: (bold=active)");     
1471        show_fingerprints(irc, ctx);
1472}
1473
1474int keygen_in_progress(irc_t *irc, const char *handle, const char *protocol)
1475{
1476        kg_t *kg;
1477       
1478        log_message(LOGLVL_DEBUG, "keygen_in_progress '%s' '%s'", handle, protocol);
1479       
1480        if(!irc->otr->sent_accountname || !irc->otr->sent_protocol)
1481                return 0;
1482
1483        /* are we currently working on this key? */
1484        if(!strcmp(handle, irc->otr->sent_accountname) &&
1485           !strcmp(protocol, irc->otr->sent_protocol))
1486                return 1;
1487       
1488        /* do we have it queued for later? */
1489        for(kg=irc->otr->todo; kg; kg=kg->next) {
1490                if(!strcmp(handle, kg->accountname) &&
1491                   !strcmp(protocol, kg->protocol))
1492                        return 1;
1493        }
1494       
1495        return 0;
1496}
1497
1498void otr_keygen(irc_t *irc, const char *handle, const char *protocol)
1499{
1500        /* do nothing if a key for the requested account is already being generated */
1501        if(keygen_in_progress(irc, handle, protocol))
1502                return;
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->nick, 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 = g_strdup(handle);
1554                (*kg)->protocol = g_strdup(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 = g_strdup(handle);
1561                irc->otr->sent_protocol = g_strdup(protocol);
1562        }
1563}
1564
1565void keygen_child_main(const char *nick, int infd, int outfd)
1566{
1567        OtrlUserState us;
1568        char *kf;
1569        FILE *input, *output;
1570        char filename[128], accountname[512], protocol[512];
1571        gcry_error_t e;
1572        int tempfd;
1573       
1574        us = otrl_userstate_create();
1575        kf = g_strdup_printf("%s%s.otr_keys", global.conf->configdir, nick);
1576        otrl_privkey_read(us, kf);
1577        g_free(kf);
1578       
1579        input = fdopen(infd, "r");
1580        output = fdopen(outfd, "w");
1581       
1582        while(!feof(input) && !ferror(input) && !feof(output) && !ferror(output)) {
1583                myfgets(accountname, 512, input);
1584                myfgets(protocol, 512, input);
1585               
1586                strncpy(filename, "/tmp/bitlbee-XXXXXX", 128);
1587                tempfd = mkstemp(filename);
1588                close(tempfd);
1589
1590                e = otrl_privkey_generate(us, filename, accountname, protocol);
1591                if(e) {
1592                        fprintf(output, "\n");  /* this means failure */
1593                        fprintf(output, "otr keygen: %s\n", gcry_strerror(e));
1594                        unlink(filename);
1595                } else {
1596                        fprintf(output, "%s\n", filename);
1597                        fprintf(output, "otr keygen for %s/%s complete\n", accountname, protocol);
1598                }
1599                fflush(output);
1600        }
1601       
1602        fclose(input);
1603        fclose(output);
1604}
1605
1606gboolean keygen_finish_handler(gpointer data, gint fd, b_input_condition cond)
1607{
1608        irc_t *irc = (irc_t *)data;
1609        char filename[512], msg[512];
1610
1611        log_message(LOGLVL_DEBUG, "keygen_finish_handler cond=%d", cond);
1612
1613        myfgets(filename, 512, irc->otr->from);
1614        myfgets(msg, 512, irc->otr->from);
1615       
1616        log_message(LOGLVL_DEBUG, "filename='%s'", filename);
1617        log_message(LOGLVL_DEBUG, "msg='%s'", msg);
1618       
1619        irc_usermsg(irc, "%s", msg);
1620        if(filename[0]) {
1621                char *kf = g_strdup_printf("%s%s.otr_keys", global.conf->configdir, irc->nick);
1622                char *tmp = g_strdup_printf("%s.new", kf);
1623                copyfile(filename, tmp);
1624                unlink(filename);
1625                rename(tmp,kf);
1626                otrl_privkey_read(irc->otr->us, kf);
1627                g_free(kf);
1628                g_free(tmp);
1629        }
1630       
1631        /* forget this job */
1632        g_free(irc->otr->sent_accountname);
1633        g_free(irc->otr->sent_protocol);
1634        irc->otr->sent_accountname = NULL;
1635        irc->otr->sent_protocol = NULL;
1636       
1637        /* see if there are any more in the queue */
1638        if(irc->otr->todo) {
1639                kg_t *p = irc->otr->todo;
1640                /* send the next one over */
1641                log_message(LOGLVL_DEBUG, "slave: keygen for %s/%s!", p->accountname, p->protocol);
1642                fprintf(irc->otr->to, "%s\n%s\n", p->accountname, p->protocol);
1643                fflush(irc->otr->to);
1644                irc->otr->sent_accountname = p->accountname;
1645                irc->otr->sent_protocol = p->protocol;
1646                irc->otr->todo = p->next;
1647                g_free(p);
1648                return TRUE;   /* keep watching */
1649        } else {
1650                /* okay, the slave is idle now, so kill him */
1651                log_message(LOGLVL_DEBUG, "all keys done. die, slave!");
1652                fclose(irc->otr->from);
1653                fclose(irc->otr->to);
1654                kill(irc->otr->keygen, SIGTERM);
1655                waitpid(irc->otr->keygen, NULL, 0);
1656                irc->otr->keygen = 0;
1657                return FALSE;  /* unregister ourselves */
1658        }
1659}
1660
1661void copyfile(const char *a, const char *b)
1662{
1663        int fda, fdb;
1664        int n;
1665        char buf[1024];
1666       
1667        log_message(LOGLVL_DEBUG, "copyfile '%s' '%s'", a, b);
1668       
1669        fda = open(a, O_RDONLY);
1670        fdb = open(b, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1671       
1672        while((n=read(fda, buf, 1024)) > 0)
1673                write(fdb, buf, n);
1674       
1675        close(fda);
1676        close(fdb);     
1677}
1678
1679void myfgets(char *s, int size, FILE *stream)
1680{
1681        if(!fgets(s, size, stream)) {
1682                s[0] = '\0';
1683        } else {
1684                int n = strlen(s);
1685                if(n>0 && s[n-1] == '\n')
1686                        s[n-1] = '\0';
1687        }
1688}
1689
1690void yes_keygen(gpointer w, void *data)
1691{
1692        account_t *acc = (account_t *)data;
1693       
1694        if(keygen_in_progress(acc->irc, acc->user, acc->prpl->name)) {
1695                irc_usermsg(acc->irc, "keygen for %s/%s already in progress",
1696                        acc->user, acc->prpl->name);
1697        } else {
1698                irc_usermsg(acc->irc, "starting background keygen for %s/%s",
1699                        acc->user, acc->prpl->name);
1700                irc_usermsg(acc->irc, "you will be notified when it completes");
1701                otr_keygen(acc->irc, acc->user, acc->prpl->name);
1702        }
1703}
1704
1705
1706#else /* WITH_OTR undefined */
1707
1708void cmd_otr(irc_t *irc, char **args)
1709{
1710        irc_usermsg(irc, "otr: n/a, compiled without OTR support");
1711}
1712
1713#endif
Note: See TracBrowser for help on using the repository browser.