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