2 * Copyright (C) 2008 Greg Kroah-Hartman <greg@kroah.com>
3 * Copyright (C) 2009 Bart Trojanowski <bart@jukie.net>
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.
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.
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.
30 #include <sys/types.h>
32 #include <curl/curl.h>
33 #include <readline/readline.h>
34 #include <libxml/xmlmemory.h>
35 #include <libxml/parser.h>
36 #include <libxml/tree.h>
38 #include "bti_version.h"
41 #define zalloc(size) calloc(size, 1)
43 #define dbg(format, arg...) \
46 printf("%s: " format , __func__ , ## arg); \
82 struct bti_curl_buffer {
88 static void display_help(void)
90 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
91 fprintf(stdout, "Version: " BTI_VERSION "\n");
92 fprintf(stdout, "Usage:\n");
93 fprintf(stdout, " bti [options]\n");
94 fprintf(stdout, "options are:\n");
95 fprintf(stdout, " --account accountname\n");
96 fprintf(stdout, " --password password\n");
97 fprintf(stdout, " --action action\n");
98 fprintf(stdout, " ('update', 'friends', 'public', 'replies' "
100 fprintf(stdout, " --user screenname\n");
101 fprintf(stdout, " --proxy PROXY:PORT\n");
102 fprintf(stdout, " --host HOST\n");
103 fprintf(stdout, " --logfile logfile\n");
104 fprintf(stdout, " --shrink-urls\n");
105 fprintf(stdout, " --bash\n");
106 fprintf(stdout, " --debug\n");
107 fprintf(stdout, " --version\n");
108 fprintf(stdout, " --help\n");
111 static void display_version(void)
113 fprintf(stdout, "bti - version %s\n", BTI_VERSION);
116 static struct session *session_alloc(void)
118 struct session *session;
120 session = zalloc(sizeof(*session));
126 static void session_free(struct session *session)
130 free(session->password);
131 free(session->account);
132 free(session->tweet);
133 free(session->proxy);
135 free(session->homedir);
140 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
142 struct bti_curl_buffer *buffer;
144 buffer = zalloc(sizeof(*buffer));
148 /* start out with a data buffer of 1 byte to
149 * make the buffer fill logic simpler */
150 buffer->data = zalloc(1);
156 buffer->action = action;
160 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
168 static const char *twitter_user_url = "http://twitter.com/statuses/user_timeline/";
169 static const char *twitter_update_url = "https://twitter.com/statuses/update.xml";
170 static const char *twitter_public_url = "http://twitter.com/statuses/public_timeline.xml";
171 static const char *twitter_friends_url = "https://twitter.com/statuses/friends_timeline.xml";
172 static const char *twitter_replies_url = "http://twitter.com/statuses/replies.xml";
174 static const char *identica_user_url = "http://identi.ca/api/statuses/user_timeline/";
175 static const char *identica_update_url = "http://identi.ca/api/statuses/update.xml";
176 static const char *identica_public_url = "http://identi.ca/api/statuses/public_timeline.xml";
177 static const char *identica_friends_url = "http://identi.ca/api/statuses/friends_timeline.xml";
178 static const char *identica_replies_url = "http://identi.ca/api/statuses/replies.xml";
180 static CURL *curl_init(void)
184 curl = curl_easy_init();
186 fprintf(stderr, "Can not init CURL!\n");
189 /* some ssl sanity checks on the connection we are making */
190 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
191 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
195 void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
197 xmlChar *text = NULL;
198 xmlChar *user = NULL;
201 current = current->xmlChildrenNode;
202 while (current != NULL) {
203 if (current->type == XML_ELEMENT_NODE) {
204 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
205 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
206 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
207 userinfo = current->xmlChildrenNode;
208 while (userinfo != NULL) {
209 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
212 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
214 userinfo = userinfo->next;
218 printf("[%s] %s\n", user, text);
225 current = current->next;
231 static void parse_timeline(char *document)
236 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
237 NULL, XML_PARSE_NOERROR);
241 current = xmlDocGetRootElement(doc);
242 if (current == NULL) {
243 fprintf(stderr, "empty document\n");
248 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
249 fprintf(stderr, "unexpected document type\n");
254 current = current->xmlChildrenNode;
255 while (current != NULL) {
256 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
257 parse_statuses(doc, current);
258 current = current->next;
265 size_t curl_callback(void *buffer, size_t size, size_t nmemb, void *userp)
267 struct bti_curl_buffer *curl_buf = userp;
268 size_t buffer_size = size * nmemb;
271 if ((!buffer) || (!buffer_size) || (!curl_buf))
274 /* add to the data we already have */
275 temp = zalloc(curl_buf->length + buffer_size + 1);
279 memcpy(temp, curl_buf->data, curl_buf->length);
280 free(curl_buf->data);
281 curl_buf->data = temp;
282 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
283 curl_buf->length += buffer_size;
284 if (curl_buf->action)
285 parse_timeline(curl_buf->data);
287 dbg("%s\n", curl_buf->data);
292 static int send_request(struct session *session)
294 char user_password[500];
296 /* is there usernames longer than 22 chars? */
298 struct bti_curl_buffer *curl_buf;
301 struct curl_httppost *formpost = NULL;
302 struct curl_httppost *lastptr = NULL;
303 struct curl_slist *slist = NULL;
308 curl_buf = bti_curl_buffer_alloc(session->action);
316 switch (session->action) {
318 snprintf(user_password, sizeof(user_password), "%s:%s",
319 session->account, session->password);
320 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
321 curl_formadd(&formpost, &lastptr,
322 CURLFORM_COPYNAME, "status",
323 CURLFORM_COPYCONTENTS, session->tweet,
326 curl_formadd(&formpost, &lastptr,
327 CURLFORM_COPYNAME, "source",
328 CURLFORM_COPYCONTENTS, "bti",
331 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
332 slist = curl_slist_append(slist, "Expect:");
333 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
334 switch (session->host) {
336 curl_easy_setopt(curl, CURLOPT_URL,
340 curl_easy_setopt(curl, CURLOPT_URL,
341 identica_update_url);
344 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
348 snprintf(user_password, sizeof(user_password), "%s:%s",
349 session->account, session->password);
350 switch (session->host) {
352 curl_easy_setopt(curl, CURLOPT_URL,
353 twitter_friends_url);
356 curl_easy_setopt(curl, CURLOPT_URL,
357 identica_friends_url);
360 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
364 switch (session->host) {
366 sprintf(user_url, "%s%s.xml", twitter_user_url,
368 curl_easy_setopt(curl, CURLOPT_URL, user_url);
371 sprintf(user_url, "%s%s.xml", identica_user_url,
373 curl_easy_setopt(curl, CURLOPT_URL, user_url);
379 snprintf(user_password, sizeof(user_password), "%s:%s",
380 session->account, session->password);
381 switch (session->host) {
383 curl_easy_setopt(curl, CURLOPT_URL,
384 twitter_replies_url);
387 curl_easy_setopt(curl, CURLOPT_URL,
388 identica_replies_url);
391 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
395 switch (session->host) {
397 curl_easy_setopt(curl, CURLOPT_URL,
401 curl_easy_setopt(curl, CURLOPT_URL,
402 identica_public_url);
412 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
415 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
417 dbg("user_password = %s\n", user_password);
418 dbg("data = %s\n", data);
419 dbg("proxy = %s\n", session->proxy);
421 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
422 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
423 if (!session->dry_run) {
424 res = curl_easy_perform(curl);
425 if (res && !session->bash) {
426 fprintf(stderr, "error(%d) trying to perform "
432 curl_easy_cleanup(curl);
433 if (session->action == ACTION_UPDATE)
434 curl_formfree(formpost);
435 bti_curl_buffer_free(curl_buf);
439 static void parse_configfile(struct session *session)
444 char *account = NULL;
445 char *password = NULL;
448 char *logfile = NULL;
454 /* config file is ~/.bti */
455 file = alloca(strlen(session->homedir) + 7);
457 sprintf(file, "%s/.bti", session->homedir);
459 config_file = fopen(file, "r");
461 /* No error if file does not exist or is unreadable. */
462 if (config_file == NULL)
466 ssize_t n = getline(&line, &len, config_file);
469 if (line[n - 1] == '\n')
471 /* Parse file. Format is the usual value pairs:
474 # is a comment character
476 *strchrnul(line, '#') = '\0';
480 /* Ignore blank lines. */
484 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
488 } else if (!strncasecmp(c, "password", 8) &&
492 password = strdup(c);
493 } else if (!strncasecmp(c, "host", 4) &&
498 } else if (!strncasecmp(c, "proxy", 5) &&
503 } else if (!strncasecmp(c, "logfile", 7) &&
508 } else if (!strncasecmp(c, "action", 6) &&
513 } else if (!strncasecmp(c, "user", 4) &&
518 } else if (!strncasecmp(c, "shrink-urls", 11) &&
521 if (!strncasecmp(c, "true", 4) ||
522 !strncasecmp(c, "yes", 3))
525 } while (!feof(config_file));
528 session->password = password;
530 session->account = account;
532 if (strcasecmp(host, "twitter") == 0)
533 session->host = HOST_TWITTER;
534 if (strcasecmp(host, "identica") == 0)
535 session->host = HOST_IDENTICA;
540 free(session->proxy);
541 session->proxy = proxy;
544 session->logfile = logfile;
546 if (strcasecmp(action, "update") == 0)
547 session->action = ACTION_UPDATE;
548 else if (strcasecmp(action, "friends") == 0)
549 session->action = ACTION_FRIENDS;
550 else if (strcasecmp(action, "user") == 0)
551 session->action = ACTION_USER;
552 else if (strcasecmp(action, "replies") == 0)
553 session->action = ACTION_REPLIES;
554 else if (strcasecmp(action, "public") == 0)
555 session->action = ACTION_PUBLIC;
557 session->action = ACTION_UNKNOWN;
561 session->user = user;
562 session->shrink_urls = shrink_urls;
564 /* Free buffer and close file. */
569 static void log_session(struct session *session, int retval)
575 /* Only log something if we have a log file set */
576 if (!session->logfile)
579 filename = alloca(strlen(session->homedir) +
580 strlen(session->logfile) + 3);
582 sprintf(filename, "%s/%s", session->homedir, session->logfile);
584 log_file = fopen(filename, "a+");
585 if (log_file == NULL)
587 switch (session->host) {
599 switch (session->action) {
602 fprintf(log_file, "%s: host=%s tweet failed\n",
603 session->time, host);
605 fprintf(log_file, "%s: host=%s tweet=%s\n",
606 session->time, host, session->tweet);
609 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
610 session->time, host);
613 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
614 session->time, host, session->user);
617 fprintf(log_file, "%s: host=%s retrieving replies\n",
618 session->time, host);
621 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
622 session->time, host);
631 static char *get_string_from_stdin(void)
636 string = zalloc(1000);
640 if (!fgets(string, 999, stdin))
642 temp = strchr(string, '\n');
647 static int find_urls(const char *tweet, int **pranges)
650 * magic obtained from
651 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
653 static const char *re_magic =
654 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
655 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
656 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
660 int ovector[10] = {0,};
661 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
662 int startoffset, tweetlen;
666 int *ranges = malloc(sizeof(int) * rbound);
668 re = pcre_compile(re_magic,
669 PCRE_NO_AUTO_CAPTURE,
670 &errptr, &erroffset, NULL);
672 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
676 tweetlen = strlen(tweet);
677 for (startoffset = 0; startoffset < tweetlen; ) {
679 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
681 if (rc == PCRE_ERROR_NOMATCH)
685 fprintf(stderr, "pcre_exec @%u: %s\n",
690 for (i = 0; i < rc; i += 2) {
691 if ((rcount+2) == rbound) {
693 ranges = realloc(ranges, sizeof(int) * rbound);
696 ranges[rcount++] = ovector[i];
697 ranges[rcount++] = ovector[i+1];
700 startoffset = ovector[1];
710 * bidirectional popen() call
712 * @param rwepipe - int array of size three
713 * @param exe - program to run
714 * @param argv - argument list
715 * @return pid or -1 on error
717 * The caller passes in an array of three integers (rwepipe), on successful
718 * execution it can then write to element 0 (stdin of exe), and read from
719 * element 1 (stdout) and 2 (stderr).
721 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
751 } else if (pid == 0) {
763 execvp(exe, (char **)argv);
783 static int pcloseRWE(int pid, int *rwepipe)
789 rc = waitpid(pid, &status, 0);
793 static char *shrink_one_url(int *rwepipe, char *big)
795 int biglen = strlen(big);
800 rc = dprintf(rwepipe[0], "%s\n", big);
804 smalllen = biglen + 128;
805 small = malloc(smalllen);
809 rc = read(rwepipe[1], small, smalllen);
810 if (rc < 0 || rc > biglen)
811 goto error_free_small;
813 if (strncmp(small, "http://", 7))
814 goto error_free_small;
817 while (smalllen && isspace(small[smalllen-1]))
818 small[--smalllen] = 0;
828 static char *shrink_urls(char *text)
835 const char *const shrink_args[] = {
841 int inlen = strlen(text);
843 dbg("before len=%u\n", inlen);
845 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
849 rcount = find_urls(text, &ranges);
853 for (i = 0; i < rcount; i += 2) {
854 int url_start = ranges[i];
855 int url_end = ranges[i+1];
856 int long_url_len = url_end - url_start;
857 char *url = strndup(text + url_start, long_url_len);
859 int not_url_len = url_start - inofs;
861 dbg("long url[%u]: %s\n", long_url_len, url);
862 url = shrink_one_url(shrink_pipe, url);
863 short_url_len = url ? strlen(url) : 0;
864 dbg("short url[%u]: %s\n", short_url_len, url);
866 if (!url || short_url_len >= long_url_len) {
867 /* The short url ended up being too long
870 strncpy(text + outofs, text + inofs,
871 not_url_len + long_url_len);
873 inofs += not_url_len + long_url_len;
874 outofs += not_url_len + long_url_len;
877 /* copy the unmodified block */
878 strncpy(text + outofs, text + inofs, not_url_len);
879 inofs += not_url_len;
880 outofs += not_url_len;
882 /* copy the new url */
883 strncpy(text + outofs, url, short_url_len);
884 inofs += long_url_len;
885 outofs += short_url_len;
891 /* copy the last block after the last match */
893 int tail = inlen - inofs;
895 strncpy(text + outofs, text + inofs, tail);
902 (void)pcloseRWE(shrink_pid, shrink_pipe);
905 dbg("after len=%u\n", outofs);
909 int main(int argc, char *argv[], char *envp[])
911 static const struct option options[] = {
912 { "debug", 0, NULL, 'd' },
913 { "account", 1, NULL, 'a' },
914 { "password", 1, NULL, 'p' },
915 { "host", 1, NULL, 'H' },
916 { "proxy", 1, NULL, 'P' },
917 { "action", 1, NULL, 'A' },
918 { "user", 1, NULL, 'u' },
919 { "logfile", 1, NULL, 'L' },
920 { "shrink-urls", 0, NULL, 's' },
921 { "help", 0, NULL, 'h' },
922 { "bash", 0, NULL, 'b' },
923 { "dry-run", 0, NULL, 'n' },
924 { "version", 0, NULL, 'v' },
927 struct session *session;
936 rl_bind_key('\t', rl_insert);
938 session = session_alloc();
940 fprintf(stderr, "no more memory...\n");
944 /* get the current time so that we can log it later */
946 session->time = strdup(ctime(&t));
947 session->time[strlen(session->time)-1] = 0x00;
949 session->homedir = strdup(getenv("HOME"));
951 curl_global_init(CURL_GLOBAL_ALL);
953 /* Set environment variables first, before reading command line options
954 * or config file values. */
955 http_proxy = getenv("http_proxy");
958 free(session->proxy);
959 session->proxy = strdup(http_proxy);
960 dbg("http_proxy = %s\n", session->proxy);
963 parse_configfile(session);
966 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:A:u:h",
975 if (session->account)
976 free(session->account);
977 session->account = strdup(optarg);
978 dbg("account = %s\n", session->account);
981 if (session->password)
982 free(session->password);
983 session->password = strdup(optarg);
984 dbg("password = %s\n", session->password);
988 free(session->proxy);
989 session->proxy = strdup(optarg);
990 dbg("proxy = %s\n", session->proxy);
993 if (strcasecmp(optarg, "update") == 0)
994 session->action = ACTION_UPDATE;
995 else if (strcasecmp(optarg, "friends") == 0)
996 session->action = ACTION_FRIENDS;
997 else if (strcasecmp(optarg, "user") == 0)
998 session->action = ACTION_USER;
999 else if (strcasecmp(optarg, "replies") == 0)
1000 session->action = ACTION_REPLIES;
1001 else if (strcasecmp(optarg, "public") == 0)
1002 session->action = ACTION_PUBLIC;
1004 session->action = ACTION_UNKNOWN;
1005 dbg("action = %d\n", session->action);
1009 free(session->user);
1010 session->user = strdup(optarg);
1011 dbg("user = %s\n", session->user);
1014 if (session->logfile)
1015 free(session->logfile);
1016 session->logfile = strdup(optarg);
1017 dbg("logfile = %s\n", session->logfile);
1020 session->shrink_urls = 1;
1023 if (strcasecmp(optarg, "twitter") == 0)
1024 session->host = HOST_TWITTER;
1025 if (strcasecmp(optarg, "identica") == 0)
1026 session->host = HOST_IDENTICA;
1027 dbg("host = %d\n", session->host);
1036 session->dry_run = 1;
1047 if (session->action == ACTION_UNKNOWN) {
1048 fprintf(stderr, "Unknown action, valid actions are:\n");
1049 fprintf(stderr, "'update', 'friends', 'public', "
1050 "'replies' or 'user'.\n");
1054 if (!session->account) {
1055 fprintf(stdout, "Enter twitter account: ");
1056 session->account = readline(NULL);
1059 if (!session->password) {
1060 fprintf(stdout, "Enter twitter password: ");
1061 session->password = readline(NULL);
1064 if (session->action == ACTION_UPDATE) {
1066 tweet = get_string_from_stdin();
1068 tweet = readline("tweet: ");
1069 if (!tweet || strlen(tweet) == 0) {
1074 if (session->shrink_urls)
1075 tweet = shrink_urls(tweet);
1077 session->tweet = zalloc(strlen(tweet) + 10);
1079 sprintf(session->tweet, "$ %s", tweet);
1081 sprintf(session->tweet, "%s", tweet);
1084 dbg("tweet = %s\n", session->tweet);
1088 session->user = strdup(session->account);
1090 dbg("account = %s\n", session->account);
1091 dbg("password = %s\n", session->password);
1092 dbg("host = %d\n", session->host);
1093 dbg("action = %d\n", session->action);
1095 /* fork ourself so that the main shell can get on
1096 * with it's life as we try to connect and handle everything
1098 if (session->bash) {
1101 dbg("child is %d\n", child);
1106 retval = send_request(session);
1107 if (retval && !session->bash)
1108 fprintf(stderr, "operation failed\n");
1110 log_session(session, retval);
1112 session_free(session);