b5a01d3921cbeeed81233fd1f318a5330bb3a158
[gregoa/bti.git] / bti.c
1 /*
2  * Copyright (C) 2008-2010 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 static 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 static const char twitter_host[]  = "http://api.twitter.com/1/statuses";
251 static const char identica_host[] = "https://identi.ca/api/statuses";
252 static const char twitter_name[]  = "twitter";
253 static 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 static void parse_statuses(struct session *session,
287                            xmlDocPtr doc, xmlNodePtr current)
288 {
289         xmlChar *text = NULL;
290         xmlChar *user = NULL;
291         xmlChar *created = NULL;
292         xmlChar *id = NULL;
293         xmlNodePtr userinfo;
294
295         current = current->xmlChildrenNode;
296         while (current != NULL) {
297                 if (current->type == XML_ELEMENT_NODE) {
298                         if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
299                                 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
300                         if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
301                                 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
302                         if (!xmlStrcmp(current->name, (const xmlChar *)"id"))
303                                 id = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
304                         if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
305                                 userinfo = current->xmlChildrenNode;
306                                 while (userinfo != NULL) {
307                                         if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
308                                                 if (user)
309                                                         xmlFree(user);
310                                                 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
311                                         }
312                                         userinfo = userinfo->next;
313                                 }
314                         }
315
316                         if (user && text && created && id) {
317                                 if (session->verbose)
318                                         printf("[%s] {%s} (%.16s) %s\n",
319                                                 user, id, created, text);
320                                 else
321                                         printf("[%s] %s\n",
322                                                 user, text);
323                                 xmlFree(user);
324                                 xmlFree(text);
325                                 xmlFree(created);
326                                 xmlFree(id);
327                                 user = NULL;
328                                 text = NULL;
329                                 created = NULL;
330                                 id = NULL;
331                         }
332                 }
333                 current = current->next;
334         }
335
336         return;
337 }
338
339 static void parse_timeline(char *document, struct session *session)
340 {
341         xmlDocPtr doc;
342         xmlNodePtr current;
343
344         doc = xmlReadMemory(document, strlen(document), "timeline.xml",
345                             NULL, XML_PARSE_NOERROR);
346         if (doc == NULL)
347                 return;
348
349         current = xmlDocGetRootElement(doc);
350         if (current == NULL) {
351                 fprintf(stderr, "empty document\n");
352                 xmlFreeDoc(doc);
353                 return;
354         }
355
356         if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
357                 fprintf(stderr, "unexpected document type\n");
358                 xmlFreeDoc(doc);
359                 return;
360         }
361
362         current = current->xmlChildrenNode;
363         while (current != NULL) {
364                 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
365                         parse_statuses(session, doc, current);
366                 current = current->next;
367         }
368         xmlFreeDoc(doc);
369
370         return;
371 }
372
373 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
374                             void *userp)
375 {
376         struct bti_curl_buffer *curl_buf = userp;
377         size_t buffer_size = size * nmemb;
378         char *temp;
379
380         if ((!buffer) || (!buffer_size) || (!curl_buf))
381                 return -EINVAL;
382
383         /* add to the data we already have */
384         temp = zalloc(curl_buf->length + buffer_size + 1);
385         if (!temp)
386                 return -ENOMEM;
387
388         memcpy(temp, curl_buf->data, curl_buf->length);
389         free(curl_buf->data);
390         curl_buf->data = temp;
391         memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
392         curl_buf->length += buffer_size;
393         if (curl_buf->action)
394                 parse_timeline(curl_buf->data, curl_buf->session);
395
396         dbg("%s\n", curl_buf->data);
397
398         return buffer_size;
399 }
400
401 static int parse_osp_reply(const char *reply, char **token, char **secret)
402 {
403         int rc;
404         int retval = 1;
405         char **rv = NULL;
406         rc = oauth_split_url_parameters(reply, &rv);
407         qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
408         if (rc == 2 || rc == 4) {
409                 if (!strncmp(rv[0], "oauth_token=", 11) &&
410                     !strncmp(rv[1], "oauth_token_secret=", 18)) {
411                         if (token)
412                                 *token = strdup(&(rv[0][12]));
413                         if (secret)
414                                 *secret = strdup(&(rv[1][19]));
415
416                         retval = 0;
417                 }
418         } else if (rc == 3) {
419                 if (!strncmp(rv[1], "oauth_token=", 11) &&
420                     !strncmp(rv[2], "oauth_token_secret=", 18)) {
421                         if (token)
422                                 *token = strdup(&(rv[1][12]));
423                         if (secret)
424                                 *secret = strdup(&(rv[2][19]));
425
426                         retval = 0;
427                 }
428         }
429
430         dbg("token: %s\n", *token);
431         dbg("secret: %s\n", *secret);
432
433         if (rv)
434                 free(rv);
435
436         return retval;
437 }
438
439 static int request_access_token(struct session *session)
440 {
441         char *post_params = NULL;
442         char *request_url = NULL;
443         char *reply       = NULL;
444         char *at_key      = NULL;
445         char *at_secret   = NULL;
446         char *verifier    = NULL;
447         char at_uri[90];
448
449         if (!session)
450                 return -EINVAL;
451
452         if (session->host == HOST_TWITTER)
453                 request_url = oauth_sign_url2(
454                                 twitter_request_token_uri, NULL,
455                                 OA_HMAC, NULL, session->consumer_key,
456                                 session->consumer_secret, NULL, NULL);
457         else if (session->host == HOST_IDENTICA)
458                 request_url = oauth_sign_url2(
459                                 identica_request_token_uri, NULL,
460                                 OA_HMAC, NULL, session->consumer_key,
461                                 session->consumer_secret, NULL, NULL);
462         reply = oauth_http_get(request_url, post_params);
463
464         if (request_url)
465                 free(request_url);
466
467         if (post_params)
468                 free(post_params);
469
470         if (!reply)
471                 return 1;
472
473         if (parse_osp_reply(reply, &at_key, &at_secret))
474                 return 1;
475
476         free(reply);
477
478         fprintf(stdout,
479                 "Please open the following link in your browser, and "
480                 "allow 'bti' to access your account. Then paste "
481                 "back the provided PIN in here.\n");
482         if (session->host == HOST_TWITTER) {
483                 fprintf(stdout, "%s%s\nPIN: ", twitter_authorize_uri, at_key);
484                 verifier = session->readline(NULL);
485                 sprintf(at_uri, "%s?oauth_verifier=%s",
486                         twitter_access_token_uri, verifier);
487         } else if (session->host == HOST_IDENTICA) {
488                 fprintf(stdout, "%s%s\nPIN: ", identica_authorize_uri, at_key);
489                 verifier = session->readline(NULL);
490                 sprintf(at_uri, "%s?oauth_verifier=%s",
491                         identica_access_token_uri, verifier);
492         }
493         request_url = oauth_sign_url2(at_uri, NULL, OA_HMAC, NULL,
494                                       session->consumer_key,
495                                       session->consumer_secret,
496                                       at_key, at_secret);
497         reply = oauth_http_get(request_url, post_params);
498
499         if (!reply)
500                 return 1;
501
502         if (parse_osp_reply(reply, &at_key, &at_secret))
503                 return 1;
504
505         free(reply);
506
507         fprintf(stdout,
508                 "Please put these two lines in your bti "
509                 "configuration file (~/.bti):\n"
510                 "access_token_key=%s\n"
511                 "access_token_secret=%s\n",
512                 at_key, at_secret);
513
514         return 0;
515 }
516
517 static int send_request(struct session *session)
518 {
519         char endpoint[500];
520         char user_password[500];
521         char data[500];
522         struct bti_curl_buffer *curl_buf;
523         CURL *curl = NULL;
524         CURLcode res;
525         struct curl_httppost *formpost = NULL;
526         struct curl_httppost *lastptr = NULL;
527         struct curl_slist *slist = NULL;
528         char *req_url = NULL;
529         char *reply = NULL;
530         char *postarg = NULL;
531         char *escaped_tweet = NULL;
532         int is_post = 0;
533
534         if (!session)
535                 return -EINVAL;
536
537         if (!session->hosturl)
538                 session->hosturl = strdup(twitter_host);
539
540         if (session->no_oauth || session->guest) {
541                 curl_buf = bti_curl_buffer_alloc(session->action);
542                 if (!curl_buf)
543                         return -ENOMEM;
544                 curl_buf->session = session;
545
546                 curl = curl_init();
547                 if (!curl)
548                         return -EINVAL;
549
550                 if (!session->hosturl)
551                         session->hosturl = strdup(twitter_host);
552
553                 switch (session->action) {
554                 case ACTION_UPDATE:
555                         snprintf(user_password, sizeof(user_password), "%s:%s",
556                                  session->account, session->password);
557                         snprintf(data, sizeof(data), "status=\"%s\"",
558                                  session->tweet);
559                         curl_formadd(&formpost, &lastptr,
560                                      CURLFORM_COPYNAME, "status",
561                                      CURLFORM_COPYCONTENTS, session->tweet,
562                                      CURLFORM_END);
563
564                         curl_formadd(&formpost, &lastptr,
565                                      CURLFORM_COPYNAME, "source",
566                                      CURLFORM_COPYCONTENTS, "bti",
567                                      CURLFORM_END);
568
569                         if (session->replyto)
570                                 curl_formadd(&formpost, &lastptr,
571                                              CURLFORM_COPYNAME, "in_reply_to_status_id",
572                                              CURLFORM_COPYCONTENTS, session->replyto,
573                                              CURLFORM_END);
574
575                         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
576                         slist = curl_slist_append(slist, "Expect:");
577                         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
578
579                         sprintf(endpoint, "%s%s", session->hosturl, update_uri);
580                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
581                         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
582                         break;
583
584                 case ACTION_FRIENDS:
585                         snprintf(user_password, sizeof(user_password), "%s:%s",
586                                  session->account, session->password);
587                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
588                                         friends_uri, session->page);
589                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
590                         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
591                         break;
592
593                 case ACTION_USER:
594                         sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
595                                 user_uri, session->user, session->page);
596                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
597                         break;
598
599                 case ACTION_REPLIES:
600                         snprintf(user_password, sizeof(user_password), "%s:%s",
601                                  session->account, session->password);
602                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
603                                 replies_uri, session->page);
604                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
605                         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
606                         break;
607
608                 case ACTION_PUBLIC:
609                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
610                                 public_uri, session->page);
611                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
612                         break;
613
614                 case ACTION_GROUP:
615                         sprintf(endpoint, "%s%s%s.xml?page=%d",
616                                 session->hosturl, group_uri, session->group,
617                                 session->page);
618                         curl_easy_setopt(curl, CURLOPT_URL, endpoint);
619                         break;
620
621                 default:
622                         break;
623                 }
624
625                 if (session->proxy)
626                         curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
627
628                 if (debug)
629                         curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
630
631                 dbg("user_password = %s\n", user_password);
632                 dbg("data = %s\n", data);
633                 dbg("proxy = %s\n", session->proxy);
634
635                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
636                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
637                 if (!session->dry_run) {
638                         res = curl_easy_perform(curl);
639                         if (res && !session->background) {
640                                 fprintf(stderr, "error(%d) trying to perform "
641                                                 "operation\n", res);
642                                 return -EINVAL;
643                         }
644                 }
645
646                 curl_easy_cleanup(curl);
647                 if (session->action == ACTION_UPDATE)
648                         curl_formfree(formpost);
649                 bti_curl_buffer_free(curl_buf);
650         } else {
651                 switch (session->action) {
652                 case ACTION_UPDATE:
653                         escaped_tweet = oauth_url_escape(session->tweet);
654                         if (session->replyto) {
655                                 sprintf(endpoint,
656                                         "%s%s?status=%s&in_reply_to_status_id=%s",
657                                         session->hosturl, update_uri,
658                                         escaped_tweet, session->replyto);
659                         } else {
660                                 sprintf(endpoint, "%s%s?status=%s",
661                                         session->hosturl, update_uri,
662                                         escaped_tweet);
663                         }
664
665                         is_post = 1;
666                         break;
667                 case ACTION_USER:
668                         sprintf(endpoint, "%s%s%s.xml?page=%d",
669                                 session->hosturl, user_uri, session->user,
670                                 session->page);
671                         break;
672                 case ACTION_REPLIES:
673                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
674                                 mentions_uri, session->page);
675                         break;
676                 case ACTION_PUBLIC:
677                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
678                                 public_uri, session->page);
679                         break;
680                 case ACTION_GROUP:
681                         sprintf(endpoint, "%s%s%s.xml?page=%d",
682                                 session->hosturl, group_uri, session->group,
683                                 session->page);
684                         break;
685                 case ACTION_FRIENDS:
686                         sprintf(endpoint, "%s%s?page=%d", session->hosturl,
687                                 friends_uri, session->page);
688                         break;
689                 case ACTION_RETWEET:
690                         sprintf(endpoint, "%s%s%s.xml", session->hosturl,
691                                 retweet_uri, session->retweet);
692                         is_post = 1;
693                         break;
694                 default:
695                         break;
696                 }
697
698                 dbg("%s\n", endpoint);
699                 if (!session->dry_run) {
700                         if (is_post) {
701                                 req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
702                                                           NULL, session->consumer_key,
703                                                           session->consumer_secret,
704                                                           session->access_token_key,
705                                                           session->access_token_secret);
706                                 reply = oauth_http_post(req_url, postarg);
707                         } else {
708                                 req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
709                                                           session->consumer_key,
710                                                           session->consumer_secret,
711                                                           session->access_token_key,
712                                                           session->access_token_secret);
713                                 reply = oauth_http_get(req_url, postarg);
714                         }
715
716                         dbg("%s\n", req_url);
717                         dbg("%s\n", reply);
718                         if (req_url)
719                                 free(req_url);
720                 }
721
722                 if ((session->action != ACTION_UPDATE) &&
723                                 (session->action != ACTION_RETWEET))
724                         parse_timeline(reply, session);
725         }
726         return 0;
727 }
728
729 static void parse_configfile(struct session *session)
730 {
731         FILE *config_file;
732         char *line = NULL;
733         size_t len = 0;
734         char *account = NULL;
735         char *password = NULL;
736         char *consumer_key = NULL;
737         char *consumer_secret = NULL;
738         char *access_token_key = NULL;
739         char *access_token_secret = NULL;
740         char *host = NULL;
741         char *proxy = NULL;
742         char *logfile = NULL;
743         char *action = NULL;
744         char *user = NULL;
745         char *replyto = NULL;
746         char *retweet = NULL;
747         int shrink_urls = 0;
748
749         config_file = fopen(session->configfile, "r");
750
751         /* No error if file does not exist or is unreadable.  */
752         if (config_file == NULL)
753                 return;
754
755         do {
756                 ssize_t n = getline(&line, &len, config_file);
757                 if (n < 0)
758                         break;
759                 if (line[n - 1] == '\n')
760                         line[n - 1] = '\0';
761                 /* Parse file.  Format is the usual value pairs:
762                    account=name
763                    passwort=value
764                    # is a comment character
765                 */
766                 *strchrnul(line, '#') = '\0';
767                 char *c = line;
768                 while (isspace(*c))
769                         c++;
770                 /* Ignore blank lines.  */
771                 if (c[0] == '\0')
772                         continue;
773
774                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
775                         c += 8;
776                         if (c[0] != '\0')
777                                 account = strdup(c);
778                 } else if (!strncasecmp(c, "password", 8) &&
779                            (c[8] == '=')) {
780                         c += 9;
781                         if (c[0] != '\0')
782                                 password = strdup(c);
783                 } else if (!strncasecmp(c, "consumer_key", 12) &&
784                            (c[12] == '=')) {
785                         c += 13;
786                         if (c[0] != '\0')
787                                 consumer_key = strdup(c);
788                 } else if (!strncasecmp(c, "consumer_secret", 15) &&
789                            (c[15] == '=')) {
790                         c += 16;
791                         if (c[0] != '\0')
792                                 consumer_secret = strdup(c);
793                 } else if (!strncasecmp(c, "access_token_key", 16) &&
794                            (c[16] == '=')) {
795                         c += 17;
796                         if (c[0] != '\0')
797                                 access_token_key = strdup(c);
798                 } else if (!strncasecmp(c, "access_token_secret", 19) &&
799                            (c[19] == '=')) {
800                         c += 20;
801                         if (c[0] != '\0')
802                                 access_token_secret = strdup(c);
803                 } else if (!strncasecmp(c, "host", 4) &&
804                            (c[4] == '=')) {
805                         c += 5;
806                         if (c[0] != '\0')
807                                 host = strdup(c);
808                 } else if (!strncasecmp(c, "proxy", 5) &&
809                            (c[5] == '=')) {
810                         c += 6;
811                         if (c[0] != '\0')
812                                 proxy = strdup(c);
813                 } else if (!strncasecmp(c, "logfile", 7) &&
814                            (c[7] == '=')) {
815                         c += 8;
816                         if (c[0] != '\0')
817                                 logfile = strdup(c);
818                 } else if (!strncasecmp(c, "replyto", 7) &&
819                            (c[7] == '=')) {
820                         c += 8;
821                         if (c[0] != '\0')
822                                 replyto = strdup(c);
823                 } else if (!strncasecmp(c, "action", 6) &&
824                            (c[6] == '=')) {
825                         c += 7;
826                         if (c[0] != '\0')
827                                 action = strdup(c);
828                 } else if (!strncasecmp(c, "user", 4) &&
829                                 (c[4] == '=')) {
830                         c += 5;
831                         if (c[0] != '\0')
832                                 user = strdup(c);
833                 } else if (!strncasecmp(c, "shrink-urls", 11) &&
834                                 (c[11] == '=')) {
835                         c += 12;
836                         if (!strncasecmp(c, "true", 4) ||
837                                         !strncasecmp(c, "yes", 3))
838                                 shrink_urls = 1;
839                 } else if (!strncasecmp(c, "verbose", 7) &&
840                                 (c[7] == '=')) {
841                         c += 8;
842                         if (!strncasecmp(c, "true", 4) ||
843                                         !strncasecmp(c, "yes", 3))
844                                 session->verbose = 1;
845                 } else if (!strncasecmp(c,"retweet", 7) &&
846                                 (c[7] == '=')) {
847                         c += 8;
848                         if (c[0] != '\0')
849                                 retweet = strdup(c);
850                 }
851         } while (!feof(config_file));
852
853         if (password)
854                 session->password = password;
855         if (account)
856                 session->account = account;
857         if (consumer_key)
858                 session->consumer_key = consumer_key;
859         if (consumer_secret)
860                 session->consumer_secret = consumer_secret;
861         if (access_token_key)
862                 session->access_token_key = access_token_key;
863         if (access_token_secret)
864                 session->access_token_secret = access_token_secret;
865         if (host) {
866                 if (strcasecmp(host, "twitter") == 0) {
867                         session->host = HOST_TWITTER;
868                         session->hosturl = strdup(twitter_host);
869                         session->hostname = strdup(twitter_name);
870                 } else if (strcasecmp(host, "identica") == 0) {
871                         session->host = HOST_IDENTICA;
872                         session->hosturl = strdup(identica_host);
873                         session->hostname = strdup(identica_name);
874                 } else {
875                         session->host = HOST_CUSTOM;
876                         session->hosturl = strdup(host);
877                         session->hostname = strdup(host);
878                 }
879                 free(host);
880         }
881         if (proxy) {
882                 if (session->proxy)
883                         free(session->proxy);
884                 session->proxy = proxy;
885         }
886         if (logfile)
887                 session->logfile = logfile;
888         if (replyto)
889                 session->replyto = replyto;
890         if (retweet)
891                 session->retweet = retweet;
892         if (action) {
893                 if (strcasecmp(action, "update") == 0)
894                         session->action = ACTION_UPDATE;
895                 else if (strcasecmp(action, "friends") == 0)
896                         session->action = ACTION_FRIENDS;
897                 else if (strcasecmp(action, "user") == 0)
898                         session->action = ACTION_USER;
899                 else if (strcasecmp(action, "replies") == 0)
900                         session->action = ACTION_REPLIES;
901                 else if (strcasecmp(action, "public") == 0)
902                         session->action = ACTION_PUBLIC;
903                 else if (strcasecmp(action, "group") == 0)
904                         session->action = ACTION_GROUP;
905                 else
906                         session->action = ACTION_UNKNOWN;
907                 free(action);
908         }
909         if (user)
910                 session->user = user;
911         session->shrink_urls = shrink_urls;
912
913         /* Free buffer and close file.  */
914         free(line);
915         fclose(config_file);
916 }
917
918 static void log_session(struct session *session, int retval)
919 {
920         FILE *log_file;
921         char *filename;
922
923         /* Only log something if we have a log file set */
924         if (!session->logfile)
925                 return;
926
927         filename = alloca(strlen(session->homedir) +
928                           strlen(session->logfile) + 3);
929
930         sprintf(filename, "%s/%s", session->homedir, session->logfile);
931
932         log_file = fopen(filename, "a+");
933         if (log_file == NULL)
934                 return;
935
936         switch (session->action) {
937         case ACTION_UPDATE:
938                 if (retval)
939                         fprintf(log_file, "%s: host=%s tweet failed\n",
940                                 session->time, session->hostname);
941                 else
942                         fprintf(log_file, "%s: host=%s tweet=%s\n",
943                                 session->time, session->hostname,
944                                 session->tweet);
945                 break;
946         case ACTION_FRIENDS:
947                 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
948                         session->time, session->hostname);
949                 break;
950         case ACTION_USER:
951                 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
952                         session->time, session->hostname, session->user);
953                 break;
954         case ACTION_REPLIES:
955                 fprintf(log_file, "%s: host=%s retrieving replies\n",
956                         session->time, session->hostname);
957                 break;
958         case ACTION_PUBLIC:
959                 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
960                         session->time, session->hostname);
961                 break;
962         case ACTION_GROUP:
963                 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
964                         session->time, session->hostname);
965                 break;
966         default:
967                 break;
968         }
969
970         fclose(log_file);
971 }
972
973 static char *get_string_from_stdin(void)
974 {
975         char *temp;
976         char *string;
977
978         string = zalloc(1000);
979         if (!string)
980                 return NULL;
981
982         if (!fgets(string, 999, stdin))
983                 return NULL;
984         temp = strchr(string, '\n');
985         if (temp)
986                 *temp = '\0';
987         return string;
988 }
989
990 static void read_password(char *buf, size_t len, char *host)
991 {
992         char pwd[80];
993         int retval;
994         struct termios old;
995         struct termios tp;
996
997         tcgetattr(0, &tp);
998         old = tp;
999
1000         tp.c_lflag &= (~ECHO);
1001         tcsetattr(0, TCSANOW, &tp);
1002
1003         fprintf(stdout, "Enter password for %s: ", host);
1004         fflush(stdout);
1005         tcflow(0, TCOOFF);
1006         retval = scanf("%79s", pwd);
1007         tcflow(0, TCOON);
1008         fprintf(stdout, "\n");
1009
1010         tcsetattr(0, TCSANOW, &old);
1011
1012         strncpy(buf, pwd, len);
1013         buf[len-1] = '\0';
1014 }
1015
1016 static int find_urls(const char *tweet, int **pranges)
1017 {
1018         /*
1019          * magic obtained from
1020          * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
1021          */
1022         static const char *re_magic =
1023                 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
1024                 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
1025                 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
1026         pcre *re;
1027         const char *errptr;
1028         int erroffset;
1029         int ovector[10] = {0,};
1030         const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
1031         int startoffset, tweetlen;
1032         int i, rc;
1033         int rbound = 10;
1034         int rcount = 0;
1035         int *ranges = malloc(sizeof(int) * rbound);
1036
1037         re = pcre_compile(re_magic,
1038                         PCRE_NO_AUTO_CAPTURE,
1039                         &errptr, &erroffset, NULL);
1040         if (!re) {
1041                 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
1042                 exit(1);
1043         }
1044
1045         tweetlen = strlen(tweet);
1046         for (startoffset = 0; startoffset < tweetlen; ) {
1047
1048                 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
1049                                 ovector, ovsize);
1050                 if (rc == PCRE_ERROR_NOMATCH)
1051                         break;
1052
1053                 if (rc < 0) {
1054                         fprintf(stderr, "pcre_exec @%u: %s\n",
1055                                 erroffset, errptr);
1056                         exit(1);
1057                 }
1058
1059                 for (i = 0; i < rc; i += 2) {
1060                         if ((rcount+2) == rbound) {
1061                                 rbound *= 2;
1062                                 ranges = realloc(ranges, sizeof(int) * rbound);
1063                         }
1064
1065                         ranges[rcount++] = ovector[i];
1066                         ranges[rcount++] = ovector[i+1];
1067                 }
1068
1069                 startoffset = ovector[1];
1070         }
1071
1072         pcre_free(re);
1073
1074         *pranges = ranges;
1075         return rcount;
1076 }
1077
1078 /**
1079  * bidirectional popen() call
1080  *
1081  * @param rwepipe - int array of size three
1082  * @param exe - program to run
1083  * @param argv - argument list
1084  * @return pid or -1 on error
1085  *
1086  * The caller passes in an array of three integers (rwepipe), on successful
1087  * execution it can then write to element 0 (stdin of exe), and read from
1088  * element 1 (stdout) and 2 (stderr).
1089  */
1090 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
1091 {
1092         int in[2];
1093         int out[2];
1094         int err[2];
1095         int pid;
1096         int rc;
1097
1098         rc = pipe(in);
1099         if (rc < 0)
1100                 goto error_in;
1101
1102         rc = pipe(out);
1103         if (rc < 0)
1104                 goto error_out;
1105
1106         rc = pipe(err);
1107         if (rc < 0)
1108                 goto error_err;
1109
1110         pid = fork();
1111         if (pid > 0) {
1112                 /* parent */
1113                 close(in[0]);
1114                 close(out[1]);
1115                 close(err[1]);
1116                 rwepipe[0] = in[1];
1117                 rwepipe[1] = out[0];
1118                 rwepipe[2] = err[0];
1119                 return pid;
1120         } else if (pid == 0) {
1121                 /* child */
1122                 close(in[1]);
1123                 close(out[0]);
1124                 close(err[0]);
1125                 close(0);
1126                 rc = dup(in[0]);
1127                 close(1);
1128                 rc = dup(out[1]);
1129                 close(2);
1130                 rc = dup(err[1]);
1131
1132                 execvp(exe, (char **)argv);
1133                 exit(1);
1134         } else
1135                 goto error_fork;
1136
1137         return pid;
1138
1139 error_fork:
1140         close(err[0]);
1141         close(err[1]);
1142 error_err:
1143         close(out[0]);
1144         close(out[1]);
1145 error_out:
1146         close(in[0]);
1147         close(in[1]);
1148 error_in:
1149         return -1;
1150 }
1151
1152 static int pcloseRWE(int pid, int *rwepipe)
1153 {
1154         int rc, status;
1155         close(rwepipe[0]);
1156         close(rwepipe[1]);
1157         close(rwepipe[2]);
1158         rc = waitpid(pid, &status, 0);
1159         return status;
1160 }
1161
1162 static char *shrink_one_url(int *rwepipe, char *big)
1163 {
1164         int biglen = strlen(big);
1165         char *small;
1166         int smalllen;
1167         int rc;
1168
1169         rc = dprintf(rwepipe[0], "%s\n", big);
1170         if (rc < 0)
1171                 return big;
1172
1173         smalllen = biglen + 128;
1174         small = malloc(smalllen);
1175         if (!small)
1176                 return big;
1177
1178         rc = read(rwepipe[1], small, smalllen);
1179         if (rc < 0 || rc > biglen)
1180                 goto error_free_small;
1181
1182         if (strncmp(small, "http://", 7))
1183                 goto error_free_small;
1184
1185         smalllen = rc;
1186         while (smalllen && isspace(small[smalllen-1]))
1187                         small[--smalllen] = 0;
1188
1189         free(big);
1190         return small;
1191
1192 error_free_small:
1193         free(small);
1194         return big;
1195 }
1196
1197 static char *shrink_urls(char *text)
1198 {
1199         int *ranges;
1200         int rcount;
1201         int i;
1202         int inofs = 0;
1203         int outofs = 0;
1204         const char *const shrink_args[] = {
1205                 "bti-shrink-urls",
1206                 NULL
1207         };
1208         int shrink_pid;
1209         int shrink_pipe[3];
1210         int inlen = strlen(text);
1211
1212         dbg("before len=%u\n", inlen);
1213
1214         shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
1215         if (shrink_pid < 0)
1216                 return text;
1217
1218         rcount = find_urls(text, &ranges);
1219         if (!rcount)
1220                 return text;
1221
1222         for (i = 0; i < rcount; i += 2) {
1223                 int url_start = ranges[i];
1224                 int url_end = ranges[i+1];
1225                 int long_url_len = url_end - url_start;
1226                 char *url = strndup(text + url_start, long_url_len);
1227                 int short_url_len;
1228                 int not_url_len = url_start - inofs;
1229
1230                 dbg("long  url[%u]: %s\n", long_url_len, url);
1231                 url = shrink_one_url(shrink_pipe, url);
1232                 short_url_len = url ? strlen(url) : 0;
1233                 dbg("short url[%u]: %s\n", short_url_len, url);
1234
1235                 if (!url || short_url_len >= long_url_len) {
1236                         /* The short url ended up being too long
1237                          * or unavailable */
1238                         if (inofs) {
1239                                 strncpy(text + outofs, text + inofs,
1240                                                 not_url_len + long_url_len);
1241                         }
1242                         inofs += not_url_len + long_url_len;
1243                         outofs += not_url_len + long_url_len;
1244
1245                 } else {
1246                         /* copy the unmodified block */
1247                         strncpy(text + outofs, text + inofs, not_url_len);
1248                         inofs += not_url_len;
1249                         outofs += not_url_len;
1250
1251                         /* copy the new url */
1252                         strncpy(text + outofs, url, short_url_len);
1253                         inofs += long_url_len;
1254                         outofs += short_url_len;
1255                 }
1256
1257                 free(url);
1258         }
1259
1260         /* copy the last block after the last match */
1261         if (inofs) {
1262                 int tail = inlen - inofs;
1263                 if (tail) {
1264                         strncpy(text + outofs, text + inofs, tail);
1265                         outofs += tail;
1266                 }
1267         }
1268
1269         free(ranges);
1270
1271         (void)pcloseRWE(shrink_pid, shrink_pipe);
1272
1273         text[outofs] = 0;
1274         dbg("after len=%u\n", outofs);
1275         return text;
1276 }
1277
1278 int main(int argc, char *argv[], char *envp[])
1279 {
1280         static const struct option options[] = {
1281                 { "debug", 0, NULL, 'd' },
1282                 { "verbose", 0, NULL, 'V' },
1283                 { "account", 1, NULL, 'a' },
1284                 { "password", 1, NULL, 'p' },
1285                 { "host", 1, NULL, 'H' },
1286                 { "proxy", 1, NULL, 'P' },
1287                 { "action", 1, NULL, 'A' },
1288                 { "user", 1, NULL, 'u' },
1289                 { "group", 1, NULL, 'G' },
1290                 { "logfile", 1, NULL, 'L' },
1291                 { "shrink-urls", 0, NULL, 's' },
1292                 { "help", 0, NULL, 'h' },
1293                 { "bash", 0, NULL, 'b' },
1294                 { "background", 0, NULL, 'B' },
1295                 { "dry-run", 0, NULL, 'n' },
1296                 { "page", 1, NULL, 'g' },
1297                 { "version", 0, NULL, 'v' },
1298                 { "config", 1, NULL, 'c' },
1299                 { "replyto", 1, NULL, 'r' },
1300                 { "retweet", 1, NULL, 'w' },
1301                 { }
1302         };
1303         struct session *session;
1304         pid_t child;
1305         char *tweet;
1306         char *retweet;
1307         static char password[80];
1308         int retval = 0;
1309         int option;
1310         char *http_proxy;
1311         time_t t;
1312         int page_nr;
1313
1314         debug = 0;
1315
1316         session = session_alloc();
1317         if (!session) {
1318                 fprintf(stderr, "no more memory...\n");
1319                 return -1;
1320         }
1321
1322         /* get the current time so that we can log it later */
1323         time(&t);
1324         session->time = strdup(ctime(&t));
1325         session->time[strlen(session->time)-1] = 0x00;
1326
1327         /* Get the home directory so we can try to find a config file */
1328         session->homedir = strdup(getenv("HOME"));
1329
1330         /* set up a default config file location (traditionally ~/.bti) */
1331         session->configfile = zalloc(strlen(session->homedir) + 7);
1332         sprintf(session->configfile, "%s/.bti", session->homedir);
1333
1334         /* Set environment variables first, before reading command line options
1335          * or config file values. */
1336         http_proxy = getenv("http_proxy");
1337         if (http_proxy) {
1338                 if (session->proxy)
1339                         free(session->proxy);
1340                 session->proxy = strdup(http_proxy);
1341                 dbg("http_proxy = %s\n", session->proxy);
1342         }
1343
1344         parse_configfile(session);
1345
1346         while (1) {
1347                 option = getopt_long_only(argc, argv,
1348                                           "dp:P:H:a:A:u:c:hg:G:sr:nVv",
1349                                           options, NULL);
1350                 if (option == -1)
1351                         break;
1352                 switch (option) {
1353                 case 'd':
1354                         debug = 1;
1355                         break;
1356                 case 'V':
1357                         session->verbose = 1;
1358                         break;
1359                 case 'a':
1360                         if (session->account)
1361                                 free(session->account);
1362                         session->account = strdup(optarg);
1363                         dbg("account = %s\n", session->account);
1364                         break;
1365                 case 'g':
1366                         page_nr = atoi(optarg);
1367                         dbg("page = %d\n", page_nr);
1368                         session->page = page_nr;
1369                         break;
1370                 case 'r':
1371                         session->replyto = strdup(optarg);
1372                         dbg("in_reply_to_status_id = %s\n", session->replyto);
1373                         break;
1374                 case 'w':
1375                         session->retweet = strdup(optarg);
1376                         dbg("Retweet ID = %s\n", session->retweet);
1377                         break;
1378                 case 'p':
1379                         if (session->password)
1380                                 free(session->password);
1381                         session->password = strdup(optarg);
1382                         dbg("password = %s\n", session->password);
1383                         break;
1384                 case 'P':
1385                         if (session->proxy)
1386                                 free(session->proxy);
1387                         session->proxy = strdup(optarg);
1388                         dbg("proxy = %s\n", session->proxy);
1389                         break;
1390                 case 'A':
1391                         if (strcasecmp(optarg, "update") == 0)
1392                                 session->action = ACTION_UPDATE;
1393                         else if (strcasecmp(optarg, "friends") == 0)
1394                                 session->action = ACTION_FRIENDS;
1395                         else if (strcasecmp(optarg, "user") == 0)
1396                                 session->action = ACTION_USER;
1397                         else if (strcasecmp(optarg, "replies") == 0)
1398                                 session->action = ACTION_REPLIES;
1399                         else if (strcasecmp(optarg, "public") == 0)
1400                                 session->action = ACTION_PUBLIC;
1401                         else if (strcasecmp(optarg, "group") == 0)
1402                                 session->action = ACTION_GROUP;
1403                         else if (strcasecmp(optarg,"retweet") == 0)
1404                                 session->action = ACTION_RETWEET;
1405                         else
1406                                 session->action = ACTION_UNKNOWN;
1407                         dbg("action = %d\n", session->action);
1408                         break;
1409                 case 'u':
1410                         if (session->user)
1411                                 free(session->user);
1412                         session->user = strdup(optarg);
1413                         dbg("user = %s\n", session->user);
1414                         break;
1415
1416                 case 'G':
1417                         if (session->group)
1418                                 free(session->group);
1419                         session->group = strdup(optarg);
1420                         dbg("group = %s\n", session->group);
1421                         break;
1422                 case 'L':
1423                         if (session->logfile)
1424                                 free(session->logfile);
1425                         session->logfile = strdup(optarg);
1426                         dbg("logfile = %s\n", session->logfile);
1427                         break;
1428                 case 's':
1429                         session->shrink_urls = 1;
1430                         break;
1431                 case 'H':
1432                         if (session->hosturl)
1433                                 free(session->hosturl);
1434                         if (session->hostname)
1435                                 free(session->hostname);
1436                         if (strcasecmp(optarg, "twitter") == 0) {
1437                                 session->host = HOST_TWITTER;
1438                                 session->hosturl = strdup(twitter_host);
1439                                 session->hostname = strdup(twitter_name);
1440                         } else if (strcasecmp(optarg, "identica") == 0) {
1441                                 session->host = HOST_IDENTICA;
1442                                 session->hosturl = strdup(identica_host);
1443                                 session->hostname = strdup(identica_name);
1444                         } else {
1445                                 session->host = HOST_CUSTOM;
1446                                 session->hosturl = strdup(optarg);
1447                                 session->hostname = strdup(optarg);
1448                         }
1449                         dbg("host = %d\n", session->host);
1450                         break;
1451                 case 'b':
1452                         session->bash = 1;
1453                         /* fall-through intended */
1454                 case 'B':
1455                         session->background = 1;
1456                         break;
1457                 case 'c':
1458                         if (session->configfile)
1459                                 free(session->configfile);
1460                         session->configfile = strdup(optarg);
1461                         dbg("configfile = %s\n", session->configfile);
1462
1463                         /*
1464                          * read the config file now.  Yes, this could override
1465                          * previously set options from the command line, but
1466                          * the user asked for it...
1467                          */
1468                         parse_configfile(session);
1469                         break;
1470                 case 'h':
1471                         display_help();
1472                         goto exit;
1473                 case 'n':
1474                         session->dry_run = 1;
1475                         break;
1476                 case 'v':
1477                         display_version();
1478                         goto exit;
1479                 default:
1480                         display_help();
1481                         goto exit;
1482                 }
1483         }
1484
1485         session_readline_init(session);
1486         /*
1487          * Show the version to make it easier to determine what
1488          * is going on here
1489          */
1490         if (debug)
1491                 display_version();
1492
1493         if (session->host == HOST_TWITTER) {
1494                 if (!session->consumer_key || !session->consumer_secret) {
1495                         if (session->action == ACTION_USER ||
1496                                         session->action == ACTION_PUBLIC) {
1497                                 /* Some actions may still work without authentication */
1498                                 session->guest = 1;
1499                         } else {
1500                                 fprintf(stderr,
1501                                                 "Twitter no longer supports HTTP basic authentication.\n"
1502                                                 "Both consumer key, and consumer secret are required"
1503                                                 " for bti in order to behave as an OAuth consumer.\n");
1504                                 goto exit;
1505                         }
1506                 }
1507                 if (session->action == ACTION_GROUP) {
1508                         fprintf(stderr, "Groups only work in Identi.ca.\n");
1509                         goto exit;
1510                 }
1511         } else {
1512                 if (!session->consumer_key || !session->consumer_secret)
1513                         session->no_oauth = 1;
1514         }
1515
1516         if (session->no_oauth) {
1517                 if (!session->account) {
1518                         fprintf(stdout, "Enter account for %s: ",
1519                                 session->hostname);
1520                         session->account = session->readline(NULL);
1521                 }
1522                 if (!session->password) {
1523                         read_password(password, sizeof(password),
1524                                       session->hostname);
1525                         session->password = strdup(password);
1526                 }
1527         } else if (!session->guest) {
1528                 if (!session->access_token_key ||
1529                     !session->access_token_secret) {
1530                         request_access_token(session);
1531                         goto exit;
1532                 }
1533         }
1534
1535         if (session->action == ACTION_UNKNOWN) {
1536                 fprintf(stderr, "Unknown action, valid actions are:\n"
1537                         "'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
1538                 goto exit;
1539         }
1540
1541         if (session->action == ACTION_GROUP && !session->group) {
1542                 fprintf(stdout, "Enter group name: ");
1543                 session->group = session->readline(NULL);
1544         }
1545
1546         if (session->action == ACTION_RETWEET) {
1547                 fprintf(stdout, "Status ID to retweet: ");
1548                 retweet = get_string_from_stdin();
1549
1550                 if (!retweet || strlen(retweet) == 0) {
1551                         dbg("no retweet?\n");
1552                         return -1;
1553                 }
1554
1555                 session->retweet = zalloc(strlen(retweet) + 10);
1556                 sprintf(session->retweet,"%s", retweet);
1557                 free(retweet);
1558                 dbg("retweet ID = %s\n", session->retweet);
1559         }
1560
1561         if (session->action == ACTION_UPDATE) {
1562                 if (session->background || !session->interactive)
1563                         tweet = get_string_from_stdin();
1564                 else
1565                         tweet = session->readline("tweet: ");
1566                 if (!tweet || strlen(tweet) == 0) {
1567                         dbg("no tweet?\n");
1568                         return -1;
1569                 }
1570
1571                 if (session->shrink_urls)
1572                         tweet = shrink_urls(tweet);
1573
1574                 session->tweet = zalloc(strlen(tweet) + 10);
1575                 if (session->bash)
1576                         sprintf(session->tweet, "%c %s",
1577                                 getuid() ? '$' : '#', tweet);
1578                 else
1579                         sprintf(session->tweet, "%s", tweet);
1580
1581                 free(tweet);
1582                 dbg("tweet = %s\n", session->tweet);
1583         }
1584
1585         if (session->page == 0)
1586                 session->page = 1;
1587         dbg("config file = %s\n", session->configfile);
1588         dbg("host = %d\n", session->host);
1589         dbg("action = %d\n", session->action);
1590
1591         /* fork ourself so that the main shell can get on
1592          * with it's life as we try to connect and handle everything
1593          */
1594         if (session->background) {
1595                 child = fork();
1596                 if (child) {
1597                         dbg("child is %d\n", child);
1598                         exit(0);
1599                 }
1600         }
1601
1602         retval = send_request(session);
1603         if (retval && !session->background)
1604                 fprintf(stderr, "operation failed\n");
1605
1606         log_session(session, retval);
1607 exit:
1608         session_readline_cleanup(session);
1609         session_free(session);
1610         return retval;;
1611 }