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