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