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