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