source: otr.c @ 1221ef0

Last change on this file since 1221ef0 was 1221ef0, checked in by Sven Moritz Hallberg <sm@…>, at 2008-02-16T15:28:08Z

show keys being generated in 'otr info'

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