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