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