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, " --version\n");
111 fprintf(stdout, " --help\n");
114 static void display_version(void)
116 fprintf(stdout, "bti - version %s\n", BTI_VERSION);
119 static struct session *session_alloc(void)
121 struct session *session;
123 session = zalloc(sizeof(*session));
129 static void session_free(struct session *session)
133 free(session->password);
134 free(session->account);
135 free(session->tweet);
136 free(session->proxy);
138 free(session->homedir);
143 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
145 struct bti_curl_buffer *buffer;
147 buffer = zalloc(sizeof(*buffer));
151 /* start out with a data buffer of 1 byte to
152 * make the buffer fill logic simpler */
153 buffer->data = zalloc(1);
159 buffer->action = action;
163 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
171 static const char *twitter_user_url = "http://twitter.com/statuses/user_timeline/";
172 static const char *twitter_update_url = "https://twitter.com/statuses/update.xml";
173 static const char *twitter_public_url = "http://twitter.com/statuses/public_timeline.xml";
174 static const char *twitter_friends_url = "https://twitter.com/statuses/friends_timeline.xml";
175 static const char *twitter_replies_url = "http://twitter.com/statuses/replies.xml";
177 static const char *identica_user_url = "http://identi.ca/api/statuses/user_timeline/";
178 static const char *identica_update_url = "http://identi.ca/api/statuses/update.xml";
179 static const char *identica_public_url = "http://identi.ca/api/statuses/public_timeline.xml";
180 static const char *identica_friends_url = "http://identi.ca/api/statuses/friends_timeline.xml";
181 static const char *identica_replies_url = "http://identi.ca/api/statuses/replies.xml";
183 static CURL *curl_init(void)
187 curl = curl_easy_init();
189 fprintf(stderr, "Can not init CURL!\n");
192 /* some ssl sanity checks on the connection we are making */
193 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
194 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
198 void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
200 xmlChar *text = NULL;
201 xmlChar *user = NULL;
204 current = current->xmlChildrenNode;
205 while (current != NULL) {
206 if (current->type == XML_ELEMENT_NODE) {
207 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
208 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
209 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
210 userinfo = current->xmlChildrenNode;
211 while (userinfo != NULL) {
212 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
215 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
217 userinfo = userinfo->next;
221 printf("[%s] %s\n", user, text);
228 current = current->next;
234 static void parse_timeline(char *document)
239 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
240 NULL, XML_PARSE_NOERROR);
244 current = xmlDocGetRootElement(doc);
245 if (current == NULL) {
246 fprintf(stderr, "empty document\n");
251 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
252 fprintf(stderr, "unexpected document type\n");
257 current = current->xmlChildrenNode;
258 while (current != NULL) {
259 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
260 parse_statuses(doc, current);
261 current = current->next;
268 size_t curl_callback(void *buffer, size_t size, size_t nmemb, void *userp)
270 struct bti_curl_buffer *curl_buf = userp;
271 size_t buffer_size = size * nmemb;
274 if ((!buffer) || (!buffer_size) || (!curl_buf))
277 /* add to the data we already have */
278 temp = zalloc(curl_buf->length + buffer_size + 1);
282 memcpy(temp, curl_buf->data, curl_buf->length);
283 free(curl_buf->data);
284 curl_buf->data = temp;
285 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
286 curl_buf->length += buffer_size;
287 if (curl_buf->action)
288 parse_timeline(curl_buf->data);
290 dbg("%s\n", curl_buf->data);
295 static int send_request(struct session *session)
297 char user_password[500];
299 /* is there usernames longer than 22 chars? */
301 struct bti_curl_buffer *curl_buf;
304 struct curl_httppost *formpost = NULL;
305 struct curl_httppost *lastptr = NULL;
306 struct curl_slist *slist = NULL;
311 curl_buf = bti_curl_buffer_alloc(session->action);
319 switch (session->action) {
321 snprintf(user_password, sizeof(user_password), "%s:%s",
322 session->account, session->password);
323 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
324 curl_formadd(&formpost, &lastptr,
325 CURLFORM_COPYNAME, "status",
326 CURLFORM_COPYCONTENTS, session->tweet,
329 curl_formadd(&formpost, &lastptr,
330 CURLFORM_COPYNAME, "source",
331 CURLFORM_COPYCONTENTS, "bti",
334 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
335 slist = curl_slist_append(slist, "Expect:");
336 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
337 switch (session->host) {
339 curl_easy_setopt(curl, CURLOPT_URL,
343 curl_easy_setopt(curl, CURLOPT_URL,
344 identica_update_url);
347 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
351 snprintf(user_password, sizeof(user_password), "%s:%s",
352 session->account, session->password);
353 switch (session->host) {
355 sprintf(user_url, "%s?page=%d", twitter_friends_url, session->page);
356 curl_easy_setopt(curl, CURLOPT_URL, user_url);
359 sprintf(user_url, "%s?page=%d", identica_friends_url, session->page);
360 curl_easy_setopt(curl, CURLOPT_URL, user_url);
363 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
367 switch (session->host) {
369 sprintf(user_url, "%s%s.xml?page=%d", twitter_user_url, session->user, session->page);
370 curl_easy_setopt(curl, CURLOPT_URL, user_url);
373 sprintf(user_url, "%s%s.xml?page=%d", identica_user_url, session->user, session->page);
374 curl_easy_setopt(curl, CURLOPT_URL, user_url);
380 snprintf(user_password, sizeof(user_password), "%s:%s",
381 session->account, session->password);
382 switch (session->host) {
384 sprintf(user_url, "%s?page=%d", twitter_replies_url, session->page);
385 curl_easy_setopt(curl, CURLOPT_URL, user_url);
388 sprintf(user_url, "%s?page=%d", identica_replies_url, session->page);
389 curl_easy_setopt(curl, CURLOPT_URL, user_url);
392 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
396 switch (session->host) {
398 sprintf(user_url, "%s?page=%d", twitter_public_url, session->page);
399 curl_easy_setopt(curl, CURLOPT_URL, user_url);
402 sprintf(user_url, "%s?page=%d", identica_public_url, session->page);
403 curl_easy_setopt(curl, CURLOPT_URL, user_url);
413 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
416 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
418 dbg("user_password = %s\n", user_password);
419 dbg("data = %s\n", data);
420 dbg("proxy = %s\n", session->proxy);
422 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
423 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
424 if (!session->dry_run) {
425 res = curl_easy_perform(curl);
426 if (res && !session->bash) {
427 fprintf(stderr, "error(%d) trying to perform "
433 curl_easy_cleanup(curl);
434 if (session->action == ACTION_UPDATE)
435 curl_formfree(formpost);
436 bti_curl_buffer_free(curl_buf);
440 static void parse_configfile(struct session *session)
445 char *account = NULL;
446 char *password = NULL;
449 char *logfile = NULL;
455 /* config file is ~/.bti */
456 file = alloca(strlen(session->homedir) + 7);
458 sprintf(file, "%s/.bti", session->homedir);
460 config_file = fopen(file, "r");
462 /* No error if file does not exist or is unreadable. */
463 if (config_file == NULL)
467 ssize_t n = getline(&line, &len, config_file);
470 if (line[n - 1] == '\n')
472 /* Parse file. Format is the usual value pairs:
475 # is a comment character
477 *strchrnul(line, '#') = '\0';
481 /* Ignore blank lines. */
485 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
489 } else if (!strncasecmp(c, "password", 8) &&
493 password = strdup(c);
494 } else if (!strncasecmp(c, "host", 4) &&
499 } else if (!strncasecmp(c, "proxy", 5) &&
504 } else if (!strncasecmp(c, "logfile", 7) &&
509 } else if (!strncasecmp(c, "action", 6) &&
514 } else if (!strncasecmp(c, "user", 4) &&
519 } else if (!strncasecmp(c, "shrink-urls", 11) &&
522 if (!strncasecmp(c, "true", 4) ||
523 !strncasecmp(c, "yes", 3))
526 } while (!feof(config_file));
529 session->password = password;
531 session->account = account;
533 if (strcasecmp(host, "twitter") == 0)
534 session->host = HOST_TWITTER;
535 if (strcasecmp(host, "identica") == 0)
536 session->host = HOST_IDENTICA;
541 free(session->proxy);
542 session->proxy = proxy;
545 session->logfile = logfile;
547 if (strcasecmp(action, "update") == 0)
548 session->action = ACTION_UPDATE;
549 else if (strcasecmp(action, "friends") == 0)
550 session->action = ACTION_FRIENDS;
551 else if (strcasecmp(action, "user") == 0)
552 session->action = ACTION_USER;
553 else if (strcasecmp(action, "replies") == 0)
554 session->action = ACTION_REPLIES;
555 else if (strcasecmp(action, "public") == 0)
556 session->action = ACTION_PUBLIC;
558 session->action = ACTION_UNKNOWN;
562 session->user = user;
563 session->shrink_urls = shrink_urls;
565 /* Free buffer and close file. */
570 static void log_session(struct session *session, int retval)
576 /* Only log something if we have a log file set */
577 if (!session->logfile)
580 filename = alloca(strlen(session->homedir) +
581 strlen(session->logfile) + 3);
583 sprintf(filename, "%s/%s", session->homedir, session->logfile);
585 log_file = fopen(filename, "a+");
586 if (log_file == NULL)
588 switch (session->host) {
600 switch (session->action) {
603 fprintf(log_file, "%s: host=%s tweet failed\n",
604 session->time, host);
606 fprintf(log_file, "%s: host=%s tweet=%s\n",
607 session->time, host, session->tweet);
610 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
611 session->time, host);
614 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
615 session->time, host, session->user);
618 fprintf(log_file, "%s: host=%s retrieving replies\n",
619 session->time, host);
622 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
623 session->time, host);
632 static char *get_string_from_stdin(void)
637 string = zalloc(1000);
641 if (!fgets(string, 999, stdin))
643 temp = strchr(string, '\n');
648 static int find_urls(const char *tweet, int **pranges)
651 * magic obtained from
652 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
654 static const char *re_magic =
655 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
656 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
657 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
661 int ovector[10] = {0,};
662 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
663 int startoffset, tweetlen;
667 int *ranges = malloc(sizeof(int) * rbound);
669 re = pcre_compile(re_magic,
670 PCRE_NO_AUTO_CAPTURE,
671 &errptr, &erroffset, NULL);
673 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
677 tweetlen = strlen(tweet);
678 for (startoffset = 0; startoffset < tweetlen; ) {
680 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
682 if (rc == PCRE_ERROR_NOMATCH)
686 fprintf(stderr, "pcre_exec @%u: %s\n",
691 for (i = 0; i < rc; i += 2) {
692 if ((rcount+2) == rbound) {
694 ranges = realloc(ranges, sizeof(int) * rbound);
697 ranges[rcount++] = ovector[i];
698 ranges[rcount++] = ovector[i+1];
701 startoffset = ovector[1];
711 * bidirectional popen() call
713 * @param rwepipe - int array of size three
714 * @param exe - program to run
715 * @param argv - argument list
716 * @return pid or -1 on error
718 * The caller passes in an array of three integers (rwepipe), on successful
719 * execution it can then write to element 0 (stdin of exe), and read from
720 * element 1 (stdout) and 2 (stderr).
722 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
752 } else if (pid == 0) {
764 execvp(exe, (char **)argv);
784 static int pcloseRWE(int pid, int *rwepipe)
790 rc = waitpid(pid, &status, 0);
794 static char *shrink_one_url(int *rwepipe, char *big)
796 int biglen = strlen(big);
801 rc = dprintf(rwepipe[0], "%s\n", big);
805 smalllen = biglen + 128;
806 small = malloc(smalllen);
810 rc = read(rwepipe[1], small, smalllen);
811 if (rc < 0 || rc > biglen)
812 goto error_free_small;
814 if (strncmp(small, "http://", 7))
815 goto error_free_small;
818 while (smalllen && isspace(small[smalllen-1]))
819 small[--smalllen] = 0;
829 static char *shrink_urls(char *text)
836 const char *const shrink_args[] = {
842 int inlen = strlen(text);
844 dbg("before len=%u\n", inlen);
846 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
850 rcount = find_urls(text, &ranges);
854 for (i = 0; i < rcount; i += 2) {
855 int url_start = ranges[i];
856 int url_end = ranges[i+1];
857 int long_url_len = url_end - url_start;
858 char *url = strndup(text + url_start, long_url_len);
860 int not_url_len = url_start - inofs;
862 dbg("long url[%u]: %s\n", long_url_len, url);
863 url = shrink_one_url(shrink_pipe, url);
864 short_url_len = url ? strlen(url) : 0;
865 dbg("short url[%u]: %s\n", short_url_len, url);
867 if (!url || short_url_len >= long_url_len) {
868 /* The short url ended up being too long
871 strncpy(text + outofs, text + inofs,
872 not_url_len + long_url_len);
874 inofs += not_url_len + long_url_len;
875 outofs += not_url_len + long_url_len;
878 /* copy the unmodified block */
879 strncpy(text + outofs, text + inofs, not_url_len);
880 inofs += not_url_len;
881 outofs += not_url_len;
883 /* copy the new url */
884 strncpy(text + outofs, url, short_url_len);
885 inofs += long_url_len;
886 outofs += short_url_len;
892 /* copy the last block after the last match */
894 int tail = inlen - inofs;
896 strncpy(text + outofs, text + inofs, tail);
903 (void)pcloseRWE(shrink_pid, shrink_pipe);
906 dbg("after len=%u\n", outofs);
910 int main(int argc, char *argv[], char *envp[])
912 static const struct option options[] = {
913 { "debug", 0, NULL, 'd' },
914 { "account", 1, NULL, 'a' },
915 { "password", 1, NULL, 'p' },
916 { "host", 1, NULL, 'H' },
917 { "proxy", 1, NULL, 'P' },
918 { "action", 1, NULL, 'A' },
919 { "user", 1, NULL, 'u' },
920 { "logfile", 1, NULL, 'L' },
921 { "shrink-urls", 0, NULL, 's' },
922 { "help", 0, NULL, 'h' },
923 { "bash", 0, NULL, 'b' },
924 { "dry-run", 0, NULL, 'n' },
925 { "page", 1, NULL, 'g' },
926 { "version", 0, NULL, 'v' },
929 struct session *session;
939 rl_bind_key('\t', rl_insert);
941 session = session_alloc();
943 fprintf(stderr, "no more memory...\n");
947 /* get the current time so that we can log it later */
949 session->time = strdup(ctime(&t));
950 session->time[strlen(session->time)-1] = 0x00;
952 session->homedir = strdup(getenv("HOME"));
954 curl_global_init(CURL_GLOBAL_ALL);
956 /* Set environment variables first, before reading command line options
957 * or config file values. */
958 http_proxy = getenv("http_proxy");
961 free(session->proxy);
962 session->proxy = strdup(http_proxy);
963 dbg("http_proxy = %s\n", session->proxy);
966 parse_configfile(session);
969 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:A:u:hg:",
978 if (session->account)
979 free(session->account);
980 session->account = strdup(optarg);
981 dbg("account = %s\n", session->account);
984 page_nr = atoi(optarg);
985 dbg("page = %d\n", page_nr);
986 session->page = page_nr;
989 if (session->password)
990 free(session->password);
991 session->password = strdup(optarg);
992 dbg("password = %s\n", session->password);
996 free(session->proxy);
997 session->proxy = strdup(optarg);
998 dbg("proxy = %s\n", session->proxy);
1001 if (strcasecmp(optarg, "update") == 0)
1002 session->action = ACTION_UPDATE;
1003 else if (strcasecmp(optarg, "friends") == 0)
1004 session->action = ACTION_FRIENDS;
1005 else if (strcasecmp(optarg, "user") == 0)
1006 session->action = ACTION_USER;
1007 else if (strcasecmp(optarg, "replies") == 0)
1008 session->action = ACTION_REPLIES;
1009 else if (strcasecmp(optarg, "public") == 0)
1010 session->action = ACTION_PUBLIC;
1012 session->action = ACTION_UNKNOWN;
1013 dbg("action = %d\n", session->action);
1017 free(session->user);
1018 session->user = strdup(optarg);
1019 dbg("user = %s\n", session->user);
1022 if (session->logfile)
1023 free(session->logfile);
1024 session->logfile = strdup(optarg);
1025 dbg("logfile = %s\n", session->logfile);
1028 session->shrink_urls = 1;
1031 if (strcasecmp(optarg, "twitter") == 0)
1032 session->host = HOST_TWITTER;
1033 if (strcasecmp(optarg, "identica") == 0)
1034 session->host = HOST_IDENTICA;
1035 dbg("host = %d\n", session->host);
1044 session->dry_run = 1;
1056 * Show the version to make it easier to determine what
1062 if (session->action == ACTION_UNKNOWN) {
1063 fprintf(stderr, "Unknown action, valid actions are:\n");
1064 fprintf(stderr, "'update', 'friends', 'public', "
1065 "'replies' or 'user'.\n");
1069 if (!session->account) {
1070 fprintf(stdout, "Enter twitter account: ");
1071 session->account = readline(NULL);
1074 if (!session->password) {
1075 fprintf(stdout, "Enter twitter password: ");
1076 session->password = readline(NULL);
1079 if (session->action == ACTION_UPDATE) {
1081 tweet = get_string_from_stdin();
1083 tweet = readline("tweet: ");
1084 if (!tweet || strlen(tweet) == 0) {
1089 if (session->shrink_urls)
1090 tweet = shrink_urls(tweet);
1092 session->tweet = zalloc(strlen(tweet) + 10);
1094 sprintf(session->tweet, "%c %s", getuid() ? '$' : '#', tweet);
1096 sprintf(session->tweet, "%s", tweet);
1099 dbg("tweet = %s\n", session->tweet);
1103 session->user = strdup(session->account);
1105 if (session->page == 0)
1107 dbg("account = %s\n", session->account);
1108 dbg("password = %s\n", session->password);
1109 dbg("host = %d\n", session->host);
1110 dbg("action = %d\n", session->action);
1112 /* fork ourself so that the main shell can get on
1113 * with it's life as we try to connect and handle everything
1115 if (session->bash) {
1118 dbg("child is %d\n", child);
1123 retval = send_request(session);
1124 if (retval && !session->bash)
1125 fprintf(stderr, "operation failed\n");
1127 log_session(session, retval);
1129 session_free(session);