aboutsummaryrefslogtreecommitdiffstats
path: root/lib/http_client.c
blob: 7ed539d01c8fe081dd653bbdc27184e530587c1d (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
  /********************************************************************\
  * BitlBee -- An IRC to other IM-networks gateway                     *
  *                                                                    *
  * Copyright 2002-2011 Wilmer van der Gaast and others                *
  \********************************************************************/

/* HTTP(S) module                                                       */

/*
  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 with
  the Debian GNU/Linux distribution in /usr/share/common-licenses/GPL;
  if not, write to the Free Software Foundation, Inc., 59 Temple Place,
  Suite 330, Boston, MA  02111-1307  USA
*/

#include <string.h>
#include <stdio.h>

#include "http_client.h"
#include "url.h"
#include "sock.h"


static gboolean http_connected( gpointer data, int source, b_input_condition cond );
static gboolean http_ssl_connected( gpointer data, int returncode, void *source, b_input_condition cond );
static gboolean http_incoming_data( gpointer data, int source, b_input_condition cond );
static void http_free( struct http_request *req );


struct http_request *http_dorequest( char *host, int port, int ssl, char *request, http_input_function func, gpointer data )
{
	struct http_request *req;
	int error = 0;
	
	req = g_new0( struct http_request, 1 );
	
	if( ssl )
	{
		req->ssl = ssl_connect( host, port, TRUE, http_ssl_connected, req );
		if( req->ssl == NULL )
			error = 1;
	}
	else
	{
		req->fd = proxy_connect( host, port, http_connected, req );
		if( req->fd < 0 )
			error = 1;
	}
	
	if( error )
	{
		http_free( req );
		return NULL;
	}
	
	req->func = func;
	req->data = data;
	req->request = g_strdup( request );
	req->request_length = strlen( request );
	req->redir_ttl = 3;
	
	if( getenv( "BITLBEE_DEBUG" ) )
		printf( "About to send HTTP request:\n%s\n", req->request );
	
	return req;
}

struct http_request *http_dorequest_url( char *url_string, http_input_function func, gpointer data )
{
	url_t *url = g_new0( url_t, 1 );
	char *request;
	void *ret;
	
	if( !url_set( url, url_string ) )
	{
		g_free( url );
		return NULL;
	}
	
	if( url->proto != PROTO_HTTP && url->proto != PROTO_HTTPS )
	{
		g_free( url );
		return NULL;
	}
	
	request = g_strdup_printf( "GET %s HTTP/1.0\r\n"
	                           "Host: %s\r\n"
	                           "Connection: close\r\n"
	                           "User-Agent: BitlBee " BITLBEE_VERSION " " ARCH "/" CPU "\r\n"
	                           "\r\n", url->file, url->host );
	
	ret = http_dorequest( url->host, url->port,
	                      url->proto == PROTO_HTTPS, request, func, data );
	
	g_free( url );
	g_free( request );
	return ret;
}

/* This one is actually pretty simple... Might get more calls if we can't write 
   the whole request at once. */
static gboolean http_connected( gpointer data, int source, b_input_condition cond )
{
	struct http_request *req = data;
	int st;
	
	if( source < 0 )
		goto error;
	
	if( req->inpa > 0 )
		b_event_remove( req->inpa );
	
	sock_make_nonblocking( req->fd );
	
	if( req->ssl )
	{
		st = ssl_write( req->ssl, req->request + req->bytes_written,
		                req->request_length - req->bytes_written );
		if( st < 0 )
		{
			if( ssl_errno != SSL_AGAIN )
			{
				ssl_disconnect( req->ssl );
				goto error;
			}
		}
	}
	else
	{
		st = write( source, req->request + req->bytes_written,
		                    req->request_length - req->bytes_written );
		if( st < 0 )
		{
			if( !sockerr_again() )
			{
				closesocket( req->fd );
				goto error;
			}
		}
	}
	
	if( st > 0 )
		req->bytes_written += st;
	
	if( req->bytes_written < req->request_length )
		req->inpa = b_input_add( source,
		                         req->ssl ? ssl_getdirection( req->ssl ) : B_EV_IO_WRITE,
	        	                 http_connected, req );
	else
		req->inpa = b_input_add( source, B_EV_IO_READ, http_incoming_data, req );
	
	return FALSE;
	
error:
	if( req->status_string == NULL )
		req->status_string = g_strdup( "Error while writing HTTP request" );
	
	req->func( req );
	http_free( req );
	return FALSE;
}

static gboolean http_ssl_connected( gpointer data, int returncode, void *source, b_input_condition cond )
{
	struct http_request *req = data;
	
	if( source == NULL )
	{
		if( returncode != 0 )
		{
			char *err = ssl_verify_strerror( returncode );
			req->status_string = g_strdup_printf(
				"Certificate verification problem 0x%x: %s",
				returncode, err ? err : "Unknown" );
			g_free( err );
		}
		return http_connected( data, -1, cond );
	}
	
	req->fd = ssl_getfd( source );
	
	return http_connected( data, req->fd, cond );
}

static gboolean http_incoming_data( gpointer data, int source, b_input_condition cond )
{
	struct http_request *req = data;
	int evil_server = 0;
	char buffer[2048];
	char *end1, *end2, *s;
	size_t content_length;
	int st;
	
	if( req->inpa > 0 )
		b_event_remove( req->inpa );
	
	if( req->ssl )
	{
		st = ssl_read( req->ssl, buffer, sizeof( buffer ) );
		if( st < 0 )
		{
			if( ssl_errno != SSL_AGAIN )
			{
				/* goto cleanup; */
				
				/* YAY! We have to deal with crappy Microsoft
				   servers that LOVE to send invalid TLS
				   packets that abort connections! \o/ */
				
				goto got_reply;
			}
		}
		else if( st == 0 )
		{
			goto got_reply;
		}
	}
	else
	{
		st = read( req->fd, buffer, sizeof( buffer ) );
		if( st < 0 )
		{
			if( !sockerr_again() )
			{
				req->status_string = g_strdup( strerror( errno ) );
				goto cleanup;
			}
		}
		else if( st == 0 )
		{
			goto got_reply;
		}
	}
	
	if( st > 0 )
	{
		req->reply_headers = g_realloc( req->reply_headers, req->bytes_read + st + 1 );
		memcpy( req->reply_headers + req->bytes_read, buffer, st );
		req->bytes_read += st;
	}
	
	/* There will be more! */
	req->inpa = b_input_add( req->fd,
	                         req->ssl ? ssl_getdirection( req->ssl ) : B_EV_IO_READ,
	                         http_incoming_data, req );
	
	if( ssl_pending( req->ssl ) )
		return http_incoming_data( data, source, cond );
	else
		return FALSE;

got_reply:
	/* Maybe if the webserver is overloaded, or when there's bad SSL
	   support... */
	if( req->bytes_read == 0 )
	{
		req->status_string = g_strdup( "Empty HTTP reply" );
		goto cleanup;
	}
	
	/* Zero termination is very convenient. */
	req->reply_headers[req->bytes_read] = 0;
	
	/* Find the separation between headers and body, and keep stupid
	   webservers in mind. */
	end1 = strstr( req->reply_headers, "\r\n\r\n" );
	end2 = strstr( req->reply_headers, "\n\n" );
	
	if( end2 && end2 < end1 )
	{
		end1 = end2 + 1;
		evil_server = 1;
	}
	else if( end1 )
	{
		end1 += 2;
	}
	else
	{
		req->status_string = g_strdup( "Malformed HTTP reply" );
		goto cleanup;
	}
	
	*end1 = 0;
	
	if( getenv( "BITLBEE_DEBUG" ) )
		printf( "HTTP response headers:\n%s\n", req->reply_headers );
	
	if( evil_server )
		req->reply_body = end1 + 1;
	else
		req->reply_body = end1 + 2;
	
	req->body_size = req->reply_headers + req->bytes_read - req->reply_body;
	
	if( ( end1 = strchr( req->reply_headers, ' ' ) ) != NULL )
	{
		if( sscanf( end1 + 1, "%d", &req->status_code ) != 1 )
		{
			req->status_string = g_strdup( "Can't parse status code" );
			req->status_code = -1;
		}
		else
		{
			char *eol;
			
			if( evil_server )
				eol = strchr( end1, '\n' );
			else
				eol = strchr( end1, '\r' );
			
			req->status_string = g_strndup( end1 + 1, eol - end1 - 1 );
			
			/* Just to be sure... */
			if( ( eol = strchr( req->status_string, '\r' ) ) )
				*eol = 0;
			if( ( eol = strchr( req->status_string, '\n' ) ) )
				*eol = 0;
		}
	}
	else
	{
		req->status_string = g_strdup( "Can't locate status code" );
		req->status_code = -1;
	}
	
	if( ( ( req->status_code >= 301 && req->status_code <= 303 ) ||
	      req->status_code == 307 ) && req->redir_ttl-- > 0 )
	{
		char *loc, *new_request, *new_host;
		int error = 0, new_port, new_proto;
		
		/* We might fill it again, so let's not leak any memory. */
		g_free( req->status_string );
		req->status_string = NULL;
		
		loc = strstr( req->reply_headers, "\nLocation: " );
		if( loc == NULL ) /* We can't handle this redirect... */
		{
			req->status_string = g_strdup( "Can't locate Location: header" );
			goto cleanup;
		}
		
		loc += 11;
		while( *loc == ' ' )
			loc ++;
		
		/* TODO/FIXME: Possibly have to handle relative redirections,
		   and rewrite Host: headers. Not necessary for now, it's
		   enough for passport authentication like this. */
		
		if( *loc == '/' )
		{
			/* Just a different pathname... */
			
			/* Since we don't cache the servername, and since we
			   don't need this yet anyway, I won't implement it. */
			
			req->status_string = g_strdup( "Can't handle recursive redirects" );
			
			goto cleanup;
		}
		else
		{
			/* A whole URL */
			url_t *url;
			char *s;
			const char *new_method;
			
			s = strstr( loc, "\r\n" );
			if( s == NULL )
				goto cleanup;
			
			url = g_new0( url_t, 1 );
			*s = 0;
			
			if( !url_set( url, loc ) )
			{
				req->status_string = g_strdup( "Malformed redirect URL" );
				g_free( url );
				goto cleanup;
			}
			
			/* Find all headers and, if necessary, the POST request contents.
			   Skip the old Host: header though. This crappy code here means
			   anything using this http_client MUST put the Host: header at
			   the top. */
			if( !( ( s = strstr( req->request, "\r\nHost: " ) ) &&
			       ( s = strstr( s + strlen( "\r\nHost: " ), "\r\n" ) ) ) )
			{
				req->status_string = g_strdup( "Error while rebuilding request string" );
				g_free( url );
				goto cleanup;
			}
			
			/* More or less HTTP/1.0 compliant, from my reading of RFC 2616.
			   Always perform a GET request unless we received a 301. 303 was
			   meant for this but it's HTTP/1.1-only and we're specifically
			   speaking HTTP/1.0. ...
			   
			   Well except someone at identi.ca's didn't bother reading any
			   RFCs and just return HTTP/1.1-specific status codes to HTTP/1.0
			   requests. Fuckers. So here we are, handle 301..303,307. */
			if( strncmp( req->request, "GET", 3 ) == 0 )
				/* GETs never become POSTs. */
				new_method = "GET";
			else if( req->status_code == 302 || req->status_code == 303 )
				/* 302 de-facto becomes GET, 303 as specified by RFC 2616#10.3.3 */
				new_method = "GET";
			else
				/* 301 de-facto should stay POST, 307 specifally RFC 2616#10.3.8 */
				new_method = "POST";
			
			/* Okay, this isn't fun! We have to rebuild the request... :-( */
			new_request = g_strdup_printf( "%s %s HTTP/1.0\r\nHost: %s%s",
			                               new_method, url->file, url->host, s );
			
			new_host = g_strdup( url->host );
			new_port = url->port;
			new_proto = url->proto;
			
			/* If we went from POST to GET, truncate the request content. */
			if( new_request[0] != req->request[0] && new_request[0] == 'G' &&
			    ( s = strstr( new_request, "\r\n\r\n" ) ) )
				s[4] = '\0';
			
			g_free( url );
		}
		
		if( req->ssl )
			ssl_disconnect( req->ssl );
		else
			closesocket( req->fd );
		
		req->fd = -1;
		req->ssl = NULL;
		
		if( getenv( "BITLBEE_DEBUG" ) )
			printf( "New headers for redirected HTTP request:\n%s\n", new_request );
	
		if( new_proto == PROTO_HTTPS )
		{
			req->ssl = ssl_connect( new_host, new_port, TRUE, http_ssl_connected, req );
			if( req->ssl == NULL )
				error = 1;
		}
		else
		{
			req->fd = proxy_connect( new_host, new_port, http_connected, req );
			if( req->fd < 0 )
				error = 1;
		}
		g_free( new_host );
		
		if( error )
		{
			req->status_string = g_strdup( "Connection problem during redirect" );
			g_free( new_request );
			goto cleanup;
		}
		
		g_free( req->request );
		g_free( req->reply_headers );
		req->request = new_request;
		req->request_length = strlen( new_request );
		req->bytes_read = req->bytes_written = req->inpa = 0;
		req->reply_headers = req->reply_body = NULL;
		
		return FALSE;
	}
	
	/* Assume that a closed connection means we're finished, this indeed
	   breaks with keep-alive connections and faulty connections. */
	/* req->finished = 1; */

cleanup:
	if( req->ssl )
		ssl_disconnect( req->ssl );
	else
		closesocket( req->fd );
	
	if( ( s = get_rfc822_header( req->reply_headers, "Content-Length", 0 ) ) &&
	    sscanf( s, "%zd", &content_length ) == 1 )
	{
		if( content_length < req->body_size )
		{
			req->status_code = -1;
			g_free( req->status_string );
			req->status_string = g_strdup( "Response truncated" );
		}
	}
	g_free( s );
	
	if( getenv( "BITLBEE_DEBUG" ) && req )
		printf( "Finishing HTTP request with status: %s\n",
		        req->status_string ? req->status_string : "NULL" );
	
	req->func( req );
	http_free( req );
	return FALSE;
}

static void http_free( struct http_request *req )
{
	g_free( req->request );
	g_free( req->reply_headers );
	g_free( req->status_string );
	g_free( req );
}
pan class="o">< node->u.array.length; i ++) { txu = twitter_xt_get_user(node->u.array.values[i]); if (txu) txl->list = g_slist_prepend(txl->list, txu); } return TRUE; } #ifdef __GLIBC__ #define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S %z %Y" #else #define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S +0000 %Y" #endif static char* expand_entities(char* text, const json_value *entities); /** * Function to fill a twitter_xml_status struct. * It sets: * - the status text and * - the created_at timestamp and * - the status id and * - the user in a twitter_xml_user struct. */ static struct twitter_xml_status *twitter_xt_get_status(const json_value *node) { struct twitter_xml_status *txs; const json_value *rt = NULL, *entities = NULL; if (node->type != json_object) return FALSE; txs = g_new0(struct twitter_xml_status, 1); JSON_O_FOREACH (node, k, v) { if (strcmp("text", k) == 0 && v->type == json_string) { txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1); strip_html(txs->text); } else if (strcmp("retweeted_status", k) == 0 && v->type == json_object) { rt = v; } else if (strcmp("created_at", k) == 0 && v->type == json_string) { struct tm parsed; /* Very sensitive to changes to the formatting of this field. :-( Also assumes the timezone used is UTC since C time handling functions suck. */ if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL) txs->created_at = mktime_utc(&parsed); } else if (strcmp("user", k) == 0 && v->type == json_object) { txs->user = twitter_xt_get_user(v); } else if (strcmp("id", k) == 0 && v->type == json_integer) { txs->rt_id = txs->id = v->u.integer; } else if (strcmp("in_reply_to_status_id", k) == 0 && v->type == json_integer) { txs->reply_to = v->u.integer; } else if (strcmp("entities", k) == 0 && v->type == json_object) { entities = v; } } /* If it's a (truncated) retweet, get the original. Even if the API claims it wasn't truncated because it may be lying. */ if (rt) { struct twitter_xml_status *rtxs = twitter_xt_get_status(rt); if (rtxs) { g_free(txs->text); txs->text = g_strdup_printf("RT @%s: %s", rtxs->user->screen_name, rtxs->text); txs->id = rtxs->id; txs_free(rtxs); } } else if (entities) { txs->text = expand_entities(txs->text, entities); } if (txs->text && txs->user && txs->id) return txs; txs_free(txs); return NULL; } /** * Function to fill a twitter_xml_status struct (DM variant). */ static struct twitter_xml_status *twitter_xt_get_dm(const json_value *node) { struct twitter_xml_status *txs; const json_value *entities = NULL; if (node->type != json_object) return FALSE; txs = g_new0(struct twitter_xml_status, 1); JSON_O_FOREACH (node, k, v) { if (strcmp("text", k) == 0 && v->type == json_string) { txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1); strip_html(txs->text); } else if (strcmp("created_at", k) == 0 && v->type == json_string) { struct tm parsed; /* Very sensitive to changes to the formatting of this field. :-( Also assumes the timezone used is UTC since C time handling functions suck. */ if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL) txs->created_at = mktime_utc(&parsed); } else if (strcmp("sender", k) == 0 && v->type == json_object) { txs->user = twitter_xt_get_user(v); } else if (strcmp("id", k) == 0 && v->type == json_integer) { txs->id = v->u.integer; } } if (entities) { txs->text = expand_entities(txs->text, entities); } if (txs->text && txs->user && txs->id) return txs; txs_free(txs); return NULL; } static char* expand_entities(char* text, const json_value *entities) { JSON_O_FOREACH (entities, k, v) { int i; if (v->type != json_array) continue; if (strcmp(k, "urls") != 0 && strcmp(k, "media") != 0) continue; for (i = 0; i < v->u.array.length; i ++) { if (v->u.array.values[i]->type != json_object) continue; const char *kort = json_o_str(v->u.array.values[i], "url"); const char *disp = json_o_str(v->u.array.values[i], "display_url"); char *pos, *new; if (!kort || !disp || !(pos = strstr(text, kort))) continue; *pos = '\0'; new = g_strdup_printf("%s%s <%s>%s", text, kort, disp, pos + strlen(kort)); g_free(text); text = new; } } return text; } /** * Function to fill a twitter_xml_list struct. * It sets: * - all <status>es within the <status> element and * - the next_cursor. */ static gboolean twitter_xt_get_status_list(struct im_connection *ic, const json_value *node, struct twitter_xml_list *txl) { struct twitter_xml_status *txs; int i; // Set the type of the list. txl->type = TXL_STATUS; if (node->type != json_array) return FALSE; // The root <statuses> node should hold the list of statuses <status> // Walk over the nodes children. for (i = 0; i < node->u.array.length; i ++) { txs = twitter_xt_get_status(node->u.array.values[i]); if (!txs) continue; txl->list = g_slist_prepend(txl->list, txs); } return TRUE; } /* Will log messages either way. Need to keep track of IDs for stream deduping. Plus, show_ids is on by default and I don't see why anyone would disable it. */ static char *twitter_msg_add_id(struct im_connection *ic, struct twitter_xml_status *txs, const char *prefix) { struct twitter_data *td = ic->proto_data; int reply_to = -1; bee_user_t *bu; if (txs->reply_to) { int i; for (i = 0; i < TWITTER_LOG_LENGTH; i++) if (td->log[i].id == txs->reply_to) { reply_to = i; break; } } if (txs->user && txs->user->screen_name && (bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) { struct twitter_user_data *tud = bu->data; if (txs->id > tud->last_id) { tud->last_id = txs->id; tud->last_time = txs->created_at; } } td->log_id = (td->log_id + 1) % TWITTER_LOG_LENGTH; td->log[td->log_id].id = txs->id; td->log[td->log_id].bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name); /* This is all getting hairy. :-( If we RT'ed something ourselves, remember OUR id instead so undo will work. In other cases, the original tweet's id should be remembered for deduplicating. */ if (strcmp(txs->user->screen_name, td->user) == 0) td->log[td->log_id].id = txs->rt_id; if (set_getbool(&ic->acc->set, "show_ids")) { if (reply_to != -1) return g_strdup_printf("\002[\002%02x->%02x\002]\002 %s%s", td->log_id, reply_to, prefix, txs->text); else return g_strdup_printf("\002[\002%02x\002]\002 %s%s", td->log_id, prefix, txs->text); } else { if (*prefix) return g_strconcat(prefix, txs->text, NULL); else return NULL; } } /** * Function that is called to see the statuses in a groupchat window. */ static void twitter_status_show_chat(struct im_connection *ic, struct twitter_xml_status *status) { struct twitter_data *td = ic->proto_data; struct groupchat *gc; gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0; char *msg; // Create a new groupchat if it does not exsist. gc = twitter_groupchat_init(ic); if (!me) /* MUST be done before twitter_msg_add_id() to avoid #872. */ twitter_add_buddy(ic, status->user->screen_name, status->user->name); msg = twitter_msg_add_id(ic, status, ""); // Say it! if (me) { imcb_chat_log(gc, "You: %s", msg ? msg : status->text); } else { imcb_chat_msg(gc, status->user->screen_name, msg ? msg : status->text, 0, status->created_at); } g_free(msg); } /** * Function that is called to see statuses as private messages. */ static void twitter_status_show_msg(struct im_connection *ic, struct twitter_xml_status *status) { struct twitter_data *td = ic->proto_data; char from[MAX_STRING] = ""; char *prefix = NULL, *text = NULL; gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0; if (td->flags & TWITTER_MODE_ONE) { g_snprintf(from, sizeof(from) - 1, "%s_%s", td->prefix, ic->acc->user); from[MAX_STRING - 1] = '\0'; } if (td->flags & TWITTER_MODE_ONE) prefix = g_strdup_printf("\002<\002%s\002>\002 ", status->user->screen_name); else if (!me) twitter_add_buddy(ic, status->user->screen_name, status->user->name); else prefix = g_strdup("You: "); text = twitter_msg_add_id(ic, status, prefix ? prefix : ""); imcb_buddy_msg(ic, *from ? from : status->user->screen_name, text ? text : status->text, 0, status->created_at); g_free(text); g_free(prefix); } static void twitter_status_show(struct im_connection *ic, struct twitter_xml_status *status) { struct twitter_data *td = ic->proto_data; if (status->user == NULL || status->text == NULL) return; /* Grrrr. Would like to do this during parsing, but can't access settings from there. */ if (set_getbool(&ic->acc->set, "strip_newlines")) strip_newlines(status->text); if (td->flags & TWITTER_MODE_CHAT) twitter_status_show_chat(ic, status); else twitter_status_show_msg(ic, status); // Update the timeline_id to hold the highest id, so that by the next request // we won't pick up the updates already in the list. td->timeline_id = MAX(td->timeline_id, status->rt_id); } static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o); static void twitter_http_stream(struct http_request *req) { struct im_connection *ic = req->data; struct twitter_data *td; json_value *parsed; int len = 0; char c, *nl; if (!g_slist_find(twitter_connections, ic)) return; ic->flags |= OPT_PONGED; td = ic->proto_data; if ((req->flags & HTTPC_EOF) || !req->reply_body) { td->stream = NULL; imcb_error(ic, "Stream closed (%s)", req->status_string); imc_logout(ic, TRUE); return; } /* MUST search for CRLF, not just LF: https://dev.twitter.com/docs/streaming-apis/processing#Parsing_responses */ if (!(nl = strstr(req->reply_body, "\r\n"))) return; len = nl - req->reply_body; if (len > 0) { c = req->reply_body[len]; req->reply_body[len] = '\0'; if ((parsed = json_parse(req->reply_body, req->body_size))) { twitter_stream_handle_object(ic, parsed); } json_value_free(parsed); req->reply_body[len] = c; } http_flush_bytes(req, len + 2); /* One notification might bring multiple events! */ if (req->body_size > 0) twitter_http_stream(req); } static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o); static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs); static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o) { struct twitter_data *td = ic->proto_data; struct twitter_xml_status *txs; json_value *c; if ((txs = twitter_xt_get_status(o))) { gboolean ret = twitter_stream_handle_status(ic, txs); txs_free(txs); return ret; } else if ((c = json_o_get(o, "direct_message")) && (txs = twitter_xt_get_dm(c))) { if (strcmp(txs->user->screen_name, td->user) != 0) imcb_buddy_msg(ic, txs->user->screen_name, txs->text, 0, txs->created_at); txs_free(txs); return TRUE; } else if ((c = json_o_get(o, "event")) && c->type == json_string) { twitter_stream_handle_event(ic, o); return TRUE; } else if ((c = json_o_get(o, "disconnect")) && c->type == json_object) { /* HACK: Because we're inside an event handler, we can't just disconnect here. Instead, just change the HTTP status string into a Twitter status string. */ char *reason = json_o_strdup(c, "reason"); if (reason) { g_free(td->stream->status_string); td->stream->status_string = reason; } return TRUE; } return FALSE; } static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs) { struct twitter_data *td = ic->proto_data; int i; for (i = 0; i < TWITTER_LOG_LENGTH; i++) { if (td->log[i].id == txs->id) { /* Got a duplicate (RT, probably). Drop it. */ return TRUE; } } if (!(strcmp(txs->user->screen_name, td->user) == 0 || set_getbool(&ic->acc->set, "fetch_mentions") || bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) { /* Tweet is from an unknown person and the user does not want to see @mentions, so drop it. twitter_stream_handle_event() picks up new follows so this simple filter should be safe. */ /* TODO: The streaming API seems to do poor @mention matching. I.e. I'm getting mentions for @WilmerSomething, not just for @Wilmer. But meh. You want spam, you get spam. */ return TRUE; } twitter_status_show(ic, txs); return TRUE; } static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o) { struct twitter_data *td = ic->proto_data; json_value *source = json_o_get(o, "source"); json_value *target = json_o_get(o, "target"); const char *type = json_o_str(o, "event"); if (!type || !source || source->type != json_object || !target || target->type != json_object) { return FALSE; } if (strcmp(type, "follow") == 0) { struct twitter_xml_user *us = twitter_xt_get_user(source); struct twitter_xml_user *ut = twitter_xt_get_user(target); if (strcmp(us->screen_name, td->user) == 0) { twitter_add_buddy(ic, ut->screen_name, ut->name); } txu_free(us); txu_free(ut); } return TRUE; } gboolean twitter_open_stream(struct im_connection *ic) { struct twitter_data *td = ic->proto_data; char *args[2] = {"with", "followings"}; if ((td->stream = twitter_http(ic, TWITTER_USER_STREAM_URL, twitter_http_stream, ic, 0, args, 2))) { /* This flag must be enabled or we'll get no data until EOF (which err, kind of, defeats the purpose of a streaming API). */ td->stream->flags |= HTTPC_STREAMING; return TRUE; } return FALSE; } static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor); static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor); /** * Get the timeline with optionally mentions */ gboolean twitter_get_timeline(struct im_connection *ic, gint64 next_cursor) { struct twitter_data *td = ic->proto_data; gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions"); if (td->flags & TWITTER_DOING_TIMELINE) { if (++td->http_fails >= 5) { imcb_error(ic, "Fetch timeout (%d)", td->flags); imc_logout(ic, TRUE); return FALSE; } } td->flags |= TWITTER_DOING_TIMELINE; twitter_get_home_timeline(ic, next_cursor); if (include_mentions) { twitter_get_mentions(ic, next_cursor); } return TRUE; } /** * Call this one after receiving timeline/mentions. Show to user once we have * both. */ void twitter_flush_timeline(struct im_connection *ic) { struct twitter_data *td = ic->proto_data; gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions"); int show_old_mentions = set_getint(&ic->acc->set, "show_old_mentions"); struct twitter_xml_list *home_timeline = td->home_timeline_obj; struct twitter_xml_list *mentions = td->mentions_obj; guint64 last_id = 0; GSList *output = NULL; GSList *l; imcb_connected(ic); if (!(td->flags & TWITTER_GOT_TIMELINE)) { return; } if (include_mentions && !(td->flags & TWITTER_GOT_MENTIONS)) { return; } if (home_timeline && home_timeline->list) { for (l = home_timeline->list; l; l = g_slist_next(l)) { output = g_slist_insert_sorted(output, l->data, twitter_compare_elements); } } if (include_mentions && mentions && mentions->list) { for (l = mentions->list; l; l = g_slist_next(l)) { if (show_old_mentions < 1 && output && twitter_compare_elements(l->data, output->data) < 0) { continue; } output = g_slist_insert_sorted(output, l->data, twitter_compare_elements); } } // See if the user wants to see the messages in a groupchat window or as private messages. while (output) { struct twitter_xml_status *txs = output->data; if (txs->id != last_id) twitter_status_show(ic, txs); last_id = txs->id; output = g_slist_remove(output, txs); } txl_free(home_timeline); txl_free(mentions); td->flags &= ~(TWITTER_DOING_TIMELINE | TWITTER_GOT_TIMELINE | TWITTER_GOT_MENTIONS); td->home_timeline_obj = td->mentions_obj = NULL; } static void twitter_http_get_home_timeline(struct http_request *req); static void twitter_http_get_mentions(struct http_request *req); /** * Get the timeline. */ static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor) { struct twitter_data *td = ic->proto_data; txl_free(td->home_timeline_obj); td->home_timeline_obj = NULL; td->flags &= ~TWITTER_GOT_TIMELINE; char *args[6]; args[0] = "cursor"; args[1] = g_strdup_printf("%lld", (long long) next_cursor); args[2] = "include_entities"; args[3] = "true"; if (td->timeline_id) { args[4] = "since_id"; args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id); } if (twitter_http(ic, TWITTER_HOME_TIMELINE_URL, twitter_http_get_home_timeline, ic, 0, args, td->timeline_id ? 6 : 4) == NULL) { if (++td->http_fails >= 5) imcb_error(ic, "Could not retrieve %s: %s", TWITTER_HOME_TIMELINE_URL, "connection failed"); td->flags |= TWITTER_GOT_TIMELINE; twitter_flush_timeline(ic); } g_free(args[1]); if (td->timeline_id) { g_free(args[5]); } } /** * Get mentions. */ static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor) { struct twitter_data *td = ic->proto_data; txl_free(td->mentions_obj); td->mentions_obj = NULL; td->flags &= ~TWITTER_GOT_MENTIONS; char *args[6]; args[0] = "cursor"; args[1] = g_strdup_printf("%lld", (long long) next_cursor); args[2] = "include_entities"; args[3] = "true"; if (td->timeline_id) { args[4] = "since_id"; args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id); } else { args[4] = "count"; args[5] = g_strdup_printf("%d", set_getint(&ic->acc->set, "show_old_mentions")); } if (twitter_http(ic, TWITTER_MENTIONS_URL, twitter_http_get_mentions, ic, 0, args, 6) == NULL) { if (++td->http_fails >= 5) imcb_error(ic, "Could not retrieve %s: %s", TWITTER_MENTIONS_URL, "connection failed"); td->flags |= TWITTER_GOT_MENTIONS; twitter_flush_timeline(ic); } g_free(args[1]); g_free(args[5]); } /** * Callback for getting the home timeline. */ static void twitter_http_get_home_timeline(struct http_request *req) { struct im_connection *ic = req->data; struct twitter_data *td; json_value *parsed; struct twitter_xml_list *txl; // Check if the connection is still active. if (!g_slist_find(twitter_connections, ic)) return; td = ic->proto_data; txl = g_new0(struct twitter_xml_list, 1); txl->list = NULL; // The root <statuses> node should hold the list of statuses <status> if (!(parsed = twitter_parse_response(ic, req))) goto end; twitter_xt_get_status_list(ic, parsed, txl); json_value_free(parsed); td->home_timeline_obj = txl; end: if (!g_slist_find(twitter_connections, ic)) return; td->flags |= TWITTER_GOT_TIMELINE; twitter_flush_timeline(ic); } /** * Callback for getting mentions. */ static void twitter_http_get_mentions(struct http_request *req) { struct im_connection *ic = req->data; struct twitter_data *td; json_value *parsed; struct twitter_xml_list *txl; // Check if the connection is still active. if (!g_slist_find(twitter_connections, ic)) return; td = ic->proto_data; txl = g_new0(struct twitter_xml_list, 1); txl->list = NULL; // The root <statuses> node should hold the list of statuses <status> if (!(parsed = twitter_parse_response(ic, req))) goto end; twitter_xt_get_status_list(ic, parsed, txl); json_value_free(parsed); td->mentions_obj = txl; end: if (!g_slist_find(twitter_connections, ic)) return; td->flags |= TWITTER_GOT_MENTIONS; twitter_flush_timeline(ic); } /** * Callback to use after sending a POST request to twitter. * (Generic, used for a few kinds of queries.) */ static void twitter_http_post(struct http_request *req) { struct im_connection *ic = req->data; struct twitter_data *td; json_value *parsed, *id; // Check if the connection is still active. if (!g_slist_find(twitter_connections, ic)) return; td = ic->proto_data; td->last_status_id = 0; if (!(parsed = twitter_parse_response(ic, req))) return; if ((id = json_o_get(parsed, "id")) && id->type == json_integer) { td->last_status_id = id->u.integer; } json_value_free(parsed); if (req->flags & TWITTER_HTTP_USER_ACK) twitter_log(ic, "Command processed successfully"); } /** * Function to POST a new status to twitter. */ void twitter_post_status(struct im_connection *ic, char *msg, guint64 in_reply_to) { char *args[4] = { "status", msg, "in_reply_to_status_id", g_strdup_printf("%llu", (unsigned long long) in_reply_to) }; twitter_http(ic, TWITTER_STATUS_UPDATE_URL, twitter_http_post, ic, 1, args, in_reply_to ? 4 : 2); g_free(args[3]); } /** * Function to POST a new message to twitter. */ void twitter_direct_messages_new(struct im_connection *ic, char *who, char *msg) { char *args[4]; args[0] = "screen_name"; args[1] = who; args[2] = "text"; args[3] = msg; // Use the same callback as for twitter_post_status, since it does basically the same. twitter_http(ic, TWITTER_DIRECT_MESSAGES_NEW_URL, twitter_http_post, ic, 1, args, 4); } void twitter_friendships_create_destroy(struct im_connection *ic, char *who, int create) { char *args[2]; args[0] = "screen_name"; args[1] = who; twitter_http(ic, create ? TWITTER_FRIENDSHIPS_CREATE_URL : TWITTER_FRIENDSHIPS_DESTROY_URL, twitter_http_post, ic, 1, args, 2); } void twitter_status_destroy(struct im_connection *ic, guint64 id) { char *url; url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_DESTROY_URL, (unsigned long long) id, ".json"); twitter_http_f(ic, url, twitter_http_post, ic, 1, NULL, 0, TWITTER_HTTP_USER_ACK); g_free(url); } void twitter_status_retweet(struct im_connection *ic, guint64 id) { char *url; url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_RETWEET_URL, (unsigned long long) id, ".json"); twitter_http_f(ic, url, twitter_http_post, ic, 1, NULL, 0, TWITTER_HTTP_USER_ACK); g_free(url); } /** * Report a user for sending spam. */ void twitter_report_spam(struct im_connection *ic, char *screen_name) { char *args[2] = { "screen_name", NULL, }; args[1] = screen_name; twitter_http_f(ic, TWITTER_REPORT_SPAM_URL, twitter_http_post, ic, 1, args, 2, TWITTER_HTTP_USER_ACK); } /** * Favourite a tweet. */ void twitter_favourite_tweet(struct im_connection *ic, guint64 id) { char *args[2] = { "id", NULL, }; args[1] = g_strdup_printf("%llu", (unsigned long long) id); twitter_http_f(ic, TWITTER_FAVORITE_CREATE_URL, twitter_http_post, ic, 1, args, 2, TWITTER_HTTP_USER_ACK); g_free(args[1]); }