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