]> ToastFreeware Gitweb - gregoa/bti.git/blob - bti.c
Name correct hosts in prompts.
[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         char *hostname;
85         int bash;
86         int shrink_urls;
87         int dry_run;
88         int page;
89         enum host host;
90         enum action action;
91 };
92
93 struct bti_curl_buffer {
94         char *data;
95         enum action action;
96         int length;
97 };
98
99 static void display_help(void)
100 {
101         fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
102         fprintf(stdout, "Version: " VERSION "\n");
103         fprintf(stdout, "Usage:\n");
104         fprintf(stdout, "  bti [options]\n");
105         fprintf(stdout, "options are:\n");
106         fprintf(stdout, "  --account accountname\n");
107         fprintf(stdout, "  --password password\n");
108         fprintf(stdout, "  --action action\n");
109         fprintf(stdout, "    ('update', 'friends', 'public', 'replies', "
110                 "'group' or 'user')\n");
111         fprintf(stdout, "  --user screenname\n");
112         fprintf(stdout, "  --group groupname\n");
113         fprintf(stdout, "  --proxy PROXY:PORT\n");
114         fprintf(stdout, "  --host HOST\n");
115         fprintf(stdout, "  --logfile logfile\n");
116         fprintf(stdout, "  --shrink-urls\n");
117         fprintf(stdout, "  --page PAGENUMBER\n");
118         fprintf(stdout, "  --bash\n");
119         fprintf(stdout, "  --debug\n");
120         fprintf(stdout, "  --verbose\n");
121         fprintf(stdout, "  --dry-run\n");
122         fprintf(stdout, "  --version\n");
123         fprintf(stdout, "  --help\n");
124 }
125
126 static void display_version(void)
127 {
128         fprintf(stdout, "bti - version %s\n", VERSION);
129 }
130
131 static struct session *session_alloc(void)
132 {
133         struct session *session;
134
135         session = zalloc(sizeof(*session));
136         if (!session)
137                 return NULL;
138         return session;
139 }
140
141 static void session_free(struct session *session)
142 {
143         if (!session)
144                 return;
145         free(session->password);
146         free(session->account);
147         free(session->tweet);
148         free(session->proxy);
149         free(session->time);
150         free(session->homedir);
151         free(session->user);
152         free(session->group);
153         free(session->hosturl);
154         free(session->hostname);
155         free(session);
156 }
157
158 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
159 {
160         struct bti_curl_buffer *buffer;
161
162         buffer = zalloc(sizeof(*buffer));
163         if (!buffer)
164                 return NULL;
165
166         /* start out with a data buffer of 1 byte to
167          * make the buffer fill logic simpler */
168         buffer->data = zalloc(1);
169         if (!buffer->data) {
170                 free(buffer);
171                 return NULL;
172         }
173         buffer->length = 0;
174         buffer->action = action;
175         return buffer;
176 }
177
178 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
179 {
180         if (!buffer)
181                 return;
182         free(buffer->data);
183         free(buffer);
184 }
185
186 static const char *twitter_host  = "https://twitter.com/statuses";
187 static const char *identica_host = "https://identi.ca/api/statuses";
188 static const char *twitter_name  = "twitter";
189 static const char *identica_name = "identi.ca";
190
191 static const char *user_uri    = "/user_timeline/";
192 static const char *update_uri  = "/update.xml";
193 static const char *public_uri  = "/public_timeline.xml";
194 static const char *friends_uri = "/friends_timeline.xml";
195 static const char *replies_uri = "/replies.xml";
196 static const char *group_uri = "/../laconica/groups/timeline/";
197
198 static CURL *curl_init(void)
199 {
200         CURL *curl;
201
202         curl = curl_easy_init();
203         if (!curl) {
204                 fprintf(stderr, "Can not init CURL!\n");
205                 return NULL;
206         }
207         /* some ssl sanity checks on the connection we are making */
208         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
209         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
210         return curl;
211 }
212
213 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
214 {
215         xmlChar *text = NULL;
216         xmlChar *user = NULL;
217         xmlChar *created = NULL;
218         xmlNodePtr userinfo;
219
220         current = current->xmlChildrenNode;
221         while (current != NULL) {
222                 if (current->type == XML_ELEMENT_NODE) {
223                         if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
224                                 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
225                         if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
226                                 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
227                         if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
228                                 userinfo = current->xmlChildrenNode;
229                                 while (userinfo != NULL) {
230                                         if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
231                                                 if (user)
232                                                         xmlFree(user);
233                                                 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
234                                         }
235                                         userinfo = userinfo->next;
236                                 }
237                         }
238
239                         if (user && text && created) {
240                                 if (verbose)
241                                         printf("[%s] (%.16s) %s\n",
242                                                 user, created, text);
243                                 else
244                                         printf("[%s] %s\n",
245                                                 user, text);
246                                 xmlFree(user);
247                                 xmlFree(text);
248                                 xmlFree(created);
249                                 user = NULL;
250                                 text = NULL;
251                                 created = NULL;
252                         }
253                 }
254                 current = current->next;
255         }
256
257         return;
258 }
259
260 static void parse_timeline(char *document)
261 {
262         xmlDocPtr doc;
263         xmlNodePtr current;
264
265         doc = xmlReadMemory(document, strlen(document), "timeline.xml",
266                             NULL, XML_PARSE_NOERROR);
267         if (doc == NULL)
268                 return;
269
270         current = xmlDocGetRootElement(doc);
271         if (current == NULL) {
272                 fprintf(stderr, "empty document\n");
273                 xmlFreeDoc(doc);
274                 return;
275         }
276
277         if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
278                 fprintf(stderr, "unexpected document type\n");
279                 xmlFreeDoc(doc);
280                 return;
281         }
282
283         current = current->xmlChildrenNode;
284         while (current != NULL) {
285                 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
286                         parse_statuses(doc, current);
287                 current = current->next;
288         }
289         xmlFreeDoc(doc);
290
291         return;
292 }
293
294 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
295                             void *userp)
296 {
297         struct bti_curl_buffer *curl_buf = userp;
298         size_t buffer_size = size * nmemb;
299         char *temp;
300
301         if ((!buffer) || (!buffer_size) || (!curl_buf))
302                 return -EINVAL;
303
304         /* add to the data we already have */
305         temp = zalloc(curl_buf->length + buffer_size + 1);
306         if (!temp)
307                 return -ENOMEM;
308
309         memcpy(temp, curl_buf->data, curl_buf->length);
310         free(curl_buf->data);
311         curl_buf->data = temp;
312         memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
313         curl_buf->length += buffer_size;
314         if (curl_buf->action)
315                 parse_timeline(curl_buf->data);
316
317         dbg("%s\n", curl_buf->data);
318
319         return buffer_size;
320 }
321
322 static int send_request(struct session *session)
323 {
324         char endpoint[100];
325         char user_password[500];
326         char data[500];
327         struct bti_curl_buffer *curl_buf;
328         CURL *curl = NULL;
329         CURLcode res;
330         struct curl_httppost *formpost = NULL;
331         struct curl_httppost *lastptr = NULL;
332         struct curl_slist *slist = NULL;
333
334         if (!session)
335                 return -EINVAL;
336
337         curl_buf = bti_curl_buffer_alloc(session->action);
338         if (!curl_buf)
339                 return -ENOMEM;
340
341         curl = curl_init();
342         if (!curl)
343                 return -EINVAL;
344
345         switch (session->action) {
346         case ACTION_UPDATE:
347                 snprintf(user_password, sizeof(user_password), "%s:%s",
348                          session->account, session->password);
349                 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
350                 curl_formadd(&formpost, &lastptr,
351                              CURLFORM_COPYNAME, "status",
352                              CURLFORM_COPYCONTENTS, session->tweet,
353                              CURLFORM_END);
354
355                 curl_formadd(&formpost, &lastptr,
356                              CURLFORM_COPYNAME, "source",
357                              CURLFORM_COPYCONTENTS, "bti",
358                              CURLFORM_END);
359
360                 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
361                 slist = curl_slist_append(slist, "Expect:");
362                 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
363
364                 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
365                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
366                 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
367
368                 break;
369         case ACTION_FRIENDS:
370                 snprintf(user_password, sizeof(user_password), "%s:%s",
371                          session->account, session->password);
372                 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
373                         friends_uri, session->page);
374                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
375                 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
376
377                 break;
378         case ACTION_USER:
379                 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
380                         user_uri, session->user, session->page);
381                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
382
383                 break;
384         case ACTION_REPLIES:
385                 snprintf(user_password, sizeof(user_password), "%s:%s",
386                          session->account, session->password);
387                 sprintf(endpoint, "%s%s?page=%d", session->hosturl, replies_uri,
388                         session->page);
389                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
390                 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
391
392                 break;
393         case ACTION_PUBLIC:
394                 sprintf(endpoint, "%s%s?page=%d", session->hosturl, public_uri,
395                         session->page);
396                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
397
398                 break;
399         case ACTION_GROUP:
400                 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
401                                 group_uri, session->group, session->page);
402                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
403
404                 break;
405         default:
406                 break;
407         }
408
409         if (session->proxy)
410                 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
411
412         if (debug)
413                 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
414
415         dbg("user_password = %s\n", user_password);
416         dbg("data = %s\n", data);
417         dbg("proxy = %s\n", session->proxy);
418
419         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
420         curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
421         if (!session->dry_run) {
422                 res = curl_easy_perform(curl);
423                 if (res && !session->bash) {
424                         fprintf(stderr, "error(%d) trying to perform "
425                                 "operation\n", res);
426                         return -EINVAL;
427                 }
428         }
429
430         curl_easy_cleanup(curl);
431         if (session->action == ACTION_UPDATE)
432                 curl_formfree(formpost);
433         bti_curl_buffer_free(curl_buf);
434         return 0;
435 }
436
437 static void parse_configfile(struct session *session)
438 {
439         FILE *config_file;
440         char *line = NULL;
441         size_t len = 0;
442         char *account = NULL;
443         char *password = NULL;
444         char *host = NULL;
445         char *proxy = NULL;
446         char *logfile = NULL;
447         char *action = NULL;
448         char *user = NULL;
449         char *file;
450         int shrink_urls = 0;
451
452         /* config file is ~/.bti  */
453         file = alloca(strlen(session->homedir) + 7);
454
455         sprintf(file, "%s/.bti", session->homedir);
456
457         config_file = fopen(file, "r");
458
459         /* No error if file does not exist or is unreadable.  */
460         if (config_file == NULL)
461                 return;
462
463         do {
464                 ssize_t n = getline(&line, &len, config_file);
465                 if (n < 0)
466                         break;
467                 if (line[n - 1] == '\n')
468                         line[n - 1] = '\0';
469                 /* Parse file.  Format is the usual value pairs:
470                    account=name
471                    passwort=value
472                    # is a comment character
473                 */
474                 *strchrnul(line, '#') = '\0';
475                 char *c = line;
476                 while (isspace(*c))
477                         c++;
478                 /* Ignore blank lines.  */
479                 if (c[0] == '\0')
480                         continue;
481
482                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
483                         c += 8;
484                         if (c[0] != '\0')
485                                 account = strdup(c);
486                 } else if (!strncasecmp(c, "password", 8) &&
487                            (c[8] == '=')) {
488                         c += 9;
489                         if (c[0] != '\0')
490                                 password = strdup(c);
491                 } else if (!strncasecmp(c, "host", 4) &&
492                            (c[4] == '=')) {
493                         c += 5;
494                         if (c[0] != '\0')
495                                 host = strdup(c);
496                 } else if (!strncasecmp(c, "proxy", 5) &&
497                            (c[5] == '=')) {
498                         c += 6;
499                         if (c[0] != '\0')
500                                 proxy = strdup(c);
501                 } else if (!strncasecmp(c, "logfile", 7) &&
502                            (c[7] == '=')) {
503                         c += 8;
504                         if (c[0] != '\0')
505                                 logfile = strdup(c);
506                 } else if (!strncasecmp(c, "action", 6) &&
507                            (c[6] == '=')) {
508                         c += 7;
509                         if (c[0] != '\0')
510                                 action = strdup(c);
511                 } else if (!strncasecmp(c, "user", 4) &&
512                                 (c[4] == '=')) {
513                         c += 5;
514                         if (c[0] != '\0')
515                                 user = strdup(c);
516                 } else if (!strncasecmp(c, "shrink-urls", 11) &&
517                                 (c[11] == '=')) {
518                         c += 12;
519                         if (!strncasecmp(c, "true", 4) ||
520                                         !strncasecmp(c, "yes", 3))
521                                 shrink_urls = 1;
522                 } else if (!strncasecmp(c, "verbose", 7) &&
523                                 (c[7] == '=')) {
524                         c += 8;
525                         if (!strncasecmp(c, "true", 4) ||
526                                         !strncasecmp(c, "yes", 3))
527                                 verbose = 1;
528                 }
529         } while (!feof(config_file));
530
531         if (password)
532                 session->password = password;
533         if (account)
534                 session->account = account;
535         if (host) {
536                 if (strcasecmp(host, "twitter") == 0) {
537                         session->host = HOST_TWITTER;
538                         session->hosturl = strdup(twitter_host);
539                         session->hostname = strdup(twitter_name);
540                 } else if (strcasecmp(host, "identica") == 0) {
541                         session->host = HOST_IDENTICA;
542                         session->hosturl = strdup(identica_host);
543                         session->hostname = strdup(identica_name);
544                 } else {
545                         session->host = HOST_CUSTOM;
546                         session->hosturl = strdup(host);
547                         session->hostname = strdup(host);
548                 }
549                 free(host);
550         }
551         if (proxy) {
552                 if (session->proxy)
553                         free(session->proxy);
554                 session->proxy = proxy;
555         }
556         if (logfile)
557                 session->logfile = logfile;
558         if (action) {
559                 if (strcasecmp(action, "update") == 0)
560                         session->action = ACTION_UPDATE;
561                 else if (strcasecmp(action, "friends") == 0)
562                         session->action = ACTION_FRIENDS;
563                 else if (strcasecmp(action, "user") == 0)
564                         session->action = ACTION_USER;
565                 else if (strcasecmp(action, "replies") == 0)
566                         session->action = ACTION_REPLIES;
567                 else if (strcasecmp(action, "public") == 0)
568                         session->action = ACTION_PUBLIC;
569                 else if (strcasecmp(action, "group") == 0)
570                         session->action = ACTION_GROUP;
571                 else
572                         session->action = ACTION_UNKNOWN;
573                 free(action);
574         }
575         if (user)
576                 session->user = user;
577         session->shrink_urls = shrink_urls;
578
579         /* Free buffer and close file.  */
580         free(line);
581         fclose(config_file);
582 }
583
584 static void log_session(struct session *session, int retval)
585 {
586         FILE *log_file;
587         char *filename;
588
589         /* Only log something if we have a log file set */
590         if (!session->logfile)
591                 return;
592
593         filename = alloca(strlen(session->homedir) +
594                           strlen(session->logfile) + 3);
595
596         sprintf(filename, "%s/%s", session->homedir, session->logfile);
597
598         log_file = fopen(filename, "a+");
599         if (log_file == NULL)
600                 return;
601
602         switch (session->action) {
603         case ACTION_UPDATE:
604                 if (retval)
605                         fprintf(log_file, "%s: host=%s tweet failed\n",
606                                 session->time, session->hostname);
607                 else
608                         fprintf(log_file, "%s: host=%s tweet=%s\n",
609                                 session->time, session->hostname, session->tweet);
610                 break;
611         case ACTION_FRIENDS:
612                 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
613                         session->time, session->hostname);
614                 break;
615         case ACTION_USER:
616                 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
617                         session->time, session->hostname, session->user);
618                 break;
619         case ACTION_REPLIES:
620                 fprintf(log_file, "%s: host=%s retrieving replies\n",
621                         session->time, session->hostname);
622                 break;
623         case ACTION_PUBLIC:
624                 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
625                         session->time, session->hostname);
626                 break;
627         case ACTION_GROUP:
628                 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
629                         session->time, session->hostname);
630                 break;
631         default:
632                 break;
633         }
634
635         fclose(log_file);
636 }
637
638 static char *get_string_from_stdin(void)
639 {
640         char *temp;
641         char *string;
642
643         string = zalloc(1000);
644         if (!string)
645                 return NULL;
646
647         if (!fgets(string, 999, stdin))
648                 return NULL;
649         temp = strchr(string, '\n');
650         *temp = '\0';
651         return string;
652 }
653
654 static void read_password(char *buf, size_t len, char *host)
655 {
656         char pwd[80];
657         int retval;
658         struct termios old;
659         struct termios tp;
660
661         tcgetattr(0, &tp);
662         old = tp;
663
664         tp.c_lflag &= (~ECHO);
665         tcsetattr(0, TCSANOW, &tp);
666
667         fprintf(stdout, "Enter password for %s: ", host);
668         fflush(stdout);
669         tcflow(0, TCOOFF);
670         retval = scanf("%79s", pwd);
671         tcflow(0, TCOON);
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 (session->hostname)
1082                                 free(session->hostname);
1083                         if (strcasecmp(optarg, "twitter") == 0) {
1084                                 session->host = HOST_TWITTER;
1085                                 session->hosturl = strdup(twitter_host);
1086                                 session->hostname = strdup(twitter_name);
1087                         } else if (strcasecmp(optarg, "identica") == 0) {
1088                                 session->host = HOST_IDENTICA;
1089                                 session->hosturl = strdup(identica_host);
1090                                 session->hostname = strdup(identica_name);
1091                         } else {
1092                                 session->host = HOST_CUSTOM;
1093                                 session->hosturl = strdup(optarg);
1094                                 session->hostname = strdup(optarg);
1095                         }
1096                         dbg("host = %d\n", session->host);
1097                         break;
1098                 case 'b':
1099                         session->bash = 1;
1100                         break;
1101                 case 'h':
1102                         display_help();
1103                         goto exit;
1104                 case 'n':
1105                         session->dry_run = 1;
1106                         break;
1107                 case 'v':
1108                         display_version();
1109                         goto exit;
1110                 default:
1111                         display_help();
1112                         goto exit;
1113                 }
1114         }
1115
1116         /*
1117          * Show the version to make it easier to determine what
1118          * is going on here
1119          */
1120         if (debug)
1121                 display_version();
1122
1123         if (session->action == ACTION_UNKNOWN) {
1124                 fprintf(stderr, "Unknown action, valid actions are:\n");
1125                 fprintf(stderr, "'update', 'friends', 'public', "
1126                         "'replies', 'group' or 'user'.\n");
1127                 goto exit;
1128         }
1129
1130         if (!session->host) {
1131                 fprintf(stderr, "You need to provide a host either in ~/.bti or with --host.\n");
1132                 goto exit;
1133         }
1134
1135         if (session->host == HOST_TWITTER && session->action == ACTION_GROUP) {
1136                 fprintf(stderr, "Groups only work in Identi.ca.\n");
1137                 goto exit;
1138         }
1139
1140         if (session->action == ACTION_GROUP && !session->group) {
1141                 fprintf(stdout, "Enter group name: ");
1142                 session->group = readline(NULL);
1143         }
1144
1145         if (!session->account) {
1146                 fprintf(stdout, "Enter account for %s: ", session->hostname);
1147                 session->account = readline(NULL);
1148         }
1149
1150         if (!session->password) {
1151                 read_password(password, sizeof(password), session->hostname);
1152                 session->password = strdup(password);
1153         }
1154
1155         if (session->action == ACTION_UPDATE) {
1156                 if (session->bash)
1157                         tweet = get_string_from_stdin();
1158                 else
1159                         tweet = readline("tweet: ");
1160                 if (!tweet || strlen(tweet) == 0) {
1161                         dbg("no tweet?\n");
1162                         return -1;
1163                 }
1164
1165                 if (session->shrink_urls)
1166                         tweet = shrink_urls(tweet);
1167
1168                 session->tweet = zalloc(strlen(tweet) + 10);
1169                 if (session->bash)
1170                         sprintf(session->tweet, "%c %s",
1171                                 getuid() ? '$' : '#', tweet);
1172                 else
1173                         sprintf(session->tweet, "%s", tweet);
1174
1175                 free(tweet);
1176                 dbg("tweet = %s\n", session->tweet);
1177         }
1178
1179         if (!session->user)
1180                 session->user = strdup(session->account);
1181
1182         if (session->page == 0)
1183                 session->page = 1;
1184         dbg("account = %s\n", session->account);
1185         dbg("password = %s\n", session->password);
1186         dbg("host = %d\n", session->host);
1187         dbg("action = %d\n", session->action);
1188
1189         /* fork ourself so that the main shell can get on
1190          * with it's life as we try to connect and handle everything
1191          */
1192         if (session->bash) {
1193                 child = fork();
1194                 if (child) {
1195                         dbg("child is %d\n", child);
1196                         exit(0);
1197                 }
1198         }
1199
1200         retval = send_request(session);
1201         if (retval && !session->bash)
1202                 fprintf(stderr, "operation failed\n");
1203
1204         log_session(session, retval);
1205 exit:
1206         session_free(session);
1207         return retval;;
1208 }