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.
32 #include <sys/types.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>
42 #define zalloc(size) calloc(size, 1)
44 #define dbg(format, arg...) \
47 fprintf(stdout, "bti: %s: " format , __func__ , \
85 struct bti_curl_buffer {
91 static void display_help(void)
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' "
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");
116 static void display_version(void)
118 fprintf(stdout, "bti - version %s\n", VERSION);
121 static struct session *session_alloc(void)
123 struct session *session;
125 session = zalloc(sizeof(*session));
131 static void session_free(struct session *session)
135 free(session->password);
136 free(session->account);
137 free(session->tweet);
138 free(session->proxy);
140 free(session->homedir);
145 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
147 struct bti_curl_buffer *buffer;
149 buffer = zalloc(sizeof(*buffer));
153 /* start out with a data buffer of 1 byte to
154 * make the buffer fill logic simpler */
155 buffer->data = zalloc(1);
161 buffer->action = action;
165 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
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";
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";
185 static CURL *curl_init(void)
189 curl = curl_easy_init();
191 fprintf(stderr, "Can not init CURL!\n");
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);
200 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
202 xmlChar *text = NULL;
203 xmlChar *user = NULL;
204 xmlChar *time = NULL;
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"))) {
220 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
222 userinfo = userinfo->next;
226 if (user && text && time) {
227 printf("[%s] (%.16s) %s\n", user, time, text);
236 current = current->next;
242 static void parse_timeline(char *document)
247 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
248 NULL, XML_PARSE_NOERROR);
252 current = xmlDocGetRootElement(doc);
253 if (current == NULL) {
254 fprintf(stderr, "empty document\n");
259 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
260 fprintf(stderr, "unexpected document type\n");
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;
276 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
279 struct bti_curl_buffer *curl_buf = userp;
280 size_t buffer_size = size * nmemb;
283 if ((!buffer) || (!buffer_size) || (!curl_buf))
286 /* add to the data we already have */
287 temp = zalloc(curl_buf->length + buffer_size + 1);
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);
299 dbg("%s\n", curl_buf->data);
304 static int send_request(struct session *session)
306 char user_password[500];
308 /* is there usernames longer than 22 chars? */
310 struct bti_curl_buffer *curl_buf;
313 struct curl_httppost *formpost = NULL;
314 struct curl_httppost *lastptr = NULL;
315 struct curl_slist *slist = NULL;
320 curl_buf = bti_curl_buffer_alloc(session->action);
328 switch (session->action) {
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,
338 curl_formadd(&formpost, &lastptr,
339 CURLFORM_COPYNAME, "source",
340 CURLFORM_COPYCONTENTS, "bti",
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) {
348 curl_easy_setopt(curl, CURLOPT_URL,
352 curl_easy_setopt(curl, CURLOPT_URL,
353 identica_update_url);
356 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
360 snprintf(user_password, sizeof(user_password), "%s:%s",
361 session->account, session->password);
362 switch (session->host) {
364 sprintf(user_url, "%s?page=%d", twitter_friends_url, session->page);
365 curl_easy_setopt(curl, CURLOPT_URL, user_url);
368 sprintf(user_url, "%s?page=%d", identica_friends_url, session->page);
369 curl_easy_setopt(curl, CURLOPT_URL, user_url);
372 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
376 switch (session->host) {
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);
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);
389 snprintf(user_password, sizeof(user_password), "%s:%s",
390 session->account, session->password);
391 switch (session->host) {
393 sprintf(user_url, "%s?page=%d", twitter_replies_url, session->page);
394 curl_easy_setopt(curl, CURLOPT_URL, user_url);
397 sprintf(user_url, "%s?page=%d", identica_replies_url, session->page);
398 curl_easy_setopt(curl, CURLOPT_URL, user_url);
401 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
405 switch (session->host) {
407 sprintf(user_url, "%s?page=%d", twitter_public_url, session->page);
408 curl_easy_setopt(curl, CURLOPT_URL, user_url);
411 sprintf(user_url, "%s?page=%d", identica_public_url, session->page);
412 curl_easy_setopt(curl, CURLOPT_URL, user_url);
422 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
425 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
427 dbg("user_password = %s\n", user_password);
428 dbg("data = %s\n", data);
429 dbg("proxy = %s\n", session->proxy);
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 "
442 curl_easy_cleanup(curl);
443 if (session->action == ACTION_UPDATE)
444 curl_formfree(formpost);
445 bti_curl_buffer_free(curl_buf);
449 static void parse_configfile(struct session *session)
454 char *account = NULL;
455 char *password = NULL;
458 char *logfile = NULL;
464 /* config file is ~/.bti */
465 file = alloca(strlen(session->homedir) + 7);
467 sprintf(file, "%s/.bti", session->homedir);
469 config_file = fopen(file, "r");
471 /* No error if file does not exist or is unreadable. */
472 if (config_file == NULL)
476 ssize_t n = getline(&line, &len, config_file);
479 if (line[n - 1] == '\n')
481 /* Parse file. Format is the usual value pairs:
484 # is a comment character
486 *strchrnul(line, '#') = '\0';
490 /* Ignore blank lines. */
494 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
498 } else if (!strncasecmp(c, "password", 8) &&
502 password = strdup(c);
503 } else if (!strncasecmp(c, "host", 4) &&
508 } else if (!strncasecmp(c, "proxy", 5) &&
513 } else if (!strncasecmp(c, "logfile", 7) &&
518 } else if (!strncasecmp(c, "action", 6) &&
523 } else if (!strncasecmp(c, "user", 4) &&
528 } else if (!strncasecmp(c, "shrink-urls", 11) &&
531 if (!strncasecmp(c, "true", 4) ||
532 !strncasecmp(c, "yes", 3))
535 } while (!feof(config_file));
538 session->password = password;
540 session->account = account;
542 if (strcasecmp(host, "twitter") == 0)
543 session->host = HOST_TWITTER;
544 if (strcasecmp(host, "identica") == 0)
545 session->host = HOST_IDENTICA;
550 free(session->proxy);
551 session->proxy = proxy;
554 session->logfile = logfile;
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;
567 session->action = ACTION_UNKNOWN;
571 session->user = user;
572 session->shrink_urls = shrink_urls;
574 /* Free buffer and close file. */
579 static void log_session(struct session *session, int retval)
585 /* Only log something if we have a log file set */
586 if (!session->logfile)
589 filename = alloca(strlen(session->homedir) +
590 strlen(session->logfile) + 3);
592 sprintf(filename, "%s/%s", session->homedir, session->logfile);
594 log_file = fopen(filename, "a+");
595 if (log_file == NULL)
597 switch (session->host) {
609 switch (session->action) {
612 fprintf(log_file, "%s: host=%s tweet failed\n",
613 session->time, host);
615 fprintf(log_file, "%s: host=%s tweet=%s\n",
616 session->time, host, session->tweet);
619 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
620 session->time, host);
623 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
624 session->time, host, session->user);
627 fprintf(log_file, "%s: host=%s retrieving replies\n",
628 session->time, host);
631 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
632 session->time, host);
641 static char *get_string_from_stdin(void)
646 string = zalloc(1000);
650 if (!fgets(string, 999, stdin))
652 temp = strchr(string, '\n');
657 static int find_urls(const char *tweet, int **pranges)
660 * magic obtained from
661 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
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;/?:@&=+$\\.\\-_!~*'()%]+)?";
670 int ovector[10] = {0,};
671 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
672 int startoffset, tweetlen;
676 int *ranges = malloc(sizeof(int) * rbound);
678 re = pcre_compile(re_magic,
679 PCRE_NO_AUTO_CAPTURE,
680 &errptr, &erroffset, NULL);
682 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
686 tweetlen = strlen(tweet);
687 for (startoffset = 0; startoffset < tweetlen; ) {
689 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
691 if (rc == PCRE_ERROR_NOMATCH)
695 fprintf(stderr, "pcre_exec @%u: %s\n",
700 for (i = 0; i < rc; i += 2) {
701 if ((rcount+2) == rbound) {
703 ranges = realloc(ranges, sizeof(int) * rbound);
706 ranges[rcount++] = ovector[i];
707 ranges[rcount++] = ovector[i+1];
710 startoffset = ovector[1];
720 * bidirectional popen() call
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
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).
731 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
761 } else if (pid == 0) {
773 execvp(exe, (char **)argv);
793 static int pcloseRWE(int pid, int *rwepipe)
799 rc = waitpid(pid, &status, 0);
803 static char *shrink_one_url(int *rwepipe, char *big)
805 int biglen = strlen(big);
810 rc = dprintf(rwepipe[0], "%s\n", big);
814 smalllen = biglen + 128;
815 small = malloc(smalllen);
819 rc = read(rwepipe[1], small, smalllen);
820 if (rc < 0 || rc > biglen)
821 goto error_free_small;
823 if (strncmp(small, "http://", 7))
824 goto error_free_small;
827 while (smalllen && isspace(small[smalllen-1]))
828 small[--smalllen] = 0;
838 static char *shrink_urls(char *text)
845 const char *const shrink_args[] = {
851 int inlen = strlen(text);
853 dbg("before len=%u\n", inlen);
855 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
859 rcount = find_urls(text, &ranges);
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);
869 int not_url_len = url_start - inofs;
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);
876 if (!url || short_url_len >= long_url_len) {
877 /* The short url ended up being too long
880 strncpy(text + outofs, text + inofs,
881 not_url_len + long_url_len);
883 inofs += not_url_len + long_url_len;
884 outofs += not_url_len + long_url_len;
887 /* copy the unmodified block */
888 strncpy(text + outofs, text + inofs, not_url_len);
889 inofs += not_url_len;
890 outofs += not_url_len;
892 /* copy the new url */
893 strncpy(text + outofs, url, short_url_len);
894 inofs += long_url_len;
895 outofs += short_url_len;
901 /* copy the last block after the last match */
903 int tail = inlen - inofs;
905 strncpy(text + outofs, text + inofs, tail);
912 (void)pcloseRWE(shrink_pid, shrink_pipe);
915 dbg("after len=%u\n", outofs);
919 int main(int argc, char *argv[], char *envp[])
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' },
938 struct session *session;
948 rl_bind_key('\t', rl_insert);
950 session = session_alloc();
952 fprintf(stderr, "no more memory...\n");
956 /* get the current time so that we can log it later */
958 session->time = strdup(ctime(&t));
959 session->time[strlen(session->time)-1] = 0x00;
961 session->homedir = strdup(getenv("HOME"));
963 curl_global_init(CURL_GLOBAL_ALL);
965 /* Set environment variables first, before reading command line options
966 * or config file values. */
967 http_proxy = getenv("http_proxy");
970 free(session->proxy);
971 session->proxy = strdup(http_proxy);
972 dbg("http_proxy = %s\n", session->proxy);
975 parse_configfile(session);
978 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:A:u:hg:sn",
987 if (session->account)
988 free(session->account);
989 session->account = strdup(optarg);
990 dbg("account = %s\n", session->account);
993 page_nr = atoi(optarg);
994 dbg("page = %d\n", page_nr);
995 session->page = page_nr;
998 if (session->password)
999 free(session->password);
1000 session->password = strdup(optarg);
1001 dbg("password = %s\n", session->password);
1005 free(session->proxy);
1006 session->proxy = strdup(optarg);
1007 dbg("proxy = %s\n", session->proxy);
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;
1021 session->action = ACTION_UNKNOWN;
1022 dbg("action = %d\n", session->action);
1026 free(session->user);
1027 session->user = strdup(optarg);
1028 dbg("user = %s\n", session->user);
1031 if (session->logfile)
1032 free(session->logfile);
1033 session->logfile = strdup(optarg);
1034 dbg("logfile = %s\n", session->logfile);
1037 session->shrink_urls = 1;
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);
1053 session->dry_run = 1;
1065 * Show the version to make it easier to determine what
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");
1078 if (!session->account) {
1079 fprintf(stdout, "Enter twitter account: ");
1080 session->account = readline(NULL);
1083 if (!session->password) {
1084 fprintf(stdout, "Enter twitter password: ");
1085 session->password = readline(NULL);
1088 if (session->action == ACTION_UPDATE) {
1090 tweet = get_string_from_stdin();
1092 tweet = readline("tweet: ");
1093 if (!tweet || strlen(tweet) == 0) {
1098 if (session->shrink_urls)
1099 tweet = shrink_urls(tweet);
1101 session->tweet = zalloc(strlen(tweet) + 10);
1103 sprintf(session->tweet, "%c %s", getuid() ? '$' : '#', tweet);
1105 sprintf(session->tweet, "%s", tweet);
1108 dbg("tweet = %s\n", session->tweet);
1112 session->user = strdup(session->account);
1114 if (session->page == 0)
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);
1121 /* fork ourself so that the main shell can get on
1122 * with it's life as we try to connect and handle everything
1124 if (session->bash) {
1127 dbg("child is %d\n", child);
1132 retval = send_request(session);
1133 if (retval && !session->bash)
1134 fprintf(stderr, "operation failed\n");
1136 log_session(session, retval);
1138 session_free(session);