source: otr.c @ 3d45471

Last change on this file since 3d45471 was 5ebff60, checked in by dequis <dx@…>, at 2015-02-20T22:50:54Z

Reindent everything to K&R style with tabs

Used uncrustify, with the configuration file in ./doc/uncrustify.cfg

Commit author set to "Indent <please@…>" so that it's easier to
skip while doing git blame.

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