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