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