source: otr.c @ 37ed402

Last change on this file since 37ed402 was 37ed402, checked in by unknown <pesco@…>, at 2013-08-02T18:08:34Z

use INSTAG_RECENT for outgoing messages

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