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 fprintf(stdout, "bti: %s: " format , __func__ , \
84 struct bti_curl_buffer {
90 static void display_help(void)
92 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
93 fprintf(stdout, "Version: " BTI_VERSION "\n");
94 fprintf(stdout, "Usage:\n");
95 fprintf(stdout, " bti [options]\n");
96 fprintf(stdout, "options are:\n");
97 fprintf(stdout, " --account accountname\n");
98 fprintf(stdout, " --password password\n");
99 fprintf(stdout, " --action action\n");
100 fprintf(stdout, " ('update', 'friends', 'public', 'replies' "
102 fprintf(stdout, " --user screenname\n");
103 fprintf(stdout, " --proxy PROXY:PORT\n");
104 fprintf(stdout, " --host HOST\n");
105 fprintf(stdout, " --logfile logfile\n");
106 fprintf(stdout, " --shrink-urls\n");
107 fprintf(stdout, " --page PAGENUMBER\n");
108 fprintf(stdout, " --bash\n");
109 fprintf(stdout, " --debug\n");
110 fprintf(stdout, " --dry-run\n");
111 fprintf(stdout, " --version\n");
112 fprintf(stdout, " --help\n");
115 static void display_version(void)
117 fprintf(stdout, "bti - version %s\n", BTI_VERSION);
120 static struct session *session_alloc(void)
122 struct session *session;
124 session = zalloc(sizeof(*session));
130 static void session_free(struct session *session)
134 free(session->password);
135 free(session->account);
136 free(session->tweet);
137 free(session->proxy);
139 free(session->homedir);
144 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
146 struct bti_curl_buffer *buffer;
148 buffer = zalloc(sizeof(*buffer));
152 /* start out with a data buffer of 1 byte to
153 * make the buffer fill logic simpler */
154 buffer->data = zalloc(1);
160 buffer->action = action;
164 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
172 static const char *twitter_user_url = "http://twitter.com/statuses/user_timeline/";
173 static const char *twitter_update_url = "https://twitter.com/statuses/update.xml";
174 static const char *twitter_public_url = "http://twitter.com/statuses/public_timeline.xml";
175 static const char *twitter_friends_url = "https://twitter.com/statuses/friends_timeline.xml";
176 static const char *twitter_replies_url = "http://twitter.com/statuses/replies.xml";
178 static const char *identica_user_url = "http://identi.ca/api/statuses/user_timeline/";
179 static const char *identica_update_url = "http://identi.ca/api/statuses/update.xml";
180 static const char *identica_public_url = "http://identi.ca/api/statuses/public_timeline.xml";
181 static const char *identica_friends_url = "http://identi.ca/api/statuses/friends_timeline.xml";
182 static const char *identica_replies_url = "http://identi.ca/api/statuses/replies.xml";
184 static CURL *curl_init(void)
188 curl = curl_easy_init();
190 fprintf(stderr, "Can not init CURL!\n");
193 /* some ssl sanity checks on the connection we are making */
194 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
195 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
199 void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
201 xmlChar *text = NULL;
202 xmlChar *user = NULL;
205 current = current->xmlChildrenNode;
206 while (current != NULL) {
207 if (current->type == XML_ELEMENT_NODE) {
208 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
209 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
210 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
211 userinfo = current->xmlChildrenNode;
212 while (userinfo != NULL) {
213 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
216 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
218 userinfo = userinfo->next;
222 printf("[%s] %s\n", user, text);
229 current = current->next;
235 static void parse_timeline(char *document)
240 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
241 NULL, XML_PARSE_NOERROR);
245 current = xmlDocGetRootElement(doc);
246 if (current == NULL) {
247 fprintf(stderr, "empty document\n");
252 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
253 fprintf(stderr, "unexpected document type\n");
258 current = current->xmlChildrenNode;
259 while (current != NULL) {
260 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
261 parse_statuses(doc, current);
262 current = current->next;
269 size_t curl_callback(void *buffer, size_t size, size_t nmemb, void *userp)
271 struct bti_curl_buffer *curl_buf = userp;
272 size_t buffer_size = size * nmemb;
275 if ((!buffer) || (!buffer_size) || (!curl_buf))
278 /* add to the data we already have */
279 temp = zalloc(curl_buf->length + buffer_size + 1);
283 memcpy(temp, curl_buf->data, curl_buf->length);
284 free(curl_buf->data);
285 curl_buf->data = temp;
286 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
287 curl_buf->length += buffer_size;
288 if (curl_buf->action)
289 parse_timeline(curl_buf->data);
291 dbg("%s\n", curl_buf->data);
296 static int send_request(struct session *session)
298 char user_password[500];
300 /* is there usernames longer than 22 chars? */
302 struct bti_curl_buffer *curl_buf;
305 struct curl_httppost *formpost = NULL;
306 struct curl_httppost *lastptr = NULL;
307 struct curl_slist *slist = NULL;
312 curl_buf = bti_curl_buffer_alloc(session->action);
320 switch (session->action) {
322 snprintf(user_password, sizeof(user_password), "%s:%s",
323 session->account, session->password);
324 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
325 curl_formadd(&formpost, &lastptr,
326 CURLFORM_COPYNAME, "status",
327 CURLFORM_COPYCONTENTS, session->tweet,
330 curl_formadd(&formpost, &lastptr,
331 CURLFORM_COPYNAME, "source",
332 CURLFORM_COPYCONTENTS, "bti",
335 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
336 slist = curl_slist_append(slist, "Expect:");
337 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
338 switch (session->host) {
340 curl_easy_setopt(curl, CURLOPT_URL,
344 curl_easy_setopt(curl, CURLOPT_URL,
345 identica_update_url);
348 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
352 snprintf(user_password, sizeof(user_password), "%s:%s",
353 session->account, session->password);
354 switch (session->host) {
356 sprintf(user_url, "%s?page=%d", twitter_friends_url, session->page);
357 curl_easy_setopt(curl, CURLOPT_URL, user_url);
360 sprintf(user_url, "%s?page=%d", identica_friends_url, session->page);
361 curl_easy_setopt(curl, CURLOPT_URL, user_url);
364 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
368 switch (session->host) {
370 sprintf(user_url, "%s%s.xml?page=%d", twitter_user_url, session->user, session->page);
371 curl_easy_setopt(curl, CURLOPT_URL, user_url);
374 sprintf(user_url, "%s%s.xml?page=%d", identica_user_url, session->user, session->page);
375 curl_easy_setopt(curl, CURLOPT_URL, user_url);
381 snprintf(user_password, sizeof(user_password), "%s:%s",
382 session->account, session->password);
383 switch (session->host) {
385 sprintf(user_url, "%s?page=%d", twitter_replies_url, session->page);
386 curl_easy_setopt(curl, CURLOPT_URL, user_url);
389 sprintf(user_url, "%s?page=%d", identica_replies_url, session->page);
390 curl_easy_setopt(curl, CURLOPT_URL, user_url);
393 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
397 switch (session->host) {
399 sprintf(user_url, "%s?page=%d", twitter_public_url, session->page);
400 curl_easy_setopt(curl, CURLOPT_URL, user_url);
403 sprintf(user_url, "%s?page=%d", identica_public_url, session->page);
404 curl_easy_setopt(curl, CURLOPT_URL, user_url);
414 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
417 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
419 dbg("user_password = %s\n", user_password);
420 dbg("data = %s\n", data);
421 dbg("proxy = %s\n", session->proxy);
423 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
424 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
425 if (!session->dry_run) {
426 res = curl_easy_perform(curl);
427 if (res && !session->bash) {
428 fprintf(stderr, "error(%d) trying to perform "
434 curl_easy_cleanup(curl);
435 if (session->action == ACTION_UPDATE)
436 curl_formfree(formpost);
437 bti_curl_buffer_free(curl_buf);
441 static void parse_configfile(struct session *session)
446 char *account = NULL;
447 char *password = NULL;
450 char *logfile = NULL;
456 /* config file is ~/.bti */
457 file = alloca(strlen(session->homedir) + 7);
459 sprintf(file, "%s/.bti", session->homedir);
461 config_file = fopen(file, "r");
463 /* No error if file does not exist or is unreadable. */
464 if (config_file == NULL)
468 ssize_t n = getline(&line, &len, config_file);
471 if (line[n - 1] == '\n')
473 /* Parse file. Format is the usual value pairs:
476 # is a comment character
478 *strchrnul(line, '#') = '\0';
482 /* Ignore blank lines. */
486 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
490 } else if (!strncasecmp(c, "password", 8) &&
494 password = strdup(c);
495 } else if (!strncasecmp(c, "host", 4) &&
500 } else if (!strncasecmp(c, "proxy", 5) &&
505 } else if (!strncasecmp(c, "logfile", 7) &&
510 } else if (!strncasecmp(c, "action", 6) &&
515 } else if (!strncasecmp(c, "user", 4) &&
520 } else if (!strncasecmp(c, "shrink-urls", 11) &&
523 if (!strncasecmp(c, "true", 4) ||
524 !strncasecmp(c, "yes", 3))
527 } while (!feof(config_file));
530 session->password = password;
532 session->account = account;
534 if (strcasecmp(host, "twitter") == 0)
535 session->host = HOST_TWITTER;
536 if (strcasecmp(host, "identica") == 0)
537 session->host = HOST_IDENTICA;
542 free(session->proxy);
543 session->proxy = proxy;
546 session->logfile = logfile;
548 if (strcasecmp(action, "update") == 0)
549 session->action = ACTION_UPDATE;
550 else if (strcasecmp(action, "friends") == 0)
551 session->action = ACTION_FRIENDS;
552 else if (strcasecmp(action, "user") == 0)
553 session->action = ACTION_USER;
554 else if (strcasecmp(action, "replies") == 0)
555 session->action = ACTION_REPLIES;
556 else if (strcasecmp(action, "public") == 0)
557 session->action = ACTION_PUBLIC;
559 session->action = ACTION_UNKNOWN;
563 session->user = user;
564 session->shrink_urls = shrink_urls;
566 /* Free buffer and close file. */
571 static void log_session(struct session *session, int retval)
577 /* Only log something if we have a log file set */
578 if (!session->logfile)
581 filename = alloca(strlen(session->homedir) +
582 strlen(session->logfile) + 3);
584 sprintf(filename, "%s/%s", session->homedir, session->logfile);
586 log_file = fopen(filename, "a+");
587 if (log_file == NULL)
589 switch (session->host) {
601 switch (session->action) {
604 fprintf(log_file, "%s: host=%s tweet failed\n",
605 session->time, host);
607 fprintf(log_file, "%s: host=%s tweet=%s\n",
608 session->time, host, session->tweet);
611 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
612 session->time, host);
615 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
616 session->time, host, session->user);
619 fprintf(log_file, "%s: host=%s retrieving replies\n",
620 session->time, host);
623 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
624 session->time, host);
633 static char *get_string_from_stdin(void)
638 string = zalloc(1000);
642 if (!fgets(string, 999, stdin))
644 temp = strchr(string, '\n');
649 static int find_urls(const char *tweet, int **pranges)
652 * magic obtained from
653 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
655 static const char *re_magic =
656 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
657 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
658 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
662 int ovector[10] = {0,};
663 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
664 int startoffset, tweetlen;
668 int *ranges = malloc(sizeof(int) * rbound);
670 re = pcre_compile(re_magic,
671 PCRE_NO_AUTO_CAPTURE,
672 &errptr, &erroffset, NULL);
674 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
678 tweetlen = strlen(tweet);
679 for (startoffset = 0; startoffset < tweetlen; ) {
681 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
683 if (rc == PCRE_ERROR_NOMATCH)
687 fprintf(stderr, "pcre_exec @%u: %s\n",
692 for (i = 0; i < rc; i += 2) {
693 if ((rcount+2) == rbound) {
695 ranges = realloc(ranges, sizeof(int) * rbound);
698 ranges[rcount++] = ovector[i];
699 ranges[rcount++] = ovector[i+1];
702 startoffset = ovector[1];
712 * bidirectional popen() call
714 * @param rwepipe - int array of size three
715 * @param exe - program to run
716 * @param argv - argument list
717 * @return pid or -1 on error
719 * The caller passes in an array of three integers (rwepipe), on successful
720 * execution it can then write to element 0 (stdin of exe), and read from
721 * element 1 (stdout) and 2 (stderr).
723 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
753 } else if (pid == 0) {
765 execvp(exe, (char **)argv);
785 static int pcloseRWE(int pid, int *rwepipe)
791 rc = waitpid(pid, &status, 0);
795 static char *shrink_one_url(int *rwepipe, char *big)
797 int biglen = strlen(big);
802 rc = dprintf(rwepipe[0], "%s\n", big);
806 smalllen = biglen + 128;
807 small = malloc(smalllen);
811 rc = read(rwepipe[1], small, smalllen);
812 if (rc < 0 || rc > biglen)
813 goto error_free_small;
815 if (strncmp(small, "http://", 7))
816 goto error_free_small;
819 while (smalllen && isspace(small[smalllen-1]))
820 small[--smalllen] = 0;
830 static char *shrink_urls(char *text)
837 const char *const shrink_args[] = {
843 int inlen = strlen(text);
845 dbg("before len=%u\n", inlen);
847 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
851 rcount = find_urls(text, &ranges);
855 for (i = 0; i < rcount; i += 2) {
856 int url_start = ranges[i];
857 int url_end = ranges[i+1];
858 int long_url_len = url_end - url_start;
859 char *url = strndup(text + url_start, long_url_len);
861 int not_url_len = url_start - inofs;
863 dbg("long url[%u]: %s\n", long_url_len, url);
864 url = shrink_one_url(shrink_pipe, url);
865 short_url_len = url ? strlen(url) : 0;
866 dbg("short url[%u]: %s\n", short_url_len, url);
868 if (!url || short_url_len >= long_url_len) {
869 /* The short url ended up being too long
872 strncpy(text + outofs, text + inofs,
873 not_url_len + long_url_len);
875 inofs += not_url_len + long_url_len;
876 outofs += not_url_len + long_url_len;
879 /* copy the unmodified block */
880 strncpy(text + outofs, text + inofs, not_url_len);
881 inofs += not_url_len;
882 outofs += not_url_len;
884 /* copy the new url */
885 strncpy(text + outofs, url, short_url_len);
886 inofs += long_url_len;
887 outofs += short_url_len;
893 /* copy the last block after the last match */
895 int tail = inlen - inofs;
897 strncpy(text + outofs, text + inofs, tail);
904 (void)pcloseRWE(shrink_pid, shrink_pipe);
907 dbg("after len=%u\n", outofs);
911 int main(int argc, char *argv[], char *envp[])
913 static const struct option options[] = {
914 { "debug", 0, NULL, 'd' },
915 { "account", 1, NULL, 'a' },
916 { "password", 1, NULL, 'p' },
917 { "host", 1, NULL, 'H' },
918 { "proxy", 1, NULL, 'P' },
919 { "action", 1, NULL, 'A' },
920 { "user", 1, NULL, 'u' },
921 { "logfile", 1, NULL, 'L' },
922 { "shrink-urls", 0, NULL, 's' },
923 { "help", 0, NULL, 'h' },
924 { "bash", 0, NULL, 'b' },
925 { "dry-run", 0, NULL, 'n' },
926 { "page", 1, NULL, 'g' },
927 { "version", 0, NULL, 'v' },
930 struct session *session;
940 rl_bind_key('\t', rl_insert);
942 session = session_alloc();
944 fprintf(stderr, "no more memory...\n");
948 /* get the current time so that we can log it later */
950 session->time = strdup(ctime(&t));
951 session->time[strlen(session->time)-1] = 0x00;
953 session->homedir = strdup(getenv("HOME"));
955 curl_global_init(CURL_GLOBAL_ALL);
957 /* Set environment variables first, before reading command line options
958 * or config file values. */
959 http_proxy = getenv("http_proxy");
962 free(session->proxy);
963 session->proxy = strdup(http_proxy);
964 dbg("http_proxy = %s\n", session->proxy);
967 parse_configfile(session);
970 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:A:u:hg:sn",
979 if (session->account)
980 free(session->account);
981 session->account = strdup(optarg);
982 dbg("account = %s\n", session->account);
985 page_nr = atoi(optarg);
986 dbg("page = %d\n", page_nr);
987 session->page = page_nr;
990 if (session->password)
991 free(session->password);
992 session->password = strdup(optarg);
993 dbg("password = %s\n", session->password);
997 free(session->proxy);
998 session->proxy = strdup(optarg);
999 dbg("proxy = %s\n", session->proxy);
1002 if (strcasecmp(optarg, "update") == 0)
1003 session->action = ACTION_UPDATE;
1004 else if (strcasecmp(optarg, "friends") == 0)
1005 session->action = ACTION_FRIENDS;
1006 else if (strcasecmp(optarg, "user") == 0)
1007 session->action = ACTION_USER;
1008 else if (strcasecmp(optarg, "replies") == 0)
1009 session->action = ACTION_REPLIES;
1010 else if (strcasecmp(optarg, "public") == 0)
1011 session->action = ACTION_PUBLIC;
1013 session->action = ACTION_UNKNOWN;
1014 dbg("action = %d\n", session->action);
1018 free(session->user);
1019 session->user = strdup(optarg);
1020 dbg("user = %s\n", session->user);
1023 if (session->logfile)
1024 free(session->logfile);
1025 session->logfile = strdup(optarg);
1026 dbg("logfile = %s\n", session->logfile);
1029 session->shrink_urls = 1;
1032 if (strcasecmp(optarg, "twitter") == 0)
1033 session->host = HOST_TWITTER;
1034 if (strcasecmp(optarg, "identica") == 0)
1035 session->host = HOST_IDENTICA;
1036 dbg("host = %d\n", session->host);
1045 session->dry_run = 1;
1057 * Show the version to make it easier to determine what
1063 if (session->action == ACTION_UNKNOWN) {
1064 fprintf(stderr, "Unknown action, valid actions are:\n");
1065 fprintf(stderr, "'update', 'friends', 'public', "
1066 "'replies' or 'user'.\n");
1070 if (!session->account) {
1071 fprintf(stdout, "Enter twitter account: ");
1072 session->account = readline(NULL);
1075 if (!session->password) {
1076 fprintf(stdout, "Enter twitter password: ");
1077 session->password = readline(NULL);
1080 if (session->action == ACTION_UPDATE) {
1082 tweet = get_string_from_stdin();
1084 tweet = readline("tweet: ");
1085 if (!tweet || strlen(tweet) == 0) {
1090 if (session->shrink_urls)
1091 tweet = shrink_urls(tweet);
1093 session->tweet = zalloc(strlen(tweet) + 10);
1095 sprintf(session->tweet, "%c %s", getuid() ? '$' : '#', tweet);
1097 sprintf(session->tweet, "%s", tweet);
1100 dbg("tweet = %s\n", session->tweet);
1104 session->user = strdup(session->account);
1106 if (session->page == 0)
1108 dbg("account = %s\n", session->account);
1109 dbg("password = %s\n", session->password);
1110 dbg("host = %d\n", session->host);
1111 dbg("action = %d\n", session->action);
1113 /* fork ourself so that the main shell can get on
1114 * with it's life as we try to connect and handle everything
1116 if (session->bash) {
1119 dbg("child is %d\n", child);
1124 retval = send_request(session);
1125 if (retval && !session->bash)
1126 fprintf(stderr, "operation failed\n");
1128 log_session(session, retval);
1130 session_free(session);