BTI should not display password while user types it
[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 #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, user_uri,
376                                 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, session->page);
384                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
385                 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
386
387                 break;
388         case ACTION_PUBLIC:
389                 sprintf(endpoint, "%s%s?page=%d", session->hosturl, public_uri, session->page);
390                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
391
392                 break;
393         case ACTION_GROUP:
394                 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
395                                 group_uri, session->group, session->page);
396                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
397
398                 break;
399         default:
400                 break;
401         }
402
403         if (session->proxy)
404                 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
405
406         if (debug)
407                 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
408
409         dbg("user_password = %s\n", user_password);
410         dbg("data = %s\n", data);
411         dbg("proxy = %s\n", session->proxy);
412
413         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
414         curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
415         if (!session->dry_run) {
416                 res = curl_easy_perform(curl);
417                 if (res && !session->bash) {
418                         fprintf(stderr, "error(%d) trying to perform "
419                                 "operation\n", res);
420                         return -EINVAL;
421                 }
422         }
423
424         curl_easy_cleanup(curl);
425         if (session->action == ACTION_UPDATE)
426                 curl_formfree(formpost);
427         bti_curl_buffer_free(curl_buf);
428         return 0;
429 }
430
431 static void parse_configfile(struct session *session)
432 {
433         FILE *config_file;
434         char *line = NULL;
435         size_t len = 0;
436         char *account = NULL;
437         char *password = NULL;
438         char *host = NULL;
439         char *proxy = NULL;
440         char *logfile = NULL;
441         char *action = NULL;
442         char *user = NULL;
443         char *file;
444         int shrink_urls = 0;
445
446         /* config file is ~/.bti  */
447         file = alloca(strlen(session->homedir) + 7);
448
449         sprintf(file, "%s/.bti", session->homedir);
450
451         config_file = fopen(file, "r");
452
453         /* No error if file does not exist or is unreadable.  */
454         if (config_file == NULL)
455                 return;
456
457         do {
458                 ssize_t n = getline(&line, &len, config_file);
459                 if (n < 0)
460                         break;
461                 if (line[n - 1] == '\n')
462                         line[n - 1] = '\0';
463                 /* Parse file.  Format is the usual value pairs:
464                    account=name
465                    passwort=value
466                    # is a comment character
467                 */
468                 *strchrnul(line, '#') = '\0';
469                 char *c = line;
470                 while (isspace(*c))
471                         c++;
472                 /* Ignore blank lines.  */
473                 if (c[0] == '\0')
474                         continue;
475
476                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
477                         c += 8;
478                         if (c[0] != '\0')
479                                 account = strdup(c);
480                 } else if (!strncasecmp(c, "password", 8) &&
481                            (c[8] == '=')) {
482                         c += 9;
483                         if (c[0] != '\0')
484                                 password = strdup(c);
485                 } else if (!strncasecmp(c, "host", 4) &&
486                            (c[4] == '=')) {
487                         c += 5;
488                         if (c[0] != '\0')
489                                 host = strdup(c);
490                 } else if (!strncasecmp(c, "proxy", 5) &&
491                            (c[5] == '=')) {
492                         c += 6;
493                         if (c[0] != '\0')
494                                 proxy = strdup(c);
495                 } else if (!strncasecmp(c, "logfile", 7) &&
496                            (c[7] == '=')) {
497                         c += 8;
498                         if (c[0] != '\0')
499                                 logfile = strdup(c);
500                 } else if (!strncasecmp(c, "action", 6) &&
501                            (c[6] == '=')) {
502                         c += 7;
503                         if (c[0] != '\0')
504                                 action = strdup(c);
505                 } else if (!strncasecmp(c, "user", 4) &&
506                                 (c[4] == '=')) {
507                         c += 5;
508                         if (c[0] != '\0')
509                                 user = strdup(c);
510                 } else if (!strncasecmp(c, "shrink-urls", 11) &&
511                                 (c[11] == '=')) {
512                         c += 12;
513                         if (!strncasecmp(c, "true", 4) ||
514                                         !strncasecmp(c, "yes", 3))
515                                 shrink_urls = 1;
516                 }
517                 else if (!strncasecmp(c, "verbose", 7) &&
518                                 (c[7] == '=')) {
519                         c += 8;
520                         if (!strncasecmp(c, "true", 4) ||
521                                         !strncasecmp(c, "yes", 3))
522                                 verbose = 1;
523                 }       
524         } while (!feof(config_file));
525
526         if (password)
527                 session->password = password;
528         if (account)
529                 session->account = account;
530         if (host) {
531                 if (strcasecmp(host, "twitter") == 0) {
532                         session->host = HOST_TWITTER;
533                         session->hosturl = strdup(twitter_host);
534                 } else if (strcasecmp(host, "identica") == 0) {
535                         session->host = HOST_IDENTICA;
536                         session->hosturl = strdup(identica_host);
537                 } else {
538                         session->host = HOST_CUSTOM;
539                         session->hosturl = strdup(host);
540                 }
541                 free(host);
542         }
543         if (proxy) {
544                 if (session->proxy)
545                         free(session->proxy);
546                 session->proxy = proxy;
547         }
548         if (logfile)
549                 session->logfile = logfile;
550         if (action) {
551                 if (strcasecmp(action, "update") == 0)
552                         session->action = ACTION_UPDATE;
553                 else if (strcasecmp(action, "friends") == 0)
554                         session->action = ACTION_FRIENDS;
555                 else if (strcasecmp(action, "user") == 0)
556                         session->action = ACTION_USER;
557                 else if (strcasecmp(action, "replies") == 0)
558                         session->action = ACTION_REPLIES;
559                 else if (strcasecmp(action, "public") == 0)
560                         session->action = ACTION_PUBLIC;
561                 else if (strcasecmp(action, "group") == 0)
562                         session->action = ACTION_GROUP;
563                 else
564                         session->action = ACTION_UNKNOWN;
565                 free(action);
566         }
567         if (user)
568                 session->user = user;
569         session->shrink_urls = shrink_urls;
570
571         /* Free buffer and close file.  */
572         free(line);
573         fclose(config_file);
574 }
575
576 static void log_session(struct session *session, int retval)
577 {
578         FILE *log_file;
579         char *filename;
580         char *host;
581
582         /* Only log something if we have a log file set */
583         if (!session->logfile)
584                 return;
585
586         filename = alloca(strlen(session->homedir) +
587                           strlen(session->logfile) + 3);
588
589         sprintf(filename, "%s/%s", session->homedir, session->logfile);
590
591         log_file = fopen(filename, "a+");
592         if (log_file == NULL)
593                 return;
594         switch (session->host) {
595         case HOST_TWITTER:
596                 host = "twitter";
597                 break;
598         case HOST_IDENTICA:
599                 host = "identi.ca";
600                 break;
601         default:
602                 host = session->hosturl;
603                 break;
604         }
605
606         switch (session->action) {
607         case ACTION_UPDATE:
608                 if (retval)
609                         fprintf(log_file, "%s: host=%s tweet failed\n",
610                                 session->time, host);
611                 else
612                         fprintf(log_file, "%s: host=%s tweet=%s\n",
613                                 session->time, host, session->tweet);
614                 break;
615         case ACTION_FRIENDS:
616                 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
617                         session->time, host);
618                 break;
619         case ACTION_USER:
620                 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
621                         session->time, host, session->user);
622                 break;
623         case ACTION_REPLIES:
624                 fprintf(log_file, "%s: host=%s retrieving replies\n",
625                         session->time, host);
626                 break;
627         case ACTION_PUBLIC:
628                 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
629                         session->time, host);
630                 break;
631         case ACTION_GROUP:
632                 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
633                         session->time, host);
634                 break;
635         default:
636                 break;
637         }
638
639         fclose(log_file);
640 }
641
642 static char *get_string_from_stdin(void)
643 {
644         char *temp;
645         char *string;
646
647         string = zalloc(1000);
648         if (!string)
649                 return NULL;
650
651         if (!fgets(string, 999, stdin))
652                 return NULL;
653         temp = strchr(string, '\n');
654         *temp = '\0';
655         return string;
656 }
657
658 void read_password(char *buf, size_t len)
659 {
660         char pwd[80];
661         struct termios old;
662         struct termios tp;
663
664         tcgetattr(0, &tp);
665         old = tp;
666         
667         tp.c_lflag &= (~ECHO);
668         tcsetattr(0, TCSANOW, &tp);
669
670         fprintf(stdout, "Enter twitter password: ");
671         fflush(stdout);
672         scanf("%79s", pwd);
673         fprintf(stdout, "\n");
674
675         tcsetattr(0, TCSANOW, &old);    
676
677         strncpy(buf, pwd, len);
678         buf[len-1] = '\0';
679 }
680
681 static int find_urls(const char *tweet, int **pranges)
682 {
683         /*
684          * magic obtained from
685          * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
686          */
687         static const char *re_magic =
688                 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
689                 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
690                 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
691         pcre *re;
692         const char *errptr;
693         int erroffset;
694         int ovector[10] = {0,};
695         const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
696         int startoffset, tweetlen;
697         int i, rc;
698         int rbound = 10;
699         int rcount = 0;
700         int *ranges = malloc(sizeof(int) * rbound);
701
702         re = pcre_compile(re_magic,
703                         PCRE_NO_AUTO_CAPTURE,
704                         &errptr, &erroffset, NULL);
705         if (!re) {
706                 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
707                 exit(1);
708         }
709
710         tweetlen = strlen(tweet);
711         for (startoffset = 0; startoffset < tweetlen; ) {
712
713                 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
714                                 ovector, ovsize);
715                 if (rc == PCRE_ERROR_NOMATCH)
716                         break;
717
718                 if (rc < 0) {
719                         fprintf(stderr, "pcre_exec @%u: %s\n",
720                                 erroffset, errptr);
721                         exit(1);
722                 }
723
724                 for (i = 0; i < rc; i += 2) {
725                         if ((rcount+2) == rbound) {
726                                 rbound *= 2;
727                                 ranges = realloc(ranges, sizeof(int) * rbound);
728                         }
729
730                         ranges[rcount++] = ovector[i];
731                         ranges[rcount++] = ovector[i+1];
732                 }
733
734                 startoffset = ovector[1];
735         }
736
737         pcre_free(re);
738
739         *pranges = ranges;
740         return rcount;
741 }
742
743 /**
744  * bidirectional popen() call
745  *
746  * @param rwepipe - int array of size three
747  * @param exe - program to run
748  * @param argv - argument list
749  * @return pid or -1 on error
750  *
751  * The caller passes in an array of three integers (rwepipe), on successful
752  * execution it can then write to element 0 (stdin of exe), and read from
753  * element 1 (stdout) and 2 (stderr).
754  */
755 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
756 {
757         int in[2];
758         int out[2];
759         int err[2];
760         int pid;
761         int rc;
762
763         rc = pipe(in);
764         if (rc < 0)
765                 goto error_in;
766
767         rc = pipe(out);
768         if (rc < 0)
769                 goto error_out;
770
771         rc = pipe(err);
772         if (rc < 0)
773                 goto error_err;
774
775         pid = fork();
776         if (pid > 0) {
777                 /* parent */
778                 close(in[0]);
779                 close(out[1]);
780                 close(err[1]);
781                 rwepipe[0] = in[1];
782                 rwepipe[1] = out[0];
783                 rwepipe[2] = err[0];
784                 return pid;
785         } else if (pid == 0) {
786                 /* child */
787                 close(in[1]);
788                 close(out[0]);
789                 close(err[0]);
790                 close(0);
791                 rc = dup(in[0]);
792                 close(1);
793                 rc = dup(out[1]);
794                 close(2);
795                 rc = dup(err[1]);
796
797                 execvp(exe, (char **)argv);
798                 exit(1);
799         } else
800                 goto error_fork;
801
802         return pid;
803
804 error_fork:
805         close(err[0]);
806         close(err[1]);
807 error_err:
808         close(out[0]);
809         close(out[1]);
810 error_out:
811         close(in[0]);
812         close(in[1]);
813 error_in:
814         return -1;
815 }
816
817 static int pcloseRWE(int pid, int *rwepipe)
818 {
819         int rc, status;
820         close(rwepipe[0]);
821         close(rwepipe[1]);
822         close(rwepipe[2]);
823         rc = waitpid(pid, &status, 0);
824         return status;
825 }
826
827 static char *shrink_one_url(int *rwepipe, char *big)
828 {
829         int biglen = strlen(big);
830         char *small;
831         int smalllen;
832         int rc;
833
834         rc = dprintf(rwepipe[0], "%s\n", big);
835         if (rc < 0)
836                 return big;
837
838         smalllen = biglen + 128;
839         small = malloc(smalllen);
840         if (!small)
841                 return big;
842
843         rc = read(rwepipe[1], small, smalllen);
844         if (rc < 0 || rc > biglen)
845                 goto error_free_small;
846
847         if (strncmp(small, "http://", 7))
848                 goto error_free_small;
849
850         smalllen = rc;
851         while (smalllen && isspace(small[smalllen-1]))
852                         small[--smalllen] = 0;
853
854         free(big);
855         return small;
856
857 error_free_small:
858         free(small);
859         return big;
860 }
861
862 static char *shrink_urls(char *text)
863 {
864         int *ranges;
865         int rcount;
866         int i;
867         int inofs = 0;
868         int outofs = 0;
869         const char *const shrink_args[] = {
870                 "bti-shrink-urls",
871                 NULL
872         };
873         int shrink_pid;
874         int shrink_pipe[3];
875         int inlen = strlen(text);
876
877         dbg("before len=%u\n", inlen);
878
879         shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
880         if (shrink_pid < 0)
881                 return text;
882
883         rcount = find_urls(text, &ranges);
884         if (!rcount)
885                 return text;
886
887         for (i = 0; i < rcount; i += 2) {
888                 int url_start = ranges[i];
889                 int url_end = ranges[i+1];
890                 int long_url_len = url_end - url_start;
891                 char *url = strndup(text + url_start, long_url_len);
892                 int short_url_len;
893                 int not_url_len = url_start - inofs;
894
895                 dbg("long  url[%u]: %s\n", long_url_len, url);
896                 url = shrink_one_url(shrink_pipe, url);
897                 short_url_len = url ? strlen(url) : 0;
898                 dbg("short url[%u]: %s\n", short_url_len, url);
899
900                 if (!url || short_url_len >= long_url_len) {
901                         /* The short url ended up being too long
902                          * or unavailable */
903                         if (inofs) {
904                                 strncpy(text + outofs, text + inofs,
905                                                 not_url_len + long_url_len);
906                         }
907                         inofs += not_url_len + long_url_len;
908                         outofs += not_url_len + long_url_len;
909
910                 } else {
911                         /* copy the unmodified block */
912                         strncpy(text + outofs, text + inofs, not_url_len);
913                         inofs += not_url_len;
914                         outofs += not_url_len;
915
916                         /* copy the new url */
917                         strncpy(text + outofs, url, short_url_len);
918                         inofs += long_url_len;
919                         outofs += short_url_len;
920                 }
921
922                 free(url);
923         }
924
925         /* copy the last block after the last match */
926         if (inofs) {
927                 int tail = inlen - inofs;
928                 if (tail) {
929                         strncpy(text + outofs, text + inofs, tail);
930                         outofs += tail;
931                 }
932         }
933
934         free(ranges);
935
936         (void)pcloseRWE(shrink_pid, shrink_pipe);
937
938         text[outofs] = 0;
939         dbg("after len=%u\n", outofs);
940         return text;
941 }
942
943 int main(int argc, char *argv[], char *envp[])
944 {
945         static const struct option options[] = {
946                 { "debug", 0, NULL, 'd' },
947                 { "verbose", 0, NULL, 'V' },
948                 { "account", 1, NULL, 'a' },
949                 { "password", 1, NULL, 'p' },
950                 { "host", 1, NULL, 'H' },
951                 { "proxy", 1, NULL, 'P' },
952                 { "action", 1, NULL, 'A' },
953                 { "user", 1, NULL, 'u' },
954                 { "group", 1, NULL, 'G' },
955                 { "logfile", 1, NULL, 'L' },
956                 { "shrink-urls", 0, NULL, 's' },
957                 { "help", 0, NULL, 'h' },
958                 { "bash", 0, NULL, 'b' },
959                 { "dry-run", 0, NULL, 'n' },
960                 { "page", 1, NULL, 'g' },
961                 { "version", 0, NULL, 'v' },
962                 { }
963         };
964         struct session *session;
965         pid_t child;
966         char *tweet;
967         static char password[80];
968         int retval = 0;
969         int option;
970         char *http_proxy;
971         time_t t;
972         int page_nr;
973
974         debug = 0;
975         verbose = 0;
976         rl_bind_key('\t', rl_insert);
977
978         session = session_alloc();
979         if (!session) {
980                 fprintf(stderr, "no more memory...\n");
981                 return -1;
982         }
983
984         /* get the current time so that we can log it later */
985         time(&t);
986         session->time = strdup(ctime(&t));
987         session->time[strlen(session->time)-1] = 0x00;
988
989         session->homedir = strdup(getenv("HOME"));
990
991         curl_global_init(CURL_GLOBAL_ALL);
992
993         /* Set environment variables first, before reading command line options
994          * or config file values. */
995         http_proxy = getenv("http_proxy");
996         if (http_proxy) {
997                 if (session->proxy)
998                         free(session->proxy);
999                 session->proxy = strdup(http_proxy);
1000                 dbg("http_proxy = %s\n", session->proxy);
1001         }
1002
1003         parse_configfile(session);
1004
1005         while (1) {
1006                 option = getopt_long_only(argc, argv, "dp:P:H:a:A:u:hg:G:snVv",
1007                                           options, NULL);
1008                 if (option == -1)
1009                         break;
1010                 switch (option) {
1011                 case 'd':
1012                         debug = 1;
1013                         break;
1014                 case 'V':
1015                         verbose = 1;
1016                         break;
1017                 case 'a':
1018                         if (session->account)
1019                                 free(session->account);
1020                         session->account = strdup(optarg);
1021                         dbg("account = %s\n", session->account);
1022                         break;
1023                 case 'g':
1024                         page_nr = atoi(optarg);
1025                         dbg("page = %d\n", page_nr);
1026                         session->page = page_nr;
1027                         break;
1028                 case 'p':
1029                         if (session->password)
1030                                 free(session->password);
1031                         session->password = strdup(optarg);
1032                         dbg("password = %s\n", session->password);
1033                         break;
1034                 case 'P':
1035                         if (session->proxy)
1036                                 free(session->proxy);
1037                         session->proxy = strdup(optarg);
1038                         dbg("proxy = %s\n", session->proxy);
1039                         break;
1040                 case 'A':
1041                         if (strcasecmp(optarg, "update") == 0)
1042                                 session->action = ACTION_UPDATE;
1043                         else if (strcasecmp(optarg, "friends") == 0)
1044                                 session->action = ACTION_FRIENDS;
1045                         else if (strcasecmp(optarg, "user") == 0)
1046                                 session->action = ACTION_USER;
1047                         else if (strcasecmp(optarg, "replies") == 0)
1048                                 session->action = ACTION_REPLIES;
1049                         else if (strcasecmp(optarg, "public") == 0)
1050                                 session->action = ACTION_PUBLIC;
1051                         else if (strcasecmp(optarg, "group") == 0)
1052                                 session->action = ACTION_GROUP;
1053                         else
1054                                 session->action = ACTION_UNKNOWN;
1055                         dbg("action = %d\n", session->action);
1056                         break;
1057                 case 'u':
1058                         if (session->user)
1059                                 free(session->user);
1060                         session->user = strdup(optarg);
1061                         dbg("user = %s\n", session->user);
1062                         break;
1063
1064                 case 'G':
1065                         if (session->group)
1066                                 free(session->group);
1067                         session->group = strdup(optarg);
1068                         dbg("group = %s\n", session->group);
1069                         break;
1070                 case 'L':
1071                         if (session->logfile)
1072                                 free(session->logfile);
1073                         session->logfile = strdup(optarg);
1074                         dbg("logfile = %s\n", session->logfile);
1075                         break;
1076                 case 's':
1077                         session->shrink_urls = 1;
1078                         break;
1079                 case 'H':
1080                         if (session->hosturl)
1081                                 free(session->hosturl);
1082                         if (strcasecmp(optarg, "twitter") == 0) {
1083                                 session->host = HOST_TWITTER;
1084                                 session->hosturl = strdup(twitter_host);
1085                         } else if (strcasecmp(optarg, "identica") == 0) {
1086                                 session->host = HOST_IDENTICA;
1087                                 session->hosturl = strdup(identica_host);
1088                         } else {
1089                                 session->host = HOST_CUSTOM;
1090                                 session->hosturl = strdup(optarg);
1091                         }
1092                         dbg("host = %d\n", session->host);
1093                         break;
1094                 case 'b':
1095                         session->bash = 1;
1096                         break;
1097                 case 'h':
1098                         display_help();
1099                         goto exit;
1100                 case 'n':
1101                         session->dry_run = 1;
1102                         break;
1103                 case 'v':
1104                         display_version();
1105                         goto exit;
1106                 default:
1107                         display_help();
1108                         goto exit;
1109                 }
1110         }
1111
1112         /*
1113          * Show the version to make it easier to determine what
1114          * is going on here
1115          */
1116         if (debug) {
1117                 display_version();
1118                 fprintf(stderr, "%s", session->group);
1119         }
1120
1121         if (session->action == ACTION_UNKNOWN) {
1122                 fprintf(stderr, "Unknown action, valid actions are:\n");
1123                 fprintf(stderr, "'update', 'friends', 'public', "
1124                         "'replies', 'group' or 'user'.\n");
1125                 goto exit;
1126         }
1127
1128         if (session->host == HOST_TWITTER && session->action == ACTION_GROUP) {
1129                 fprintf(stderr, "Groups only work in Identi.ca.\n");
1130                 goto exit;
1131         }
1132
1133         if (session->action == ACTION_GROUP && !session->group) {
1134                 fprintf(stdout, "Enter group name: ");
1135                 session->group = readline(NULL);
1136         }
1137
1138         if (!session->account) {
1139                 fprintf(stdout, "Enter twitter account: ");
1140                 session->account = readline(NULL);
1141         }
1142
1143         if (!session->password) {
1144                 read_password(password, sizeof(password));
1145                 session->password = strdup(password);
1146                 free(password);
1147         }
1148
1149         if (session->action == ACTION_UPDATE) {
1150                 if (session->bash)
1151                         tweet = get_string_from_stdin();
1152                 else
1153                         tweet = readline("tweet: ");
1154                 if (!tweet || strlen(tweet) == 0) {
1155                         dbg("no tweet?\n");
1156                         return -1;
1157                 }
1158
1159                 if (session->shrink_urls)
1160                         tweet = shrink_urls(tweet);
1161
1162                 session->tweet = zalloc(strlen(tweet) + 10);
1163                 if (session->bash)
1164                         sprintf(session->tweet, "%c %s", getuid() ? '$' : '#', tweet);
1165                 else
1166                         sprintf(session->tweet, "%s", tweet);
1167
1168                 free(tweet);
1169                 dbg("tweet = %s\n", session->tweet);
1170         }
1171
1172         if (!session->user)
1173                 session->user = strdup(session->account);
1174
1175         if (session->page == 0)
1176                 session->page = 1;
1177         dbg("account = %s\n", session->account);
1178         dbg("password = %s\n", session->password);
1179         dbg("host = %d\n", session->host);
1180         dbg("action = %d\n", session->action);
1181
1182         /* fork ourself so that the main shell can get on
1183          * with it's life as we try to connect and handle everything
1184          */
1185         if (session->bash) {
1186                 child = fork();
1187                 if (child) {
1188                         dbg("child is %d\n", child);
1189                         exit(0);
1190                 }
1191         }
1192
1193         retval = send_request(session);
1194         if (retval && !session->bash)
1195                 fprintf(stderr, "operation failed\n");
1196
1197         log_session(session, retval);
1198 exit:
1199         session_free(session);
1200         return retval;;
1201 }