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