aboutsummaryrefslogtreecommitdiffstats
path: root/protocols/jabber/si.c
blob: 4f989959406f87f3f44d7d22122ab2079dd5b9e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/***************************************************************************\
*                                                                           *
*  BitlBee - An IRC to IM gateway                                           *
*  Jabber module - SI packets                                               *
*                                                                           *
*  Copyright 2007 Uli Meis <a.sporto+bee@gmail.com>                         *
*                                                                           *
*  This program is free software; you can redistribute it and/or modify     *
*  it under the terms of the GNU General Public License as published by     *
*  the Free Software Foundation; either version 2 of the License, or        *
*  (at your option) any later version.                                      *
*                                                                           *
*  This program 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 General Public License for more details.                             *
*                                                                           *
*  You should have received a copy of the GNU General Public License along  *
*  with this program; if not, write to the Free Software Foundation, Inc.,  *
*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
*                                                                           *
\***************************************************************************/

#include "jabber.h"
#include "sha1.h"

void jabber_si_answer_request(file_transfer_t *ft);
int jabber_si_send_request(struct im_connection *ic, char *who, struct jabber_transfer *tf);

/* file_transfer free() callback */
void jabber_si_free_transfer(file_transfer_t *ft)
{
	struct jabber_transfer *tf = ft->data;
	struct jabber_data *jd = tf->ic->proto_data;

	if (tf->watch_in) {
		b_event_remove(tf->watch_in);
		tf->watch_in = 0;
	}

	jd->filetransfers = g_slist_remove(jd->filetransfers, tf);

	if (tf->fd != -1) {
		closesocket(tf->fd);
		tf->fd = -1;
	}

	if (tf->disco_timeout) {
		b_event_remove(tf->disco_timeout);
	}

	g_free(tf->ini_jid);
	g_free(tf->tgt_jid);
	g_free(tf->iq_id);
	g_free(tf->sid);
	g_free(tf);
}

/* file_transfer canceled() callback */
void jabber_si_canceled(file_transfer_t *ft, char *reason)
{
	struct jabber_transfer *tf = ft->data;
	struct xt_node *reply, *iqnode;

	if (tf->accepted) {
		return;
	}

	iqnode = jabber_make_packet("iq", "error", tf->ini_jid, NULL);
	xt_add_attr(iqnode, "id", tf->iq_id);
	reply = jabber_make_error_packet(iqnode, "forbidden", "cancel", "403");
	xt_free_node(iqnode);

	if (!jabber_write_packet(tf->ic, reply)) {
		imcb_log(tf->ic, "WARNING: Error generating reply to file transfer request");
	}
	xt_free_node(reply);

}

int jabber_si_check_features(struct jabber_transfer *tf, GSList *features)
{
	int foundft = FALSE, foundbt = FALSE, foundsi = FALSE;

	while (features) {
		if (!strcmp(features->data, XMLNS_FILETRANSFER)) {
			foundft = TRUE;
		}
		if (!strcmp(features->data, XMLNS_BYTESTREAMS)) {
			foundbt = TRUE;
		}
		if (!strcmp(features->data, XMLNS_SI)) {
			foundsi = TRUE;
		}

		features = g_slist_next(features);
	}

	if (!foundft) {
		imcb_file_canceled(tf->ic, tf->ft, "Buddy's client doesn't feature file transfers");
	} else if (!foundbt) {
		imcb_file_canceled(tf->ic, tf->ft, "Buddy's client doesn't feature byte streams (required)");
	} else if (!foundsi) {
		imcb_file_canceled(tf->ic, tf->ft, "Buddy's client doesn't feature stream initiation (required)");
	}

	return foundft && foundbt && foundsi;
}

void jabber_si_transfer_start(struct jabber_transfer *tf)
{

	if (!jabber_si_check_features(tf, tf->bud->features)) {
		return;
	}

	/* send the request to our buddy */
	jabber_si_send_request(tf->ic, tf->bud->full_jid, tf);

	/* and start the receive logic */
	imcb_file_recv_start(tf->ic, tf->ft);

}

gboolean jabber_si_waitfor_disco(gpointer data, gint fd, b_input_condition cond)
{
	struct jabber_transfer *tf = data;
	struct jabber_data *jd = tf->ic->proto_data;

	tf->disco_timeout_fired++;

	if (tf->bud->features && jd->have_streamhosts == 1) {
		tf->disco_timeout = 0;
		jabber_si_transfer_start(tf);
		return FALSE;
	}

	/* 8 seconds should be enough for server and buddy to respond */
	if (tf->disco_timeout_fired < 16) {
		return TRUE;
	}

	if (!tf->bud->features && jd->have_streamhosts != 1) {
		imcb_log(tf->ic, "Couldn't get buddy's features nor discover all services of the server");
	} else if (!tf->bud->features) {
		imcb_log(tf->ic, "Couldn't get buddy's features");
	} else {
		imcb_log(tf->ic, "Couldn't discover some of the server's services");
	}

	tf->disco_timeout = 0;
	jabber_si_transfer_start(tf);
	return FALSE;
}

void jabber_si_transfer_request(struct im_connection *ic, file_transfer_t *ft, char *who)
{
	struct jabber_transfer *tf;
	struct jabber_data *jd = ic->proto_data;
	struct jabber_buddy *bud;
	char *server = jd->server, *s;

	if ((s = strchr(who, '=')) && jabber_chat_by_jid(ic, s + 1)) {
		bud = jabber_buddy_by_ext_jid(ic, who, 0);
	} else {
		bud = jabber_buddy_by_jid(ic, who, 0);
	}

	if (bud == NULL) {
		imcb_file_canceled(ic, ft, "Couldn't find buddy (BUG?)");
		return;
	}

	imcb_log(ic, "Trying to send %s(%zd bytes) to %s", ft->file_name, ft->file_size, who);

	tf = g_new0(struct jabber_transfer, 1);

	tf->ic = ic;
	tf->ft = ft;
	tf->fd = -1;
	tf->ft->data = tf;
	tf->ft->free = jabber_si_free_transfer;
	tf->bud = bud;
	ft->write = jabber_bs_send_write;

	jd->filetransfers = g_slist_prepend(jd->filetransfers, tf);

	/* query buddy's features and server's streaming proxies if necessary */

	if (!tf->bud->features) {
		jabber_iq_query_features(ic, bud->full_jid);
	}

	/* If <auto> is not set don't check for proxies */
	if ((jd->have_streamhosts != 1) && (jd->streamhosts == NULL) &&
	    (strstr(set_getstr(&ic->acc->set, "proxy"), "<auto>") != NULL)) {
		jd->have_streamhosts = 0;
		jabber_iq_query_server(ic, server, XMLNS_DISCO_ITEMS);
	} else if (jd->streamhosts != NULL) {
		jd->have_streamhosts = 1;
	}

	/* if we had to do a query, wait for the result.
	 * Otherwise fire away. */
	if (!tf->bud->features || jd->have_streamhosts != 1) {
		tf->disco_timeout = b_timeout_add(500, jabber_si_waitfor_disco, tf);
	} else {
		jabber_si_transfer_start(tf);
	}
}

/*
 * First function that gets called when a file transfer request comes in.
 * A lot to parse.
 *
 * We choose a stream type from the options given by the initiator.
 * Then we wait for imcb to call the accept or cancel callbacks.
 */
int jabber_si_handle_request(struct im_connection *ic, struct xt_node *node, struct xt_node *sinode)
{
	struct xt_node *c, *d, *reply;
	char *sid, *ini_jid, *tgt_jid, *iq_id, *s, *ext_jid, *size_s;
	struct jabber_buddy *bud;
	int requestok = FALSE;
	char *name, *cmp;
	size_t size;
	struct jabber_transfer *tf;
	struct jabber_data *jd = ic->proto_data;
	file_transfer_t *ft;

	/* All this means we expect something like this: ( I think )
	 * <iq from=... to=... id=...>
	 *      <si id=id xmlns=si profile=ft>
	 *              <file xmlns=ft/>
	 *              <feature xmlns=feature>
	 *                      <x xmlns=xdata type=submit>
	 *                              <field var=stream-method>
	 *
	 */
	if (!(ini_jid          = xt_find_attr(node, "from")) ||
	    !(tgt_jid          = xt_find_attr(node, "to")) ||
	    !(iq_id            = xt_find_attr(node, "id")) ||
	    !(sid              = xt_find_attr(sinode, "id")) ||
	    !(cmp              = xt_find_attr(sinode, "profile")) ||
	    !(0               == strcmp(cmp, XMLNS_FILETRANSFER)) ||
	    !(d                = xt_find_node(sinode->children, "file")) ||
	    !(cmp = xt_find_attr(d, "xmlns")) ||
	    !(0               == strcmp(cmp, XMLNS_FILETRANSFER)) ||
	    !(name             = xt_find_attr(d, "name")) ||
	    !(size_s           = xt_find_attr(d, "size")) ||
	    !(1               == sscanf(size_s, "%zd", &size)) ||
	    !(d                = xt_find_node(sinode->children, "feature")) ||
	    !(cmp              = xt_find_attr(d, "xmlns")) ||
	    !(0               == strcmp(cmp, XMLNS_FEATURE)) ||
	    !(d                = xt_find_node(d->children, "x")) ||
	    !(cmp              = xt_find_attr(d, "xmlns")) ||
	    !(0               == strcmp(cmp, XMLNS_XDATA)) ||
	    !(cmp              = xt_find_attr(d, "type")) ||
	    !(0               == strcmp(cmp, "form")) ||
	    !(d                = xt_find_node(d->children, "field")) ||
	    !(cmp              = xt_find_attr(d, "var")) ||
	    !(0               == strcmp(cmp, "stream-method"))) {
		imcb_log(ic, "WARNING: Received incomplete Stream Initiation request");
	} else {
		/* Check if we support one of the options */

		c = d->children;
		while ((c = xt_find_node(c, "option"))) {
			if ((d = xt_find_node(c->children, "value")) &&
			    (d->text != NULL) &&
			    (strcmp(d->text, XMLNS_BYTESTREAMS) == 0)) {
				requestok = TRUE;
				break;
			} else {
				c = c->next;
			}
		}

		if (!requestok) {
			imcb_log(ic, "WARNING: Unsupported file transfer request from %s", ini_jid);
		}
	}

	if (requestok) {
		/* Figure out who the transfer should come from... */

		ext_jid = ini_jid;
		if ((s = strchr(ini_jid, '/'))) {
			if ((bud = jabber_buddy_by_jid(ic, ini_jid, GET_BUDDY_EXACT))) {
				bud->last_msg = time(NULL);
				ext_jid = bud->ext_jid ? : bud->bare_jid;
			} else {
				*s = 0; /* We need to generate a bare JID now. */
			}
		}

		if (!(ft = imcb_file_send_start(ic, ext_jid, name, size))) {
			imcb_log(ic, "WARNING: Error handling transfer request from %s", ini_jid);
			requestok = FALSE;
		}

		if (s) {
			*s = '/';
		}
	}

	if (!requestok) {
		reply = jabber_make_error_packet(node, "item-not-found", "cancel", NULL);
		if (!jabber_write_packet(ic, reply)) {
			imcb_log(ic, "WARNING: Error generating reply to file transfer request");
		}
		xt_free_node(reply);
		return XT_HANDLED;
	}

	/* Request is fine. */

	tf = g_new0(struct jabber_transfer, 1);

	tf->ini_jid = g_strdup(ini_jid);
	tf->tgt_jid = g_strdup(tgt_jid);
	tf->iq_id = g_strdup(iq_id);
	tf->sid = g_strdup(sid);
	tf->ic = ic;
	tf->ft = ft;
	tf->fd = -1;
	tf->ft->data = tf;
	tf->ft->accept = jabber_si_answer_request;
	tf->ft->free = jabber_si_free_transfer;
	tf->ft->canceled = jabber_si_canceled;

	jd->filetransfers = g_slist_prepend(jd->filetransfers, tf);

	return XT_HANDLED;
}

/*
 * imc called the accept callback which probably means that the user accepted this file transfer.
 * We send our response to the initiator.
 * In the next step, the initiator will send us a request for the given stream type.
 * (currently that can only be a SOCKS5 bytestream)
 */
void jabber_si_answer_request(file_transfer_t *ft)
{
	struct jabber_transfer *tf = ft->data;
	struct xt_node *node, *sinode, *reply;

	/* generate response, start with the SI tag */
	sinode = xt_new_node("si", NULL, NULL);
	xt_add_attr(sinode, "xmlns", XMLNS_SI);
	xt_add_attr(sinode, "profile", XMLNS_FILETRANSFER);
	xt_add_attr(sinode, "id", tf->sid);

	/* now the file tag */
	node = xt_new_node("file", NULL, NULL);
	xt_add_attr(node, "xmlns", XMLNS_FILETRANSFER);

	xt_add_child(sinode, node);

	/* and finally the feature tag */
	node = xt_new_node("field", NULL, NULL);
	xt_add_attr(node, "var", "stream-method");
	xt_add_attr(node, "type", "list-single");

	/* Currently all we can do. One could also implement in-band (IBB) */
	xt_add_child(node, xt_new_node("value", XMLNS_BYTESTREAMS, NULL));

	node = xt_new_node("x", NULL, node);
	xt_add_attr(node, "xmlns", XMLNS_XDATA);
	xt_add_attr(node, "type", "submit");

	node = xt_new_node("feature", NULL, node);
	xt_add_attr(node, "xmlns", XMLNS_FEATURE);

	xt_add_child(sinode, node);

	reply = jabber_make_packet("iq", "result", tf->ini_jid, sinode);
	xt_add_attr(reply, "id", tf->iq_id);

	if (!jabber_write_packet(tf->ic, reply)) {
		imcb_log(tf->ic, "WARNING: Error generating reply to file transfer request");
	} else {
		tf->accepted = TRUE;
	}
	xt_free_node(reply);
}

static xt_status jabber_si_handle_response(struct im_connection *ic, struct xt_node *node, struct xt_node *orig)
{
	struct xt_node *c, *d;
	char *ini_jid = NULL, *tgt_jid, *iq_id, *cmp;
	GSList *tflist;
	struct jabber_transfer *tf = NULL;
	struct jabber_data *jd = ic->proto_data;
	struct jabber_error *err;

	if (!(tgt_jid = xt_find_attr(node, "from")) ||
	    !(ini_jid = xt_find_attr(node, "to")) ||
	    !(iq_id   = xt_find_attr(node, "id"))) {
		imcb_log(ic, "Invalid SI response from=%s to=%s", tgt_jid, ini_jid);
		return XT_HANDLED;
	}

	/* Let's see if we can find out what this bytestream should be for... */

	for (tflist = jd->filetransfers; tflist; tflist = g_slist_next(tflist)) {
		struct jabber_transfer *tft = tflist->data;
		if ((strcmp(tft->iq_id, iq_id) == 0)) {
			tf = tft;
			break;
		}
	}

	if (!tf) {
		imcb_log(ic, "WARNING: Received bytestream request from %s that doesn't match an SI request", ini_jid);
		return XT_HANDLED;
	}

	err = jabber_error_parse(xt_find_node(node->children, "error"), XMLNS_STANZA_ERROR);

	if (err) {
		if (g_strcmp0(err->code, "forbidden") == 0) {
			imcb_log(ic, "File %s: %s rejected the transfer", tf->ft->file_name, tgt_jid);
		} else {
			imcb_log(ic, "Error: Stream initiation request failed: %s (%s)", err->code, err->text);
		}
		imcb_file_canceled(ic, tf->ft, "Stream initiation request failed");
		jabber_error_free(err);
		return XT_HANDLED;
	}

	/* All this means we expect something like this: ( I think )
	 * <iq from=... to=... id=...>
	 *      <si xmlns=si>
	 *      [	<file xmlns=ft/>    ] <-- not necessary
	 *              <feature xmlns=feature>
	 *                      <x xmlns=xdata type=submit>
	 *                              <field var=stream-method>
	 *                                      <value>
	 */
	if (!(c = xt_find_node(node->children, "si")) ||
	    !(cmp = xt_find_attr(c, "xmlns")) ||
	    !(strcmp(cmp, XMLNS_SI) == 0) ||
	    !(d = xt_find_node(c->children, "feature")) ||
	    !(cmp = xt_find_attr(d, "xmlns")) ||
	    !(strcmp(cmp, XMLNS_FEATURE) == 0) ||
	    !(d = xt_find_node(d->children, "x")) ||
	    !(cmp = xt_find_attr(d, "xmlns")) ||
	    !(strcmp(cmp, XMLNS_XDATA) == 0) ||
	    !(cmp = xt_find_attr(d, "type")) ||
	    !(strcmp(cmp, "submit") == 0) ||
	    !(d = xt_find_node(d->children, "field")) ||
	    !(cmp = xt_find_attr(d, "var")) ||
	    !(strcmp(cmp, "stream-method") == 0) ||
	    !(d = xt_find_node(d->children, "value"))) {
		imcb_log(ic, "WARNING: Received incomplete Stream Initiation response");
		return XT_HANDLED;
	}

	if (!(strcmp(d->text, XMLNS_BYTESTREAMS) == 0)) {
		/* since we should only have advertised what we can do and the peer should
		 * only have chosen what we offered, this should never happen */
		imcb_log(ic, "WARNING: Received invalid Stream Initiation response, method %s", d->text);

		return XT_HANDLED;
	}

	tf->ini_jid = g_strdup(ini_jid);
	tf->tgt_jid = g_strdup(tgt_jid);

	imcb_log(ic, "File %s: %s accepted the transfer!", tf->ft->file_name, tgt_jid);

	jabber_bs_send_start(tf);

	return XT_HANDLED;
}

int jabber_si_send_request(struct im_connection *ic, char *who, struct jabber_transfer *tf)
{
	struct xt_node *node, *sinode;
	struct jabber_buddy *bud;

	/* who knows how many bits the future holds :) */
	char filesizestr[ 1 + ( int ) (0.301029995663981198f * sizeof(size_t) * 8) ];

	const char *methods[] =
	{
		XMLNS_BYTESTREAMS,
		//XMLNS_IBB,
		NULL
	};
	const char **m;
	char *s;

	/* Maybe we should hash this? */
	tf->sid = g_strdup_printf("BitlBeeJabberSID%d", tf->ft->local_id);

	if ((s = strchr(who, '=')) && jabber_chat_by_jid(ic, s + 1)) {
		bud = jabber_buddy_by_ext_jid(ic, who, 0);
	} else {
		bud = jabber_buddy_by_jid(ic, who, 0);
	}

	/* start with the SI tag */
	sinode = xt_new_node("si", NULL, NULL);
	xt_add_attr(sinode, "xmlns", XMLNS_SI);
	xt_add_attr(sinode, "profile", XMLNS_FILETRANSFER);
	xt_add_attr(sinode, "id", tf->sid);

/*	if( mimetype )
                xt_add_attr( node, "mime-type", mimetype ); */

	/* now the file tag */
/*	if( desc )
                node = xt_new_node( "desc", descr, NULL ); */
	node = xt_new_node("range", NULL, NULL);

	sprintf(filesizestr, "%zd", tf->ft->file_size);
	node = xt_new_node("file", NULL, node);
	xt_add_attr(node, "xmlns", XMLNS_FILETRANSFER);
	xt_add_attr(node, "name", tf->ft->file_name);
	xt_add_attr(node, "size", filesizestr);
/*	if (hash)
                xt_add_attr( node, "hash", hash );
        if (date)
                xt_add_attr( node, "date", date ); */

	xt_add_child(sinode, node);

	/* and finally the feature tag */
	node = xt_new_node("field", NULL, NULL);
	xt_add_attr(node, "var", "stream-method");
	xt_add_attr(node, "type", "list-single");

	for (m = methods; *m; m++) {
		xt_add_child(node, xt_new_node("option", NULL, xt_new_node("value", (char *) *m, NULL)));
	}

	node = xt_new_node("x", NULL, node);
	xt_add_attr(node, "xmlns", XMLNS_XDATA);
	xt_add_attr(node, "type", "form");

	node = xt_new_node("feature", NULL, node);
	xt_add_attr(node, "xmlns", XMLNS_FEATURE);

	xt_add_child(sinode, node);

	/* and we are there... */
	node = jabber_make_packet("iq", "set", bud ? bud->full_jid : who, sinode);
	jabber_cache_add(ic, node, jabber_si_handle_response);
	tf->iq_id = g_strdup(xt_find_attr(node, "id"));

	return jabber_write_packet(ic, node);
}
rr_mail.rfc822_attachment.nil? # Attached mail didn't parse, so treat as text curr_mail.content_type = 'text/plain' end end if curr_mail.content_type == 'application/vnd.ms-outlook' || curr_mail.content_type == 'application/ms-tnef' ensure_parts_counted # fills in rfc822_attachment variable if curr_mail.rfc822_attachment.nil? # Attached mail didn't parse, so treat as binary curr_mail.content_type = 'application/octet-stream' end end # If the part is an attachment of email if curr_mail.content_type == 'message/rfc822' || curr_mail.content_type == 'application/vnd.ms-outlook' || curr_mail.content_type == 'application/ms-tnef' ensure_parts_counted # fills in rfc822_attachment variable leaves_found += _get_attachment_leaves_recursive(curr_mail.rfc822_attachment, curr_mail.rfc822_attachment) else # Store leaf curr_mail.within_rfc822_attachment = within_rfc822_attachment leaves_found += [curr_mail] end # restore original charset curr_mail.charset = charset end return leaves_found end # Removes anything cached about the object in the database, and saves def clear_in_database_caches! self.cached_attachment_text_clipped = nil self.cached_main_body_text_unfolded = nil self.cached_main_body_text_folded = nil self.save! end # Internal function to cache two sorts of main body text. # Cached as loading raw_email can be quite huge, and need this for just # search results def _cache_main_body_text text = self.get_main_body_text_internal # Strip the uudecode parts from main text # - this also effectively does a .dup as well, so text mods don't alter original text = text.split(/^begin.+^`\n^end\n/m).join(" ") if text.size > 1000000 # 1 MB ish raise "main body text more than 1 MB, need to implement clipping like for attachment text, or there is some other MIME decoding problem or similar" end # remove emails for privacy/anti-spam reasons self.mask_special_emails!(text) self.remove_privacy_sensitive_things!(text) # Remove existing quoted sections folded_quoted_text = self.remove_lotus_quoting(text, 'FOLDED_QUOTED_SECTION') folded_quoted_text = IncomingMessage.remove_quoted_sections(folded_quoted_text, "FOLDED_QUOTED_SECTION") self.cached_main_body_text_unfolded = text self.cached_main_body_text_folded = folded_quoted_text self.save! end # Returns body text from main text part of email, converted to UTF-8, with uudecode removed, # emails and privacy sensitive things remove, censored, and folded to remove excess quoted text # (marked with FOLDED_QUOTED_SECTION) # XXX returns a .dup of the text, so calling functions can in place modify it def get_main_body_text_folded if self.cached_main_body_text_folded.nil? self._cache_main_body_text end return self.cached_main_body_text_folded end def get_main_body_text_unfolded if self.cached_main_body_text_unfolded.nil? self._cache_main_body_text end return self.cached_main_body_text_unfolded end # Returns body text from main text part of email, converted to UTF-8 def get_main_body_text_internal parse_raw_email! main_part = get_main_body_text_part return _convert_part_body_to_text(main_part) end # Given a main text part, converts it to text def _convert_part_body_to_text(part) if part.nil? text = "[ Email has no body, please see attachments ]" source_charset = "utf-8" else text = part.body # by default, TMail converts to UTF8 in this call source_charset = part.charset if part.content_type == 'text/html' # e.g. http://www.whatdotheyknow.com/request/35/response/177 # XXX This is a bit of a hack as it is calling a # convert to text routine. Could instead call a # sanitize HTML one. # If the text isn't UTF8, it means TMail had a problem # converting it (invalid characters, etc), and we # should instead tell elinks to respect the source # charset use_charset = "utf-8" begin text = Iconv.conv('utf-8', 'utf-8', text) rescue Iconv::IllegalSequence use_charset = source_charset end text = self.class._get_attachment_text_internal_one_file(part.content_type, text, use_charset) end end # If TMail can't convert text, it just returns it, so we sanitise it. begin # Test if it's good UTF-8 text = Iconv.conv('utf-8', 'utf-8', text) rescue Iconv::IllegalSequence # Text looks like unlabelled nonsense, # strip out anything that isn't UTF-8 begin source_charset = 'utf-8' if source_charset.nil? text = Iconv.conv('utf-8//IGNORE', source_charset, text) + _("\n\n[ {{site_name}} note: The above text was badly encoded, and has had strange characters removed. ]", :site_name => Configuration::site_name) rescue Iconv::InvalidEncoding, Iconv::IllegalSequence if source_charset != "utf-8" source_charset = "utf-8" retry end end end # Fix DOS style linefeeds to Unix style ones (or other later regexps won't work) # Needed for e.g. http://www.whatdotheyknow.com/request/60/response/98 text = text.gsub(/\r\n/, "\n") # Compress extra spaces down to save space, and to stop regular expressions # breaking in strange extreme cases. e.g. for # http://www.whatdotheyknow.com/request/spending_on_consultants text = text.gsub(/ +/, " ") return text end # Returns part which contains main body text, or nil if there isn't one def get_main_body_text_part leaves = self.foi_attachments # Find first part which is text/plain or text/html # (We have to include HTML, as increasingly there are mail clients that # include no text alternative for the main part, and we don't want to # instead use the first text attachment # e.g. http://www.whatdotheyknow.com/request/list_of_public_authorties) leaves.each do |p| if p.content_type == 'text/plain' or p.content_type == 'text/html' return p end end # Otherwise first part which is any sort of text leaves.each do |p| if p.content_type.match(/^text/) return p end end # ... or if none, consider first part p = leaves[0] # if it is a known type then don't use it, return no body (nil) if !p.nil? && AlaveteliFileTypes.mimetype_to_extension(p.content_type) # this is guess of case where there are only attachments, no body text # e.g. http://www.whatdotheyknow.com/request/cost_benefit_analysis_for_real_n return nil end # otherwise return it assuming it is text (sometimes you get things # like binary/octet-stream, or the like, which are really text - XXX if # you find an example, put URL here - perhaps we should be always returning # nil in this case) return p end # Returns attachments that are uuencoded in main body part def _uudecode_and_save_attachments(text) # Find any uudecoded things buried in it, yeuchly uus = text.scan(/^begin.+^`\n^end\n/m) attachments = [] for uu in uus # Decode the string content = nil tempfile = Tempfile.new('foiuu') tempfile.print uu tempfile.flush content = AlaveteliExternalCommand.run("uudecode", "-o", "/dev/stdout", tempfile.path) tempfile.close # Make attachment type from it, working out filename and mime type filename = uu.match(/^begin\s+[0-9]+\s+(.*)$/)[1] calc_mime = AlaveteliFileTypes.filename_and_content_to_mimetype(filename, content) if calc_mime calc_mime = normalise_content_type(calc_mime) content_type = calc_mime else content_type = 'application/octet-stream' end hexdigest = Digest::MD5.hexdigest(content) attachment = self.foi_attachments.find_or_create_by_hexdigest(:hexdigest => hexdigest) attachment.update_attributes(:filename => filename, :content_type => content_type, :body => content, :display_size => "0K") attachment.save! attachments << attachment end return attachments end def get_attachments_for_display parse_raw_email! # return what user would consider attachments, i.e. not the main body main_part = get_main_body_text_part attachments = [] for attachment in self.foi_attachments attachments << attachment if attachment != main_part end return attachments end def extract_attachments! leaves = get_attachment_leaves # XXX check where else this is called from # XXX we have to call ensure_parts_counted after get_attachment_leaves # which is really messy. ensure_parts_counted attachments = [] for leaf in leaves body = leaf.body # As leaf.body causes MIME decoding which uses lots of RAM, do garbage collection here # to prevent excess memory use. XXX not really sure if this helps reduce # peak RAM use overall. Anyway, maybe there is something better to do than this. GC.start if leaf.within_rfc822_attachment within_rfc822_subject = leaf.within_rfc822_attachment.subject # Test to see if we are in the first part of the attached # RFC822 message and it is text, if so add headers. # XXX should probably use hunting algorithm to find main text part, rather than # just expect it to be first. This will do for now though. # Example request that needs this: # http://www.whatdotheyknow.com/request/2923/response/7013/attach/2/Cycle%20Path%20Bank.txt if leaf.within_rfc822_attachment == leaf && leaf.content_type == 'text/plain' headers = "" for header in [ 'Date', 'Subject', 'From', 'To', 'Cc' ] if leaf.within_rfc822_attachment.header.include?(header.downcase) header_value = leaf.within_rfc822_attachment.header[header.downcase] # Example message which has a blank Date header: # http://www.whatdotheyknow.com/request/30747/response/80253/attach/html/17/Common%20Purpose%20Advisory%20Group%20Meeting%20Tuesday%202nd%20March.txt.html if !header_value.blank? headers = headers + header + ": " + header_value.to_s + "\n" end end end # XXX call _convert_part_body_to_text here, but need to get charset somehow # e.g. http://www.whatdotheyknow.com/request/1593/response/3088/attach/4/Freedom%20of%20Information%20request%20-%20car%20oval%20sticker:%20Article%2020,%20Convention%20on%20Road%20Traffic%201949.txt body = headers + "\n" + body # This is quick way of getting all headers, but instead we only add some a) to # make it more usable, b) as at least one authority accidentally leaked security # information into a header. #attachment.body = leaf.within_rfc822_attachment.port.to_s end end hexdigest = Digest::MD5.hexdigest(body) attachment = self.foi_attachments.find_or_create_by_hexdigest(:hexdigest => hexdigest) attachment.update_attributes(:url_part_number => leaf.url_part_number, :content_type => leaf.content_type, :filename => MailHandler.get_part_file_name(leaf), :charset => leaf.charset, :within_rfc822_subject => within_rfc822_subject, :body => body) attachment.save! attachments << attachment.id end main_part = get_main_body_text_part # we don't use get_main_body_text_internal, as we want to avoid charset # conversions, since /usr/bin/uudecode needs to deal with those. # e.g. for https://secure.mysociety.org/admin/foi/request/show_raw_email/24550 if !main_part.nil? uudecoded_attachments = _uudecode_and_save_attachments(main_part.body) c = @count_first_uudecode_count for uudecode_attachment in uudecoded_attachments c += 1 uudecode_attachment.url_part_number = c uudecode_attachment.save! attachments << uudecode_attachment.id end end # now get rid of any attachments we no longer have FoiAttachment.destroy_all("id NOT IN (#{attachments.join(',')}) AND incoming_message_id = #{self.id}") end # Returns body text as HTML with quotes flattened, and emails removed. def get_body_for_html_display(collapse_quoted_sections = true) # Find the body text and remove emails for privacy/anti-spam reasons text = get_main_body_text_unfolded folded_quoted_text = get_main_body_text_folded # Remove quoted sections, adding HTML. XXX The FOLDED_QUOTED_SECTION is # a nasty hack so we can escape other HTML before adding the unfold # links, without escaping them. Rather than using some proper parser # making a tree structure (I don't know of one that is to hand, that # works well in this kind of situation, such as with regexps). if collapse_quoted_sections text = folded_quoted_text end text = MySociety::Format.simplify_angle_bracketed_urls(text) text = CGI.escapeHTML(text) text = MySociety::Format.make_clickable(text, :contract => 1) text.gsub!(/\[(email address|mobile number)\]/, '[<a href="/help/officers#mobiles">\1</a>]') if collapse_quoted_sections text = text.gsub(/(\s*FOLDED_QUOTED_SECTION\s*)+/m, "FOLDED_QUOTED_SECTION") text.strip! # if there is nothing but quoted stuff, then show the subject if text == "FOLDED_QUOTED_SECTION" text = "[Subject only] " + CGI.escapeHTML(self.subject) + text end # and display link for quoted stuff text = text.gsub(/FOLDED_QUOTED_SECTION/, "\n\n" + '<span class="unfold_link"><a href="?unfold=1#incoming-'+self.id.to_s+'">'+_("show quoted sections")+'</a></span>' + "\n\n") else if folded_quoted_text.include?('FOLDED_QUOTED_SECTION') text = text + "\n\n" + '<span class="unfold_link"><a href="?#incoming-'+self.id.to_s+'">'+_("hide quoted sections")+'</a></span>' end end text.strip! text = text.gsub(/\n/, '<br>') text = text.gsub(/(?:<br>\s*){2,}/, '<br><br>') # remove excess linebreaks that unnecessarily space it out return text.html_safe end # Returns text of email for using in quoted section when replying def get_body_for_quoting # Get the body text with emails and quoted sections removed text = get_main_body_text_folded text.gsub!("FOLDED_QUOTED_SECTION", " ") text.strip! raise "internal error" if text.nil? return text end MAX_ATTACHMENT_TEXT_CLIPPED = 1000000 # 1Mb ish # Returns text version of attachment text def get_attachment_text_full text = self._get_attachment_text_internal self.mask_special_emails!(text) self.remove_privacy_sensitive_things!(text) # This can be useful for memory debugging #STDOUT.puts 'xxx '+ MySociety::DebugHelpers::allocated_string_size_around_gc # Save clipped version for snippets if self.cached_attachment_text_clipped.nil? self.cached_attachment_text_clipped = text[0..MAX_ATTACHMENT_TEXT_CLIPPED] self.save! end return text end # Returns a version reduced to a sensible maximum size - this # is for performance reasons when showing snippets in search results. def get_attachment_text_clipped if self.cached_attachment_text_clipped.nil? # As side effect, get_attachment_text_full makes snippet text attachment_text = self.get_attachment_text_full raise "internal error" if self.cached_attachment_text_clipped.nil? end return self.cached_attachment_text_clipped end def IncomingMessage._get_attachment_text_internal_one_file(content_type, body, charset = 'utf-8') # note re. charset: TMail always tries to convert email bodies # to UTF8 by default, so normally it should already be that. text = '' # XXX - tell all these command line tools to return utf-8 if content_type == 'text/plain' text += body + "\n\n" else tempfile = Tempfile.new('foiextract') tempfile.print body tempfile.flush if content_type == 'application/vnd.ms-word' AlaveteliExternalCommand.run("wvText", tempfile.path, tempfile.path + ".txt") # Try catdoc if we get into trouble (e.g. for InfoRequestEvent 2701) if not File.exists?(tempfile.path + ".txt") AlaveteliExternalCommand.run("catdoc", tempfile.path, :append_to => text) else text += File.read(tempfile.path + ".txt") + "\n\n" File.unlink(tempfile.path + ".txt") end elsif content_type == 'application/rtf' # catdoc on RTF prodcues less comments and extra bumf than --text option to unrtf AlaveteliExternalCommand.run("catdoc", tempfile.path, :append_to => text) elsif content_type == 'text/html' # lynx wordwraps links in its output, which then don't # get formatted properly by Alaveteli. We use elinks # instead, which doesn't do that. AlaveteliExternalCommand.run("elinks", "-eval", "set document.codepage.assume = \"#{charset}\"", "-eval", "set document.codepage.force_assumed = 1", "-dump-charset", "utf-8", "-force-html", "-dump", tempfile.path, :append_to => text, :env => {"LANG" => "C"}) elsif content_type == 'application/vnd.ms-excel' # Bit crazy using /usr/bin/strings - but xls2csv, xlhtml and # py_xls2txt only extract text from cells, not from floating # notes. catdoc may be fooled by weird character sets, but will # probably do for UK FOI requests. AlaveteliExternalCommand.run("/usr/bin/strings", tempfile.path, :append_to => text) elsif content_type == 'application/vnd.ms-powerpoint' # ppthtml seems to catch more text, but only outputs HTML when # we want text, so just use catppt for now AlaveteliExternalCommand.run("catppt", tempfile.path, :append_to => text) elsif content_type == 'application/pdf' AlaveteliExternalCommand.run("pdftotext", tempfile.path, "-", :append_to => text) elsif content_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' # This is Microsoft's XML office document format. # Just pull out the main XML file, and strip it of text. xml = AlaveteliExternalCommand.run("/usr/bin/unzip", "-qq", "-c", tempfile.path, "word/document.xml") if !xml.nil? doc = REXML::Document.new(xml) text += doc.each_element( './/text()' ){}.join(" ") end elsif content_type == 'application/zip' # recurse into zip files begin zip_file = Zip::ZipFile.open(tempfile.path) text += IncomingMessage._get_attachment_text_from_zip_file(zip_file) zip_file.close() rescue $stderr.puts("Error processing zip file: #{$!.inspect}") end end tempfile.close end return text end def IncomingMessage._get_attachment_text_from_zip_file(zip_file) text = "" for entry in zip_file if entry.file? filename = entry.to_s begin body = entry.get_input_stream.read rescue # move to next attachment silently if there were problems # XXX really should reduce this to specific exceptions? # e.g. password protected next end calc_mime = AlaveteliFileTypes.filename_to_mimetype(filename) if calc_mime content_type = calc_mime else content_type = 'application/octet-stream' end text += _get_attachment_text_internal_one_file(content_type, body) end end return text end def _get_attachment_text_internal # Extract text from each attachment text = '' attachments = self.get_attachments_for_display for attachment in attachments text += IncomingMessage._get_attachment_text_internal_one_file(attachment.content_type, attachment.body, attachment.charset) end # Remove any bad characters text = Iconv.conv('utf-8//IGNORE', 'utf-8', text) return text end # Returns text for indexing def get_text_for_indexing_full return get_body_for_quoting + "\n\n" + get_attachment_text_full end # Used for excerpts in search results, when loading full text would be too slow def get_text_for_indexing_clipped return get_body_for_quoting + "\n\n" + get_attachment_text_clipped end # Has message arrived "recently"? def recently_arrived (Time.now - self.created_at) <= 3.days end def fully_destroy ActiveRecord::Base.transaction do for o in self.outgoing_message_followups o.incoming_message_followup = nil o.save! end info_request_event = InfoRequestEvent.find_by_incoming_message_id(self.id) info_request_event.track_things_sent_emails.each { |a| a.destroy } info_request_event.user_info_request_sent_alerts.each { |a| a.destroy } info_request_event.destroy self.raw_email.destroy_file_representation! self.destroy end end # Search all info requests for def IncomingMessage.find_all_unknown_mime_types for incoming_message in IncomingMessage.find(:all) for attachment in incoming_message.get_attachments_for_display raise "internal error incoming_message " + incoming_message.id.to_s if attachment.content_type.nil? if AlaveteliFileTypes.mimetype_to_extension(attachment.content_type).nil? $stderr.puts "Unknown type for /request/" + incoming_message.info_request.id.to_s + "#incoming-"+incoming_message.id.to_s $stderr.puts " " + attachment.filename.to_s + " " + attachment.content_type.to_s end end end return nil end # Returns space separated list of file extensions of attachments to this message. Defaults to # the normal extension for known mime type, otherwise uses other extensions. def get_present_file_extensions ret = {} for attachment in self.get_attachments_for_display ext = AlaveteliFileTypes.mimetype_to_extension(attachment.content_type) ext = File.extname(attachment.filename).gsub(/^[.]/, "") if ext.nil? && !attachment.filename.nil? ret[ext] = 1 if !ext.nil? end return ret.keys.join(" ") end # Return space separated list of all file extensions known def IncomingMessage.get_all_file_extensions return AlaveteliFileTypes.all_extensions.join(" ") end # Return false if for some reason this is a message that we shouldn't let them reply to def valid_to_reply_to? # check validity of email if empty_from_field? return false end email = self.from_email if !MySociety::Validate.is_valid_email(email) return false end # reject postmaster - authorities seem to nearly always not respond to # email to postmaster, and it tends to only happen after delivery failure. # likewise Mailer-Daemon, Auto_Reply... prefix = email prefix =~ /^(.*)@/ prefix = $1 if !prefix.nil? && prefix.downcase.match(/^(postmaster|mailer-daemon|auto_reply|do.?not.?reply|no.reply)$/) return false end if !self.mail['return-path'].nil? && self.mail['return-path'].addr == "<>" return false end if !self.mail['auto-submitted'].nil? return false end return true end def normalise_content_type(content_type) # e.g. http://www.whatdotheyknow.com/request/93/response/250 if content_type == 'application/excel' or content_type == 'application/msexcel' or content_type == 'application/x-ms-excel' content_type = 'application/vnd.ms-excel' end if content_type == 'application/mspowerpoint' or content_type == 'application/x-ms-powerpoint' content_type = 'application/vnd.ms-powerpoint' end if content_type == 'application/msword' or content_type == 'application/x-ms-word' content_type = 'application/vnd.ms-word' end if content_type == 'application/x-zip-compressed' content_type = 'application/zip' end # e.g. http://www.whatdotheyknow.com/request/copy_of_current_swessex_scr_opt#incoming-9928 if content_type == 'application/acrobat' content_type = 'application/pdf' end return content_type end def for_admin_column self.class.content_columns.each do |column| yield(column.human_name, self.send(column.name), column.type.to_s, column.name) end end private :normalise_content_type end