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