updated man pages generated from the docbook source
[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                 dbg("%s\n", endpoint);
753                 if (!session->dry_run) {
754                         if (is_post) {
755                                 req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
756                                                           NULL, session->consumer_key,
757                                                           session->consumer_secret,
758                                                           session->access_token_key,
759                                                           session->access_token_secret);
760                                 reply = oauth_http_post(req_url, postarg);
761                         } else {
762                                 req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
763                                                           session->consumer_key,
764                                                           session->consumer_secret,
765                                                           session->access_token_key,
766                                                           session->access_token_secret);
767                                 reply = oauth_http_get(req_url, postarg);
768                         }
769
770                         dbg("%s\n", req_url);
771                         dbg("%s\n", reply);
772                         if (req_url)
773                                 free(req_url);
774                 }
775
776                 if ((session->action != ACTION_UPDATE) &&
777                                 (session->action != ACTION_RETWEET))
778                         parse_timeline(reply);
779         }
780         return 0;
781 }
782
783 static void parse_configfile(struct session *session)
784 {
785         FILE *config_file;
786         char *line = NULL;
787         size_t len = 0;
788         char *account = NULL;
789         char *password = NULL;
790         char *consumer_key = NULL;
791         char *consumer_secret = NULL;
792         char *access_token_key = NULL;
793         char *access_token_secret = NULL;
794         char *host = NULL;
795         char *proxy = NULL;
796         char *logfile = NULL;
797         char *action = NULL;
798         char *user = NULL;
799         char *replyto = NULL;
800         char *retweet = NULL;
801         int shrink_urls = 0;
802
803         config_file = fopen(session->configfile, "r");
804
805         /* No error if file does not exist or is unreadable.  */
806         if (config_file == NULL)
807                 return;
808
809         do {
810                 ssize_t n = getline(&line, &len, config_file);
811                 if (n < 0)
812                         break;
813                 if (line[n - 1] == '\n')
814                         line[n - 1] = '\0';
815                 /* Parse file.  Format is the usual value pairs:
816                    account=name
817                    passwort=value
818                    # is a comment character
819                 */
820                 *strchrnul(line, '#') = '\0';
821                 char *c = line;
822                 while (isspace(*c))
823                         c++;
824                 /* Ignore blank lines.  */
825                 if (c[0] == '\0')
826                         continue;
827
828                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
829                         c += 8;
830                         if (c[0] != '\0')
831                                 account = strdup(c);
832                 } else if (!strncasecmp(c, "password", 8) &&
833                            (c[8] == '=')) {
834                         c += 9;
835                         if (c[0] != '\0')
836                                 password = strdup(c);
837                 } else if (!strncasecmp(c, "consumer_key", 12) &&
838                            (c[12] == '=')) {
839                         c += 13;
840                         if (c[0] != '\0')
841                                 consumer_key = strdup(c);
842                 } else if (!strncasecmp(c, "consumer_secret", 15) &&
843                            (c[15] == '=')) {
844                         c += 16;
845                         if (c[0] != '\0')
846                                 consumer_secret = strdup(c);
847                 } else if (!strncasecmp(c, "access_token_key", 16) &&
848                            (c[16] == '=')) {
849                         c += 17;
850                         if (c[0] != '\0')
851                                 access_token_key = strdup(c);
852                 } else if (!strncasecmp(c, "access_token_secret", 19) &&
853                            (c[19] == '=')) {
854                         c += 20;
855                         if (c[0] != '\0')
856                                 access_token_secret = strdup(c);
857                 } else if (!strncasecmp(c, "host", 4) &&
858                            (c[4] == '=')) {
859                         c += 5;
860                         if (c[0] != '\0')
861                                 host = strdup(c);
862                 } else if (!strncasecmp(c, "proxy", 5) &&
863                            (c[5] == '=')) {
864                         c += 6;
865                         if (c[0] != '\0')
866                                 proxy = strdup(c);
867                 } else if (!strncasecmp(c, "logfile", 7) &&
868                            (c[7] == '=')) {
869                         c += 8;
870                         if (c[0] != '\0')
871                                 logfile = strdup(c);
872                 } else if (!strncasecmp(c, "replyto", 7) &&
873                            (c[7] == '=')) {
874                         c += 8;
875                         if (c[0] != '\0')
876                                 replyto = strdup(c);
877                 } else if (!strncasecmp(c, "action", 6) &&
878                            (c[6] == '=')) {
879                         c += 7;
880                         if (c[0] != '\0')
881                                 action = strdup(c);
882                 } else if (!strncasecmp(c, "user", 4) &&
883                                 (c[4] == '=')) {
884                         c += 5;
885                         if (c[0] != '\0')
886                                 user = strdup(c);
887                 } else if (!strncasecmp(c, "shrink-urls", 11) &&
888                                 (c[11] == '=')) {
889                         c += 12;
890                         if (!strncasecmp(c, "true", 4) ||
891                                         !strncasecmp(c, "yes", 3))
892                                 shrink_urls = 1;
893                 } else if (!strncasecmp(c, "verbose", 7) &&
894                                 (c[7] == '=')) {
895                         c += 8;
896                         if (!strncasecmp(c, "true", 4) ||
897                                         !strncasecmp(c, "yes", 3))
898                                 verbose = 1;
899                 } else if (!strncasecmp(c,"retweet", 7) &&
900                                 (c[7] == '=')) {
901                         c += 8;
902                         if (c[0] != '\0')
903                                 retweet = strdup(c);
904                 }
905         } while (!feof(config_file));
906
907         if (password)
908                 session->password = password;
909         if (account)
910                 session->account = account;
911         if (consumer_key)
912                 session->consumer_key = consumer_key;
913         if (consumer_secret)
914                 session->consumer_secret = consumer_secret;
915         if (access_token_key)
916                 session->access_token_key = access_token_key;
917         if (access_token_secret)
918                 session->access_token_secret = access_token_secret;
919         if (host) {
920                 if (strcasecmp(host, "twitter") == 0) {
921                         session->host = HOST_TWITTER;
922                         session->hosturl = strdup(twitter_host);
923                         session->hostname = strdup(twitter_name);
924                 } else if (strcasecmp(host, "identica") == 0) {
925                         session->host = HOST_IDENTICA;
926                         session->hosturl = strdup(identica_host);
927                         session->hostname = strdup(identica_name);
928                 } else {
929                         session->host = HOST_CUSTOM;
930                         session->hosturl = strdup(host);
931                         session->hostname = strdup(host);
932                 }
933                 free(host);
934         }
935         if (proxy) {
936                 if (session->proxy)
937                         free(session->proxy);
938                 session->proxy = proxy;
939         }
940         if (logfile)
941                 session->logfile = logfile;
942         if (replyto)
943                 session->replyto = replyto;
944         if (retweet)
945                 session->retweet = retweet;
946         if (action) {
947                 if (strcasecmp(action, "update") == 0)
948                         session->action = ACTION_UPDATE;
949                 else if (strcasecmp(action, "friends") == 0)
950                         session->action = ACTION_FRIENDS;
951                 else if (strcasecmp(action, "user") == 0)
952                         session->action = ACTION_USER;
953                 else if (strcasecmp(action, "replies") == 0)
954                         session->action = ACTION_REPLIES;
955                 else if (strcasecmp(action, "public") == 0)
956                         session->action = ACTION_PUBLIC;
957                 else if (strcasecmp(action, "group") == 0)
958                         session->action = ACTION_GROUP;
959                 else
960                         session->action = ACTION_UNKNOWN;
961                 free(action);
962         }
963         if (user)
964                 session->user = user;
965         session->shrink_urls = shrink_urls;
966
967         /* Free buffer and close file.  */
968         free(line);
969         fclose(config_file);
970 }
971
972 static void log_session(struct session *session, int retval)
973 {
974         FILE *log_file;
975         char *filename;
976
977         /* Only log something if we have a log file set */
978         if (!session->logfile)
979                 return;
980
981         filename = alloca(strlen(session->homedir) +
982                           strlen(session->logfile) + 3);
983
984         sprintf(filename, "%s/%s", session->homedir, session->logfile);
985
986         log_file = fopen(filename, "a+");
987         if (log_file == NULL)
988                 return;
989
990         switch (session->action) {
991         case ACTION_UPDATE:
992                 if (retval)
993                         fprintf(log_file, "%s: host=%s tweet failed\n",
994                                 session->time, session->hostname);
995                 else
996                         fprintf(log_file, "%s: host=%s tweet=%s\n",
997                                 session->time, session->hostname,
998                                 session->tweet);
999                 break;
1000         case ACTION_FRIENDS:
1001                 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
1002                         session->time, session->hostname);
1003                 break;
1004         case ACTION_USER:
1005                 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
1006                         session->time, session->hostname, session->user);
1007                 break;
1008         case ACTION_REPLIES:
1009                 fprintf(log_file, "%s: host=%s retrieving replies\n",
1010                         session->time, session->hostname);
1011                 break;
1012         case ACTION_PUBLIC:
1013                 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
1014                         session->time, session->hostname);
1015                 break;
1016         case ACTION_GROUP:
1017                 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
1018                         session->time, session->hostname);
1019                 break;
1020         default:
1021                 break;
1022         }
1023
1024         fclose(log_file);
1025 }
1026
1027 static char *get_string_from_stdin(void)
1028 {
1029         char *temp;
1030         char *string;
1031
1032         string = zalloc(1000);
1033         if (!string)
1034                 return NULL;
1035
1036         if (!fgets(string, 999, stdin))
1037                 return NULL;
1038         temp = strchr(string, '\n');
1039         if (temp)
1040                 *temp = '\0';
1041         return string;
1042 }
1043
1044 static void read_password(char *buf, size_t len, char *host)
1045 {
1046         char pwd[80];
1047         int retval;
1048         struct termios old;
1049         struct termios tp;
1050
1051         tcgetattr(0, &tp);
1052         old = tp;
1053
1054         tp.c_lflag &= (~ECHO);
1055         tcsetattr(0, TCSANOW, &tp);
1056
1057         fprintf(stdout, "Enter password for %s: ", host);
1058         fflush(stdout);
1059         tcflow(0, TCOOFF);
1060         retval = scanf("%79s", pwd);
1061         tcflow(0, TCOON);
1062         fprintf(stdout, "\n");
1063
1064         tcsetattr(0, TCSANOW, &old);
1065
1066         strncpy(buf, pwd, len);
1067         buf[len-1] = '\0';
1068 }
1069
1070 static int find_urls(const char *tweet, int **pranges)
1071 {
1072         /*
1073          * magic obtained from
1074          * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
1075          */
1076         static const char *re_magic =
1077                 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
1078                 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
1079                 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
1080         pcre *re;
1081         const char *errptr;
1082         int erroffset;
1083         int ovector[10] = {0,};
1084         const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
1085         int startoffset, tweetlen;
1086         int i, rc;
1087         int rbound = 10;
1088         int rcount = 0;
1089         int *ranges = malloc(sizeof(int) * rbound);
1090
1091         re = pcre_compile(re_magic,
1092                         PCRE_NO_AUTO_CAPTURE,
1093                         &errptr, &erroffset, NULL);
1094         if (!re) {
1095                 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
1096                 exit(1);
1097         }
1098
1099         tweetlen = strlen(tweet);
1100         for (startoffset = 0; startoffset < tweetlen; ) {
1101
1102                 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
1103                                 ovector, ovsize);
1104                 if (rc == PCRE_ERROR_NOMATCH)
1105                         break;
1106
1107                 if (rc < 0) {
1108                         fprintf(stderr, "pcre_exec @%u: %s\n",
1109                                 erroffset, errptr);
1110                         exit(1);
1111                 }
1112
1113                 for (i = 0; i < rc; i += 2) {
1114                         if ((rcount+2) == rbound) {
1115                                 rbound *= 2;
1116                                 ranges = realloc(ranges, sizeof(int) * rbound);
1117                         }
1118
1119                         ranges[rcount++] = ovector[i];
1120                         ranges[rcount++] = ovector[i+1];
1121                 }
1122
1123                 startoffset = ovector[1];
1124         }
1125
1126         pcre_free(re);
1127
1128         *pranges = ranges;
1129         return rcount;
1130 }
1131
1132 /**
1133  * bidirectional popen() call
1134  *
1135  * @param rwepipe - int array of size three
1136  * @param exe - program to run
1137  * @param argv - argument list
1138  * @return pid or -1 on error
1139  *
1140  * The caller passes in an array of three integers (rwepipe), on successful
1141  * execution it can then write to element 0 (stdin of exe), and read from
1142  * element 1 (stdout) and 2 (stderr).
1143  */
1144 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
1145 {
1146         int in[2];
1147         int out[2];
1148         int err[2];
1149         int pid;
1150         int rc;
1151
1152         rc = pipe(in);
1153         if (rc < 0)
1154                 goto error_in;
1155
1156         rc = pipe(out);
1157         if (rc < 0)
1158                 goto error_out;
1159
1160         rc = pipe(err);
1161         if (rc < 0)
1162                 goto error_err;
1163
1164         pid = fork();
1165         if (pid > 0) {
1166                 /* parent */
1167                 close(in[0]);
1168                 close(out[1]);
1169                 close(err[1]);
1170                 rwepipe[0] = in[1];
1171                 rwepipe[1] = out[0];
1172                 rwepipe[2] = err[0];
1173                 return pid;
1174         } else if (pid == 0) {
1175                 /* child */
1176                 close(in[1]);
1177                 close(out[0]);
1178                 close(err[0]);
1179                 close(0);
1180                 rc = dup(in[0]);
1181                 close(1);
1182                 rc = dup(out[1]);
1183                 close(2);
1184                 rc = dup(err[1]);
1185
1186                 execvp(exe, (char **)argv);
1187                 exit(1);
1188         } else
1189                 goto error_fork;
1190
1191         return pid;
1192
1193 error_fork:
1194         close(err[0]);
1195         close(err[1]);
1196 error_err:
1197         close(out[0]);
1198         close(out[1]);
1199 error_out:
1200         close(in[0]);
1201         close(in[1]);
1202 error_in:
1203         return -1;
1204 }
1205
1206 static int pcloseRWE(int pid, int *rwepipe)
1207 {
1208         int rc, status;
1209         close(rwepipe[0]);
1210         close(rwepipe[1]);
1211         close(rwepipe[2]);
1212         rc = waitpid(pid, &status, 0);
1213         return status;
1214 }
1215
1216 static char *shrink_one_url(int *rwepipe, char *big)
1217 {
1218         int biglen = strlen(big);
1219         char *small;
1220         int smalllen;
1221         int rc;
1222
1223         rc = dprintf(rwepipe[0], "%s\n", big);
1224         if (rc < 0)
1225                 return big;
1226
1227         smalllen = biglen + 128;
1228         small = malloc(smalllen);
1229         if (!small)
1230                 return big;
1231
1232         rc = read(rwepipe[1], small, smalllen);
1233         if (rc < 0 || rc > biglen)
1234                 goto error_free_small;
1235
1236         if (strncmp(small, "http://", 7))
1237                 goto error_free_small;
1238
1239         smalllen = rc;
1240         while (smalllen && isspace(small[smalllen-1]))
1241                         small[--smalllen] = 0;
1242
1243         free(big);
1244         return small;
1245
1246 error_free_small:
1247         free(small);
1248         return big;
1249 }
1250
1251 static char *shrink_urls(char *text)
1252 {
1253         int *ranges;
1254         int rcount;
1255         int i;
1256         int inofs = 0;
1257         int outofs = 0;
1258         const char *const shrink_args[] = {
1259                 "bti-shrink-urls",
1260                 NULL
1261         };
1262         int shrink_pid;
1263         int shrink_pipe[3];
1264         int inlen = strlen(text);
1265
1266         dbg("before len=%u\n", inlen);
1267
1268         shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
1269         if (shrink_pid < 0)
1270                 return text;
1271
1272         rcount = find_urls(text, &ranges);
1273         if (!rcount)
1274                 return text;
1275
1276         for (i = 0; i < rcount; i += 2) {
1277                 int url_start = ranges[i];
1278                 int url_end = ranges[i+1];
1279                 int long_url_len = url_end - url_start;
1280                 char *url = strndup(text + url_start, long_url_len);
1281                 int short_url_len;
1282                 int not_url_len = url_start - inofs;
1283
1284                 dbg("long  url[%u]: %s\n", long_url_len, url);
1285                 url = shrink_one_url(shrink_pipe, url);
1286                 short_url_len = url ? strlen(url) : 0;
1287                 dbg("short url[%u]: %s\n", short_url_len, url);
1288
1289                 if (!url || short_url_len >= long_url_len) {
1290                         /* The short url ended up being too long
1291                          * or unavailable */
1292                         if (inofs) {
1293                                 strncpy(text + outofs, text + inofs,
1294                                                 not_url_len + long_url_len);
1295                         }
1296                         inofs += not_url_len + long_url_len;
1297                         outofs += not_url_len + long_url_len;
1298
1299                 } else {
1300                         /* copy the unmodified block */
1301                         strncpy(text + outofs, text + inofs, not_url_len);
1302                         inofs += not_url_len;
1303                         outofs += not_url_len;
1304
1305                         /* copy the new url */
1306                         strncpy(text + outofs, url, short_url_len);
1307                         inofs += long_url_len;
1308                         outofs += short_url_len;
1309                 }
1310
1311                 free(url);
1312         }
1313
1314         /* copy the last block after the last match */
1315         if (inofs) {
1316                 int tail = inlen - inofs;
1317                 if (tail) {
1318                         strncpy(text + outofs, text + inofs, tail);
1319                         outofs += tail;
1320                 }
1321         }
1322
1323         free(ranges);
1324
1325         (void)pcloseRWE(shrink_pid, shrink_pipe);
1326
1327         text[outofs] = 0;
1328         dbg("after len=%u\n", outofs);
1329         return text;
1330 }
1331
1332 int main(int argc, char *argv[], char *envp[])
1333 {
1334         static const struct option options[] = {
1335                 { "debug", 0, NULL, 'd' },
1336                 { "verbose", 0, NULL, 'V' },
1337                 { "account", 1, NULL, 'a' },
1338                 { "password", 1, NULL, 'p' },
1339                 { "host", 1, NULL, 'H' },
1340                 { "proxy", 1, NULL, 'P' },
1341                 { "action", 1, NULL, 'A' },
1342                 { "user", 1, NULL, 'u' },
1343                 { "group", 1, NULL, 'G' },
1344                 { "logfile", 1, NULL, 'L' },
1345                 { "shrink-urls", 0, NULL, 's' },
1346                 { "help", 0, NULL, 'h' },
1347                 { "bash", 0, NULL, 'b' },
1348                 { "background", 0, NULL, 'B' },
1349                 { "dry-run", 0, NULL, 'n' },
1350                 { "page", 1, NULL, 'g' },
1351                 { "version", 0, NULL, 'v' },
1352                 { "config", 1, NULL, 'c' },
1353                 { "replyto", 1, NULL, 'r' },
1354                 { "retweet", 1, NULL, 'w' },
1355                 { }
1356         };
1357         struct session *session;
1358         pid_t child;
1359         char *tweet;
1360         char *retweet;
1361         static char password[80];
1362         int retval = 0;
1363         int option;
1364         char *http_proxy;
1365         time_t t;
1366         int page_nr;
1367
1368         debug = 0;
1369         verbose = 0;
1370
1371         session = session_alloc();
1372         if (!session) {
1373                 fprintf(stderr, "no more memory...\n");
1374                 return -1;
1375         }
1376
1377         /* get the current time so that we can log it later */
1378         time(&t);
1379         session->time = strdup(ctime(&t));
1380         session->time[strlen(session->time)-1] = 0x00;
1381
1382         /* Get the home directory so we can try to find a config file */
1383         session->homedir = strdup(getenv("HOME"));
1384
1385         /* set up a default config file location (traditionally ~/.bti) */
1386         session->configfile = zalloc(strlen(session->homedir) + 7);
1387         sprintf(session->configfile, "%s/.bti", session->homedir);
1388
1389         /* Set environment variables first, before reading command line options
1390          * or config file values. */
1391         http_proxy = getenv("http_proxy");
1392         if (http_proxy) {
1393                 if (session->proxy)
1394                         free(session->proxy);
1395                 session->proxy = strdup(http_proxy);
1396                 dbg("http_proxy = %s\n", session->proxy);
1397         }
1398
1399         parse_configfile(session);
1400
1401         while (1) {
1402                 option = getopt_long_only(argc, argv,
1403                                           "dp:P:H:a:A:u:c:hg:G:sr:nVv",
1404                                           options, NULL);
1405                 if (option == -1)
1406                         break;
1407                 switch (option) {
1408                 case 'd':
1409                         debug = 1;
1410                         break;
1411                 case 'V':
1412                         verbose = 1;
1413                         break;
1414                 case 'a':
1415                         if (session->account)
1416                                 free(session->account);
1417                         session->account = strdup(optarg);
1418                         dbg("account = %s\n", session->account);
1419                         break;
1420                 case 'g':
1421                         page_nr = atoi(optarg);
1422                         dbg("page = %d\n", page_nr);
1423                         session->page = page_nr;
1424                         break;
1425                 case 'r':
1426                         session->replyto = strdup(optarg);
1427                         dbg("in_reply_to_status_id = %s\n", session->replyto);
1428                         break;
1429                 case 'w':
1430                         session->retweet = strdup(optarg);
1431                         dbg("Retweet ID = %s\n", session->retweet);
1432                         break;
1433                 case 'p':
1434                         if (session->password)
1435                                 free(session->password);
1436                         session->password = strdup(optarg);
1437                         dbg("password = %s\n", session->password);
1438                         break;
1439                 case 'P':
1440                         if (session->proxy)
1441                                 free(session->proxy);
1442                         session->proxy = strdup(optarg);
1443                         dbg("proxy = %s\n", session->proxy);
1444                         break;
1445                 case 'A':
1446                         if (strcasecmp(optarg, "update") == 0)
1447                                 session->action = ACTION_UPDATE;
1448                         else if (strcasecmp(optarg, "friends") == 0)
1449                                 session->action = ACTION_FRIENDS;
1450                         else if (strcasecmp(optarg, "user") == 0)
1451                                 session->action = ACTION_USER;
1452                         else if (strcasecmp(optarg, "replies") == 0)
1453                                 session->action = ACTION_REPLIES;
1454                         else if (strcasecmp(optarg, "public") == 0)
1455                                 session->action = ACTION_PUBLIC;
1456                         else if (strcasecmp(optarg, "group") == 0)
1457                                 session->action = ACTION_GROUP;
1458                         else if (strcasecmp(optarg,"retweet") == 0)
1459                                 session->action = ACTION_RETWEET;
1460                         else
1461                                 session->action = ACTION_UNKNOWN;
1462                         dbg("action = %d\n", session->action);
1463                         break;
1464                 case 'u':
1465                         if (session->user)
1466                                 free(session->user);
1467                         session->user = strdup(optarg);
1468                         dbg("user = %s\n", session->user);
1469                         break;
1470
1471                 case 'G':
1472                         if (session->group)
1473                                 free(session->group);
1474                         session->group = strdup(optarg);
1475                         dbg("group = %s\n", session->group);
1476                         break;
1477                 case 'L':
1478                         if (session->logfile)
1479                                 free(session->logfile);
1480                         session->logfile = strdup(optarg);
1481                         dbg("logfile = %s\n", session->logfile);
1482                         break;
1483                 case 's':
1484                         session->shrink_urls = 1;
1485                         break;
1486                 case 'H':
1487                         if (session->hosturl)
1488                                 free(session->hosturl);
1489                         if (session->hostname)
1490                                 free(session->hostname);
1491                         if (strcasecmp(optarg, "twitter") == 0) {
1492                                 session->host = HOST_TWITTER;
1493                                 session->hosturl = strdup(twitter_host);
1494                                 session->hostname = strdup(twitter_name);
1495                         } else if (strcasecmp(optarg, "identica") == 0) {
1496                                 session->host = HOST_IDENTICA;
1497                                 session->hosturl = strdup(identica_host);
1498                                 session->hostname = strdup(identica_name);
1499                         } else {
1500                                 session->host = HOST_CUSTOM;
1501                                 session->hosturl = strdup(optarg);
1502                                 session->hostname = strdup(optarg);
1503                         }
1504                         dbg("host = %d\n", session->host);
1505                         break;
1506                 case 'b':
1507                         session->bash = 1;
1508                         /* fall-through intended */
1509                 case 'B':
1510                         session->background = 1;
1511                         break;
1512                 case 'c':
1513                         if (session->configfile)
1514                                 free(session->configfile);
1515                         session->configfile = strdup(optarg);
1516                         dbg("configfile = %s\n", session->configfile);
1517
1518                         /*
1519                          * read the config file now.  Yes, this could override
1520                          * previously set options from the command line, but
1521                          * the user asked for it...
1522                          */
1523                         parse_configfile(session);
1524                         break;
1525                 case 'h':
1526                         display_help();
1527                         goto exit;
1528                 case 'n':
1529                         session->dry_run = 1;
1530                         break;
1531                 case 'v':
1532                         display_version();
1533                         goto exit;
1534                 default:
1535                         display_help();
1536                         goto exit;
1537                 }
1538         }
1539
1540         session_readline_init(session);
1541         /*
1542          * Show the version to make it easier to determine what
1543          * is going on here
1544          */
1545         if (debug)
1546                 display_version();
1547
1548         if (session->host == HOST_TWITTER) {
1549                 if (!session->consumer_key || !session->consumer_secret) {
1550                         fprintf(stderr,
1551                                 "Twitter no longer supports HTTP basic authentication.\n"
1552                                 "Both consumer key, and consumer secret are required"
1553                                 " for bti in order to behave as an OAuth consumer.\n");
1554                         goto exit;
1555                 }
1556                 if (session->action == ACTION_GROUP) {
1557                         fprintf(stderr, "Groups only work in Identi.ca.\n");
1558                         goto exit;
1559                 }
1560         } else {
1561                 if (!session->consumer_key || !session->consumer_secret)
1562                         session->no_oauth = 1;
1563         }
1564
1565         if (session->no_oauth) {
1566                 if (!session->account) {
1567                         fprintf(stdout, "Enter account for %s: ",
1568                                 session->hostname);
1569                         session->account = session->readline(NULL);
1570                 }
1571                 if (!session->password) {
1572                         read_password(password, sizeof(password),
1573                                       session->hostname);
1574                         session->password = strdup(password);
1575                 }
1576         } else {
1577                 if (!session->access_token_key ||
1578                     !session->access_token_secret) {
1579                         request_access_token(session);
1580                         goto exit;
1581                 }
1582         }
1583
1584         if (session->action == ACTION_UNKNOWN) {
1585                 fprintf(stderr, "Unknown action, valid actions are:\n"
1586                         "'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
1587                 goto exit;
1588         }
1589
1590         if (session->action == ACTION_GROUP && !session->group) {
1591                 fprintf(stdout, "Enter group name: ");
1592                 session->group = session->readline(NULL);
1593         }
1594
1595         if (session->action == ACTION_RETWEET) {
1596                 fprintf(stdout, "Status ID to retweet: ");
1597                 retweet = get_string_from_stdin();
1598
1599                 if (!retweet || strlen(retweet) == 0) {
1600                         dbg("no retweet?\n");
1601                         return -1;
1602                 }
1603
1604                 session->retweet = zalloc(strlen(retweet) + 10);
1605                 sprintf(session->retweet,"%s", retweet);
1606                 free(retweet);
1607                 dbg("retweet ID = %s\n", session->retweet);
1608         }
1609
1610         if (session->action == ACTION_UPDATE) {
1611                 if (session->background || !session->interactive)
1612                         tweet = get_string_from_stdin();
1613                 else
1614                         tweet = session->readline("tweet: ");
1615                 if (!tweet || strlen(tweet) == 0) {
1616                         dbg("no tweet?\n");
1617                         return -1;
1618                 }
1619
1620                 if (session->shrink_urls)
1621                         tweet = shrink_urls(tweet);
1622
1623                 session->tweet = zalloc(strlen(tweet) + 10);
1624                 if (session->bash)
1625                         sprintf(session->tweet, "%c %s",
1626                                 getuid() ? '$' : '#', tweet);
1627                 else
1628                         sprintf(session->tweet, "%s", tweet);
1629
1630                 free(tweet);
1631                 dbg("tweet = %s\n", session->tweet);
1632         }
1633
1634         if (session->page == 0)
1635                 session->page = 1;
1636         dbg("config file = %s\n", session->configfile);
1637         dbg("host = %d\n", session->host);
1638         dbg("action = %d\n", session->action);
1639
1640         /* fork ourself so that the main shell can get on
1641          * with it's life as we try to connect and handle everything
1642          */
1643         if (session->background) {
1644                 child = fork();
1645                 if (child) {
1646                         dbg("child is %d\n", child);
1647                         exit(0);
1648                 }
1649         }
1650
1651         retval = send_request(session);
1652         if (retval && !session->background)
1653                 fprintf(stderr, "operation failed\n");
1654
1655         log_session(session, retval);
1656 exit:
1657         session_readline_cleanup(session);
1658         session_free(session);
1659         return retval;;
1660 }