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