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