source: otr.c @ 81a15da

Last change on this file since 81a15da was 098a75b, checked in by dequis <dx@…>, at 2015-03-22T13:35:08Z

Fix a bunch of memory leaks

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