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