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