]> ToastFreeware Gitweb - gregoa/bti.git/blob - bti.c
7f828791030669fd5d03519abdfaa5f390bbb99d
[gregoa/bti.git] / bti.c
1 /*
2  * Copyright (C) 2008-2011 Greg Kroah-Hartman <greg@kroah.com>
3  * Copyright (C) 2009 Bart Trojanowski <bart@jukie.net>
4  * Copyright (C) 2009-2010 Amir Mohammad Saied <amirsaied@gmail.com>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  */
19
20 #define _GNU_SOURCE
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stddef.h>
25 #include <string.h>
26 #include <getopt.h>
27 #include <errno.h>
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <time.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <curl/curl.h>
36 #include <libxml/xmlmemory.h>
37 #include <libxml/parser.h>
38 #include <libxml/tree.h>
39 #include <pcre.h>
40 #include <termios.h>
41 #include <dlfcn.h>
42 #include <oauth.h>
43 #include "bti.h"
44
45 #define zalloc(size)    calloc(size, 1)
46
47 #define dbg(format, arg...)                                             \
48         do {                                                            \
49                 if (debug)                                              \
50                         fprintf(stdout, "bti: %s: " format , __func__ , \
51                                 ## arg);                                \
52         } while (0)
53
54
55 int debug;
56
57 static void display_help(void)
58 {
59         fprintf(stdout, "bti - send tweet to twitter or identi.ca\n"
60                 "Version: %s\n"
61                 "Usage:\n"
62                 "  bti [options]\n"
63                 "options are:\n"
64                 "  --account accountname\n"
65                 "  --password password\n"
66                 "  --action action\n"
67                 "    ('update', 'friends', 'public', 'replies', or 'user')\n"
68                 "  --user screenname\n"
69                 "  --group groupname\n"
70                 "  --proxy PROXY:PORT\n"
71                 "  --host HOST\n"
72                 "  --logfile logfile\n"
73                 "  --config configfile\n"
74                 "  --replyto ID\n"
75                 "  --retweet ID\n"
76                 "  --shrink-urls\n"
77                 "  --page PAGENUMBER\n"
78                 "  --bash\n"
79                 "  --background\n"
80                 "  --debug\n"
81                 "  --verbose\n"
82                 "  --dry-run\n"
83                 "  --version\n"
84                 "  --help\n", VERSION);
85 }
86
87 static void display_version(void)
88 {
89         fprintf(stdout, "bti - version %s\n", VERSION);
90 }
91
92 static char *get_string(const char *name)
93 {
94         char *temp;
95         char *string;
96
97         string = zalloc(1000);
98         if (!string)
99                 exit(1);
100         if (name != NULL)
101                 fprintf(stdout, "%s", name);
102         if (!fgets(string, 999, stdin))
103                 return NULL;
104         temp = strchr(string, '\n');
105         if (temp)
106                 *temp = '\0';
107         return string;
108 }
109
110 /*
111  * Try to get a handle to a readline function from a variety of different
112  * libraries.  If nothing is present on the system, then fall back to an
113  * internal one.
114  *
115  * Logic originally based off of code in the e2fsutils package in the
116  * lib/ss/get_readline.c file, which is licensed under the MIT license.
117  *
118  * This keeps us from having to relicense the bti codebase if readline
119  * ever changes its license, as there is no link-time dependancy.
120  * It is a run-time thing only, and we handle any readline-like library
121  * in the same manner, making bti not be a derivative work of any
122  * other program.
123  */
124 static void session_readline_init(struct session *session)
125 {
126         /* Libraries we will try to use for readline/editline functionality */
127         const char *libpath = "libreadline.so.6:libreadline.so.5:"
128                                 "libreadline.so.4:libreadline.so:libedit.so.2:"
129                                 "libedit.so:libeditline.so.0:libeditline.so";
130         void *handle = NULL;
131         char *tmp, *cp, *next;
132         int (*bind_key)(int, void *);
133         void (*insert)(void);
134
135         /* default to internal function if we can't or won't find anything */
136         session->readline = get_string;
137         if (!isatty(0))
138                 return;
139         session->interactive = 1;
140
141         tmp = malloc(strlen(libpath)+1);
142         if (!tmp)
143                 return;
144         strcpy(tmp, libpath);
145         for (cp = tmp; cp; cp = next) {
146                 next = strchr(cp, ':');
147                 if (next)
148                         *next++ = 0;
149                 if (*cp == 0)
150                         continue;
151                 handle = dlopen(cp, RTLD_NOW);
152                 if (handle) {
153                         dbg("Using %s for readline library\n", cp);
154                         break;
155                 }
156         }
157         free(tmp);
158         if (!handle) {
159                 dbg("No readline library found.\n");
160                 return;
161         }
162
163         session->readline_handle = handle;
164         session->readline = (char *(*)(const char *))dlsym(handle, "readline");
165         if (session->readline == NULL) {
166                 /* something odd happened, default back to internal stuff */
167                 session->readline_handle = NULL;
168                 session->readline = get_string;
169                 return;
170         }
171
172         /*
173          * If we found a library, turn off filename expansion
174          * as that makes no sense from within bti.
175          */
176         bind_key = (int (*)(int, void *))dlsym(handle, "rl_bind_key");
177         insert = (void (*)(void))dlsym(handle, "rl_insert");
178         if (bind_key && insert)
179                 bind_key('\t', insert);
180 }
181
182 static void session_readline_cleanup(struct session *session)
183 {
184         if (session->readline_handle)
185                 dlclose(session->readline_handle);
186 }
187
188 static struct session *session_alloc(void)
189 {
190         struct session *session;
191
192         session = zalloc(sizeof(*session));
193         if (!session)
194                 return NULL;
195         return session;
196 }
197
198 static void session_free(struct session *session)
199 {
200         if (!session)
201                 return;
202         free(session->retweet);
203         free(session->replyto);
204         free(session->password);
205         free(session->account);
206         free(session->consumer_key);
207         free(session->consumer_secret);
208         free(session->access_token_key);
209         free(session->access_token_secret);
210         free(session->tweet);
211         free(session->proxy);
212         free(session->time);
213         free(session->homedir);
214         free(session->user);
215         free(session->group);
216         free(session->hosturl);
217         free(session->hostname);
218         free(session->configfile);
219         free(session);
220 }
221
222 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
223 {
224         struct bti_curl_buffer *buffer;
225
226         buffer = zalloc(sizeof(*buffer));
227         if (!buffer)
228                 return NULL;
229
230         /* start out with a data buffer of 1 byte to
231          * make the buffer fill logic simpler */
232         buffer->data = zalloc(1);
233         if (!buffer->data) {
234                 free(buffer);
235                 return NULL;
236         }
237         buffer->length = 0;
238         buffer->action = action;
239         return buffer;
240 }
241
242 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
243 {
244         if (!buffer)
245                 return;
246         free(buffer->data);
247         free(buffer);
248 }
249
250 const char twitter_host[]  = "http://api.twitter.com/1/statuses";
251 const char identica_host[] = "https://identi.ca/api/statuses";
252 const char twitter_name[]  = "twitter";
253 const char identica_name[] = "identi.ca";
254
255 static const char twitter_request_token_uri[]  = "http://twitter.com/oauth/request_token";
256 static const char twitter_access_token_uri[]   = "http://twitter.com/oauth/access_token";
257 static const char twitter_authorize_uri[]      = "http://twitter.com/oauth/authorize?oauth_token=";
258 static const char identica_request_token_uri[] = "http://identi.ca/api/oauth/request_token?oauth_callback=oob";
259 static const char identica_access_token_uri[]  = "http://identi.ca/api/oauth/access_token";
260 static const char identica_authorize_uri[]     = "http://identi.ca/api/oauth/authorize?oauth_token=";
261
262 static const char user_uri[]     = "/user_timeline/";
263 static const char update_uri[]   = "/update.xml";
264 static const char public_uri[]   = "/public_timeline.xml";
265 static const char friends_uri[]  = "/friends_timeline.xml";
266 static const char mentions_uri[] = "/mentions.xml";
267 static const char replies_uri[]  = "/replies.xml";
268 static const char retweet_uri[]  = "/retweet/";
269 static const char group_uri[]    = "/../statusnet/groups/timeline/";
270
271 static CURL *curl_init(void)
272 {
273         CURL *curl;
274
275         curl = curl_easy_init();
276         if (!curl) {
277                 fprintf(stderr, "Can not init CURL!\n");
278                 return NULL;
279         }
280         /* some ssl sanity checks on the connection we are making */
281         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
282         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
283         return curl;
284 }
285
286 /* The final place data is sent to the screen/pty/tty */
287 static void bti_output_line(struct session *session, xmlChar *user,
288                             xmlChar *id, xmlChar *created, xmlChar *text)
289 {
290         if (session->verbose)
291                 printf("[%s] {%s} (%.16s) %s\n", user, id, created, text);
292         else
293                 printf("[%s] %s\n", user, text);
294 }
295
296 static void parse_statuses(struct session *session,
297                            xmlDocPtr doc, xmlNodePtr current)
298 {
299         xmlChar *text = NULL;
300         xmlChar *user = NULL;
301         xmlChar *created = NULL;
302         xmlChar *id = NULL;
303         xmlNodePtr userinfo;
304
305         current = current->xmlChildrenNode;
306         while (current != NULL) {
307                 if (current->type == XML_ELEMENT_NODE) {
308                         if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
309                                 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
310                         if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
311                                 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
312                         if (!xmlStrcmp(current->name, (const xmlChar *)"id"))
313                                 id = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
314                         if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
315                                 userinfo = current->xmlChildrenNode;
316                                 while (userinfo != NULL) {
317                                         if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
318                                                 if (user)
319                                                         xmlFree(user);
320                                                 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
321                                         }
322                                         userinfo = userinfo->next;
323                                 }
324                         }
325
326                         if (user && text && created && id) {
327                                 bti_output_line(session, user, id, created, text);
328                                 xmlFree(user);
329                                 xmlFree(text);
330                                 xmlFree(created);
331                                 xmlFree(id);
332                                 user = NULL;
333                                 text = NULL;
334                                 created = NULL;
335                                 id = NULL;
336                         }
337                 }
338                 current = current->next;
339         }
340
341         return;
342 }
343
344 static void parse_timeline(char *document, struct session *session)
345 {
346         xmlDocPtr doc;
347         xmlNodePtr current;
348
349         doc = xmlReadMemory(document, strlen(document), "timeline.xml",
350                             NULL, XML_PARSE_NOERROR);
351         if (doc == NULL)
352                 return;
353
354         current = xmlDocGetRootElement(doc);
355         if (current == NULL) {
356                 fprintf(stderr, "empty document\n");
357                 xmlFreeDoc(doc);
358                 return;
359         }
360
361         if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
362                 fprintf(stderr, "unexpected document type\n");
363                 xmlFreeDoc(doc);
364                 return;
365         }
366
367         current = current->xmlChildrenNode;
368         while (current != NULL) {
369                 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
370                         parse_statuses(session, doc, current);
371                 current = current->next;
372         }
373         xmlFreeDoc(doc);
374
375         return;
376 }
377
378 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
379                             void *userp)
380 {
381         struct bti_curl_buffer *curl_buf = userp;
382         size_t buffer_size = size * nmemb;
383         char *temp;
384
385         if ((!buffer) || (!buffer_size) || (!curl_buf))
386                 return -EINVAL;
387
388         /* add to the data we already have */
389         temp = zalloc(curl_buf->length + buffer_size + 1);
390         if (!temp)
391                 return -ENOMEM;
392
393         memcpy(temp, curl_buf->data, curl_buf->length);
394         free(curl_buf->data);
395         curl_buf->data = temp;
396         memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
397         curl_buf->length += buffer_size;
398         if (curl_buf->action)
399                 parse_timeline(curl_buf->data, curl_buf->session);
400
401         dbg("%s\n", curl_buf->data);
402
403         return buffer_size;
404 }
405
406 static int parse_osp_reply(const char *reply, char **token, char **secret)
407 {
408         int rc;
409         int retval = 1;
410         char **rv = NULL;
411         rc = oauth_split_url_parameters(reply, &rv);
412         qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
413         if (rc == 2 || rc == 4) {
414                 if (!strncmp(rv[0], "oauth_token=", 11) &&
415                     !strncmp(rv[1], "oauth_token_secret=", 18)) {
416                         if (token)
417                                 *token = strdup(&(rv[0][12]));
418                         if (secret)
419                                 *secret = strdup(&(rv[1][19]));
420
421                         retval = 0;
422                 }
423         } else if (rc == 3) {
424                 if (!strncmp(rv[1], "oauth_token=", 11) &&
425                     !strncmp(rv[2], "oauth_token_secret=", 18)) {
426                         if (token)
427                                 *token = strdup(&(rv[1][12]));
428                         if (secret)
429                                 *secret = strdup(&(rv[2][19]));
430
431                         retval = 0;
432                 }
433         }
434
435         dbg("token: %s\n", *token);
436         dbg("secret: %s\n", *secret);
437
438         if (rv)
439                 free(rv);
440
441         return retval;
442 }
443
444 static int request_access_token(struct session *session)
445 {
446         char *post_params = NULL;
447         char *request_url = NULL;
448         char *reply       = NULL;
449         char *at_key      = NULL;
450         char *at_secret   = NULL;
451         char *verifier    = NULL;
452         char at_uri[90];
453
454         if (!session)
455                 return -EINVAL;
456
457         if (session->host == HOST_TWITTER)
458                 request_url = oauth_sign_url2(
459                                 twitter_request_token_uri, NULL,
460                                 OA_HMAC, NULL, session->consumer_key,
461                                 session->consumer_secret, NULL, NULL);
462         else if (session->host == HOST_IDENTICA)
463                 request_url = oauth_sign_url2(
464                                 identica_request_token_uri, NULL,
465                                 OA_HMAC, NULL, session->consumer_key,
466                                 session->consumer_secret, NULL, NULL);
467         reply = oauth_http_get(request_url, post_params);
468
469         if (request_url)
470                 free(request_url);
471
472         if (post_params)
473                 free(post_params);
474
475         if (!reply)
476                 return 1;
477
478         if (parse_osp_reply(reply, &at_key, &at_secret))
479                 return 1;
480
481         free(reply);
482
483         fprintf(stdout,
484                 "Please open the following link in your browser, and "
485                 "allow 'bti' to access your account. Then paste "
486                 "back the provided PIN in here.\n");
487         if (session->host == HOST_TWITTER) {
488                 fprintf(stdout, "%s%s\nPIN: ", twitter_authorize_uri, at_key);
489                 verifier = session->readline(NULL);
490                 sprintf(at_uri, "%s?oauth_verifier=%s",
491                         twitter_access_token_uri, verifier);
492         } else if (session->host == HOST_IDENTICA) {
493                 fprintf(stdout, "%s%s\nPIN: ", identica_authorize_uri, at_key);
494                 verifier = session->readline(NULL);
495                 sprintf(at_uri, "%s?oauth_verifier=%s",
496                         identica_access_token_uri, verifier);
497         }
498         request_url = oauth_sign_url2(at_uri, NULL, OA_HMAC, NULL,
499                                       session->consumer_key,
500                                       session->consumer_secret,
501                                       at_key, at_secret);
502         reply = oauth_http_get(request_url, post_params);
503
504         if (!reply)
505                 return 1;
506
507         if (parse_osp_reply(reply, &at_key, &at_secret))
508                 return 1;
509
510         free(reply);
511
512         fprintf(stdout,
513                 "Please put these two lines in your bti "
514                 "configuration file (~/.bti):\n"
515                 "access_token_key=%s\n"
516                 "access_token_secret=%s\n",
517                 at_key, at_secret);
518
519         return 0;
520 }
521
522 static int send_request(struct session *session)
523 {
524         char endpoint[500];
525         char user_password[500];
526         char data[500];
527         struct bti_curl_buffer *curl_buf;
528         CURL *curl = NULL;
529         CURLcode res;
530         struct curl_httppost *formpost = NULL;
531         struct curl_httppost *lastptr = NULL;
532         struct curl_slist *slist = NULL;
533         char *req_url = NULL;
534         char *reply = NULL;
535         char *postarg = NULL;
536         char *escaped_tweet = NULL;
537         int is_post = 0;
538
539         if (!session)
540                 return -EINVAL;
541
542         if (!session->hosturl)
543                 session->hosturl = strdup(twitter_host);
544
545         if (session->no_oauth || session->guest) {
546                 curl_buf = bti_curl_buffer_alloc(session->action);
547                 if (!curl_buf)
548                         return -ENOMEM;
549                 curl_buf->session = session;
550
551                 curl = curl_init();
552                 if (!curl)
553                         return -EINVAL;
554
555                 if (!session->hosturl)
556                         session->hosturl = strdup(twitter_host);
557
558                 switch (session->action) {
559                 case ACTION_UPDATE:
560                         snprintf(user_password, sizeof(user_password), "%s:%s",
561                                  session->account, session->password);
562                         snprintf(data, sizeof(data), "status=\"%s\"",
563                                  session->tweet);
564                         curl_formadd(&formpost, &lastptr,
565                                      CURLFORM_COPYNAME, "status",
566                                      CURLFORM_COPYCONTENTS, session->tweet,
567                                      CURLFORM_END);
568
569                         curl_formadd(&formpost, &lastptr,
570                                      CURLFORM_COPYNAME, "source",
571                                      CURLFORM_COPYCONTENTS, "bti",
572                                      CURLFORM_END);
573
574                         if (session->replyto)
575                                 curl_formadd(&formpost, &lastptr,
576                                              CURLFORM_COPYNAME, "in_reply_to_status_id",
577                                              CURLFORM_COPYCONTENTS, session->replyto,
578                                              CURLFORM_END);
579
580                         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
581                         slist = curl_slist_append(slist, "Expect:");
582                         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
583
584                         sprintf(endpoint, "%s%s", session->hosturl, update_uri);
585                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
586                         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
587                         break;
588
589                 case ACTION_FRIENDS:
590                         snprintf(user_password, sizeof(user_password), "%s:%s",
591                                  session->account, session->password);
592                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
593                                         friends_uri, session->page);
594                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
595                         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
596                         break;
597
598                 case ACTION_USER:
599                         sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
600                                 user_uri, session->user, session->page);
601                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
602                         break;
603
604                 case ACTION_REPLIES:
605                         snprintf(user_password, sizeof(user_password), "%s:%s",
606                                  session->account, session->password);
607                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
608                                 replies_uri, session->page);
609                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
610                         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
611                         break;
612
613                 case ACTION_PUBLIC:
614                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
615                                 public_uri, session->page);
616                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
617                         break;
618
619                 case ACTION_GROUP:
620                         sprintf(endpoint, "%s%s%s.xml?page=%d",
621                                 session->hosturl, group_uri, session->group,
622                                 session->page);
623                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
624                         break;
625
626                 default:
627                         break;
628                 }
629
630                 if (session->proxy)
631                         curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
632
633                 if (debug)
634                         curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
635
636                 dbg("user_password = %s\n", user_password);
637                 dbg("data = %s\n", data);
638                 dbg("proxy = %s\n", session->proxy);
639
640                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
641                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
642                 if (!session->dry_run) {
643                         res = curl_easy_perform(curl);
644                         if (!session->background) {
645                                 if (res) {
646                                         fprintf(stderr, "error(%d) trying to perform "
647                                                 "operation\n", res);
648                                         return -EINVAL;
649                                 } else {
650                                         xmlDocPtr doc;
651                                         xmlNodePtr current;
652
653                                         doc = xmlReadMemory(curl_buf->data, curl_buf->length,
654                                                             "response.xml", NULL, XML_PARSE_NOERROR);
655                                         if (doc == NULL)
656                                                 return -EINVAL;
657
658                                         current = xmlDocGetRootElement(doc);
659                                         if (current == NULL) {
660                                                 fprintf(stderr, "empty document\n");
661                                                 xmlFreeDoc(doc);
662                                                 return -EINVAL;
663                                         }
664
665                                         if (xmlStrcmp(current->name, (const xmlChar *) "status")) {
666                                                 fprintf(stderr, "unexpected document type\n");
667                                                 xmlFreeDoc(doc);
668                                                 return -EINVAL;
669                                         }
670
671                                         xmlFreeDoc(doc);
672                                 }
673                         }
674                 }
675
676                 curl_easy_cleanup(curl);
677                 if (session->action == ACTION_UPDATE)
678                         curl_formfree(formpost);
679                 bti_curl_buffer_free(curl_buf);
680         } else {
681                 switch (session->action) {
682                 case ACTION_UPDATE:
683                         escaped_tweet = oauth_url_escape(session->tweet);
684                         if (session->replyto) {
685                                 sprintf(endpoint,
686                                         "%s%s?status=%s&in_reply_to_status_id=%s",
687                                         session->hosturl, update_uri,
688                                         escaped_tweet, session->replyto);
689                         } else {
690                                 sprintf(endpoint, "%s%s?status=%s",
691                                         session->hosturl, update_uri,
692                                         escaped_tweet);
693                         }
694
695                         is_post = 1;
696                         break;
697                 case ACTION_USER:
698                         sprintf(endpoint, "%s%s%s.xml?page=%d",
699                                 session->hosturl, user_uri, session->user,
700                                 session->page);
701                         break;
702                 case ACTION_REPLIES:
703                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
704                                 mentions_uri, session->page);
705                         break;
706                 case ACTION_PUBLIC:
707                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
708                                 public_uri, session->page);
709                         break;
710                 case ACTION_GROUP:
711                         sprintf(endpoint, "%s%s%s.xml?page=%d",
712                                 session->hosturl, group_uri, session->group,
713                                 session->page);
714                         break;
715                 case ACTION_FRIENDS:
716                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
717                                 friends_uri, session->page);
718                         break;
719                 case ACTION_RETWEET:
720                         sprintf(endpoint, "%s%s%s.xml", session->hosturl,
721                                 retweet_uri, session->retweet);
722                         is_post = 1;
723                         break;
724                 default:
725                         break;
726                 }
727
728                 dbg("%s\n", endpoint);
729                 if (!session->dry_run) {
730                         if (is_post) {
731                                 req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
732                                                           NULL, session->consumer_key,
733                                                           session->consumer_secret,
734                                                           session->access_token_key,
735                                                           session->access_token_secret);
736                                 reply = oauth_http_post(req_url, postarg);
737                         } else {
738                                 req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
739                                                           session->consumer_key,
740                                                           session->consumer_secret,
741                                                           session->access_token_key,
742                                                           session->access_token_secret);
743                                 reply = oauth_http_get(req_url, postarg);
744                         }
745
746                         dbg("%s\n", req_url);
747                         dbg("%s\n", reply);
748                         if (req_url)
749                                 free(req_url);
750                 }
751
752                 if (!reply) {
753                         fprintf(stderr, "Error retrieving from URL (%s)\n", endpoint);
754                         return -EIO;
755                 }
756
757                 if ((session->action != ACTION_UPDATE) &&
758                                 (session->action != ACTION_RETWEET))
759                         parse_timeline(reply, session);
760         }
761         return 0;
762 }
763
764 static void log_session(struct session *session, int retval)
765 {
766         FILE *log_file;
767         char *filename;
768
769         /* Only log something if we have a log file set */
770         if (!session->logfile)
771                 return;
772
773         filename = alloca(strlen(session->homedir) +
774                           strlen(session->logfile) + 3);
775
776         sprintf(filename, "%s/%s", session->homedir, session->logfile);
777
778         log_file = fopen(filename, "a+");
779         if (log_file == NULL)
780                 return;
781
782         switch (session->action) {
783         case ACTION_UPDATE:
784                 if (retval)
785                         fprintf(log_file, "%s: host=%s tweet failed\n",
786                                 session->time, session->hostname);
787                 else
788                         fprintf(log_file, "%s: host=%s tweet=%s\n",
789                                 session->time, session->hostname,
790                                 session->tweet);
791                 break;
792         case ACTION_FRIENDS:
793                 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
794                         session->time, session->hostname);
795                 break;
796         case ACTION_USER:
797                 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
798                         session->time, session->hostname, session->user);
799                 break;
800         case ACTION_REPLIES:
801                 fprintf(log_file, "%s: host=%s retrieving replies\n",
802                         session->time, session->hostname);
803                 break;
804         case ACTION_PUBLIC:
805                 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
806                         session->time, session->hostname);
807                 break;
808         case ACTION_GROUP:
809                 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
810                         session->time, session->hostname);
811                 break;
812         default:
813                 break;
814         }
815
816         fclose(log_file);
817 }
818
819 static char *get_string_from_stdin(void)
820 {
821         char *temp;
822         char *string;
823
824         string = zalloc(1000);
825         if (!string)
826                 return NULL;
827
828         if (!fgets(string, 999, stdin))
829                 return NULL;
830         temp = strchr(string, '\n');
831         if (temp)
832                 *temp = '\0';
833         return string;
834 }
835
836 static void read_password(char *buf, size_t len, char *host)
837 {
838         char pwd[80];
839         int retval;
840         struct termios old;
841         struct termios tp;
842
843         tcgetattr(0, &tp);
844         old = tp;
845
846         tp.c_lflag &= (~ECHO);
847         tcsetattr(0, TCSANOW, &tp);
848
849         fprintf(stdout, "Enter password for %s: ", host);
850         fflush(stdout);
851         tcflow(0, TCOOFF);
852         retval = scanf("%79s", pwd);
853         tcflow(0, TCOON);
854         fprintf(stdout, "\n");
855
856         tcsetattr(0, TCSANOW, &old);
857
858         strncpy(buf, pwd, len);
859         buf[len-1] = '\0';
860 }
861
862 static int find_urls(const char *tweet, int **pranges)
863 {
864         /*
865          * magic obtained from
866          * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
867          */
868         static const char *re_magic =
869                 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
870                 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
871                 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
872         pcre *re;
873         const char *errptr;
874         int erroffset;
875         int ovector[10] = {0,};
876         const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
877         int startoffset, tweetlen;
878         int i, rc;
879         int rbound = 10;
880         int rcount = 0;
881         int *ranges = malloc(sizeof(int) * rbound);
882
883         re = pcre_compile(re_magic,
884                         PCRE_NO_AUTO_CAPTURE,
885                         &errptr, &erroffset, NULL);
886         if (!re) {
887                 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
888                 exit(1);
889         }
890
891         tweetlen = strlen(tweet);
892         for (startoffset = 0; startoffset < tweetlen; ) {
893
894                 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
895                                 ovector, ovsize);
896                 if (rc == PCRE_ERROR_NOMATCH)
897                         break;
898
899                 if (rc < 0) {
900                         fprintf(stderr, "pcre_exec @%u: %s\n",
901                                 erroffset, errptr);
902                         exit(1);
903                 }
904
905                 for (i = 0; i < rc; i += 2) {
906                         if ((rcount+2) == rbound) {
907                                 rbound *= 2;
908                                 ranges = realloc(ranges, sizeof(int) * rbound);
909                         }
910
911                         ranges[rcount++] = ovector[i];
912                         ranges[rcount++] = ovector[i+1];
913                 }
914
915                 startoffset = ovector[1];
916         }
917
918         pcre_free(re);
919
920         *pranges = ranges;
921         return rcount;
922 }
923
924 /**
925  * bidirectional popen() call
926  *
927  * @param rwepipe - int array of size three
928  * @param exe - program to run
929  * @param argv - argument list
930  * @return pid or -1 on error
931  *
932  * The caller passes in an array of three integers (rwepipe), on successful
933  * execution it can then write to element 0 (stdin of exe), and read from
934  * element 1 (stdout) and 2 (stderr).
935  */
936 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
937 {
938         int in[2];
939         int out[2];
940         int err[2];
941         int pid;
942         int rc;
943
944         rc = pipe(in);
945         if (rc < 0)
946                 goto error_in;
947
948         rc = pipe(out);
949         if (rc < 0)
950                 goto error_out;
951
952         rc = pipe(err);
953         if (rc < 0)
954                 goto error_err;
955
956         pid = fork();
957         if (pid > 0) {
958                 /* parent */
959                 close(in[0]);
960                 close(out[1]);
961                 close(err[1]);
962                 rwepipe[0] = in[1];
963                 rwepipe[1] = out[0];
964                 rwepipe[2] = err[0];
965                 return pid;
966         } else if (pid == 0) {
967                 /* child */
968                 close(in[1]);
969                 close(out[0]);
970                 close(err[0]);
971                 close(0);
972                 rc = dup(in[0]);
973                 close(1);
974                 rc = dup(out[1]);
975                 close(2);
976                 rc = dup(err[1]);
977
978                 execvp(exe, (char **)argv);
979                 exit(1);
980         } else
981                 goto error_fork;
982
983         return pid;
984
985 error_fork:
986         close(err[0]);
987         close(err[1]);
988 error_err:
989         close(out[0]);
990         close(out[1]);
991 error_out:
992         close(in[0]);
993         close(in[1]);
994 error_in:
995         return -1;
996 }
997
998 static int pcloseRWE(int pid, int *rwepipe)
999 {
1000         int rc, status;
1001         close(rwepipe[0]);
1002         close(rwepipe[1]);
1003         close(rwepipe[2]);
1004         rc = waitpid(pid, &status, 0);
1005         return status;
1006 }
1007
1008 static char *shrink_one_url(int *rwepipe, char *big)
1009 {
1010         int biglen = strlen(big);
1011         char *small;
1012         int smalllen;
1013         int rc;
1014
1015         rc = dprintf(rwepipe[0], "%s\n", big);
1016         if (rc < 0)
1017                 return big;
1018
1019         smalllen = biglen + 128;
1020         small = malloc(smalllen);
1021         if (!small)
1022                 return big;
1023
1024         rc = read(rwepipe[1], small, smalllen);
1025         if (rc < 0 || rc > biglen)
1026                 goto error_free_small;
1027
1028         if (strncmp(small, "http://", 7))
1029                 goto error_free_small;
1030
1031         smalllen = rc;
1032         while (smalllen && isspace(small[smalllen-1]))
1033                         small[--smalllen] = 0;
1034
1035         free(big);
1036         return small;
1037
1038 error_free_small:
1039         free(small);
1040         return big;
1041 }
1042
1043 static char *shrink_urls(char *text)
1044 {
1045         int *ranges;
1046         int rcount;
1047         int i;
1048         int inofs = 0;
1049         int outofs = 0;
1050         const char *const shrink_args[] = {
1051                 "bti-shrink-urls",
1052                 NULL
1053         };
1054         int shrink_pid;
1055         int shrink_pipe[3];
1056         int inlen = strlen(text);
1057
1058         dbg("before len=%u\n", inlen);
1059
1060         shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
1061         if (shrink_pid < 0)
1062                 return text;
1063
1064         rcount = find_urls(text, &ranges);
1065         if (!rcount)
1066                 return text;
1067
1068         for (i = 0; i < rcount; i += 2) {
1069                 int url_start = ranges[i];
1070                 int url_end = ranges[i+1];
1071                 int long_url_len = url_end - url_start;
1072                 char *url = strndup(text + url_start, long_url_len);
1073                 int short_url_len;
1074                 int not_url_len = url_start - inofs;
1075
1076                 dbg("long  url[%u]: %s\n", long_url_len, url);
1077                 url = shrink_one_url(shrink_pipe, url);
1078                 short_url_len = url ? strlen(url) : 0;
1079                 dbg("short url[%u]: %s\n", short_url_len, url);
1080
1081                 if (!url || short_url_len >= long_url_len) {
1082                         /* The short url ended up being too long
1083                          * or unavailable */
1084                         if (inofs) {
1085                                 strncpy(text + outofs, text + inofs,
1086                                                 not_url_len + long_url_len);
1087                         }
1088                         inofs += not_url_len + long_url_len;
1089                         outofs += not_url_len + long_url_len;
1090
1091                 } else {
1092                         /* copy the unmodified block */
1093                         strncpy(text + outofs, text + inofs, not_url_len);
1094                         inofs += not_url_len;
1095                         outofs += not_url_len;
1096
1097                         /* copy the new url */
1098                         strncpy(text + outofs, url, short_url_len);
1099                         inofs += long_url_len;
1100                         outofs += short_url_len;
1101                 }
1102
1103                 free(url);
1104         }
1105
1106         /* copy the last block after the last match */
1107         if (inofs) {
1108                 int tail = inlen - inofs;
1109                 if (tail) {
1110                         strncpy(text + outofs, text + inofs, tail);
1111                         outofs += tail;
1112                 }
1113         }
1114
1115         free(ranges);
1116
1117         (void)pcloseRWE(shrink_pid, shrink_pipe);
1118
1119         text[outofs] = 0;
1120         dbg("after len=%u\n", outofs);
1121         return text;
1122 }
1123
1124 int main(int argc, char *argv[], char *envp[])
1125 {
1126         static const struct option options[] = {
1127                 { "debug", 0, NULL, 'd' },
1128                 { "verbose", 0, NULL, 'V' },
1129                 { "account", 1, NULL, 'a' },
1130                 { "password", 1, NULL, 'p' },
1131                 { "host", 1, NULL, 'H' },
1132                 { "proxy", 1, NULL, 'P' },
1133                 { "action", 1, NULL, 'A' },
1134                 { "user", 1, NULL, 'u' },
1135                 { "group", 1, NULL, 'G' },
1136                 { "logfile", 1, NULL, 'L' },
1137                 { "shrink-urls", 0, NULL, 's' },
1138                 { "help", 0, NULL, 'h' },
1139                 { "bash", 0, NULL, 'b' },
1140                 { "background", 0, NULL, 'B' },
1141                 { "dry-run", 0, NULL, 'n' },
1142                 { "page", 1, NULL, 'g' },
1143                 { "version", 0, NULL, 'v' },
1144                 { "config", 1, NULL, 'c' },
1145                 { "replyto", 1, NULL, 'r' },
1146                 { "retweet", 1, NULL, 'w' },
1147                 { }
1148         };
1149         struct session *session;
1150         pid_t child;
1151         char *tweet;
1152         static char password[80];
1153         int retval = 0;
1154         int option;
1155         char *http_proxy;
1156         time_t t;
1157         int page_nr;
1158
1159         debug = 0;
1160
1161         session = session_alloc();
1162         if (!session) {
1163                 fprintf(stderr, "no more memory...\n");
1164                 return -1;
1165         }
1166
1167         /* get the current time so that we can log it later */
1168         time(&t);
1169         session->time = strdup(ctime(&t));
1170         session->time[strlen(session->time)-1] = 0x00;
1171
1172         /* Get the home directory so we can try to find a config file */
1173         session->homedir = strdup(getenv("HOME"));
1174
1175         /* set up a default config file location (traditionally ~/.bti) */
1176         session->configfile = zalloc(strlen(session->homedir) + 7);
1177         sprintf(session->configfile, "%s/.bti", session->homedir);
1178
1179         /* Set environment variables first, before reading command line options
1180          * or config file values. */
1181         http_proxy = getenv("http_proxy");
1182         if (http_proxy) {
1183                 if (session->proxy)
1184                         free(session->proxy);
1185                 session->proxy = strdup(http_proxy);
1186                 dbg("http_proxy = %s\n", session->proxy);
1187         }
1188
1189         bti_parse_configfile(session);
1190
1191         while (1) {
1192                 option = getopt_long_only(argc, argv,
1193                                           "dp:P:H:a:A:u:c:hg:G:sr:nVvw:",
1194                                           options, NULL);
1195                 if (option == -1)
1196                         break;
1197                 switch (option) {
1198                 case 'd':
1199                         debug = 1;
1200                         break;
1201                 case 'V':
1202                         session->verbose = 1;
1203                         break;
1204                 case 'a':
1205                         if (session->account)
1206                                 free(session->account);
1207                         session->account = strdup(optarg);
1208                         dbg("account = %s\n", session->account);
1209                         break;
1210                 case 'g':
1211                         page_nr = atoi(optarg);
1212                         dbg("page = %d\n", page_nr);
1213                         session->page = page_nr;
1214                         break;
1215                 case 'r':
1216                         session->replyto = strdup(optarg);
1217                         dbg("in_reply_to_status_id = %s\n", session->replyto);
1218                         break;
1219                 case 'w':
1220                         session->retweet = strdup(optarg);
1221                         dbg("Retweet ID = %s\n", session->retweet);
1222                         break;
1223                 case 'p':
1224                         if (session->password)
1225                                 free(session->password);
1226                         session->password = strdup(optarg);
1227                         dbg("password = %s\n", session->password);
1228                         break;
1229                 case 'P':
1230                         if (session->proxy)
1231                                 free(session->proxy);
1232                         session->proxy = strdup(optarg);
1233                         dbg("proxy = %s\n", session->proxy);
1234                         break;
1235                 case 'A':
1236                         if (strcasecmp(optarg, "update") == 0)
1237                                 session->action = ACTION_UPDATE;
1238                         else if (strcasecmp(optarg, "friends") == 0)
1239                                 session->action = ACTION_FRIENDS;
1240                         else if (strcasecmp(optarg, "user") == 0)
1241                                 session->action = ACTION_USER;
1242                         else if (strcasecmp(optarg, "replies") == 0)
1243                                 session->action = ACTION_REPLIES;
1244                         else if (strcasecmp(optarg, "public") == 0)
1245                                 session->action = ACTION_PUBLIC;
1246                         else if (strcasecmp(optarg, "group") == 0)
1247                                 session->action = ACTION_GROUP;
1248                         else if (strcasecmp(optarg,"retweet") == 0)
1249                                 session->action = ACTION_RETWEET;
1250                         else
1251                                 session->action = ACTION_UNKNOWN;
1252                         dbg("action = %d\n", session->action);
1253                         break;
1254                 case 'u':
1255                         if (session->user)
1256                                 free(session->user);
1257                         session->user = strdup(optarg);
1258                         dbg("user = %s\n", session->user);
1259                         break;
1260
1261                 case 'G':
1262                         if (session->group)
1263                                 free(session->group);
1264                         session->group = strdup(optarg);
1265                         dbg("group = %s\n", session->group);
1266                         break;
1267                 case 'L':
1268                         if (session->logfile)
1269                                 free(session->logfile);
1270                         session->logfile = strdup(optarg);
1271                         dbg("logfile = %s\n", session->logfile);
1272                         break;
1273                 case 's':
1274                         session->shrink_urls = 1;
1275                         break;
1276                 case 'H':
1277                         if (session->hosturl)
1278                                 free(session->hosturl);
1279                         if (session->hostname)
1280                                 free(session->hostname);
1281                         if (strcasecmp(optarg, "twitter") == 0) {
1282                                 session->host = HOST_TWITTER;
1283                                 session->hosturl = strdup(twitter_host);
1284                                 session->hostname = strdup(twitter_name);
1285                         } else if (strcasecmp(optarg, "identica") == 0) {
1286                                 session->host = HOST_IDENTICA;
1287                                 session->hosturl = strdup(identica_host);
1288                                 session->hostname = strdup(identica_name);
1289                         } else {
1290                                 session->host = HOST_CUSTOM;
1291                                 session->hosturl = strdup(optarg);
1292                                 session->hostname = strdup(optarg);
1293                         }
1294                         dbg("host = %d\n", session->host);
1295                         break;
1296                 case 'b':
1297                         session->bash = 1;
1298                         /* fall-through intended */
1299                 case 'B':
1300                         session->background = 1;
1301                         break;
1302                 case 'c':
1303                         if (session->configfile)
1304                                 free(session->configfile);
1305                         session->configfile = strdup(optarg);
1306                         dbg("configfile = %s\n", session->configfile);
1307
1308                         /*
1309                          * read the config file now.  Yes, this could override
1310                          * previously set options from the command line, but
1311                          * the user asked for it...
1312                          */
1313                         bti_parse_configfile(session);
1314                         break;
1315                 case 'h':
1316                         display_help();
1317                         goto exit;
1318                 case 'n':
1319                         session->dry_run = 1;
1320                         break;
1321                 case 'v':
1322                         display_version();
1323                         goto exit;
1324                 default:
1325                         display_help();
1326                         goto exit;
1327                 }
1328         }
1329
1330         session_readline_init(session);
1331         /*
1332          * Show the version to make it easier to determine what
1333          * is going on here
1334          */
1335         if (debug)
1336                 display_version();
1337
1338         if (session->host == HOST_TWITTER) {
1339                 if (!session->consumer_key || !session->consumer_secret) {
1340                         if (session->action == ACTION_USER ||
1341                                         session->action == ACTION_PUBLIC) {
1342                                 /* Some actions may still work without authentication */
1343                                 session->guest = 1;
1344                         } else {
1345                                 fprintf(stderr,
1346                                                 "Twitter no longer supports HTTP basic authentication.\n"
1347                                                 "Both consumer key, and consumer secret are required"
1348                                                 " for bti in order to behave as an OAuth consumer.\n");
1349                                 goto exit;
1350                         }
1351                 }
1352                 if (session->action == ACTION_GROUP) {
1353                         fprintf(stderr, "Groups only work in Identi.ca.\n");
1354                         goto exit;
1355                 }
1356         } else {
1357                 if (!session->consumer_key || !session->consumer_secret)
1358                         session->no_oauth = 1;
1359         }
1360
1361         if (session->no_oauth) {
1362                 if (!session->account) {
1363                         fprintf(stdout, "Enter account for %s: ",
1364                                 session->hostname);
1365                         session->account = session->readline(NULL);
1366                 }
1367                 if (!session->password) {
1368                         read_password(password, sizeof(password),
1369                                       session->hostname);
1370                         session->password = strdup(password);
1371                 }
1372         } else if (!session->guest) {
1373                 if (!session->access_token_key ||
1374                     !session->access_token_secret) {
1375                         request_access_token(session);
1376                         goto exit;
1377                 }
1378         }
1379
1380         if (session->action == ACTION_UNKNOWN) {
1381                 fprintf(stderr, "Unknown action, valid actions are:\n"
1382                         "'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
1383                 goto exit;
1384         }
1385
1386         if (session->action == ACTION_GROUP && !session->group) {
1387                 fprintf(stdout, "Enter group name: ");
1388                 session->group = session->readline(NULL);
1389         }
1390
1391         if (session->action == ACTION_RETWEET) {
1392                 if (!session->retweet) {
1393                         char *rtid;
1394
1395                         fprintf(stdout, "Status ID to retweet: ");
1396                         rtid = get_string_from_stdin();
1397                         session->retweet = zalloc(strlen(rtid) + 10);
1398                         sprintf(session->retweet,"%s", rtid);
1399                         free(rtid);
1400                 }
1401
1402                 if (!session->retweet || strlen(session->retweet) == 0) {
1403                         dbg("no retweet?\n");
1404                         return -1;
1405                 }
1406
1407                 dbg("retweet ID = %s\n", session->retweet);
1408         }
1409
1410         if (session->action == ACTION_UPDATE) {
1411                 if (session->background || !session->interactive)
1412                         tweet = get_string_from_stdin();
1413                 else
1414                         tweet = session->readline("tweet: ");
1415                 if (!tweet || strlen(tweet) == 0) {
1416                         dbg("no tweet?\n");
1417                         return -1;
1418                 }
1419
1420                 if (session->shrink_urls)
1421                         tweet = shrink_urls(tweet);
1422
1423                 session->tweet = zalloc(strlen(tweet) + 10);
1424                 if (session->bash)
1425                         sprintf(session->tweet, "%c %s",
1426                                 getuid() ? '$' : '#', tweet);
1427                 else
1428                         sprintf(session->tweet, "%s", tweet);
1429
1430                 free(tweet);
1431                 dbg("tweet = %s\n", session->tweet);
1432         }
1433
1434         if (session->page == 0)
1435                 session->page = 1;
1436         dbg("config file = %s\n", session->configfile);
1437         dbg("host = %d\n", session->host);
1438         dbg("action = %d\n", session->action);
1439
1440         /* fork ourself so that the main shell can get on
1441          * with it's life as we try to connect and handle everything
1442          */
1443         if (session->background) {
1444                 child = fork();
1445                 if (child) {
1446                         dbg("child is %d\n", child);
1447                         exit(0);
1448                 }
1449         }
1450
1451         retval = send_request(session);
1452         if (retval && !session->background)
1453                 fprintf(stderr, "operation failed\n");
1454
1455         log_session(session, retval);
1456 exit:
1457         session_readline_cleanup(session);
1458         session_free(session);
1459         return retval;;
1460 }