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