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__ , \
87 struct bti_curl_buffer {
93 static void display_help(void)
95 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
96 fprintf(stdout, "Version: " VERSION "\n");
97 fprintf(stdout, "Usage:\n");
98 fprintf(stdout, " bti [options]\n");
99 fprintf(stdout, "options are:\n");
100 fprintf(stdout, " --account accountname\n");
101 fprintf(stdout, " --password password\n");
102 fprintf(stdout, " --action action\n");
103 fprintf(stdout, " ('update', 'friends', 'public', 'replies' "
105 fprintf(stdout, " --user screenname\n");
106 fprintf(stdout, " --proxy PROXY:PORT\n");
107 fprintf(stdout, " --host HOST\n");
108 fprintf(stdout, " --logfile logfile\n");
109 fprintf(stdout, " --shrink-urls\n");
110 fprintf(stdout, " --page PAGENUMBER\n");
111 fprintf(stdout, " --bash\n");
112 fprintf(stdout, " --debug\n");
113 fprintf(stdout, " --dry-run\n");
114 fprintf(stdout, " --version\n");
115 fprintf(stdout, " --help\n");
118 static void display_version(void)
120 fprintf(stdout, "bti - version %s\n", VERSION);
123 static struct session *session_alloc(void)
125 struct session *session;
127 session = zalloc(sizeof(*session));
133 static void session_free(struct session *session)
137 free(session->password);
138 free(session->account);
139 free(session->tweet);
140 free(session->proxy);
142 free(session->homedir);
144 free(session->hosturl);
148 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
150 struct bti_curl_buffer *buffer;
152 buffer = zalloc(sizeof(*buffer));
156 /* start out with a data buffer of 1 byte to
157 * make the buffer fill logic simpler */
158 buffer->data = zalloc(1);
164 buffer->action = action;
168 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
176 static const char *twitter_host = "http://twitter.com/statuses";
177 static const char *identica_host = "https://identi.ca/api/statuses";
179 static const char *user_uri = "/user_timeline/";
180 static const char *update_uri = "/update.xml";
181 static const char *public_uri = "/public_timeline.xml";
182 static const char *friends_uri = "/friends_timeline.xml";
183 static const char *replies_uri = "/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 *created = 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 created = 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 && created) {
227 printf("[%s] (%.16s) %s\n",
228 user, created, text);
237 current = current->next;
243 static void parse_timeline(char *document)
248 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
249 NULL, XML_PARSE_NOERROR);
253 current = xmlDocGetRootElement(doc);
254 if (current == NULL) {
255 fprintf(stderr, "empty document\n");
260 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
261 fprintf(stderr, "unexpected document type\n");
266 current = current->xmlChildrenNode;
267 while (current != NULL) {
268 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
269 parse_statuses(doc, current);
270 current = current->next;
277 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
280 struct bti_curl_buffer *curl_buf = userp;
281 size_t buffer_size = size * nmemb;
284 if ((!buffer) || (!buffer_size) || (!curl_buf))
287 /* add to the data we already have */
288 temp = zalloc(curl_buf->length + buffer_size + 1);
292 memcpy(temp, curl_buf->data, curl_buf->length);
293 free(curl_buf->data);
294 curl_buf->data = temp;
295 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
296 curl_buf->length += buffer_size;
297 if (curl_buf->action)
298 parse_timeline(curl_buf->data);
300 dbg("%s\n", curl_buf->data);
305 static int send_request(struct session *session)
308 char user_password[500];
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);
347 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
348 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
349 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
353 snprintf(user_password, sizeof(user_password), "%s:%s",
354 session->account, session->password);
355 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
356 friends_uri, session->page);
357 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
358 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
362 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl, user_uri,
363 session->user, session->page);
364 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
368 snprintf(user_password, sizeof(user_password), "%s:%s",
369 session->account, session->password);
370 sprintf(endpoint, "%s%s?page=%d", session->hosturl, replies_uri, session->page);
371 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
372 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
376 sprintf(endpoint, "%s%s?page=%d", session->hosturl, public_uri, session->page);
377 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
385 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
388 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
390 dbg("user_password = %s\n", user_password);
391 dbg("data = %s\n", data);
392 dbg("proxy = %s\n", session->proxy);
394 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
395 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
396 if (!session->dry_run) {
397 res = curl_easy_perform(curl);
398 if (res && !session->bash) {
399 fprintf(stderr, "error(%d) trying to perform "
405 curl_easy_cleanup(curl);
406 if (session->action == ACTION_UPDATE)
407 curl_formfree(formpost);
408 bti_curl_buffer_free(curl_buf);
412 static void parse_configfile(struct session *session)
417 char *account = NULL;
418 char *password = NULL;
421 char *logfile = NULL;
427 /* config file is ~/.bti */
428 file = alloca(strlen(session->homedir) + 7);
430 sprintf(file, "%s/.bti", session->homedir);
432 config_file = fopen(file, "r");
434 /* No error if file does not exist or is unreadable. */
435 if (config_file == NULL)
439 ssize_t n = getline(&line, &len, config_file);
442 if (line[n - 1] == '\n')
444 /* Parse file. Format is the usual value pairs:
447 # is a comment character
449 *strchrnul(line, '#') = '\0';
453 /* Ignore blank lines. */
457 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
461 } else if (!strncasecmp(c, "password", 8) &&
465 password = strdup(c);
466 } else if (!strncasecmp(c, "host", 4) &&
471 } else if (!strncasecmp(c, "proxy", 5) &&
476 } else if (!strncasecmp(c, "logfile", 7) &&
481 } else if (!strncasecmp(c, "action", 6) &&
486 } else if (!strncasecmp(c, "user", 4) &&
491 } else if (!strncasecmp(c, "shrink-urls", 11) &&
494 if (!strncasecmp(c, "true", 4) ||
495 !strncasecmp(c, "yes", 3))
498 } while (!feof(config_file));
501 session->password = password;
503 session->account = account;
505 if (strcasecmp(host, "twitter") == 0) {
506 session->host = HOST_TWITTER;
507 session->hosturl = strdup(twitter_host);
508 } else if (strcasecmp(host, "identica") == 0) {
509 session->host = HOST_IDENTICA;
510 session->hosturl = strdup(identica_host);
512 session->host = HOST_CUSTOM;
513 session->hosturl = strdup(host);
519 free(session->proxy);
520 session->proxy = proxy;
523 session->logfile = logfile;
525 if (strcasecmp(action, "update") == 0)
526 session->action = ACTION_UPDATE;
527 else if (strcasecmp(action, "friends") == 0)
528 session->action = ACTION_FRIENDS;
529 else if (strcasecmp(action, "user") == 0)
530 session->action = ACTION_USER;
531 else if (strcasecmp(action, "replies") == 0)
532 session->action = ACTION_REPLIES;
533 else if (strcasecmp(action, "public") == 0)
534 session->action = ACTION_PUBLIC;
536 session->action = ACTION_UNKNOWN;
540 session->user = user;
541 session->shrink_urls = shrink_urls;
543 /* Free buffer and close file. */
548 static void log_session(struct session *session, int retval)
554 /* Only log something if we have a log file set */
555 if (!session->logfile)
558 filename = alloca(strlen(session->homedir) +
559 strlen(session->logfile) + 3);
561 sprintf(filename, "%s/%s", session->homedir, session->logfile);
563 log_file = fopen(filename, "a+");
564 if (log_file == NULL)
566 switch (session->host) {
574 host = session->hosturl;
578 switch (session->action) {
581 fprintf(log_file, "%s: host=%s tweet failed\n",
582 session->time, host);
584 fprintf(log_file, "%s: host=%s tweet=%s\n",
585 session->time, host, session->tweet);
588 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
589 session->time, host);
592 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
593 session->time, host, session->user);
596 fprintf(log_file, "%s: host=%s retrieving replies\n",
597 session->time, host);
600 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
601 session->time, host);
610 static char *get_string_from_stdin(void)
615 string = zalloc(1000);
619 if (!fgets(string, 999, stdin))
621 temp = strchr(string, '\n');
626 static int find_urls(const char *tweet, int **pranges)
629 * magic obtained from
630 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
632 static const char *re_magic =
633 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
634 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
635 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
639 int ovector[10] = {0,};
640 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
641 int startoffset, tweetlen;
645 int *ranges = malloc(sizeof(int) * rbound);
647 re = pcre_compile(re_magic,
648 PCRE_NO_AUTO_CAPTURE,
649 &errptr, &erroffset, NULL);
651 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
655 tweetlen = strlen(tweet);
656 for (startoffset = 0; startoffset < tweetlen; ) {
658 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
660 if (rc == PCRE_ERROR_NOMATCH)
664 fprintf(stderr, "pcre_exec @%u: %s\n",
669 for (i = 0; i < rc; i += 2) {
670 if ((rcount+2) == rbound) {
672 ranges = realloc(ranges, sizeof(int) * rbound);
675 ranges[rcount++] = ovector[i];
676 ranges[rcount++] = ovector[i+1];
679 startoffset = ovector[1];
689 * bidirectional popen() call
691 * @param rwepipe - int array of size three
692 * @param exe - program to run
693 * @param argv - argument list
694 * @return pid or -1 on error
696 * The caller passes in an array of three integers (rwepipe), on successful
697 * execution it can then write to element 0 (stdin of exe), and read from
698 * element 1 (stdout) and 2 (stderr).
700 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
730 } else if (pid == 0) {
742 execvp(exe, (char **)argv);
762 static int pcloseRWE(int pid, int *rwepipe)
768 rc = waitpid(pid, &status, 0);
772 static char *shrink_one_url(int *rwepipe, char *big)
774 int biglen = strlen(big);
779 rc = dprintf(rwepipe[0], "%s\n", big);
783 smalllen = biglen + 128;
784 small = malloc(smalllen);
788 rc = read(rwepipe[1], small, smalllen);
789 if (rc < 0 || rc > biglen)
790 goto error_free_small;
792 if (strncmp(small, "http://", 7))
793 goto error_free_small;
796 while (smalllen && isspace(small[smalllen-1]))
797 small[--smalllen] = 0;
807 static char *shrink_urls(char *text)
814 const char *const shrink_args[] = {
820 int inlen = strlen(text);
822 dbg("before len=%u\n", inlen);
824 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
828 rcount = find_urls(text, &ranges);
832 for (i = 0; i < rcount; i += 2) {
833 int url_start = ranges[i];
834 int url_end = ranges[i+1];
835 int long_url_len = url_end - url_start;
836 char *url = strndup(text + url_start, long_url_len);
838 int not_url_len = url_start - inofs;
840 dbg("long url[%u]: %s\n", long_url_len, url);
841 url = shrink_one_url(shrink_pipe, url);
842 short_url_len = url ? strlen(url) : 0;
843 dbg("short url[%u]: %s\n", short_url_len, url);
845 if (!url || short_url_len >= long_url_len) {
846 /* The short url ended up being too long
849 strncpy(text + outofs, text + inofs,
850 not_url_len + long_url_len);
852 inofs += not_url_len + long_url_len;
853 outofs += not_url_len + long_url_len;
856 /* copy the unmodified block */
857 strncpy(text + outofs, text + inofs, not_url_len);
858 inofs += not_url_len;
859 outofs += not_url_len;
861 /* copy the new url */
862 strncpy(text + outofs, url, short_url_len);
863 inofs += long_url_len;
864 outofs += short_url_len;
870 /* copy the last block after the last match */
872 int tail = inlen - inofs;
874 strncpy(text + outofs, text + inofs, tail);
881 (void)pcloseRWE(shrink_pid, shrink_pipe);
884 dbg("after len=%u\n", outofs);
888 int main(int argc, char *argv[], char *envp[])
890 static const struct option options[] = {
891 { "debug", 0, NULL, 'd' },
892 { "account", 1, NULL, 'a' },
893 { "password", 1, NULL, 'p' },
894 { "host", 1, NULL, 'H' },
895 { "proxy", 1, NULL, 'P' },
896 { "action", 1, NULL, 'A' },
897 { "user", 1, NULL, 'u' },
898 { "logfile", 1, NULL, 'L' },
899 { "shrink-urls", 0, NULL, 's' },
900 { "help", 0, NULL, 'h' },
901 { "bash", 0, NULL, 'b' },
902 { "dry-run", 0, NULL, 'n' },
903 { "page", 1, NULL, 'g' },
904 { "version", 0, NULL, 'v' },
907 struct session *session;
917 rl_bind_key('\t', rl_insert);
919 session = session_alloc();
921 fprintf(stderr, "no more memory...\n");
925 /* get the current time so that we can log it later */
927 session->time = strdup(ctime(&t));
928 session->time[strlen(session->time)-1] = 0x00;
930 session->homedir = strdup(getenv("HOME"));
932 curl_global_init(CURL_GLOBAL_ALL);
934 /* Set environment variables first, before reading command line options
935 * or config file values. */
936 http_proxy = getenv("http_proxy");
939 free(session->proxy);
940 session->proxy = strdup(http_proxy);
941 dbg("http_proxy = %s\n", session->proxy);
944 parse_configfile(session);
947 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:A:u:hg:sn",
956 if (session->account)
957 free(session->account);
958 session->account = strdup(optarg);
959 dbg("account = %s\n", session->account);
962 page_nr = atoi(optarg);
963 dbg("page = %d\n", page_nr);
964 session->page = page_nr;
967 if (session->password)
968 free(session->password);
969 session->password = strdup(optarg);
970 dbg("password = %s\n", session->password);
974 free(session->proxy);
975 session->proxy = strdup(optarg);
976 dbg("proxy = %s\n", session->proxy);
979 if (strcasecmp(optarg, "update") == 0)
980 session->action = ACTION_UPDATE;
981 else if (strcasecmp(optarg, "friends") == 0)
982 session->action = ACTION_FRIENDS;
983 else if (strcasecmp(optarg, "user") == 0)
984 session->action = ACTION_USER;
985 else if (strcasecmp(optarg, "replies") == 0)
986 session->action = ACTION_REPLIES;
987 else if (strcasecmp(optarg, "public") == 0)
988 session->action = ACTION_PUBLIC;
990 session->action = ACTION_UNKNOWN;
991 dbg("action = %d\n", session->action);
996 session->user = strdup(optarg);
997 dbg("user = %s\n", session->user);
1000 if (session->logfile)
1001 free(session->logfile);
1002 session->logfile = strdup(optarg);
1003 dbg("logfile = %s\n", session->logfile);
1006 session->shrink_urls = 1;
1009 if (session->hosturl)
1010 free(session->hosturl);
1011 if (strcasecmp(optarg, "twitter") == 0) {
1012 session->host = HOST_TWITTER;
1013 session->hosturl = strdup(twitter_host);
1014 } else if (strcasecmp(optarg, "identica") == 0) {
1015 session->host = HOST_IDENTICA;
1016 session->hosturl = strdup(identica_host);
1018 session->host = HOST_CUSTOM;
1019 session->hosturl = strdup(optarg);
1021 dbg("host = %d\n", session->host);
1030 session->dry_run = 1;
1042 * Show the version to make it easier to determine what
1048 if (session->action == ACTION_UNKNOWN) {
1049 fprintf(stderr, "Unknown action, valid actions are:\n");
1050 fprintf(stderr, "'update', 'friends', 'public', "
1051 "'replies' or 'user'.\n");
1055 if (!session->account) {
1056 fprintf(stdout, "Enter twitter account: ");
1057 session->account = readline(NULL);
1060 if (!session->password) {
1061 fprintf(stdout, "Enter twitter password: ");
1062 session->password = readline(NULL);
1065 if (session->action == ACTION_UPDATE) {
1067 tweet = get_string_from_stdin();
1069 tweet = readline("tweet: ");
1070 if (!tweet || strlen(tweet) == 0) {
1075 if (session->shrink_urls)
1076 tweet = shrink_urls(tweet);
1078 session->tweet = zalloc(strlen(tweet) + 10);
1080 sprintf(session->tweet, "%c %s", getuid() ? '$' : '#', tweet);
1082 sprintf(session->tweet, "%s", tweet);
1085 dbg("tweet = %s\n", session->tweet);
1089 session->user = strdup(session->account);
1091 if (session->page == 0)
1093 dbg("account = %s\n", session->account);
1094 dbg("password = %s\n", session->password);
1095 dbg("host = %d\n", session->host);
1096 dbg("action = %d\n", session->action);
1098 /* fork ourself so that the main shell can get on
1099 * with it's life as we try to connect and handle everything
1101 if (session->bash) {
1104 dbg("child is %d\n", child);
1109 retval = send_request(session);
1110 if (retval && !session->bash)
1111 fprintf(stderr, "operation failed\n");
1113 log_session(session, retval);
1115 session_free(session);