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