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