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); \
83 struct bti_curl_buffer {
89 static void display_help(void)
91 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
92 fprintf(stdout, "Version: " BTI_VERSION "\n");
93 fprintf(stdout, "Usage:\n");
94 fprintf(stdout, " bti [options]\n");
95 fprintf(stdout, "options are:\n");
96 fprintf(stdout, " --account accountname\n");
97 fprintf(stdout, " --password password\n");
98 fprintf(stdout, " --action action\n");
99 fprintf(stdout, " ('update', 'friends', 'public', 'replies' "
101 fprintf(stdout, " --user screenname\n");
102 fprintf(stdout, " --proxy PROXY:PORT\n");
103 fprintf(stdout, " --host HOST\n");
104 fprintf(stdout, " --logfile logfile\n");
105 fprintf(stdout, " --shrink-urls\n");
106 fprintf(stdout, " --bash\n");
107 fprintf(stdout, " --debug\n");
108 fprintf(stdout, " --version\n");
109 fprintf(stdout, " --help\n");
112 static void display_version(void)
114 fprintf(stdout, "bti - version %s\n", BTI_VERSION);
117 static struct session *session_alloc(void)
119 struct session *session;
121 session = zalloc(sizeof(*session));
127 static void session_free(struct session *session)
131 free(session->password);
132 free(session->account);
133 free(session->tweet);
134 free(session->proxy);
136 free(session->homedir);
141 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
143 struct bti_curl_buffer *buffer;
145 buffer = zalloc(sizeof(*buffer));
149 /* start out with a data buffer of 1 byte to
150 * make the buffer fill logic simpler */
151 buffer->data = zalloc(1);
157 buffer->action = action;
161 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
169 static const char *twitter_user_url = "http://twitter.com/statuses/user_timeline/";
170 static const char *twitter_update_url = "https://twitter.com/statuses/update.xml";
171 static const char *twitter_public_url = "http://twitter.com/statuses/public_timeline.xml";
172 static const char *twitter_friends_url = "https://twitter.com/statuses/friends_timeline.xml";
173 static const char *twitter_replies_url = "http://twitter.com/statuses/replies.xml";
175 static const char *identica_user_url = "http://identi.ca/api/statuses/user_timeline/";
176 static const char *identica_update_url = "http://identi.ca/api/statuses/update.xml";
177 static const char *identica_public_url = "http://identi.ca/api/statuses/public_timeline.xml";
178 static const char *identica_friends_url = "http://identi.ca/api/statuses/friends_timeline.xml";
179 static const char *identica_replies_url = "http://identi.ca/api/statuses/replies.xml";
181 static CURL *curl_init(void)
185 curl = curl_easy_init();
187 fprintf(stderr, "Can not init CURL!\n");
190 /* some ssl sanity checks on the connection we are making */
191 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
192 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
196 void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
198 xmlChar *text = NULL;
199 xmlChar *user = NULL;
202 current = current->xmlChildrenNode;
203 while (current != NULL) {
204 if (current->type == XML_ELEMENT_NODE) {
205 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
206 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
207 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
208 userinfo = current->xmlChildrenNode;
209 while (userinfo != NULL) {
210 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
213 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
215 userinfo = userinfo->next;
219 printf("[%s] %s\n", user, text);
226 current = current->next;
232 static void parse_timeline(char *document)
237 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
238 NULL, XML_PARSE_NOERROR);
242 current = xmlDocGetRootElement(doc);
243 if (current == NULL) {
244 fprintf(stderr, "empty document\n");
249 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
250 fprintf(stderr, "unexpected document type\n");
255 current = current->xmlChildrenNode;
256 while (current != NULL) {
257 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
258 parse_statuses(doc, current);
259 current = current->next;
266 size_t curl_callback(void *buffer, size_t size, size_t nmemb, void *userp)
268 struct bti_curl_buffer *curl_buf = userp;
269 size_t buffer_size = size * nmemb;
272 if ((!buffer) || (!buffer_size) || (!curl_buf))
275 /* add to the data we already have */
276 temp = zalloc(curl_buf->length + buffer_size + 1);
280 memcpy(temp, curl_buf->data, curl_buf->length);
281 free(curl_buf->data);
282 curl_buf->data = temp;
283 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
284 curl_buf->length += buffer_size;
285 if (curl_buf->action)
286 parse_timeline(curl_buf->data);
288 dbg("%s\n", curl_buf->data);
293 static int send_request(struct session *session)
295 char user_password[500];
297 /* is there usernames longer than 22 chars? */
299 struct bti_curl_buffer *curl_buf;
302 struct curl_httppost *formpost = NULL;
303 struct curl_httppost *lastptr = NULL;
304 struct curl_slist *slist = NULL;
309 curl_buf = bti_curl_buffer_alloc(session->action);
317 switch (session->action) {
319 snprintf(user_password, sizeof(user_password), "%s:%s",
320 session->account, session->password);
321 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
322 curl_formadd(&formpost, &lastptr,
323 CURLFORM_COPYNAME, "status",
324 CURLFORM_COPYCONTENTS, session->tweet,
327 curl_formadd(&formpost, &lastptr,
328 CURLFORM_COPYNAME, "source",
329 CURLFORM_COPYCONTENTS, "bti",
332 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
333 slist = curl_slist_append(slist, "Expect:");
334 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
335 switch (session->host) {
337 curl_easy_setopt(curl, CURLOPT_URL,
341 curl_easy_setopt(curl, CURLOPT_URL,
342 identica_update_url);
345 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
349 snprintf(user_password, sizeof(user_password), "%s:%s",
350 session->account, session->password);
351 switch (session->host) {
353 sprintf(user_url, "%s?page=%d", twitter_friends_url, session->page);
354 curl_easy_setopt(curl, CURLOPT_URL, user_url);
357 sprintf(user_url, "%s?page=%d", identica_friends_url, session->page);
358 curl_easy_setopt(curl, CURLOPT_URL, user_url);
361 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
365 switch (session->host) {
367 sprintf(user_url, "%s%s.xml?page=%d", twitter_user_url, session->user, session->page);
368 curl_easy_setopt(curl, CURLOPT_URL, user_url);
371 sprintf(user_url, "%s%s.xml?page=%d", identica_user_url, session->user, session->page);
372 curl_easy_setopt(curl, CURLOPT_URL, user_url);
378 snprintf(user_password, sizeof(user_password), "%s:%s",
379 session->account, session->password);
380 switch (session->host) {
382 sprintf(user_url, "%s?page=%d", twitter_replies_url, session->page);
383 curl_easy_setopt(curl, CURLOPT_URL, user_url);
386 sprintf(user_url, "%s?page=%d", identica_replies_url, session->page);
387 curl_easy_setopt(curl, CURLOPT_URL, user_url);
390 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
394 switch (session->host) {
396 sprintf(user_url, "%s?page=%d", twitter_public_url, session->page);
397 curl_easy_setopt(curl, CURLOPT_URL, user_url);
400 sprintf(user_url, "%s?page=%d", identica_public_url, session->page);
401 curl_easy_setopt(curl, CURLOPT_URL, user_url);
411 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
414 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
416 dbg("user_password = %s\n", user_password);
417 dbg("data = %s\n", data);
418 dbg("proxy = %s\n", session->proxy);
420 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
421 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
422 if (!session->dry_run) {
423 res = curl_easy_perform(curl);
424 if (res && !session->bash) {
425 fprintf(stderr, "error(%d) trying to perform "
431 curl_easy_cleanup(curl);
432 if (session->action == ACTION_UPDATE)
433 curl_formfree(formpost);
434 bti_curl_buffer_free(curl_buf);
438 static void parse_configfile(struct session *session)
443 char *account = NULL;
444 char *password = NULL;
447 char *logfile = NULL;
453 /* config file is ~/.bti */
454 file = alloca(strlen(session->homedir) + 7);
456 sprintf(file, "%s/.bti", session->homedir);
458 config_file = fopen(file, "r");
460 /* No error if file does not exist or is unreadable. */
461 if (config_file == NULL)
465 ssize_t n = getline(&line, &len, config_file);
468 if (line[n - 1] == '\n')
470 /* Parse file. Format is the usual value pairs:
473 # is a comment character
475 *strchrnul(line, '#') = '\0';
479 /* Ignore blank lines. */
483 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
487 } else if (!strncasecmp(c, "password", 8) &&
491 password = strdup(c);
492 } else if (!strncasecmp(c, "host", 4) &&
497 } else if (!strncasecmp(c, "proxy", 5) &&
502 } else if (!strncasecmp(c, "logfile", 7) &&
507 } else if (!strncasecmp(c, "action", 6) &&
512 } else if (!strncasecmp(c, "user", 4) &&
517 } else if (!strncasecmp(c, "shrink-urls", 11) &&
520 if (!strncasecmp(c, "true", 4) ||
521 !strncasecmp(c, "yes", 3))
524 } while (!feof(config_file));
527 session->password = password;
529 session->account = account;
531 if (strcasecmp(host, "twitter") == 0)
532 session->host = HOST_TWITTER;
533 if (strcasecmp(host, "identica") == 0)
534 session->host = HOST_IDENTICA;
539 free(session->proxy);
540 session->proxy = proxy;
543 session->logfile = logfile;
545 if (strcasecmp(action, "update") == 0)
546 session->action = ACTION_UPDATE;
547 else if (strcasecmp(action, "friends") == 0)
548 session->action = ACTION_FRIENDS;
549 else if (strcasecmp(action, "user") == 0)
550 session->action = ACTION_USER;
551 else if (strcasecmp(action, "replies") == 0)
552 session->action = ACTION_REPLIES;
553 else if (strcasecmp(action, "public") == 0)
554 session->action = ACTION_PUBLIC;
556 session->action = ACTION_UNKNOWN;
560 session->user = user;
561 session->shrink_urls = shrink_urls;
563 /* Free buffer and close file. */
568 static void log_session(struct session *session, int retval)
574 /* Only log something if we have a log file set */
575 if (!session->logfile)
578 filename = alloca(strlen(session->homedir) +
579 strlen(session->logfile) + 3);
581 sprintf(filename, "%s/%s", session->homedir, session->logfile);
583 log_file = fopen(filename, "a+");
584 if (log_file == NULL)
586 switch (session->host) {
598 switch (session->action) {
601 fprintf(log_file, "%s: host=%s tweet failed\n",
602 session->time, host);
604 fprintf(log_file, "%s: host=%s tweet=%s\n",
605 session->time, host, session->tweet);
608 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
609 session->time, host);
612 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
613 session->time, host, session->user);
616 fprintf(log_file, "%s: host=%s retrieving replies\n",
617 session->time, host);
620 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
621 session->time, host);
630 static char *get_string_from_stdin(void)
635 string = zalloc(1000);
639 if (!fgets(string, 999, stdin))
641 temp = strchr(string, '\n');
646 static int find_urls(const char *tweet, int **pranges)
649 * magic obtained from
650 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
652 static const char *re_magic =
653 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
654 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
655 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
659 int ovector[10] = {0,};
660 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
661 int startoffset, tweetlen;
665 int *ranges = malloc(sizeof(int) * rbound);
667 re = pcre_compile(re_magic,
668 PCRE_NO_AUTO_CAPTURE,
669 &errptr, &erroffset, NULL);
671 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
675 tweetlen = strlen(tweet);
676 for (startoffset = 0; startoffset < tweetlen; ) {
678 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
680 if (rc == PCRE_ERROR_NOMATCH)
684 fprintf(stderr, "pcre_exec @%u: %s\n",
689 for (i = 0; i < rc; i += 2) {
690 if ((rcount+2) == rbound) {
692 ranges = realloc(ranges, sizeof(int) * rbound);
695 ranges[rcount++] = ovector[i];
696 ranges[rcount++] = ovector[i+1];
699 startoffset = ovector[1];
709 * bidirectional popen() call
711 * @param rwepipe - int array of size three
712 * @param exe - program to run
713 * @param argv - argument list
714 * @return pid or -1 on error
716 * The caller passes in an array of three integers (rwepipe), on successful
717 * execution it can then write to element 0 (stdin of exe), and read from
718 * element 1 (stdout) and 2 (stderr).
720 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
750 } else if (pid == 0) {
762 execvp(exe, (char **)argv);
782 static int pcloseRWE(int pid, int *rwepipe)
788 rc = waitpid(pid, &status, 0);
792 static char *shrink_one_url(int *rwepipe, char *big)
794 int biglen = strlen(big);
799 rc = dprintf(rwepipe[0], "%s\n", big);
803 smalllen = biglen + 128;
804 small = malloc(smalllen);
808 rc = read(rwepipe[1], small, smalllen);
809 if (rc < 0 || rc > biglen)
810 goto error_free_small;
812 if (strncmp(small, "http://", 7))
813 goto error_free_small;
816 while (smalllen && isspace(small[smalllen-1]))
817 small[--smalllen] = 0;
827 static char *shrink_urls(char *text)
834 const char *const shrink_args[] = {
840 int inlen = strlen(text);
842 dbg("before len=%u\n", inlen);
844 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
848 rcount = find_urls(text, &ranges);
852 for (i = 0; i < rcount; i += 2) {
853 int url_start = ranges[i];
854 int url_end = ranges[i+1];
855 int long_url_len = url_end - url_start;
856 char *url = strndup(text + url_start, long_url_len);
858 int not_url_len = url_start - inofs;
860 dbg("long url[%u]: %s\n", long_url_len, url);
861 url = shrink_one_url(shrink_pipe, url);
862 short_url_len = url ? strlen(url) : 0;
863 dbg("short url[%u]: %s\n", short_url_len, url);
865 if (!url || short_url_len >= long_url_len) {
866 /* The short url ended up being too long
869 strncpy(text + outofs, text + inofs,
870 not_url_len + long_url_len);
872 inofs += not_url_len + long_url_len;
873 outofs += not_url_len + long_url_len;
876 /* copy the unmodified block */
877 strncpy(text + outofs, text + inofs, not_url_len);
878 inofs += not_url_len;
879 outofs += not_url_len;
881 /* copy the new url */
882 strncpy(text + outofs, url, short_url_len);
883 inofs += long_url_len;
884 outofs += short_url_len;
890 /* copy the last block after the last match */
892 int tail = inlen - inofs;
894 strncpy(text + outofs, text + inofs, tail);
901 (void)pcloseRWE(shrink_pid, shrink_pipe);
904 dbg("after len=%u\n", outofs);
908 int main(int argc, char *argv[], char *envp[])
910 static const struct option options[] = {
911 { "debug", 0, NULL, 'd' },
912 { "account", 1, NULL, 'a' },
913 { "password", 1, NULL, 'p' },
914 { "host", 1, NULL, 'H' },
915 { "proxy", 1, NULL, 'P' },
916 { "action", 1, NULL, 'A' },
917 { "user", 1, NULL, 'u' },
918 { "logfile", 1, NULL, 'L' },
919 { "shrink-urls", 0, NULL, 's' },
920 { "help", 0, NULL, 'h' },
921 { "bash", 0, NULL, 'b' },
922 { "dry-run", 0, NULL, 'n' },
923 { "page", 1, NULL, 'g' },
924 { "version", 0, NULL, 'v' },
927 struct session *session;
937 rl_bind_key('\t', rl_insert);
939 session = session_alloc();
941 fprintf(stderr, "no more memory...\n");
945 /* get the current time so that we can log it later */
947 session->time = strdup(ctime(&t));
948 session->time[strlen(session->time)-1] = 0x00;
950 session->homedir = strdup(getenv("HOME"));
952 curl_global_init(CURL_GLOBAL_ALL);
954 /* Set environment variables first, before reading command line options
955 * or config file values. */
956 http_proxy = getenv("http_proxy");
959 free(session->proxy);
960 session->proxy = strdup(http_proxy);
961 dbg("http_proxy = %s\n", session->proxy);
964 parse_configfile(session);
967 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:A:u:hg:",
976 if (session->account)
977 free(session->account);
978 session->account = strdup(optarg);
979 dbg("account = %s\n", session->account);
982 page_nr = atoi(optarg);
983 dbg("page = %d\n", page_nr);
984 session->page = page_nr;
987 if (session->password)
988 free(session->password);
989 session->password = strdup(optarg);
990 dbg("password = %s\n", session->password);
994 free(session->proxy);
995 session->proxy = strdup(optarg);
996 dbg("proxy = %s\n", session->proxy);
999 if (strcasecmp(optarg, "update") == 0)
1000 session->action = ACTION_UPDATE;
1001 else if (strcasecmp(optarg, "friends") == 0)
1002 session->action = ACTION_FRIENDS;
1003 else if (strcasecmp(optarg, "user") == 0)
1004 session->action = ACTION_USER;
1005 else if (strcasecmp(optarg, "replies") == 0)
1006 session->action = ACTION_REPLIES;
1007 else if (strcasecmp(optarg, "public") == 0)
1008 session->action = ACTION_PUBLIC;
1010 session->action = ACTION_UNKNOWN;
1011 dbg("action = %d\n", session->action);
1015 free(session->user);
1016 session->user = strdup(optarg);
1017 dbg("user = %s\n", session->user);
1020 if (session->logfile)
1021 free(session->logfile);
1022 session->logfile = strdup(optarg);
1023 dbg("logfile = %s\n", session->logfile);
1026 session->shrink_urls = 1;
1029 if (strcasecmp(optarg, "twitter") == 0)
1030 session->host = HOST_TWITTER;
1031 if (strcasecmp(optarg, "identica") == 0)
1032 session->host = HOST_IDENTICA;
1033 dbg("host = %d\n", session->host);
1042 session->dry_run = 1;
1053 if (session->action == ACTION_UNKNOWN) {
1054 fprintf(stderr, "Unknown action, valid actions are:\n");
1055 fprintf(stderr, "'update', 'friends', 'public', "
1056 "'replies' or 'user'.\n");
1060 if (!session->account) {
1061 fprintf(stdout, "Enter twitter account: ");
1062 session->account = readline(NULL);
1065 if (!session->password) {
1066 fprintf(stdout, "Enter twitter password: ");
1067 session->password = readline(NULL);
1070 if (session->action == ACTION_UPDATE) {
1072 tweet = get_string_from_stdin();
1074 tweet = readline("tweet: ");
1075 if (!tweet || strlen(tweet) == 0) {
1080 if (session->shrink_urls)
1081 tweet = shrink_urls(tweet);
1083 session->tweet = zalloc(strlen(tweet) + 10);
1085 sprintf(session->tweet, "$ %s", tweet);
1087 sprintf(session->tweet, "%s", tweet);
1090 dbg("tweet = %s\n", session->tweet);
1094 session->user = strdup(session->account);
1096 if (session->page == 0)
1098 dbg("account = %s\n", session->account);
1099 dbg("password = %s\n", session->password);
1100 dbg("host = %d\n", session->host);
1101 dbg("action = %d\n", session->action);
1103 /* fork ourself so that the main shell can get on
1104 * with it's life as we try to connect and handle everything
1106 if (session->bash) {
1109 dbg("child is %d\n", child);
1114 retval = send_request(session);
1115 if (retval && !session->bash)
1116 fprintf(stderr, "operation failed\n");
1118 log_session(session, retval);
1120 session_free(session);