message.c 62.8 KB
Newer Older
cypherpunk's avatar
cypherpunk committed
1
2
/*
 *  Off-the-Record Messaging library
3
4
5
 *  Copyright (C) 2004-2014  Ian Goldberg, David Goulet, Rob Smits,
 *                           Chris Alexander, Willy Lew, Lisa Du,
 *                           Nikita Borisov
cypherpunk's avatar
cypherpunk committed
6
7
8
9
10
11
12
13
14
15
16
17
18
 *                           <otr@cypherpunks.ca>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of version 2.1 of the GNU Lesser General
 *  Public License as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
Rob Smits's avatar
Rob Smits committed
19
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
cypherpunk's avatar
cypherpunk committed
20
21
22
23
24
25
26
27
28
29
30
31
 */

/* system headers */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* libgcrypt headers */
#include <gcrypt.h>

/* libotr headers */
#include "privkey.h"
Rob Smits's avatar
Rob Smits committed
32
#include "userstate.h"
cypherpunk's avatar
cypherpunk committed
33
#include "proto.h"
34
#include "auth.h"
cypherpunk's avatar
cypherpunk committed
35
#include "message.h"
cypherpunk's avatar
cypherpunk committed
36
#include "sm.h"
Rob Smits's avatar
Rob Smits committed
37
#include "instag.h"
cypherpunk's avatar
cypherpunk committed
38

39

cypherpunk's avatar
cypherpunk committed
40
41
/* The API version */
extern unsigned int otrl_api_version;
cypherpunk's avatar
cypherpunk committed
42
43
44
45
46
47
48
49

/* How long after sending a packet should we wait to send a heartbeat? */
#define HEARTBEAT_INTERVAL 60

/* How old are messages allowed to be in order to be candidates for
 * resending in response to a rekey? */
#define RESEND_INTERVAL 60

50
51
52
53
54
55
56
57
58
/* How long should we wait for the last of the logged-in instances of
 * our buddy to respond before marking our private key as a candidate
 * for wiping (in seconds)? */
#define MAX_AKE_WAIT_TIME 60

/* How frequently should we check our ConnContexts for wipeable private
 * keys (and wipe them) (in seconds)? */
#define POLL_DEFAULT_INTERVAL 70

cypherpunk's avatar
   
cypherpunk committed
59
60
61
62
63
64
65
66
/* Send a message to the network, fragmenting first if necessary.
 * All messages to be sent to the network should go through this
 * method immediately before they are sent, ie after encryption. */
static gcry_error_t fragment_and_send(const OtrlMessageAppOps *ops,
	void *opdata, ConnContext *context, const char *message,
	OtrlFragmentPolicy fragPolicy, char **returnFragment)
{
    int mms = 0;
Rob Smits's avatar
Rob Smits committed
67

cypherpunk's avatar
   
cypherpunk committed
68
    if (message && ops->inject_message) {
Rob Smits's avatar
Rob Smits committed
69
	int msglen;
cypherpunk's avatar
   
cypherpunk committed
70

Rob Smits's avatar
Rob Smits committed
71
	if (ops->max_message_size) {
cypherpunk's avatar
   
cypherpunk committed
72
	    mms = ops->max_message_size(opdata, context);
Rob Smits's avatar
Rob Smits committed
73
74
	}
	msglen = strlen(message);
cypherpunk's avatar
   
cypherpunk committed
75
76

	/* Don't incur overhead of fragmentation unless necessary */
Rob Smits's avatar
Rob Smits committed
77
	if(mms != 0 && msglen > mms) {
cypherpunk's avatar
   
cypherpunk committed
78
79
80
	    char **fragments;
	    gcry_error_t err;
	    int i;
Rob Smits's avatar
Rob Smits committed
81
82
83
	    int headerlen = context->protocol_version == 3 ? 37 : 19;
	    /* Like ceil(msglen/(mms - headerlen)) */
	    int fragment_count = ((msglen - 1) / (mms - headerlen)) + 1;
cypherpunk's avatar
   
cypherpunk committed
84
85

	    err = otrl_proto_fragment_create(mms, fragment_count, &fragments,
Rob Smits's avatar
Rob Smits committed
86
		    context, message);
cypherpunk's avatar
   
cypherpunk committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
	    if (err) {
		return err;
	    }

	    /* Determine which fragments to send and which to return
	     * based on given Fragment Policy.  If the first fragment
	     * should be returned instead of sent, store it. */
	    if (fragPolicy == OTRL_FRAGMENT_SEND_ALL_BUT_FIRST) {
		*returnFragment = strdup(fragments[0]);
	    } else {
		ops->inject_message(opdata, context->accountname,
			context->protocol, context->username, fragments[0]);
	    }
	    for (i=1; i<fragment_count-1; i++) {
		ops->inject_message(opdata, context->accountname,
			context->protocol, context->username, fragments[i]);
	    }
	    /* If the last fragment should be stored instead of sent,
	     * store it */
	    if (fragPolicy == OTRL_FRAGMENT_SEND_ALL_BUT_LAST) {
		*returnFragment = strdup(fragments[fragment_count-1]);
	    } else {
		ops->inject_message(opdata, context->accountname,
Rob Smits's avatar
Rob Smits committed
110
111
			context->protocol, context->username,
			fragments[fragment_count-1]);
cypherpunk's avatar
   
cypherpunk committed
112
113
114
115
116
117
118
	    }
	    /* Now free all fragment memory */
	    otrl_proto_fragment_free(&fragments, fragment_count);

	} else {
	    /* No fragmentation necessary */
	    if (fragPolicy == OTRL_FRAGMENT_SEND_ALL) {
Rob Smits's avatar
Rob Smits committed
119
120
		ops->inject_message(opdata, context->accountname,
			context->protocol, context->username, message);
cypherpunk's avatar
   
cypherpunk committed
121
122
	    } else {
		/* Copy and return the entire given message. */
Rob Smits's avatar
Rob Smits committed
123
		*returnFragment = strdup(message);
cypherpunk's avatar
   
cypherpunk committed
124
125
126
	    }
	}
    }
Rob Smits's avatar
Rob Smits committed
127

cypherpunk's avatar
   
cypherpunk committed
128
129
130
    return gcry_error(GPG_ERR_NO_ERROR);
}

Rob Smits's avatar
Rob Smits committed
131
132
133
134
135
136
137
138
139
140
141
static void populate_context_instag(OtrlUserState us, const OtrlMessageAppOps
	*ops, void *opdata, const char *accountname, const char *protocol,
	ConnContext *context) {
    OtrlInsTag *p_instag;

    p_instag = otrl_instag_find(us, accountname, protocol);
    if ((!p_instag) && ops->create_instag) {
	ops->create_instag(opdata, accountname, protocol);
	p_instag = otrl_instag_find(us, accountname, protocol);
    }

142
143
144
145
    if (p_instag && p_instag->instag >= OTRL_MIN_VALID_INSTAG) {
	context->our_instance = p_instag->instag;
    } else {
	context->our_instance = otrl_instag_get_new();
Rob Smits's avatar
Rob Smits committed
146
147
148
    }
}

cypherpunk's avatar
cypherpunk committed
149
150
151
152
153
154
155
156
157
158
159
160
161
/* Deallocate a message allocated by other otrl_message_* routines. */
void otrl_message_free(char *message)
{
    free(message);
}

/* Handle a message about to be sent to the network.  It is safe to pass
 * all messages about to be sent to this routine.  add_appdata is a
 * function that will be called in the event that a new ConnContext is
 * created.  It will be passed the data that you supplied, as well as a
 * pointer to the new ConnContext.  You can use this to add
 * application-specific information to the ConnContext using the
 * "context->app" field, for example.  If you don't need to do this, you
cypherpunk's avatar
   
cypherpunk committed
162
 * can pass NULL for the last two arguments of otrl_message_sending.
cypherpunk's avatar
cypherpunk committed
163
164
165
166
 *
 * tlvs is a chain of OtrlTLVs to append to the private message.  It is
 * usually correct to just pass NULL here.
 *
Rob Smits's avatar
Rob Smits committed
167
168
169
170
171
172
173
174
 * If non-NULL, ops->convert_msg will be called just before encrypting a
 * message.
 *
 * "instag" specifies the instance tag of the buddy (protocol version 3 only).
 * Meta-instances may also be specified (e.g., OTRL_INSTAG_MOST_SECURE).
 * If "contextp" is not NULL, it will be set to the ConnContext used for
 * sending the message.
 *
cypherpunk's avatar
   
cypherpunk committed
175
176
177
178
179
180
181
182
183
 * If no fragmentation or msg injection is wanted, use OTRL_FRAGMENT_SEND_SKIP
 * as the OtrlFragmentPolicy. In this case, this function will assign *messagep
 * with the encrypted msg. If the routine returns non-zero, then the library
 * tried to encrypt the message, but for some reason failed. DO NOT send the
 * message in the clear in that case. If *messagep gets set by the call to
 * something non-NULL, then you should replace your message with the contents
 * of *messagep, and send that instead.
 *
 * Other fragmentation policies are OTRL_FRAGMENT_SEND_ALL,
Rob Smits's avatar
Rob Smits committed
184
185
186
 * OTRL_FRAGMENT_SEND_ALL_BUT_LAST, or OTRL_FRAGMENT_SEND_ALL_BUT_FIRST. In
 * these cases, the appropriate fragments will be automatically sent. For the
 * last two policies, the remaining fragment will be passed in *original_msg.
cypherpunk's avatar
   
cypherpunk committed
187
 *
Rob Smits's avatar
Rob Smits committed
188
 * Call otrl_message_free(*messagep) if you don't need *messagep or when you're
cypherpunk's avatar
cypherpunk committed
189
 * done with it. */
cypherpunk's avatar
   
cypherpunk committed
190
191
192
gcry_error_t otrl_message_sending(OtrlUserState us,
	const OtrlMessageAppOps *ops,
	void *opdata, const char *accountname, const char *protocol,
Rob Smits's avatar
Rob Smits committed
193
194
195
	const char *recipient, otrl_instag_t their_instag,
	const char *original_msg, OtrlTLV *tlvs, char **messagep,
	OtrlFragmentPolicy fragPolicy, ConnContext **contextp,
cypherpunk's avatar
cypherpunk committed
196
197
198
	void (*add_appdata)(void *data, ConnContext *context),
	void *data)
{
Rob Smits's avatar
Rob Smits committed
199
    ConnContext * context = NULL;
cypherpunk's avatar
cypherpunk committed
200
    char * msgtosend;
cypherpunk's avatar
   
cypherpunk committed
201
202
    const char * err_msg;
    gcry_error_t err_code, err;
cypherpunk's avatar
cypherpunk committed
203
204
    OtrlPolicy policy = OTRL_POLICY_DEFAULT;
    int context_added = 0;
Rob Smits's avatar
Rob Smits committed
205
206
    int convert_called = 0;
    char *converted_msg = NULL;
cypherpunk's avatar
cypherpunk committed
207

208
209
210
211
    if (messagep) {
	*messagep = NULL;
    }

cypherpunk's avatar
   
cypherpunk committed
212
    err = gcry_error(GPG_ERR_NO_ERROR);	/* Default to no error */
cypherpunk's avatar
cypherpunk committed
213

Rob Smits's avatar
Rob Smits committed
214
215
216
217
    if (contextp) {
	*contextp = NULL;
    }

cypherpunk's avatar
   
cypherpunk committed
218
    if (!accountname || !protocol || !recipient ||
Rob Smits's avatar
Rob Smits committed
219
		!original_msg || !messagep) {
220
	err = gcry_error(GPG_ERR_INV_VALUE);
Rob Smits's avatar
Rob Smits committed
221
	goto fragment;
cypherpunk's avatar
   
cypherpunk committed
222
    }
cypherpunk's avatar
cypherpunk committed
223
224
225

    /* See if we have a fingerprint for this user */
    context = otrl_context_find(us, recipient, accountname, protocol,
Rob Smits's avatar
Rob Smits committed
226
	    their_instag, 1, &context_added, add_appdata, data);
cypherpunk's avatar
cypherpunk committed
227
228
229
230
231
232

    /* Update the context list if we added one */
    if (context_added && ops->update_context_list) {
	ops->update_context_list(opdata);
    }

Rob Smits's avatar
Rob Smits committed
233
234
235
236
237
238
239
240
241
242
    /* Find or generate the instance tag if needed */
    if (!context->our_instance) {
	populate_context_instag(us, ops, opdata, accountname, protocol,
	    context);
    }

    if (contextp) {
	*contextp = context;
    }

cypherpunk's avatar
cypherpunk committed
243
244
245
246
247
248
    /* Check the policy */
    if (ops->policy) {
	policy = ops->policy(opdata, context);
    }

    /* Should we go on at all? */
249
    if ((policy & OTRL_POLICY_VERSION_MASK) == 0) {
Rob Smits's avatar
Rob Smits committed
250
251
	err =  gcry_error(GPG_ERR_NO_ERROR);
	goto fragment;
cypherpunk's avatar
cypherpunk committed
252
253
    }

254

cypherpunk's avatar
cypherpunk committed
255
    /* If this is an OTR Query message, don't encrypt it. */
Rob Smits's avatar
Rob Smits committed
256
    if (otrl_proto_message_type(original_msg) == OTRL_MSGTYPE_QUERY) {
cypherpunk's avatar
cypherpunk committed
257
	/* Replace the "?OTR?" with a custom message */
258
	char *bettermsg = otrl_proto_default_query_msg(accountname, policy);
cypherpunk's avatar
cypherpunk committed
259
260
261
	if (bettermsg) {
	    *messagep = bettermsg;
	}
262
	context->otr_offer = OFFER_SENT;
cypherpunk's avatar
   
cypherpunk committed
263
264
	err = gcry_error(GPG_ERR_NO_ERROR);
	goto fragment;
cypherpunk's avatar
cypherpunk committed
265
266
    }

267
268
    /* What is the current message disposition? */
    switch(context->msgstate) {
Rob Smits's avatar
Rob Smits committed
269

270
271
272
273
274
	case OTRL_MSGSTATE_PLAINTEXT:
	    if ((policy & OTRL_POLICY_REQUIRE_ENCRYPTION)) {
		/* We're trying to send an unencrypted message with a policy
		 * that disallows that.  Don't do that, but try to start
		 * up OTR instead. */
cypherpunk's avatar
   
cypherpunk committed
275
276
277
		if (ops->handle_msg_event) {
		    ops->handle_msg_event(opdata,
			    OTRL_MSGEVENT_ENCRYPTION_REQUIRED,
Rob Smits's avatar
Rob Smits committed
278
			    context, NULL, gcry_error(GPG_ERR_NO_ERROR));
cypherpunk's avatar
cypherpunk committed
279
		}
cypherpunk's avatar
   
cypherpunk committed
280
281

		context->context_priv->lastmessage =
Rob Smits's avatar
Rob Smits committed
282
			gcry_malloc_secure(strlen(original_msg) + 1);
cypherpunk's avatar
   
cypherpunk committed
283
		if (context->context_priv->lastmessage) {
284
285
		    char *bettermsg = otrl_proto_default_query_msg(accountname,
			    policy);
Rob Smits's avatar
Rob Smits committed
286
		    strcpy(context->context_priv->lastmessage, original_msg);
cypherpunk's avatar
   
cypherpunk committed
287
		    context->context_priv->lastsent = time(NULL);
Rob Smits's avatar
Rob Smits committed
288
		    otrl_context_update_recent_child(context, 1);
cypherpunk's avatar
   
cypherpunk committed
289
		    context->context_priv->may_retransmit = 2;
290
291
		    if (bettermsg) {
			*messagep = bettermsg;
Rob Smits's avatar
Rob Smits committed
292
			context->otr_offer = OFFER_SENT;
293
		    } else {
cypherpunk's avatar
   
cypherpunk committed
294
295
			err = gcry_error(GPG_ERR_ENOMEM);
			goto fragment;
296
297
298
299
300
301
302
303
		    }
		}
	    } else {
		if ((policy & OTRL_POLICY_SEND_WHITESPACE_TAG) &&
			context->otr_offer != OFFER_REJECTED) {
		    /* See if this user can speak OTR.  Append the
		     * OTR_MESSAGE_TAG to the plaintext message, and see
		     * if he responds. */
Rob Smits's avatar
Rob Smits committed
304
		    size_t msglen = strlen(original_msg);
305
306
307
308
309
		    size_t basetaglen = strlen(OTRL_MESSAGE_TAG_BASE);
		    size_t v1taglen = (policy & OTRL_POLICY_ALLOW_V1) ?
			strlen(OTRL_MESSAGE_TAG_V1) : 0;
		    size_t v2taglen = (policy & OTRL_POLICY_ALLOW_V2) ?
			strlen(OTRL_MESSAGE_TAG_V2) : 0;
Rob Smits's avatar
Rob Smits committed
310
311
		    size_t v3taglen = (policy & OTRL_POLICY_ALLOW_V3) ?
			strlen(OTRL_MESSAGE_TAG_V3) : 0;
312
		    char *taggedmsg = malloc(msglen + basetaglen + v1taglen
Rob Smits's avatar
Rob Smits committed
313
			    + v2taglen + v3taglen + 1);
314
		    if (taggedmsg) {
Rob Smits's avatar
Rob Smits committed
315
			strcpy(taggedmsg, original_msg);
316
317
318
319
320
321
322
323
324
			strcpy(taggedmsg + msglen, OTRL_MESSAGE_TAG_BASE);
			if (v1taglen) {
			    strcpy(taggedmsg + msglen + basetaglen,
				    OTRL_MESSAGE_TAG_V1);
			}
			if (v2taglen) {
			    strcpy(taggedmsg + msglen + basetaglen + v1taglen,
				    OTRL_MESSAGE_TAG_V2);
			}
Rob Smits's avatar
Rob Smits committed
325
326
327
328
			if (v3taglen) {
			    strcpy(taggedmsg + msglen + basetaglen + v1taglen
				    + v2taglen, OTRL_MESSAGE_TAG_V3);
			}
329
			*messagep = taggedmsg;
330
			context->otr_offer = OFFER_SENT;
331
		    }
cypherpunk's avatar
cypherpunk committed
332
333
		}
	    }
334
335
	    break;
	case OTRL_MSGSTATE_ENCRYPTED:
cypherpunk's avatar
   
cypherpunk committed
336
	    /* convert the original message if necessary */
Rob Smits's avatar
Rob Smits committed
337
338
339
340
341
342
343
	    if (ops->convert_msg) {
		ops->convert_msg(opdata, context, OTRL_CONVERT_SENDING,
			&converted_msg, original_msg);

		if (converted_msg) {
		    convert_called = 1;
		}
cypherpunk's avatar
   
cypherpunk committed
344
345
	    }

346
	    /* Create the new, encrypted message */
Rob Smits's avatar
Rob Smits committed
347
348
349
350
351
352
353
354
355
356
357
358
	    if (convert_called) {
		err_code = otrl_proto_create_data(&msgtosend, context,
			converted_msg, tlvs, 0, NULL);

		if (ops->convert_free) {
		    ops->convert_free(opdata, context, converted_msg);
		    converted_msg = NULL;
		}
	    } else {
		err_code = otrl_proto_create_data(&msgtosend, context,
			original_msg, tlvs, 0, NULL);
	    }
cypherpunk's avatar
   
cypherpunk committed
359
360
	    if (!err_code) {
		context->context_priv->lastsent = time(NULL);
Rob Smits's avatar
Rob Smits committed
361
		otrl_context_update_recent_child(context, 1);
362
		*messagep = msgtosend;
cypherpunk's avatar
cypherpunk committed
363
	    } else {
364
365
		/* Uh, oh.  Whatever we do, *don't* send the message in the
		 * clear. */
cypherpunk's avatar
   
cypherpunk committed
366
		if (ops->handle_msg_event) {
Rob Smits's avatar
Rob Smits committed
367
368
		    ops->handle_msg_event(opdata,
			    OTRL_MSGEVENT_ENCRYPTION_ERROR,
Rob Smits's avatar
Rob Smits committed
369
			    context, NULL, gcry_error(GPG_ERR_NO_ERROR));
370
		}
cypherpunk's avatar
   
cypherpunk committed
371
		if (ops->otr_error_message) {
Rob Smits's avatar
Rob Smits committed
372
		    err_msg = ops->otr_error_message(opdata, context,
cypherpunk's avatar
   
cypherpunk committed
373
			OTRL_ERRCODE_ENCRYPTION_ERROR);
Rob Smits's avatar
Rob Smits committed
374
		    *messagep = malloc(strlen(OTR_ERROR_PREFIX) +
cypherpunk's avatar
   
cypherpunk committed
375
376
377
378
379
380
381
382
383
384
385
386
			strlen(err_msg) + 1);
		    if (*messagep) {
			strcpy(*messagep, OTR_ERROR_PREFIX);
			strcat(*messagep, err_msg);
		    }
		    if (ops->otr_error_message_free) {
			ops->otr_error_message_free(opdata, err_msg);
		    }
		    if (!(*messagep)) {
			err = gcry_error(GPG_ERR_ENOMEM);
			goto fragment;
		    }
387
		}
cypherpunk's avatar
cypherpunk committed
388
	    }
389
390
	    break;
	case OTRL_MSGSTATE_FINISHED:
cypherpunk's avatar
   
cypherpunk committed
391
392
	    if (ops->handle_msg_event) {
		ops->handle_msg_event(opdata, OTRL_MSGEVENT_CONNECTION_ENDED,
Rob Smits's avatar
Rob Smits committed
393
		    context, NULL, gcry_error(GPG_ERR_NO_ERROR));
cypherpunk's avatar
cypherpunk committed
394
	    }
cypherpunk's avatar
   
cypherpunk committed
395
	    *messagep = strdup("");
396
	    if (!(*messagep)) {
cypherpunk's avatar
   
cypherpunk committed
397
398
		err = gcry_error(GPG_ERR_ENOMEM);
		goto fragment;
cypherpunk's avatar
cypherpunk committed
399
	    }
400
	    break;
cypherpunk's avatar
cypherpunk committed
401
402
    }

cypherpunk's avatar
   
cypherpunk committed
403
404
fragment:
    if (fragPolicy == OTRL_FRAGMENT_SEND_SKIP ) {
Rob Smits's avatar
Rob Smits committed
405
406
	/* Do not fragment/inject. Default behaviour of libotr3.2.0 */
	return err;
cypherpunk's avatar
   
cypherpunk committed
407
408
    } else {
	/* Fragment and send according to policy */
409
	if (!err && messagep && *messagep) {
Rob Smits's avatar
Rob Smits committed
410
	    if (context) {
411
		char *rmessagep = NULL;
412
		err = fragment_and_send(ops, opdata, context, *messagep,
413
414
415
416
417
418
419
					fragPolicy, &rmessagep);
		if (rmessagep) {
		    /* Free the current message pointer and return back the
		     * returned fragmented one. */
		    free(*messagep);
		    *messagep = rmessagep;
		}
cypherpunk's avatar
   
cypherpunk committed
420
	    }
Rob Smits's avatar
Rob Smits committed
421
422
	}
	return err;
cypherpunk's avatar
   
cypherpunk committed
423
    }
cypherpunk's avatar
cypherpunk committed
424
425
}

426
427
428
429
/* If err == 0, send the last auth message for the given context to the
 * appropriate user.  Otherwise, display an appripriate error dialog.
 * Return the value of err that was passed. */
static gcry_error_t send_or_error_auth(const OtrlMessageAppOps *ops,
430
431
	void *opdata, gcry_error_t err, ConnContext *context,
	OtrlUserState us)
cypherpunk's avatar
cypherpunk committed
432
433
{
    if (!err) {
434
	const char *msg = context->auth.lastauthmsg;
cypherpunk's avatar
cypherpunk committed
435
	if (msg && *msg) {
Rob Smits's avatar
Rob Smits committed
436
	    fragment_and_send(ops, opdata, context, msg,
cypherpunk's avatar
   
cypherpunk committed
437
		    OTRL_FRAGMENT_SEND_ALL, NULL);
438
	    time_t now = time(NULL);
439
440
441
442
443
	    /* Update the "last sent" fields, unless this is a version 3
	     * message typing to update the master context (as happens
	     * when sending a v3 COMMIT message, for example). */
	    if (context != context->m_context ||
		    context->auth.protocol_version != 3) {
444
		context->context_priv->lastsent = now;
445
446
		otrl_context_update_recent_child(context, 1);
	    }
447

448
	    /* If this is a master context, and we're sending a v3 COMMIT
449
450
451
	     * message, update the commit_sent_time timestamp, so we can
	     * expire it. */
	    if (context == context->m_context &&
452
453
		    context->auth.authstate == OTRL_AUTHSTATE_AWAITING_DHKEY &&
		    context->auth.protocol_version == 3) {
454
		context->auth.commit_sent_time = now;
455
456
457
458
459
460
		/* If there's not already a timer running to clean up
		 * this private key, try to start one. */
		if (us->timer_running == 0 && ops && ops->timer_control) {
		    ops->timer_control(opdata, POLL_DEFAULT_INTERVAL);
		    us->timer_running = 1;
		}
461
	    }
cypherpunk's avatar
cypherpunk committed
462
463
	}
    } else {
Rob Smits's avatar
Rob Smits committed
464
	if (ops->handle_msg_event) {
cypherpunk's avatar
   
cypherpunk committed
465
466
	    ops->handle_msg_event(opdata, OTRL_MSGEVENT_SETUP_ERROR,
		    context, NULL, err);
Rob Smits's avatar
Rob Smits committed
467
	}
cypherpunk's avatar
cypherpunk committed
468
469
470
471
    }
    return err;
}

472
473
474
475
476
477
478
479
480
481
482
typedef struct {
    int gone_encrypted;
    OtrlUserState us;
    const OtrlMessageAppOps *ops;
    void *opdata;
    ConnContext *context;
    int ignore_message;
    char **messagep;
} EncrData;

static gcry_error_t go_encrypted(const OtrlAuthInfo *auth, void *asdata)
cypherpunk's avatar
cypherpunk committed
483
{
484
485
486
487
    EncrData *edata = asdata;
    gcry_error_t err = gcry_error(GPG_ERR_NO_ERROR);
    Fingerprint *found_print = NULL;
    int fprint_added = 0;
cypherpunk's avatar
   
cypherpunk committed
488
    OtrlMessageState oldstate = edata->context->msgstate;
cypherpunk's avatar
   
cypherpunk committed
489
    Fingerprint *oldprint = edata->context->active_fingerprint;
490
491
492

    /* See if we're talking to ourselves */
    if (!gcry_mpi_cmp(auth->their_pub, auth->our_dh.pub)) {
Rob Smits's avatar
Rob Smits committed
493
494
	/* Yes, we are. */
	if (edata->ops->handle_msg_event) {
cypherpunk's avatar
   
cypherpunk committed
495
496
	    edata->ops->handle_msg_event(edata->opdata,
		    OTRL_MSGEVENT_MSG_REFLECTED, edata->context,
Rob Smits's avatar
Rob Smits committed
497
		    NULL, gcry_error(GPG_ERR_NO_ERROR));
Rob Smits's avatar
Rob Smits committed
498
	}
499
500
	edata->ignore_message = 1;
	return gcry_error(GPG_ERR_NO_ERROR);
cypherpunk's avatar
cypherpunk committed
501
502
    }

503
504
505
506
507
508
509
510
511
512
513
514
515
516
    found_print = otrl_context_find_fingerprint(edata->context,
	    edata->context->auth.their_fingerprint, 1, &fprint_added);

    if (fprint_added) {
	/* Inform the user of the new fingerprint */
	if (edata->ops->new_fingerprint) {
	    edata->ops->new_fingerprint(edata->opdata, edata->us,
		    edata->context->accountname, edata->context->protocol,
		    edata->context->username,
		    edata->context->auth.their_fingerprint);
	}
	/* Arrange that the new fingerprint be written to disk */
	if (edata->ops->write_fingerprints) {
	    edata->ops->write_fingerprints(edata->opdata);
cypherpunk's avatar
cypherpunk committed
517
518
519
	}
    }

520
521
    /* Is this a new session or just a refresh of an existing one? */
    if (edata->context->msgstate == OTRL_MSGSTATE_ENCRYPTED &&
cypherpunk's avatar
   
cypherpunk committed
522
	    oldprint == found_print &&
Rob Smits's avatar
Rob Smits committed
523
524
	    edata->context->context_priv->our_keyid - 1 ==
	    edata->context->auth.our_keyid &&
cypherpunk's avatar
   
cypherpunk committed
525
	    !gcry_mpi_cmp(edata->context->context_priv->our_old_dh_key.pub,
526
		edata->context->auth.our_dh.pub) &&
cypherpunk's avatar
   
cypherpunk committed
527
528
	    ((edata->context->context_priv->their_keyid > 0 &&
	      edata->context->context_priv->their_keyid ==
529
		    edata->context->auth.their_keyid &&
cypherpunk's avatar
   
cypherpunk committed
530
	      !gcry_mpi_cmp(edata->context->context_priv->their_y,
531
		  edata->context->auth.their_pub)) ||
cypherpunk's avatar
   
cypherpunk committed
532
533
	    (edata->context->context_priv->their_keyid > 1 &&
	     edata->context->context_priv->their_keyid - 1 ==
534
		    edata->context->auth.their_keyid &&
cypherpunk's avatar
   
cypherpunk committed
535
536
	     edata->context->context_priv->their_old_y != NULL &&
	     !gcry_mpi_cmp(edata->context->context_priv->their_old_y,
537
538
539
540
		 edata->context->auth.their_pub)))) {
	/* This is just a refresh of the existing session. */
	if (edata->ops->still_secure) {
	    edata->ops->still_secure(edata->opdata, edata->context,
cypherpunk's avatar
   
cypherpunk committed
541
		    edata->context->auth.initiated);
cypherpunk's avatar
cypherpunk committed
542
	}
543
544
	edata->ignore_message = 1;
	return gcry_error(GPG_ERR_NO_ERROR);
cypherpunk's avatar
cypherpunk committed
545
546
    }

547
548
549
550
    /* Copy the information from the auth into the context */
    memmove(edata->context->sessionid,
	    edata->context->auth.secure_session_id, 20);
    edata->context->sessionid_len =
Rob Smits's avatar
Rob Smits committed
551
	    edata->context->auth.secure_session_id_len;
552
    edata->context->sessionid_half =
Rob Smits's avatar
Rob Smits committed
553
	    edata->context->auth.session_id_half;
cypherpunk's avatar
   
cypherpunk committed
554
    edata->context->protocol_version =
Rob Smits's avatar
Rob Smits committed
555
	    edata->context->auth.protocol_version;
556

Rob Smits's avatar
Rob Smits committed
557
558
    edata->context->context_priv->their_keyid =
	    edata->context->auth.their_keyid;
cypherpunk's avatar
   
cypherpunk committed
559
560
    gcry_mpi_release(edata->context->context_priv->their_y);
    gcry_mpi_release(edata->context->context_priv->their_old_y);
Rob Smits's avatar
Rob Smits committed
561
562
    edata->context->context_priv->their_y =
	    gcry_mpi_copy(edata->context->auth.their_pub);
cypherpunk's avatar
   
cypherpunk committed
563
    edata->context->context_priv->their_old_y = NULL;
564

Rob Smits's avatar
Rob Smits committed
565
566
    if (edata->context->context_priv->our_keyid - 1 !=
	edata->context->auth.our_keyid ||
cypherpunk's avatar
   
cypherpunk committed
567
	gcry_mpi_cmp(edata->context->context_priv->our_old_dh_key.pub,
Rob Smits's avatar
Rob Smits committed
568
		edata->context->auth.our_dh.pub)) {
cypherpunk's avatar
   
cypherpunk committed
569
570
571
	otrl_dh_keypair_free(&(edata->context->context_priv->our_dh_key));
	otrl_dh_keypair_free(&(edata->context->context_priv->our_old_dh_key));
	otrl_dh_keypair_copy(&(edata->context->context_priv->our_old_dh_key),
572
		&(edata->context->auth.our_dh));
Rob Smits's avatar
Rob Smits committed
573
574
	otrl_dh_gen_keypair(
		edata->context->context_priv->our_old_dh_key.groupid,
cypherpunk's avatar
   
cypherpunk committed
575
		&(edata->context->context_priv->our_dh_key));
Rob Smits's avatar
Rob Smits committed
576
577
	edata->context->context_priv->our_keyid = edata->context->auth.our_keyid
		+ 1;
578
579
580
    }

    /* Create the session keys from the DH keys */
cypherpunk's avatar
   
cypherpunk committed
581
582
    otrl_dh_session_free(&(edata->context->context_priv->sesskeys[0][0]));
    err = otrl_dh_session(&(edata->context->context_priv->sesskeys[0][0]),
Rob Smits's avatar
Rob Smits committed
583
584
	    &(edata->context->context_priv->our_dh_key),
	    edata->context->context_priv->their_y);
585
    if (err) return err;
cypherpunk's avatar
   
cypherpunk committed
586
587
    otrl_dh_session_free(&(edata->context->context_priv->sesskeys[1][0]));
    err = otrl_dh_session(&(edata->context->context_priv->sesskeys[1][0]),
Rob Smits's avatar
Rob Smits committed
588
589
	    &(edata->context->context_priv->our_old_dh_key),
	    edata->context->context_priv->their_y);
590
591
    if (err) return err;

cypherpunk's avatar
   
cypherpunk committed
592
    edata->context->context_priv->generation++;
593
594
595
596
597
    edata->context->active_fingerprint = found_print;
    edata->context->msgstate = OTRL_MSGSTATE_ENCRYPTED;

    if (edata->ops->update_context_list) {
	edata->ops->update_context_list(edata->opdata);
cypherpunk's avatar
cypherpunk committed
598
    }
cypherpunk's avatar
   
cypherpunk committed
599
    if (oldstate == OTRL_MSGSTATE_ENCRYPTED && oldprint == found_print) {
cypherpunk's avatar
   
cypherpunk committed
600
601
602
603
604
605
606
607
	if (edata->ops->still_secure) {
	    edata->ops->still_secure(edata->opdata, edata->context,
		    edata->context->auth.initiated);
	}
    } else {
	if (edata->ops->gone_secure) {
	    edata->ops->gone_secure(edata->opdata, edata->context);
	}
608
609
610
611
612
613
    }

    edata->gone_encrypted = 1;

    return gpg_error(GPG_ERR_NO_ERROR);
}
cypherpunk's avatar
cypherpunk committed
614

615
616
617
618
619
620
621
622
623
static void maybe_resend(EncrData *edata)
{
    gcry_error_t err;
    time_t now;

    if (!edata->gone_encrypted) return;

    /* See if there's a message we sent recently that should be resent. */
    now = time(NULL);
cypherpunk's avatar
   
cypherpunk committed
624
625
626
    if (edata->context->context_priv->lastmessage != NULL &&
	    edata->context->context_priv->may_retransmit &&
	    edata->context->context_priv->lastsent >= (now - RESEND_INTERVAL)) {
627
	char *resendmsg;
cypherpunk's avatar
   
cypherpunk committed
628
629
630
631
632
633
634
635
	char *msg_to_send;
	int resending = (edata->context->context_priv->may_retransmit == 1);

	/* Initialize msg_to_send */
	if (resending) {
	    const char *resent_prefix;
	    int used_ops_resentmp = 1;
	    resent_prefix = edata->ops->resent_msg_prefix ?
Rob Smits's avatar
Rob Smits committed
636
				    edata->ops->resent_msg_prefix(edata->opdata,
cypherpunk's avatar
   
cypherpunk committed
637
638
639
640
641
642
643
644
645
646
647
648
				    edata->context) : NULL;
	    if (!resent_prefix) {
		resent_prefix = "[resent]"; /* Assign default prefix */
		used_ops_resentmp = 0;
	    }
	    msg_to_send = malloc(
		    strlen(edata->context->context_priv->lastmessage) +
		    strlen(resent_prefix) + 2);
	    if (msg_to_send) {
		strcpy(msg_to_send, resent_prefix);
		strcat(msg_to_send, " ");
		strcat(msg_to_send, edata->context->context_priv->lastmessage);
649
650
	    } else {
		return;  /* Out of memory; don't try to resend */
cypherpunk's avatar
   
cypherpunk committed
651
652
653
654
655
656
657
658
	    }
	    if (used_ops_resentmp) {
		edata->ops->resent_msg_prefix_free(edata->opdata,
			resent_prefix);
	    }
	} else {
	    msg_to_send = edata->context->context_priv->lastmessage;
	}
659
660
661

	/* Re-encrypt the message with the new keys */
	err = otrl_proto_create_data(&resendmsg,
cypherpunk's avatar
   
cypherpunk committed
662
		edata->context, msg_to_send, NULL, 0, NULL);
663
	if (resending) {
cypherpunk's avatar
   
cypherpunk committed
664
665
		free(msg_to_send);
	}
666
667
	if (!err) {
	    /* Resend the message */
cypherpunk's avatar
   
cypherpunk committed
668
669
	    fragment_and_send(edata->ops, edata->opdata, edata->context,
		    resendmsg, OTRL_FRAGMENT_SEND_ALL, NULL);
670
	    free(resendmsg);
cypherpunk's avatar
   
cypherpunk committed
671
	    edata->context->context_priv->lastsent = now;
Rob Smits's avatar
Rob Smits committed
672
	    otrl_context_update_recent_child(edata->context, 1);
cypherpunk's avatar
   
cypherpunk committed
673
	    if (resending) {
Rob Smits's avatar
Rob Smits committed
674
		/* We're not sending it for the first time; let the user
cypherpunk's avatar
   
cypherpunk committed
675
676
677
678
		 * know we resent it */
		if (edata->ops->handle_msg_event) {
		    edata->ops->handle_msg_event(edata->opdata,
			    OTRL_MSGEVENT_MSG_RESENT, edata->context,
Rob Smits's avatar
Rob Smits committed
679
			    NULL, gcry_error(GPG_ERR_NO_ERROR));
680
681
		}
	    }
cypherpunk's avatar
   
cypherpunk committed
682
	    edata->ignore_message = 1;
683
684
	}
    }
cypherpunk's avatar
cypherpunk committed
685
686
}

cypherpunk's avatar
cypherpunk committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
/* Set the trust level based on the result of the SMP */
static void set_smp_trust(const OtrlMessageAppOps *ops, void *opdata,
	ConnContext *context, int trusted)
{
    otrl_context_set_trust(context->active_fingerprint, trusted ? "smp" : "");

    /* Write the new info to disk, redraw the ui, and redraw the
     * OTR buttons. */
    if (ops->write_fingerprints) {
	ops->write_fingerprints(opdata);
    }
}

static void init_respond_smp(OtrlUserState us, const OtrlMessageAppOps *ops,
cypherpunk's avatar
   
cypherpunk committed
701
702
	void *opdata, ConnContext *context, const char *question,
	const unsigned char *secret, size_t secretlen, int initiating)
cypherpunk's avatar
cypherpunk committed
703
704
705
706
707
708
709
710
{
    unsigned char *smpmsg = NULL;
    int smpmsglen;
    unsigned char combined_secret[SM_DIGEST_SIZE];
    gcry_error_t err;
    unsigned char our_fp[20];
    unsigned char *combined_buf;
    size_t combined_buf_len;
cypherpunk's avatar
   
cypherpunk committed
711
712
    OtrlTLV *sendtlv;
    char *sendsmp = NULL;
cypherpunk's avatar
cypherpunk committed
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751

    if (!context || context->msgstate != OTRL_MSGSTATE_ENCRYPTED) return;

    /*
     * Construct the combined secret as a SHA256 hash of:
     * Version byte (0x01), Initiator fingerprint (20 bytes),
     * responder fingerprint (20 bytes), secure session id, input secret
     */
    otrl_privkey_fingerprint_raw(us, our_fp, context->accountname,
	    context->protocol);

    combined_buf_len = 41 + context->sessionid_len + secretlen;
    combined_buf = malloc(combined_buf_len);
    combined_buf[0] = 0x01;
    if (initiating) {
	memmove(combined_buf + 1, our_fp, 20);
	memmove(combined_buf + 21,
		context->active_fingerprint->fingerprint, 20);
    } else {
	memmove(combined_buf + 1,
		context->active_fingerprint->fingerprint, 20);
	memmove(combined_buf + 21, our_fp, 20);
    }
    memmove(combined_buf + 41, context->sessionid,
	    context->sessionid_len);
    memmove(combined_buf + 41 + context->sessionid_len,
	    secret, secretlen);
    gcry_md_hash_buffer(SM_HASH_ALGORITHM, combined_secret, combined_buf,
	    combined_buf_len);
    free(combined_buf);

    if (initiating) {
	otrl_sm_step1(context->smstate, combined_secret, SM_DIGEST_SIZE,
		&smpmsg, &smpmsglen);
    } else {
	otrl_sm_step2b(context->smstate, combined_secret, SM_DIGEST_SIZE,
		&smpmsg, &smpmsglen);
    }

cypherpunk's avatar
   
cypherpunk committed
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
    /* If we've got a question, attach it to the smpmsg */
    if (question != NULL) {
	size_t qlen = strlen(question);
	unsigned char *qsmpmsg = malloc(qlen + 1 + smpmsglen);
	if (!qsmpmsg) {
	    free(smpmsg);
	    return;
	}
	strcpy((char *)qsmpmsg, question);
	memmove(qsmpmsg + qlen + 1, smpmsg, smpmsglen);
	free(smpmsg);
	smpmsg = qsmpmsg;
	smpmsglen += qlen + 1;
    }

cypherpunk's avatar
cypherpunk committed
767
    /* Send msg with next smp msg content */
cypherpunk's avatar
   
cypherpunk committed
768
769
770
    sendtlv = otrl_tlv_new(initiating ?
	    (question != NULL ? OTRL_TLV_SMP1Q : OTRL_TLV_SMP1)
	    : OTRL_TLV_SMP2,
cypherpunk's avatar
cypherpunk committed
771
772
	    smpmsglen, smpmsg);
    err = otrl_proto_create_data(&sendsmp, context, "", sendtlv,
Rob Smits's avatar
Rob Smits committed
773
	    OTRL_MSGFLAGS_IGNORE_UNREADABLE, NULL);
cypherpunk's avatar
cypherpunk committed
774
    if (!err) {
Rob Smits's avatar
Rob Smits committed
775
	/*  Send it, and set the next expected message to the
cypherpunk's avatar
cypherpunk committed
776
	 *  logical response */
Rob Smits's avatar
Rob Smits committed
777
	err = fragment_and_send(ops, opdata, context,
cypherpunk's avatar
cypherpunk committed
778
		sendsmp, OTRL_FRAGMENT_SEND_ALL, NULL);
Rob Smits's avatar
Rob Smits committed
779
780
	context->smstate->nextExpected =
		initiating ? OTRL_SMP_EXPECT2 : OTRL_SMP_EXPECT3;
cypherpunk's avatar
cypherpunk committed
781
782
783
784
785
786
787
788
789
790
791
    }
    free(sendsmp);
    otrl_tlv_free(sendtlv);
    free(smpmsg);
}

/* Initiate the Socialist Millionaires' Protocol */
void otrl_message_initiate_smp(OtrlUserState us, const OtrlMessageAppOps *ops,
	void *opdata, ConnContext *context, const unsigned char *secret,
	size_t secretlen)
{
cypherpunk's avatar
   
cypherpunk committed
792
793
794
795
796
797
798
799
800
801
    init_respond_smp(us, ops, opdata, context, NULL, secret, secretlen, 1);
}

/* Initiate the Socialist Millionaires' Protocol and send a prompt
 * question to the buddy */
void otrl_message_initiate_smp_q(OtrlUserState us,
	const OtrlMessageAppOps *ops, void *opdata, ConnContext *context,
	const char *question, const unsigned char *secret, size_t secretlen)
{
    init_respond_smp(us, ops, opdata, context, question, secret, secretlen, 1);
cypherpunk's avatar
cypherpunk committed
802
803
804
805
806
807
808
}

/* Respond to a buddy initiating the Socialist Millionaires' Protocol */
void otrl_message_respond_smp(OtrlUserState us, const OtrlMessageAppOps *ops,
	void *opdata, ConnContext *context, const unsigned char *secret,
	size_t secretlen)
{
cypherpunk's avatar
   
cypherpunk committed
809
    init_respond_smp(us, ops, opdata, context, NULL, secret, secretlen, 0);
cypherpunk's avatar
cypherpunk committed
810
811
812
813
814
815
816
817
818
819
820
}

/* Abort the SMP.  Called when an unexpected SMP message breaks the
 * normal flow. */
void otrl_message_abort_smp(OtrlUserState us, const OtrlMessageAppOps *ops,
	void *opdata, ConnContext *context)
{
    OtrlTLV *sendtlv = otrl_tlv_new(OTRL_TLV_SMP_ABORT, 0,
	    (const unsigned char *)"");
    char *sendsmp = NULL;
    gcry_error_t err;
cypherpunk's avatar
   
cypherpunk committed
821

cypherpunk's avatar
   
cypherpunk committed
822
823
    context->smstate->nextExpected = OTRL_SMP_EXPECT1;

cypherpunk's avatar
cypherpunk committed
824
825
    err = otrl_proto_create_data(&sendsmp,
	    context, "", sendtlv,
cypherpunk's avatar
   
cypherpunk committed
826
	    OTRL_MSGFLAGS_IGNORE_UNREADABLE, NULL);
cypherpunk's avatar
cypherpunk committed
827
828
    if (!err) {
	/* Send the abort signal so our buddy knows we've stopped */
cypherpunk's avatar
   
cypherpunk committed
829
	err = fragment_and_send(ops, opdata, context,
cypherpunk's avatar
cypherpunk committed
830
831
832
833
834
835
		sendsmp, OTRL_FRAGMENT_SEND_ALL, NULL);
    }
    free(sendsmp);
    otrl_tlv_free(sendtlv);
}

Rob Smits's avatar
Rob Smits committed
836
837
838
839
static void message_malformed(const OtrlMessageAppOps *ops,
	void *opdata, ConnContext *context) {
    if (ops->handle_msg_event) {
	ops->handle_msg_event(opdata, OTRL_MSGEVENT_RCVDMSG_MALFORMED, context,
Rob Smits's avatar
Rob Smits committed
840
	    NULL, gcry_error(GPG_ERR_NO_ERROR));
Rob Smits's avatar
Rob Smits committed
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
    }

    if (ops->inject_message && ops->otr_error_message) {
	const char *err_msg = ops->otr_error_message(opdata, context,
		OTRL_ERRCODE_MSG_MALFORMED);

	if (err_msg) {
	    char *buf = malloc(strlen(OTR_ERROR_PREFIX) + strlen(err_msg) + 1);

	    if (buf) {
		strcpy(buf, OTR_ERROR_PREFIX);
		strcat(buf, err_msg);
		ops->inject_message(opdata, context->accountname,
			context->protocol, context->username, buf);
		free(buf);
	    }

	    if (ops->otr_error_message_free) {
		ops->otr_error_message_free(opdata, err_msg);
	    }
	}
    }
}


cypherpunk's avatar
cypherpunk committed
866
867
868
869
870
871
872
/* Handle a message just received from the network.  It is safe to pass
 * all received messages to this routine.  add_appdata is a function
 * that will be called in the event that a new ConnContext is created.
 * It will be passed the data that you supplied, as well as
 * a pointer to the new ConnContext.  You can use this to add
 * application-specific information to the ConnContext using the
 * "context->app" field, for example.  If you don't need to do this, you
cypherpunk's avatar
   
cypherpunk committed
873
874
 * can pass NULL for the last two arguments of otrl_message_receiving.
 *
875
 * If non-NULL, ops->convert_msg will be called after a data message is
Rob Smits's avatar
Rob Smits committed
876
877
 * decrypted.
 *
878
 * If "contextp" is not NULL, it will be set to the ConnContext used for
Rob Smits's avatar
Rob Smits committed
879
 * receiving the message.
cypherpunk's avatar
cypherpunk committed
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
 *
 * If otrl_message_receiving returns 1, then the message you received
 * was an internal protocol message, and no message should be delivered
 * to the user.
 *
 * If it returns 0, then check if *messagep was set to non-NULL.  If
 * so, replace the received message with the contents of *messagep, and
 * deliver that to the user instead.  You must call
 * otrl_message_free(*messagep) when you're done with it.  If tlvsp is
 * non-NULL, *tlvsp will be set to a chain of any TLVs that were
 * transmitted along with this message.  You must call
 * otrl_tlv_free(*tlvsp) when you're done with those.
 *
 * If otrl_message_receiving returns 0 and *messagep is NULL, then this
 * was an ordinary, non-OTR message, which should just be delivered to
 * the user without modification. */
cypherpunk's avatar
   
cypherpunk committed
896
int otrl_message_receiving(OtrlUserState us, const OtrlMessageAppOps *ops,
cypherpunk's avatar
cypherpunk committed
897
898
	void *opdata, const char *accountname, const char *protocol,
	const char *sender, const char *message, char **newmessagep,
Rob Smits's avatar
Rob Smits committed
899
	OtrlTLV **tlvsp, ConnContext **contextp,
cypherpunk's avatar
cypherpunk committed
900
901
902
	void (*add_appdata)(void *data, ConnContext *context),
	void *data)
{
Rob Smits's avatar
Rob Smits committed
903
    ConnContext *context, *m_context, *best_context;
904
    OtrlMessageType msgtype;
cypherpunk's avatar
cypherpunk committed
905
906
    int context_added = 0;
    OtrlPolicy policy = OTRL_POLICY_DEFAULT;
Rob Smits's avatar
Rob Smits committed
907
    char *unfragmessage = NULL, *otrtag = NULL;
908
    EncrData edata;
909
    otrl_instag_t our_instance = 0, their_instance = 0;
Rob Smits's avatar
Rob Smits committed
910
911
    int version;
    gcry_error_t err;
cypherpunk's avatar
cypherpunk committed
912
913

    if (!accountname || !protocol || !sender || !message || !newmessagep)
Rob Smits's avatar
Rob Smits committed
914
	return 0;
cypherpunk's avatar
cypherpunk committed
915
916
917
918

    *newmessagep = NULL;
    if (tlvsp) *tlvsp = NULL;

Rob Smits's avatar
Rob Smits committed
919
920
921
922
923
924
925
926
    if (contextp) {
	*contextp = NULL;
    }

    /* Find the master context and state with this correspondent */
    m_context = otrl_context_find(us, sender, accountname,
	    protocol, OTRL_INSTAG_MASTER, 1, &context_added, add_appdata, data);
    context = m_context;
cypherpunk's avatar
cypherpunk committed
927
928
929
930
931
932

    /* Update the context list if we added one */
    if (context_added && ops->update_context_list) {
	ops->update_context_list(opdata);
    }

Rob Smits's avatar
Rob Smits committed
933
934
935
936
937
938
939
940
941
942
    best_context = otrl_context_find(us, sender, accountname,
	    protocol, OTRL_INSTAG_BEST, 0, NULL, add_appdata, data);

    /* Find or generate the instance tag if needed */
    if (!context->our_instance) {
	populate_context_instag(us, ops, opdata, accountname, protocol,
		context);
    }


cypherpunk's avatar
cypherpunk committed
943
944
945
946
947
948
    /* Check the policy */
    if (ops->policy) {
	policy = ops->policy(opdata, context);
    }

    /* Should we go on at all? */
949
    if ((policy & OTRL_POLICY_VERSION_MASK) == 0) {
Rob Smits's avatar
Rob Smits committed
950
	return 0;
cypherpunk's avatar
cypherpunk committed
951
952
    }

Rob Smits's avatar
Rob Smits committed
953
954
955
956
957
958
959
960
961
962
963
964
    otrtag = strstr(message, "?OTR");
    if (otrtag) {
	/* See if we have a V3 fragment */
	if (strstr(message, "?OTR|")) {
	    /* Get the instance tag from fragment header*/
	    sscanf(otrtag, "?OTR|%x|%x,", &their_instance, &our_instance);
	    /* Ignore message if it is intended for a different instance */
	    if (our_instance && context->our_instance != our_instance) {

		    if (ops->handle_msg_event) {
			ops->handle_msg_event(opdata,
				OTRL_MSGEVENT_RCVDMSG_FOR_OTHER_INSTANCE,
Rob Smits's avatar
Rob Smits committed
965
				m_context, NULL, gcry_error(GPG_ERR_NO_ERROR));
Rob Smits's avatar
Rob Smits committed
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
		    }
		    return 1;
	    }
	    /* Get the context for this instance */
	    if (their_instance >= OTRL_MIN_VALID_INSTAG) {
		context = otrl_context_find(us, sender, accountname,
			protocol, their_instance, 1, &context_added,
			add_appdata, data);
	    } else {
		message_malformed(ops, opdata, context);
		return 1;
	    }
	}
	switch(otrl_proto_fragment_accumulate(&unfragmessage,
		context, message)) {
	    case OTRL_FRAGMENT_UNFRAGMENTED:
		/* Do nothing */
		break;
	    case OTRL_FRAGMENT_INCOMPLETE:
		/* We've accumulated this fragment, but we don't have a
		 * complete message yet */
		return 1;
	    case OTRL_FRAGMENT_COMPLETE:
		/* We've got a new complete message, in unfragmessage. */
		message = unfragmessage;
		otrtag = strstr(message, "?OTR");
		break;
	}
cypherpunk's avatar
   
cypherpunk committed
994
995
    }

cypherpunk's avatar
cypherpunk committed
996
997
998
    /* What type of message is it?  Note that this just checks the
     * header; it's not necessarily a _valid_ message of this type. */
    msgtype = otrl_proto_message_type(message);
Rob Smits's avatar
Rob Smits committed
999
    version = otrl_proto_message_version(message);
cypherpunk's avatar
cypherpunk committed
1000
1001

    /* See if they responded to our OTR offer */
1002
1003
    if ((policy & OTRL_POLICY_SEND_WHITESPACE_TAG)) {
	if (msgtype != OTRL_MSGTYPE_NOTOTR) {
cypherpunk's avatar
cypherpunk committed
1004
1005
1006
1007
1008
1009
	    context->otr_offer = OFFER_ACCEPTED;
	} else if (context->otr_offer == OFFER_SENT) {
	    context->otr_offer = OFFER_REJECTED;
	}
    }

Rob Smits's avatar
Rob Smits committed
1010
1011
1012
1013
    /* Check that this version is allowed by the policy */
    if (((version == 3) && !(policy & OTRL_POLICY_ALLOW_V3))
	|| ((version == 2) && !(policy & OTRL_POLICY_ALLOW_V2))
	|| ((version == 1) && !(policy & OTRL_POLICY_ALLOW_V1))) {
1014
1015
	    edata.ignore_message = 1;
	    goto end;
Rob Smits's avatar
Rob Smits committed
1016
1017
1018
    }
    /* Check the to and from instance tags */
    if (version == 3) {
1019
1020
1021
1022
	err = gcry_error(GPG_ERR_INV_VALUE);
	if (otrtag) {
	    err = otrl_proto_instance(otrtag, &their_instance, &our_instance);
	}
Rob Smits's avatar
Rob Smits committed
1023
	if (!err) {
Rob Smits's avatar
Rob Smits committed
1024
1025
1026
1027
	    if ((msgtype == OTRL_MSGTYPE_DH_COMMIT && our_instance &&
		    context->our_instance != our_instance) ||
		    (msgtype != OTRL_MSGTYPE_DH_COMMIT &&
		    context->our_instance != our_instance)) {
Rob Smits's avatar
Rob Smits committed
1028
1029
1030
		if (ops->handle_msg_event) {
		    ops->handle_msg_event(opdata,
			    OTRL_MSGEVENT_RCVDMSG_FOR_OTHER_INSTANCE,
Rob Smits's avatar
Rob Smits committed
1031
			    m_context, NULL, gcry_error(GPG_ERR_NO_ERROR));
Rob Smits's avatar
Rob Smits committed
1032
		}
1033
1034
1035
		/* ignore message intended for a different instance */
		edata.ignore_message = 1;
		goto end;
Rob Smits's avatar
Rob Smits committed
1036
1037
1038
1039
1040
1041
1042
1043
1044
	    }

	    if (their_instance >= OTRL_MIN_VALID_INSTAG) {
		context = otrl_context_find(us, sender, accountname,
			protocol, their_instance, 1, &context_added,
			add_appdata, data);
	    }
	}

1045
1046
	if (err || their_instance < OTRL_MIN_VALID_INSTAG) {
	    message_malformed(ops, opdata, context);
1047
1048
	    edata.ignore_message = 1;
	    goto end;
1049
1050
	}

Rob Smits's avatar
Rob Smits committed
1051
1052
1053
1054
1055
1056
	if (context_added) {
	    /* Context added because of new instance (either here or when
	     * accumulating fragments */
	    /* Copy information from m_context to the new instance context */
	    context->auth.protocol_version = 3;
	    context->protocol_version = 3;
1057
1058
1059
1060
1061
1062
1063
1064
	    context->msgstate = m_context->msgstate;

	    if (m_context->context_priv->may_retransmit) {
		gcry_free(context->context_priv->lastmessage);
		context->context_priv->lastmessage = m_context->context_priv->lastmessage;
		m_context->context_priv->lastmessage = NULL;
		context->context_priv->may_retransmit = m_context->context_priv->may_retransmit;
		m_context->context_priv->may_retransmit = 0;
Rob Smits's avatar
Rob Smits committed
1065
1066
	    }

1067
	    if (msgtype == OTRL_MSGTYPE_DH_KEY) {
Rob Smits's avatar
Rob Smits committed
1068
		otrl_auth_copy_on_key(&(m_context->auth), &(context->auth));
1069
	    } else if (msgtype != OTRL_MSGTYPE_DH_COMMIT) {
1070
1071
		edata.ignore_message = 1;
		goto end;
Rob Smits's avatar
Rob Smits committed
1072
1073
1074
1075
1076
1077
	    }

	    /* Update the context list */
	    if (ops->update_context_list) {
		ops->update_context_list(opdata);
	    }
1078
	} else if (m_context != context) {
Rob Smits's avatar
Rob Smits committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
	    /* Switching from m_context to existing instance context */
	    if (msgtype == OTRL_MSGTYPE_DH_KEY && m_context->auth.authstate
		    == OTRL_AUTHSTATE_AWAITING_DHKEY &&
		    !(context->auth.authstate ==
		    OTRL_AUTHSTATE_AWAITING_DHKEY)) {
		context->msgstate = m_context->msgstate;
		context->auth.protocol_version = 3;
		context->protocol_version = 3;
		otrl_auth_copy_on_key(&(m_context->auth), &(context->auth));
	    }
Ian Goldberg's avatar
Ian Goldberg committed
1089
	}
Rob Smits's avatar
Rob Smits committed
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
    }

    if (contextp) {
	*contextp = context;
    }

    /* update time of last received message */
    context->context_priv->lastrecv = time(NULL);
    otrl_context_update_recent_child(context, 0);

1100
1101
1102
1103
1104
1105
1106
1107
    edata.gone_encrypted = 0;
    edata.us = us;
    edata.context = context;
    edata.ops = ops;
    edata.opdata = opdata;
    edata.ignore_message = -1;
    edata.messagep = newmessagep;

cypherpunk's avatar
cypherpunk committed
1108
    switch(msgtype) {
1109
1110
1111
1112
1113
1114
	unsigned int bestversion;
	const char *startwhite, *endwhite;
	DH_keypair *our_dh;
	unsigned int our_keyid;
	OtrlPrivKey *privkey;
	int haveauthmsg;
Rob Smits's avatar
Rob Smits committed
1115

1116
1117
1118
1119
	case OTRL_MSGTYPE_QUERY:
	    /* See if we should use an existing DH keypair, or generate
	     * a fresh one. */
	    if (context->msgstate == OTRL_MSGSTATE_ENCRYPTED) {
cypherpunk's avatar
   
cypherpunk committed
1120
1121
		our_dh = &(context->context_priv->our_old_dh_key);
		our_keyid = context->context_priv->our_keyid - 1;
1122
1123
1124
1125
1126
1127
1128
	    } else {
		our_dh = NULL;
		our_keyid = 0;
	    }

	    /* Find the best version of OTR that we both speak */
	    switch(otrl_proto_query_bestversion(message, policy)) {
Rob Smits's avatar
Rob Smits committed
1129
1130
		case 3:
		    err = otrl_auth_start_v23(&(context->auth), 3);
1131
		    send_or_error_auth(ops, opdata, err, context, us);
Rob Smits's avatar
Rob Smits committed
1132
		    break;
1133
		case 2:
Rob Smits's avatar
Rob Smits committed
1134
		    err = otrl_auth_start_v23(&(context->auth), 2);
1135
		    send_or_error_auth(ops, opdata, err, context, us);
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
		    break;
		case 1:
		    /* Get our private key */
		    privkey = otrl_privkey_find(us, context->accountname,
			    context->protocol);
		    if (privkey == NULL) {
			/* We've got no private key! */
			if (ops->create_privkey) {
			    ops->create_privkey(opdata, context->accountname,
				    context->protocol);
			    privkey = otrl_privkey_find(us,
				    context->accountname, context->protocol);
cypherpunk's avatar
cypherpunk committed
1148
1149
			}
		    }
1150
1151
1152
		    if (privkey) {
			err = otrl_auth_start_v1(&(context->auth), our_dh,
				our_keyid, privkey);
1153
			send_or_error_auth(ops, opdata, err, context, us);
1154
		    }
cypherpunk's avatar
cypherpunk committed
1155
		    break;
1156
1157
		default:
		    /* Just ignore this message */
cypherpunk's avatar
cypherpunk committed
1158
1159
1160
		    break;
	    }
	    /* Don't display the Query message to the user. */
1161
	    if (edata.ignore_message == -1) edata.ignore_message = 1;
cypherpunk's avatar
cypherpunk committed
1162
1163
	    break;

1164
	case OTRL_MSGTYPE_DH_COMMIT:
Rob Smits's avatar
Rob Smits committed
1165
	    err = otrl_auth_handle_commit(&(context->auth), otrtag, version);
1166
	    send_or_error_auth(ops, opdata, err, context, us);
1167
1168
1169
1170
1171

	    if (edata.ignore_message == -1) edata.ignore_message = 1;
	    break;

	case OTRL_MSGTYPE_DH_KEY:
Rob Smits's avatar
Rob Smits committed
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
	    /* Get our private key */
	    privkey = otrl_privkey_find(us, context->accountname,
		    context->protocol);
	    if (privkey == NULL) {
		/* We've got no private key! */
		if (ops->create_privkey) {
		    ops->create_privkey(opdata, context->accountname,
			    context->protocol);
		    privkey = otrl_privkey_find(us,
			    context->accountname, context->protocol);
1182
		}
Rob Smits's avatar
Rob Smits committed
1183
1184
1185
1186
1187
	    }
	    if (privkey) {
		err = otrl_auth_handle_key(&(context->auth), otrtag,
			&haveauthmsg, privkey);
		if (err || haveauthmsg) {
1188
		    send_or_error_auth(ops, opdata, err, context, us);
1189
1190
		}
	    }
cypherpunk's avatar
cypherpunk committed
1191

1192
1193
1194
1195
	    if (edata.ignore_message == -1) edata.ignore_message = 1;
	    break;

	case OTRL_MSGTYPE_REVEALSIG:
Rob Smits's avatar
Rob Smits committed
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
	    /* Get our private key */
	    privkey = otrl_privkey_find(us, context->accountname,
		    context->protocol);
	    if (privkey == NULL) {
		/* We've got no private key! */
		if (ops->create_privkey) {
		    ops->create_privkey(opdata, context->accountname,
			    context->protocol);
		    privkey = otrl_privkey_find(us,
			    context->accountname, context->protocol);
1206
		}
Rob Smits's avatar
Rob Smits committed
1207
1208
1209
1210
1211
1212
	    }
	    if (privkey) {
		err = otrl_auth_handle_revealsig(&(context->auth),
			otrtag, &haveauthmsg, privkey, go_encrypted,
			&edata);
		if (err || haveauthmsg) {
1213
		    send_or_error_auth(ops, opdata, err, context, us);
Rob Smits's avatar
Rob Smits committed
1214
		    maybe_resend(&edata);
1215
1216
		}
	    }
cypherpunk's avatar
cypherpunk committed
1217

1218
1219
	    if (edata.ignore_message == -1) edata.ignore_message = 1;
	    break;
cypherpunk's avatar
cypherpunk committed
1220

1221
	case OTRL_MSGTYPE_SIGNATURE:
Rob Smits's avatar
Rob Smits committed
1222
1223
1224
	    err = otrl_auth_handle_signature(&(context->auth),
		    otrtag, &haveauthmsg, go_encrypted, &edata);
	    if (err || haveauthmsg) {
1225
		send_or_error_auth(ops, opdata, err, context, us);
Rob Smits's avatar
Rob Smits committed
1226
		maybe_resend(&edata);
1227
	    }
cypherpunk's avatar
   
cypherpunk committed
1228

1229
1230
	    if (edata.ignore_message == -1) edata.ignore_message = 1;
	    break;
cypherpunk's avatar
cypherpunk committed
1231

1232
	case OTRL_MSGTYPE_V1_KEYEXCH:
Rob Smits's avatar
Rob Smits committed
1233
1234
1235
1236
1237
1238