source: otr.c @ 22ec21d

Last change on this file since 22ec21d was 22ec21d, checked in by unknown <pesco@…>, at 2013-08-02T11:52:22Z

regularly call otrl_message_poll

  • Property mode set to 100644
File size: 52.0 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_MASTER; // 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        /* libotr 4.0.0 has a bug where it doesn't set opdata */
668        if(!opdata) {
669                /* crude fallback */
670                return 800;
671        }
672
673        struct im_connection *ic =
674                check_imc(opdata, context->accountname, context->protocol);
675 
676        return ic->acc->prpl->mms;
677}
678
679const char *op_account_name(void *opdata, const char *account, const char *protocol)
680{
681        struct im_connection *ic = (struct im_connection *)opdata;
682        irc_t *irc = ic->bee->ui_data;
683
684        return peernick(irc, account, protocol);
685}
686
687void op_convert_msg(void *opdata, ConnContext *ctx, OtrlConvertType typ,
688        char **dst, const char *src)
689{
690        struct im_connection *ic =
691                check_imc(opdata, ctx->accountname, ctx->protocol);
692        irc_t *irc = ic->bee->ui_data;
693        irc_user_t *iu = peeruser(irc, ctx->username, ctx->protocol);
694
695        if(typ == OTRL_CONVERT_RECEIVING) {
696                char *msg = g_strdup(src);
697
698                /* HTML decoding */
699                if(set_getbool(&ic->bee->set, "otr_does_html") &&
700                   !(ic->flags & OPT_DOES_HTML) &&
701                   set_getbool(&ic->bee->set, "strip_html")) {
702                        strip_html(msg);
703                        *dst = msg;
704                }
705
706                /* coloring */
707                if(set_getbool(&ic->bee->set, "otr_color_encrypted")) {
708                        int color;                /* color according to f'print trust */
709                        char *pre="", *sep="";    /* optional parts */
710                        const char *trust = ctx->active_fingerprint->trust;
711
712                        if(trust && trust[0] != '\0')
713                                color=3;   /* green */
714                        else
715                                color=5;   /* red */
716
717                        /* in a query window, keep "/me " uncolored at the beginning */
718                        if(g_strncasecmp(msg, "/me ", 4) == 0
719                           && irc_user_msgdest(iu) == irc->user->nick) {
720                                msg += 4;  /* skip */
721                                pre = "/me ";
722                        }
723
724                        /* comma in first place could mess with the color code */
725                        if(msg[0] == ',') {
726                            /* insert a space between color spec and message */
727                            sep = " ";
728                        }
729
730                        *dst = g_strdup_printf("%s\x03%.2d%s%s\x0F", pre,
731                                color, sep, msg);
732                        g_free(msg);
733                }
734        } else {
735                /* HTML encoding */
736                /* consider OTR plaintext to be HTML if otr_does_html is set */
737                if(ctx && ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED &&
738                   set_getbool(&ic->bee->set, "otr_does_html") &&
739                   (g_strncasecmp(src, "<html>", 6) != 0)) {
740                        *dst = escape_html(src);
741                }
742        }
743}
744
745void op_convert_free(void *opdata, ConnContext *ctx, char *msg)
746{
747        g_free(msg);
748}
749       
750/* Socialist Millionaires' Protocol */
751void op_handle_smp_event(void *opdata, OtrlSMPEvent ev, ConnContext *ctx,
752        unsigned short percent, char *question)
753{
754        struct im_connection *ic =
755                check_imc(opdata, ctx->accountname, ctx->protocol);
756        irc_t *irc = ic->bee->ui_data;
757        OtrlUserState us = irc->otr->us;
758        irc_user_t *u = peeruser(irc, ctx->username, ctx->protocol);
759
760        if(!u) return;
761
762        switch(ev) {
763        case OTRL_SMPEVENT_ASK_FOR_SECRET:
764                irc_rootmsg(irc, "smp: initiated by %s"
765                        " - respond with \x02otr smp %s <secret>\x02",
766                        u->nick, u->nick);
767                break;
768        case OTRL_SMPEVENT_ASK_FOR_ANSWER:
769                irc_rootmsg(irc, "smp: initiated by %s with question: \x02\"%s\"\x02", u->nick,
770                        question);
771                irc_rootmsg(irc, "smp: respond with \x02otr smp %s <answer>\x02",
772                        u->nick);
773                break;
774        case OTRL_SMPEVENT_CHEATED:
775                irc_rootmsg(irc, "smp %s: opponent violated protocol, aborting",
776                        u->nick);
777                otrl_message_abort_smp(us, &otr_ops, u->bu->ic, ctx);
778                otrl_sm_state_free(ctx->smstate);
779                break;
780        case OTRL_SMPEVENT_NONE:
781                break;
782        case OTRL_SMPEVENT_IN_PROGRESS:
783                break;
784        case OTRL_SMPEVENT_SUCCESS:
785                if(ctx->smstate->received_question) {
786                        irc_rootmsg(irc, "smp %s: correct answer, you are trusted",
787                                u->nick);
788                } else {
789                        irc_rootmsg(irc, "smp %s: secrets proved equal, fingerprint trusted",
790                                u->nick);
791                }
792                otrl_sm_state_free(ctx->smstate);
793                break;
794        case OTRL_SMPEVENT_FAILURE:
795                if(ctx->smstate->received_question) {
796                        irc_rootmsg(irc, "smp %s: wrong answer, you are not trusted",
797                                u->nick);
798                } else {
799                        irc_rootmsg(irc, "smp %s: secrets did not match, fingerprint not trusted",
800                                u->nick);
801                }
802                otrl_sm_state_free(ctx->smstate);
803                break;
804        case OTRL_SMPEVENT_ABORT:
805                irc_rootmsg(irc, "smp: received abort from %s", u->nick);
806                otrl_sm_state_free(ctx->smstate);
807                break;
808        case OTRL_SMPEVENT_ERROR:
809                irc_rootmsg(irc, "smp %s: protocol error, aborting",
810                        u->nick);
811                otrl_message_abort_smp(us, &otr_ops, u->bu->ic, ctx);
812                otrl_sm_state_free(ctx->smstate);
813                break;
814        }
815}
816
817void op_handle_msg_event(void *opdata, OtrlMessageEvent ev, ConnContext *ctx,
818        const char *message, gcry_error_t err)
819{
820        switch(ev) {
821        case OTRL_MSGEVENT_ENCRYPTION_REQUIRED:
822                display_otr_message(opdata, ctx,
823                        "policy requires encryption - message not sent");
824                break;
825        case OTRL_MSGEVENT_ENCRYPTION_ERROR:
826                display_otr_message(opdata, ctx,
827                        "error during encryption - message not sent");
828                break;
829        case OTRL_MSGEVENT_CONNECTION_ENDED:
830                display_otr_message(opdata, ctx,
831                        "other end has disconnected OTR - "
832                        "close connection or reconnect!");
833                break;
834        case OTRL_MSGEVENT_SETUP_ERROR:
835                display_otr_message(opdata, ctx,
836                        "OTR connection failed: %s", gcry_strerror(err));
837                break;
838        case OTRL_MSGEVENT_MSG_REFLECTED:
839                display_otr_message(opdata, ctx,
840                        "received our own OTR message (!?)");
841                break;
842        case OTRL_MSGEVENT_MSG_RESENT:
843                display_otr_message(opdata, ctx,
844                        "the previous message was resent");
845                break;
846        case OTRL_MSGEVENT_RCVDMSG_NOT_IN_PRIVATE:
847                display_otr_message(opdata, ctx,
848                        "unexpected encrypted message received");
849                break;
850        case OTRL_MSGEVENT_RCVDMSG_UNREADABLE:
851                display_otr_message(opdata, ctx,
852                        "unreadable encrypted message received");
853                break;
854        case OTRL_MSGEVENT_RCVDMSG_MALFORMED:
855                display_otr_message(opdata, ctx,
856                        "malformed OTR message received");
857                break;
858        case OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR:
859                display_otr_message(opdata, ctx,
860                        "OTR error message received: %s", message);
861                break;
862        case OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED:
863                display_otr_message(opdata, ctx,
864                        "unencrypted message received: %s", message);
865                break;
866        case OTRL_MSGEVENT_RCVDMSG_UNRECOGNIZED:
867                display_otr_message(opdata, ctx,
868                        "unrecognized OTR message received");
869                break;
870        default:
871                /* ignore  XXX log? */
872                break;
873        }
874}
875
876const char *op_otr_error_message(void *opdata, ConnContext *ctx,
877        OtrlErrorCode err_code)
878{
879        switch(err_code) {
880        case OTRL_ERRCODE_ENCRYPTION_ERROR:
881                return "i failed to encrypt a message";
882        case OTRL_ERRCODE_MSG_NOT_IN_PRIVATE:
883                return "you sent an encrypted message i didn't expect";
884        case OTRL_ERRCODE_MSG_UNREADABLE:
885                return "could not read encrypted message";
886        case OTRL_ERRCODE_MSG_MALFORMED:
887                return "you sent a malformed OTR message";
888        default:
889                return "i suffered an unexpected OTR error";
890        }
891}
892
893
894
895/*** OTR sub-command handlers ***/
896
897void cmd_otr_reconnect(irc_t *irc, char **args)
898{
899        cmd_otr_disconnect(irc, args);
900        cmd_otr_connect(irc, args);
901}
902
903void cmd_otr_disconnect(irc_t *irc, char **args)
904{
905        irc_user_t *u;
906
907        u = irc_user_by_name(irc, args[1]);
908        if(!u || !u->bu || !u->bu->ic) {
909                irc_rootmsg(irc, "%s: unknown user", args[1]);
910                return;
911        }
912       
913        /* XXX we disconnect all instances; is that what we want? */
914        otrl_message_disconnect_all_instances(irc->otr->us, &otr_ops,
915                u->bu->ic, u->bu->ic->acc->user, u->bu->ic->acc->prpl->name, u->bu->handle);
916       
917        /* for some reason, libotr (4.0.0) doesn't do this itself: */
918        if(!(u->flags & IRC_USER_OTR_ENCRYPTED))
919                return;
920
921        ConnContext *ctx, *p;
922        ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
923                u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);
924        if(!ctx) { /* huh? */
925                u->flags &= ( IRC_USER_OTR_ENCRYPTED | IRC_USER_OTR_TRUSTED );
926                return;
927        }
928
929        for(p=ctx; p && p->m_context == ctx->m_context; p=p->next)
930                op_gone_insecure(u->bu->ic, p);
931}
932
933void cmd_otr_connect(irc_t *irc, char **args)
934{
935        irc_user_t *u;
936
937        u = irc_user_by_name(irc, args[1]);
938        if(!u || !u->bu || !u->bu->ic) {
939                irc_rootmsg(irc, "%s: unknown user", args[1]);
940                return;
941        }
942        if(!(u->bu->flags & BEE_USER_ONLINE)) {
943                irc_rootmsg(irc, "%s is offline", args[1]);
944                return;
945        }
946       
947        bee_user_msg(irc->b, u->bu, "?OTR?v2?", 0);
948}
949
950void cmd_otr_smp(irc_t *irc, char **args)
951{
952        otr_smp_or_smpq(irc, args[1], NULL, args[2]);   /* no question */
953}
954
955void cmd_otr_smpq(irc_t *irc, char **args)
956{
957        otr_smp_or_smpq(irc, args[1], args[2], args[3]);
958}
959
960void cmd_otr_trust(irc_t *irc, char **args)
961{
962        irc_user_t *u;
963        ConnContext *ctx;
964        unsigned char raw[20];
965        Fingerprint *fp;
966        int i,j;
967       
968        u = irc_user_by_name(irc, args[1]);
969        if(!u || !u->bu || !u->bu->ic) {
970                irc_rootmsg(irc, "%s: unknown user", args[1]);
971                return;
972        }
973       
974        ctx = otrl_context_find(irc->otr->us, u->bu->handle,
975                u->bu->ic->acc->user, u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
976        if(!ctx) {
977                irc_rootmsg(irc, "%s: no otr context with user", args[1]);
978                return;
979        }
980       
981        /* convert given fingerprint to raw representation */
982        for(i=0; i<5; i++) {
983                for(j=0; j<4; j++) {
984                        char *p = args[2+i]+(2*j);
985                        char *q = p+1;
986                        int x, y;
987                       
988                        if(!*p || !*q) {
989                                irc_rootmsg(irc, "failed: truncated fingerprint block %d", i+1);
990                                return;
991                        }
992                       
993                        x = hexval(*p);
994                        y = hexval(*q);
995                        if(x<0) {
996                                irc_rootmsg(irc, "failed: %d. hex digit of block %d out of range", 2*j+1, i+1);
997                                return;
998                        }
999                        if(y<0) {
1000                                irc_rootmsg(irc, "failed: %d. hex digit of block %d out of range", 2*j+2, i+1);
1001                                return;
1002                        }
1003
1004                        raw[i*4+j] = x*16 + y;
1005                }
1006        }
1007        fp = otrl_context_find_fingerprint(ctx, raw, 0, NULL);
1008        if(!fp) {
1009                irc_rootmsg(irc, "failed: no such fingerprint for %s", args[1]);
1010        } else {
1011                char *trust = args[7] ? args[7] : "affirmed";
1012                otrl_context_set_trust(fp, trust);
1013                irc_rootmsg(irc, "fingerprint match, trust set to \"%s\"", trust);
1014                if(u->flags & IRC_USER_OTR_ENCRYPTED)
1015                        u->flags |= IRC_USER_OTR_TRUSTED;
1016                otr_update_modeflags(irc, u);
1017        }
1018}
1019
1020void cmd_otr_info(irc_t *irc, char **args)
1021{
1022        if(!args[1]) {
1023                show_general_otr_info(irc);
1024        } else {
1025                char *arg = g_strdup(args[1]);
1026                char *myhandle, *handle=NULL, *protocol;
1027                ConnContext *ctx;
1028               
1029                /* interpret arg as 'user/protocol/account' if possible */
1030                protocol = strchr(arg, '/');
1031                myhandle = NULL;
1032                if(protocol) {
1033                        *(protocol++) = '\0';
1034                        myhandle = strchr(protocol, '/');
1035                }
1036                if(protocol && myhandle) {
1037                        *(myhandle++) = '\0';
1038                        handle = arg;
1039                        ctx = otrl_context_find(irc->otr->us, handle, myhandle, protocol, 0, OTRL_INSTAG_MASTER, NULL, NULL, NULL);  // XXX
1040                        if(!ctx) {
1041                                irc_rootmsg(irc, "no such context");
1042                                g_free(arg);
1043                                return;
1044                        }
1045                } else {
1046                        irc_user_t *u = irc_user_by_name(irc, args[1]);
1047                        if(!u || !u->bu || !u->bu->ic) {
1048                                irc_rootmsg(irc, "%s: unknown user", args[1]);
1049                                g_free(arg);
1050                                return;
1051                        }
1052                        ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
1053                                u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1054                        if(!ctx) {
1055                                irc_rootmsg(irc, "no otr context with %s", args[1]);
1056                                g_free(arg);
1057                                return;
1058                        }
1059                }
1060       
1061                /* show how we resolved the (nick) argument, if we did */
1062                if(handle!=arg) {
1063                        irc_rootmsg(irc, "%s is %s/%s; we are %s/%s to them", args[1],
1064                                ctx->username, ctx->protocol, ctx->accountname, ctx->protocol);
1065                }
1066                show_otr_context_info(irc, ctx);
1067                g_free(arg);
1068        }
1069}
1070
1071void cmd_otr_keygen(irc_t *irc, char **args)
1072{
1073        int i, n;
1074        account_t *a;
1075       
1076        n = atoi(args[1]);
1077        if(n<0 || (!n && strcmp(args[1], "0"))) {
1078                irc_rootmsg(irc, "%s: invalid account number", args[1]);
1079                return;
1080        }
1081       
1082        a = irc->b->accounts;
1083        for(i=0; i<n && a; i++, a=a->next);
1084        if(!a) {
1085                irc_rootmsg(irc, "%s: no such account", args[1]);
1086                return;
1087        }
1088       
1089        if(keygen_in_progress(irc, a->user, a->prpl->name)) {
1090                irc_rootmsg(irc, "keygen for account %d already in progress", n);
1091                return;
1092        }
1093       
1094        if(otrl_privkey_find(irc->otr->us, a->user, a->prpl->name)) {
1095                char *s = g_strdup_printf("account %d already has a key, replace it?", n);
1096                query_add(irc, NULL, s, yes_keygen, NULL, NULL, a);
1097                g_free(s);
1098        } else {
1099                otr_keygen(irc, a->user, a->prpl->name);
1100        }
1101}
1102
1103void yes_forget_fingerprint(void *data)
1104{
1105        pair_t *p = (pair_t *)data;
1106        irc_t *irc = (irc_t *)p->fst;
1107        Fingerprint *fp = (Fingerprint *)p->snd;
1108
1109        g_free(p);
1110       
1111        if(fp == fp->context->active_fingerprint) {
1112                irc_rootmsg(irc, "that fingerprint is active, terminate otr connection first");
1113                return;
1114        }
1115               
1116        otrl_context_forget_fingerprint(fp, 0);
1117}
1118
1119void yes_forget_context(void *data)
1120{
1121        pair_t *p = (pair_t *)data;
1122        irc_t *irc = (irc_t *)p->fst;
1123        ConnContext *ctx = (ConnContext *)p->snd;
1124
1125        g_free(p);
1126       
1127        if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
1128                irc_rootmsg(irc, "active otr connection with %s, terminate it first",
1129                        peernick(irc, ctx->username, ctx->protocol));
1130                return;
1131        }
1132               
1133        if(ctx->msgstate == OTRL_MSGSTATE_FINISHED)
1134                otrl_context_force_plaintext(ctx);
1135        otrl_context_forget(ctx);
1136}
1137
1138void yes_forget_key(void *data)
1139{
1140        OtrlPrivKey *key = (OtrlPrivKey *)data;
1141       
1142        otrl_privkey_forget(key);
1143        /* Hm, libotr doesn't seem to offer a function for explicitly /writing/
1144           keyfiles. So the key will be back on the next load... */
1145        /* TODO: Actually erase forgotten keys from storage? */
1146}
1147
1148void cmd_otr_forget(irc_t *irc, char **args)
1149{
1150        if(!strcmp(args[1], "fingerprint"))
1151        {
1152                irc_user_t *u;
1153                ConnContext *ctx;
1154                Fingerprint *fp;
1155                char human[54];
1156                char *s;
1157                pair_t *p;
1158               
1159                if(!args[3]) {
1160                        irc_rootmsg(irc, "otr %s %s: not enough arguments (2 req.)", args[0], args[1]);
1161                        return;
1162                }
1163               
1164                /* TODO: allow context specs ("user/proto/account") in 'otr forget fingerprint'? */
1165                u = irc_user_by_name(irc, args[2]);
1166                if(!u || !u->bu || !u->bu->ic) {
1167                        irc_rootmsg(irc, "%s: unknown user", args[2]);
1168                        return;
1169                }
1170               
1171                ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
1172                        u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1173                if(!ctx) {
1174                        irc_rootmsg(irc, "no otr context with %s", args[2]);
1175                        return;
1176                }
1177               
1178                fp = match_fingerprint(irc, ctx, ((const char **)args)+3);
1179                if(!fp) {
1180                        /* match_fingerprint does error messages */
1181                        return;
1182                }
1183               
1184                if(fp == ctx->active_fingerprint) {
1185                        irc_rootmsg(irc, "that fingerprint is active, terminate otr connection first");
1186                        return;
1187                }
1188               
1189                otrl_privkey_hash_to_human(human, fp->fingerprint);
1190                s = g_strdup_printf("about to forget fingerprint %s, are you sure?", human);
1191                p = g_malloc(sizeof(pair_t));
1192                if(!p)
1193                        return;
1194                p->fst = irc;
1195                p->snd = fp;
1196                query_add(irc, NULL, s, yes_forget_fingerprint, NULL, NULL, p);
1197                g_free(s);
1198        }
1199       
1200        else if(!strcmp(args[1], "context"))
1201        {
1202                irc_user_t *u;
1203                ConnContext *ctx;
1204                char *s;
1205                pair_t *p;
1206               
1207                /* TODO: allow context specs ("user/proto/account") in 'otr forget contex'? */
1208                u = irc_user_by_name(irc, args[2]);
1209                if(!u || !u->bu || !u->bu->ic) {
1210                        irc_rootmsg(irc, "%s: unknown user", args[2]);
1211                        return;
1212                }
1213               
1214                ctx = otrl_context_find(irc->otr->us, u->bu->handle, u->bu->ic->acc->user,
1215                        u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1216                if(!ctx) {
1217                        irc_rootmsg(irc, "no otr context with %s", args[2]);
1218                        return;
1219                }
1220               
1221                if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
1222                        irc_rootmsg(irc, "active otr connection with %s, terminate it first", args[2]);
1223                        return;
1224                }
1225               
1226                s = g_strdup_printf("about to forget otr data about %s, are you sure?", args[2]);
1227                p = g_malloc(sizeof(pair_t));
1228                if(!p)
1229                        return;
1230                p->fst = irc;
1231                p->snd = ctx;
1232                query_add(irc, NULL, s, yes_forget_context, NULL, NULL, p);
1233                g_free(s);
1234        }
1235       
1236        else if(!strcmp(args[1], "key"))
1237        {
1238                OtrlPrivKey *key;
1239                char *s;
1240               
1241                key = match_privkey(irc, ((const char **)args)+2);
1242                if(!key) {
1243                        /* match_privkey does error messages */
1244                        return;
1245                }
1246               
1247                s = g_strdup_printf("about to forget the private key for %s/%s, are you sure?",
1248                        key->accountname, key->protocol);
1249                query_add(irc, NULL, s, yes_forget_key, NULL, NULL, key);
1250                g_free(s);
1251        }
1252       
1253        else
1254        {
1255                irc_rootmsg(irc, "otr %s: unknown subcommand \"%s\", see \x02help otr forget\x02",
1256                        args[0], args[1]);
1257        }
1258}
1259
1260
1261/*** local helpers / subroutines: ***/
1262
1263void log_otr_message(void *opdata, const char *fmt, ...)
1264{
1265        va_list va;
1266
1267        va_start(va, fmt);
1268        char *msg = g_strdup_vprintf(fmt, va);
1269        va_end(va);
1270       
1271        log_message(LOGLVL_INFO, "otr: %s", msg);
1272}
1273
1274void display_otr_message(void *opdata, ConnContext *ctx, const char *fmt, ...)
1275{
1276        struct im_connection *ic =
1277                check_imc(opdata, ctx->accountname, ctx->protocol);
1278        irc_t *irc = ic->bee->ui_data;
1279        irc_user_t *u = peeruser(irc, ctx->username, ctx->protocol);
1280        va_list va;
1281
1282        va_start(va, fmt);
1283        char *msg = g_strdup_vprintf(fmt, va);
1284        va_end(va);
1285
1286        if(u) {
1287                /* display as a notice from this particular user */
1288                irc_usernotice(u, "%s", msg);
1289        } else {
1290                irc_rootmsg(irc, "[otr] %s", msg);
1291        }
1292
1293        g_free(msg);
1294}
1295
1296/* combined handler for the 'otr smp' and 'otr smpq' commands */
1297void otr_smp_or_smpq(irc_t *irc, const char *nick, const char *question,
1298                const char *secret)
1299{
1300        irc_user_t *u;
1301        ConnContext *ctx;
1302
1303        u = irc_user_by_name(irc, nick);
1304        if(!u || !u->bu || !u->bu->ic) {
1305                irc_rootmsg(irc, "%s: unknown user", nick);
1306                return;
1307        }
1308        if(!(u->bu->flags & BEE_USER_ONLINE)) {
1309                irc_rootmsg(irc, "%s is offline", nick);
1310                return;
1311        }
1312       
1313        ctx = otrl_context_find(irc->otr->us, u->bu->handle,
1314                u->bu->ic->acc->user, u->bu->ic->acc->prpl->name, OTRL_INSTAG_MASTER, 0, NULL, NULL, NULL);  // XXX
1315        if(!ctx || ctx->msgstate != OTRL_MSGSTATE_ENCRYPTED) {
1316                irc_rootmsg(irc, "smp: otr inactive with %s, try \x02otr connect"
1317                                " %s\x02", nick, nick);
1318                return;
1319        }
1320
1321        if(ctx->smstate->nextExpected != OTRL_SMP_EXPECT1) {
1322                log_message(LOGLVL_INFO,
1323                        "SMP already in phase %d, sending abort before reinitiating",
1324                        ctx->smstate->nextExpected+1);
1325                otrl_message_abort_smp(irc->otr->us, &otr_ops, u->bu->ic, ctx);
1326                otrl_sm_state_free(ctx->smstate);
1327        }
1328
1329        if(question) {
1330                /* this was 'otr smpq', just initiate */
1331                irc_rootmsg(irc, "smp: initiating with %s...", u->nick);
1332                otrl_message_initiate_smp_q(irc->otr->us, &otr_ops, u->bu->ic, ctx,
1333                        question, (unsigned char *)secret, strlen(secret));
1334                /* smp is now in EXPECT2 */
1335        } else {
1336                /* this was 'otr smp', initiate or reply */
1337                /* warning: the following assumes that smstates are cleared whenever an SMP
1338                   is completed or aborted! */ 
1339                if(ctx->smstate->secret == NULL) {
1340                        irc_rootmsg(irc, "smp: initiating with %s...", u->nick);
1341                        otrl_message_initiate_smp(irc->otr->us, &otr_ops,
1342                                u->bu->ic, ctx, (unsigned char *)secret, strlen(secret));
1343                        /* smp is now in EXPECT2 */
1344                } else {
1345                        /* if we're still in EXPECT1 but smstate is initialized, we must have
1346                           received the SMP1, so let's issue a response */
1347                        irc_rootmsg(irc, "smp: responding to %s...", u->nick);
1348                        otrl_message_respond_smp(irc->otr->us, &otr_ops,
1349                                u->bu->ic, ctx, (unsigned char *)secret, strlen(secret));
1350                        /* smp is now in EXPECT3 */
1351                }
1352        }
1353}
1354
1355/* timeout handler that calls otrl_message_poll */
1356gboolean ev_message_poll(gpointer data, gint fd, b_input_condition cond)
1357{
1358        otr_t *otr = data;
1359
1360        otrl_message_poll(otr->us, &otr_ops, NULL);
1361
1362        return TRUE;    /* cycle timer */
1363}
1364
1365/* helper to assert that account and protocol names given to ops below always
1366   match the im_connection passed through as opdata */
1367struct im_connection *check_imc(void *opdata, const char *accountname,
1368        const char *protocol)
1369{
1370        struct im_connection *ic = (struct im_connection *)opdata;
1371
1372        if (strcmp(accountname, ic->acc->user) != 0) {
1373                log_message(LOGLVL_WARNING,
1374                        "otr: internal account name mismatch: '%s' vs '%s'",
1375                        accountname, ic->acc->user);
1376        }
1377        if (strcmp(protocol, ic->acc->prpl->name) != 0) {
1378                log_message(LOGLVL_WARNING,
1379                        "otr: internal protocol name mismatch: '%s' vs '%s'",
1380                        protocol, ic->acc->prpl->name);
1381        }
1382       
1383        return ic;
1384}
1385
1386irc_user_t *peeruser(irc_t *irc, const char *handle, const char *protocol)
1387{
1388        GSList *l;
1389       
1390        for(l=irc->b->users; l; l = l->next) {
1391                bee_user_t *bu = l->data;
1392                struct prpl *prpl;
1393                if(!bu->ui_data || !bu->ic || !bu->handle)
1394                        continue;
1395                prpl = bu->ic->acc->prpl;
1396                if(strcmp(prpl->name, protocol) == 0
1397                        && prpl->handle_cmp(bu->handle, handle) == 0) {
1398                        return bu->ui_data;
1399                }
1400        }
1401       
1402        return NULL;
1403}
1404
1405int hexval(char a)
1406{
1407        int x=tolower(a);
1408       
1409        if(x>='a' && x<='f')
1410                x = x - 'a' + 10;
1411        else if(x>='0' && x<='9')
1412                x = x - '0';
1413        else
1414                return -1;
1415       
1416        return x;
1417}
1418
1419const char *peernick(irc_t *irc, const char *handle, const char *protocol)
1420{
1421        static char fallback[512];
1422       
1423        irc_user_t *u = peeruser(irc, handle, protocol);
1424        if(u) {
1425                return u->nick;
1426        } else {
1427                g_snprintf(fallback, 511, "%s/%s", handle, protocol);
1428                return fallback;
1429        }
1430}
1431
1432void otr_update_uflags(ConnContext *context, irc_user_t *u)
1433{
1434        const char *trust;
1435
1436        if(context->active_fingerprint) {
1437                u->flags |= IRC_USER_OTR_ENCRYPTED;
1438
1439                trust = context->active_fingerprint->trust;
1440                if(trust && trust[0])
1441                        u->flags |= IRC_USER_OTR_TRUSTED;
1442                else
1443                        u->flags &= ~IRC_USER_OTR_TRUSTED;
1444        } else {
1445                u->flags &= ~IRC_USER_OTR_ENCRYPTED;
1446        }
1447}
1448
1449int otr_update_modeflags(irc_t *irc, irc_user_t *u)
1450{
1451        return 0;
1452}
1453
1454void show_fingerprints(irc_t *irc, ConnContext *ctx)
1455{
1456        char human[45];
1457        Fingerprint *fp;
1458        const char *trust;
1459        int count=0;
1460       
1461        for(fp=&ctx->fingerprint_root; fp; fp=fp->next) {
1462                if(!fp->fingerprint)
1463                        continue;
1464                count++;
1465                otrl_privkey_hash_to_human(human, fp->fingerprint);
1466                if(!fp->trust || fp->trust[0] == '\0') {
1467                        trust="untrusted";
1468                } else {
1469                        trust=fp->trust;
1470                }
1471                if(fp == ctx->active_fingerprint) {
1472                        irc_rootmsg(irc, "    \x02%s (%s)\x02", human, trust);
1473                } else {
1474                        irc_rootmsg(irc, "    %s (%s)", human, trust);
1475                }
1476        }
1477        if(count==0)
1478                irc_rootmsg(irc, "    (none)");
1479}
1480
1481Fingerprint *match_fingerprint(irc_t *irc, ConnContext *ctx, const char **args)
1482{
1483        Fingerprint *fp, *fp2;
1484        char human[45];
1485        char prefix[45], *p;
1486        int n;
1487        int i,j;
1488       
1489        /* assemble the args into a prefix in standard "human" form */
1490        n=0;
1491        p=prefix;
1492        for(i=0; args[i]; i++) {
1493                for(j=0; args[i][j]; j++) {
1494                        char c = toupper(args[i][j]);
1495                       
1496                        if(n>=40) {
1497                                irc_rootmsg(irc, "too many fingerprint digits given, expected at most 40");
1498                                return NULL;
1499                        }
1500                       
1501                        if( (c>='A' && c<='F') || (c>='0' && c<='9') ) {
1502                                *(p++) = c;
1503                        } else {
1504                                irc_rootmsg(irc, "invalid hex digit '%c' in block %d", args[i][j], i+1);
1505                                return NULL;
1506                        }
1507                       
1508                        n++;
1509                        if(n%8 == 0)
1510                                *(p++) = ' ';
1511                }
1512        }
1513        *p = '\0';
1514       
1515        /* find first fingerprint with the given prefix */
1516        n = strlen(prefix);
1517        for(fp=&ctx->fingerprint_root; fp; fp=fp->next) {
1518                if(!fp->fingerprint)
1519                        continue;
1520                otrl_privkey_hash_to_human(human, fp->fingerprint);
1521                if(!strncmp(prefix, human, n))
1522                        break;
1523        }
1524        if(!fp) {
1525                irc_rootmsg(irc, "%s: no match", prefix);
1526                return NULL;
1527        }
1528       
1529        /* make sure the match, if any, is unique */
1530        for(fp2=fp->next; fp2; fp2=fp2->next) {
1531                if(!fp2->fingerprint)
1532                        continue;
1533                otrl_privkey_hash_to_human(human, fp2->fingerprint);
1534                if(!strncmp(prefix, human, n))
1535                        break;
1536        }
1537        if(fp2) {
1538                irc_rootmsg(irc, "%s: multiple matches", prefix);
1539                return NULL;
1540        }
1541       
1542        return fp;
1543}
1544
1545OtrlPrivKey *match_privkey(irc_t *irc, const char **args)
1546{
1547        OtrlPrivKey *k, *k2;
1548        char human[45];
1549        char prefix[45], *p;
1550        int n;
1551        int i,j;
1552       
1553        /* assemble the args into a prefix in standard "human" form */
1554        n=0;
1555        p=prefix;
1556        for(i=0; args[i]; i++) {
1557                for(j=0; args[i][j]; j++) {
1558                        char c = toupper(args[i][j]);
1559                       
1560                        if(n>=40) {
1561                                irc_rootmsg(irc, "too many fingerprint digits given, expected at most 40");
1562                                return NULL;
1563                        }
1564                       
1565                        if( (c>='A' && c<='F') || (c>='0' && c<='9') ) {
1566                                *(p++) = c;
1567                        } else {
1568                                irc_rootmsg(irc, "invalid hex digit '%c' in block %d", args[i][j], i+1);
1569                                return NULL;
1570                        }
1571                       
1572                        n++;
1573                        if(n%8 == 0)
1574                                *(p++) = ' ';
1575                }
1576        }
1577        *p = '\0';
1578       
1579        /* find first key which matches the given prefix */
1580        n = strlen(prefix);
1581        for(k=irc->otr->us->privkey_root; k; k=k->next) {
1582                p = otrl_privkey_fingerprint(irc->otr->us, human, k->accountname, k->protocol);
1583                if(!p) /* gah! :-P */
1584                        continue;
1585                if(!strncmp(prefix, human, n))
1586                        break;
1587        }
1588        if(!k) {
1589                irc_rootmsg(irc, "%s: no match", prefix);
1590                return NULL;
1591        }
1592       
1593        /* make sure the match, if any, is unique */
1594        for(k2=k->next; k2; k2=k2->next) {
1595                p = otrl_privkey_fingerprint(irc->otr->us, human, k2->accountname, k2->protocol);
1596                if(!p) /* gah! :-P */
1597                        continue;
1598                if(!strncmp(prefix, human, n))
1599                        break;
1600        }
1601        if(k2) {
1602                irc_rootmsg(irc, "%s: multiple matches", prefix);
1603                return NULL;
1604        }
1605       
1606        return k;
1607}
1608
1609void show_general_otr_info(irc_t *irc)
1610{
1611        ConnContext *ctx;
1612        OtrlPrivKey *key;
1613        char human[45];
1614        kg_t *kg;
1615
1616        /* list all privkeys (including ones being generated) */
1617        irc_rootmsg(irc, "\x1fprivate keys:\x1f");
1618        for(key=irc->otr->us->privkey_root; key; key=key->next) {
1619                const char *hash;
1620               
1621                switch(key->pubkey_type) {
1622                case OTRL_PUBKEY_TYPE_DSA:
1623                        irc_rootmsg(irc, "  %s/%s - DSA", key->accountname, key->protocol);
1624                        break;
1625                default:
1626                        irc_rootmsg(irc, "  %s/%s - type %d", key->accountname, key->protocol,
1627                                key->pubkey_type);
1628                }
1629
1630                /* No, it doesn't make much sense to search for the privkey again by
1631                   account/protocol, but libotr currently doesn't provide a direct routine
1632                   for hashing a given 'OtrlPrivKey'... */
1633                hash = otrl_privkey_fingerprint(irc->otr->us, human, key->accountname, key->protocol);
1634                if(hash) /* should always succeed */
1635                        irc_rootmsg(irc, "    %s", human);
1636        }
1637        if(irc->otr->sent_accountname) {
1638                irc_rootmsg(irc, "  %s/%s - DSA", irc->otr->sent_accountname,
1639                        irc->otr->sent_protocol);
1640                irc_rootmsg(irc, "    (being generated)");
1641        }
1642        for(kg=irc->otr->todo; kg; kg=kg->next) {
1643                irc_rootmsg(irc, "  %s/%s - DSA", kg->accountname, kg->protocol);
1644                irc_rootmsg(irc, "    (queued)");
1645        }
1646        if(key == irc->otr->us->privkey_root &&
1647           !irc->otr->sent_accountname &&
1648           kg == irc->otr->todo)
1649                irc_rootmsg(irc, "  (none)");
1650
1651        /* list all contexts */
1652        irc_rootmsg(irc, "%s", "");
1653        irc_rootmsg(irc, "\x1f" "connection contexts:\x1f (bold=currently encrypted)");
1654        for(ctx=irc->otr->us->context_root; ctx; ctx=ctx->next) {\
1655                irc_user_t *u;
1656                char *userstring;
1657               
1658                u = peeruser(irc, ctx->username, ctx->protocol);
1659                if(u)
1660                        userstring = g_strdup_printf("%s/%s/%s (%s)",
1661                                ctx->username, ctx->protocol, ctx->accountname, u->nick);
1662                else
1663                        userstring = g_strdup_printf("%s/%s/%s",
1664                                ctx->username, ctx->protocol, ctx->accountname);
1665               
1666                if(ctx->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
1667                        irc_rootmsg(irc, \x02%s\x02", userstring);
1668                } else {
1669                        irc_rootmsg(irc, "  %s", userstring);
1670                }
1671               
1672                g_free(userstring);
1673        }
1674        if(ctx == irc->otr->us->context_root)
1675                irc_rootmsg(irc, "  (none)");
1676}
1677
1678void show_otr_context_info(irc_t *irc, ConnContext *ctx)
1679{
1680        switch(ctx->otr_offer) {
1681        case OFFER_NOT:
1682                irc_rootmsg(irc, "  otr offer status: none sent");
1683                break;
1684        case OFFER_SENT:
1685                irc_rootmsg(irc, "  otr offer status: awaiting reply");
1686                break;
1687        case OFFER_ACCEPTED:
1688                irc_rootmsg(irc, "  otr offer status: accepted our offer");
1689                break;
1690        case OFFER_REJECTED:
1691                irc_rootmsg(irc, "  otr offer status: ignored our offer");
1692                break;
1693        default:
1694                irc_rootmsg(irc, "  otr offer status: %d", ctx->otr_offer);
1695        }
1696
1697        switch(ctx->msgstate) {
1698        case OTRL_MSGSTATE_PLAINTEXT:
1699                irc_rootmsg(irc, "  connection state: cleartext");
1700                break;
1701        case OTRL_MSGSTATE_ENCRYPTED:
1702                irc_rootmsg(irc, "  connection state: encrypted (v%d)", ctx->protocol_version);
1703                break;
1704        case OTRL_MSGSTATE_FINISHED:
1705                irc_rootmsg(irc, "  connection state: shut down");
1706                break;
1707        default:
1708                irc_rootmsg(irc, "  connection state: %d", ctx->msgstate);
1709        }
1710
1711        irc_rootmsg(irc, "  fingerprints: (bold=active)");     
1712        show_fingerprints(irc, ctx);
1713}
1714
1715int keygen_in_progress(irc_t *irc, const char *handle, const char *protocol)
1716{
1717        kg_t *kg;
1718       
1719        if(!irc->otr->sent_accountname || !irc->otr->sent_protocol)
1720                return 0;
1721
1722        /* are we currently working on this key? */
1723        if(!strcmp(handle, irc->otr->sent_accountname) &&
1724           !strcmp(protocol, irc->otr->sent_protocol))
1725                return 1;
1726       
1727        /* do we have it queued for later? */
1728        for(kg=irc->otr->todo; kg; kg=kg->next) {
1729                if(!strcmp(handle, kg->accountname) &&
1730                   !strcmp(protocol, kg->protocol))
1731                        return 1;
1732        }
1733       
1734        return 0;
1735}
1736
1737void otr_keygen(irc_t *irc, const char *handle, const char *protocol)
1738{
1739        /* do nothing if a key for the requested account is already being generated */
1740        if(keygen_in_progress(irc, handle, protocol))
1741                return;
1742
1743        /* see if we already have a keygen child running. if not, start one and put a
1744           handler on its output. */
1745        if(!irc->otr->keygen || waitpid(irc->otr->keygen, NULL, WNOHANG)) {
1746                pid_t p;
1747                int to[2], from[2];
1748                FILE *tof, *fromf;
1749               
1750                if(pipe(to) < 0 || pipe(from) < 0) {
1751                        irc_rootmsg(irc, "otr keygen: couldn't create pipe: %s", strerror(errno));
1752                        return;
1753                }
1754               
1755                tof = fdopen(to[1], "w");
1756                fromf = fdopen(from[0], "r");
1757                if(!tof || !fromf) {
1758                        irc_rootmsg(irc, "otr keygen: couldn't streamify pipe: %s", strerror(errno));
1759                        return;
1760                }
1761               
1762                p = fork();
1763                if(p<0) {
1764                        irc_rootmsg(irc, "otr keygen: couldn't fork: %s", strerror(errno));
1765                        return;
1766                }
1767               
1768                if(!p) {
1769                        /* child process */
1770                        signal(SIGTERM, exit);
1771                        keygen_child_main(irc->otr->us, to[0], from[1]);
1772                        exit(0);
1773                }
1774               
1775                irc->otr->keygen = p;
1776                irc->otr->to = tof;
1777                irc->otr->from = fromf;
1778                irc->otr->sent_accountname = NULL;
1779                irc->otr->sent_protocol = NULL;
1780                irc->otr->todo = NULL;
1781                b_input_add(from[0], B_EV_IO_READ, keygen_finish_handler, irc);
1782        }
1783       
1784        /* is the keygen slave currently working? */
1785        if(irc->otr->sent_accountname) {
1786                /* enqueue our job for later transmission */
1787                kg_t **kg = &irc->otr->todo;
1788                while(*kg)
1789                        kg=&((*kg)->next);
1790                *kg = g_new0(kg_t, 1);
1791                (*kg)->accountname = g_strdup(handle);
1792                (*kg)->protocol = g_strdup(protocol);
1793        } else {
1794                /* send our job over and remember it */
1795                fprintf(irc->otr->to, "%s\n%s\n", handle, protocol);
1796                fflush(irc->otr->to);
1797                irc->otr->sent_accountname = g_strdup(handle);
1798                irc->otr->sent_protocol = g_strdup(protocol);
1799        }
1800}
1801
1802void keygen_child_main(OtrlUserState us, int infd, int outfd)
1803{
1804        FILE *input, *output;
1805        char filename[128], accountname[512], protocol[512];
1806        gcry_error_t e;
1807        int tempfd;
1808       
1809        input = fdopen(infd, "r");
1810        output = fdopen(outfd, "w");
1811       
1812        while(!feof(input) && !ferror(input) && !feof(output) && !ferror(output)) {
1813                myfgets(accountname, 512, input);
1814                myfgets(protocol, 512, input);
1815               
1816                strncpy(filename, "/tmp/bitlbee-XXXXXX", 128);
1817                tempfd = mkstemp(filename);
1818                close(tempfd);
1819
1820                e = otrl_privkey_generate(us, filename, accountname, protocol);
1821                if(e) {
1822                        fprintf(output, "\n");  /* this means failure */
1823                        fprintf(output, "otr keygen: %s\n", gcry_strerror(e));
1824                        unlink(filename);
1825                } else {
1826                        fprintf(output, "%s\n", filename);
1827                        fprintf(output, "otr keygen for %s/%s complete\n", accountname, protocol);
1828                }
1829                fflush(output);
1830        }
1831       
1832        fclose(input);
1833        fclose(output);
1834}
1835
1836gboolean keygen_finish_handler(gpointer data, gint fd, b_input_condition cond)
1837{
1838        irc_t *irc = (irc_t *)data;
1839        char filename[512], msg[512];
1840
1841        myfgets(filename, 512, irc->otr->from);
1842        myfgets(msg, 512, irc->otr->from);
1843       
1844        irc_rootmsg(irc, "%s", msg);
1845        if(filename[0]) {
1846                if(strsane(irc->user->nick)) {
1847                        char *kf = g_strdup_printf("%s%s.otr_keys", global.conf->configdir, irc->user->nick);
1848                        char *tmp = g_strdup_printf("%s.new", kf);
1849                        copyfile(filename, tmp);
1850                        unlink(filename);
1851                        rename(tmp,kf);
1852                        otrl_privkey_read(irc->otr->us, kf);
1853                        g_free(kf);
1854                        g_free(tmp);
1855                } else {
1856                        otrl_privkey_read(irc->otr->us, filename);
1857                        unlink(filename);
1858                }
1859        }
1860       
1861        /* forget this job */
1862        g_free(irc->otr->sent_accountname);
1863        g_free(irc->otr->sent_protocol);
1864        irc->otr->sent_accountname = NULL;
1865        irc->otr->sent_protocol = NULL;
1866       
1867        /* see if there are any more in the queue */
1868        if(irc->otr->todo) {
1869                kg_t *p = irc->otr->todo;
1870                /* send the next one over */
1871                fprintf(irc->otr->to, "%s\n%s\n", p->accountname, p->protocol);
1872                fflush(irc->otr->to);
1873                irc->otr->sent_accountname = p->accountname;
1874                irc->otr->sent_protocol = p->protocol;
1875                irc->otr->todo = p->next;
1876                g_free(p);
1877                return TRUE;   /* keep watching */
1878        } else {
1879                /* okay, the slave is idle now, so kill him */
1880                fclose(irc->otr->from);
1881                fclose(irc->otr->to);
1882                irc->otr->from = irc->otr->to = NULL;
1883                kill(irc->otr->keygen, SIGTERM);
1884                waitpid(irc->otr->keygen, NULL, 0);
1885                irc->otr->keygen = 0;
1886                return FALSE;  /* unregister ourselves */
1887        }
1888}
1889
1890void copyfile(const char *a, const char *b)
1891{
1892        int fda, fdb;
1893        int n;
1894        char buf[1024];
1895       
1896        fda = open(a, O_RDONLY);
1897        fdb = open(b, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1898       
1899        while((n=read(fda, buf, 1024)) > 0)
1900                write(fdb, buf, n);
1901       
1902        close(fda);
1903        close(fdb);     
1904}
1905
1906void myfgets(char *s, int size, FILE *stream)
1907{
1908        if(!fgets(s, size, stream)) {
1909                s[0] = '\0';
1910        } else {
1911                int n = strlen(s);
1912                if(n>0 && s[n-1] == '\n')
1913                        s[n-1] = '\0';
1914        }
1915}
1916
1917void yes_keygen(void *data)
1918{
1919        account_t *acc = (account_t *)data;
1920        irc_t *irc = acc->bee->ui_data;
1921       
1922        if(keygen_in_progress(irc, acc->user, acc->prpl->name)) {
1923                irc_rootmsg(irc, "keygen for %s/%s already in progress",
1924                        acc->user, acc->prpl->name);
1925        } else {
1926                irc_rootmsg(irc, "starting background keygen for %s/%s",
1927                        acc->user, acc->prpl->name);
1928                irc_rootmsg(irc, "you will be notified when it completes");
1929                otr_keygen(irc, acc->user, acc->prpl->name);
1930        }
1931}
1932
1933/* check whether a string is safe to use in a path component */
1934int strsane(const char *s)
1935{
1936        return strpbrk(s, "/\\") == NULL;
1937}
1938
1939/* vim: set noet ts=4 sw=4: */
Note: See TracBrowser for help on using the repository browser.