2 * Copyright (C) 2008 Greg Kroah-Hartman <greg@kroah.com>
3 * Copyright (C) 2009 Bart Trojanowski <bart@jukie.net>
4 * Copyright (C) 2009 Amir Mohammad Saied <amirsaied@gmail.com>
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation version 2 of the License.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
33 #include <sys/types.h>
35 #include <curl/curl.h>
36 #include <readline/readline.h>
37 #include <libxml/xmlmemory.h>
38 #include <libxml/parser.h>
39 #include <libxml/tree.h>
43 #define zalloc(size) calloc(size, 1)
45 #define dbg(format, arg...) \
48 fprintf(stdout, "bti: %s: " format , __func__ , \
89 struct bti_curl_buffer {
95 static void display_help(void)
97 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
98 fprintf(stdout, "Version: " VERSION "\n");
99 fprintf(stdout, "Usage:\n");
100 fprintf(stdout, " bti [options]\n");
101 fprintf(stdout, "options are:\n");
102 fprintf(stdout, " --account accountname\n");
103 fprintf(stdout, " --password password\n");
104 fprintf(stdout, " --action action\n");
105 fprintf(stdout, " ('update', 'friends', 'public', 'replies' "
107 fprintf(stdout, " --user screenname\n");
108 fprintf(stdout, " --proxy PROXY:PORT\n");
109 fprintf(stdout, " --host HOST\n");
110 fprintf(stdout, " --logfile logfile\n");
111 fprintf(stdout, " --shrink-urls\n");
112 fprintf(stdout, " --page PAGENUMBER\n");
113 fprintf(stdout, " --bash\n");
114 fprintf(stdout, " --debug\n");
115 fprintf(stdout, " --verbose\n");
116 fprintf(stdout, " --dry-run\n");
117 fprintf(stdout, " --version\n");
118 fprintf(stdout, " --help\n");
121 static void display_version(void)
123 fprintf(stdout, "bti - version %s\n", VERSION);
126 static struct session *session_alloc(void)
128 struct session *session;
130 session = zalloc(sizeof(*session));
136 static void session_free(struct session *session)
140 free(session->password);
141 free(session->account);
142 free(session->tweet);
143 free(session->proxy);
145 free(session->homedir);
147 free(session->hosturl);
151 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
153 struct bti_curl_buffer *buffer;
155 buffer = zalloc(sizeof(*buffer));
159 /* start out with a data buffer of 1 byte to
160 * make the buffer fill logic simpler */
161 buffer->data = zalloc(1);
167 buffer->action = action;
171 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
179 static const char *twitter_host = "https://twitter.com/statuses";
180 static const char *identica_host = "https://identi.ca/api/statuses";
182 static const char *user_uri = "/user_timeline/";
183 static const char *update_uri = "/update.xml";
184 static const char *public_uri = "/public_timeline.xml";
185 static const char *friends_uri = "/friends_timeline.xml";
186 static const char *replies_uri = "/replies.xml";
188 static CURL *curl_init(void)
192 curl = curl_easy_init();
194 fprintf(stderr, "Can not init CURL!\n");
197 /* some ssl sanity checks on the connection we are making */
198 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
199 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
203 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
205 xmlChar *text = NULL;
206 xmlChar *user = NULL;
207 xmlChar *created = NULL;
210 current = current->xmlChildrenNode;
211 while (current != NULL) {
212 if (current->type == XML_ELEMENT_NODE) {
213 if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
214 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
215 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
216 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
217 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
218 userinfo = current->xmlChildrenNode;
219 while (userinfo != NULL) {
220 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
223 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
225 userinfo = userinfo->next;
229 if (user && text && created) {
231 printf("[%s] (%.16s) %s\n",
232 user, created, text);
244 current = current->next;
250 static void parse_timeline(char *document)
255 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
256 NULL, XML_PARSE_NOERROR);
260 current = xmlDocGetRootElement(doc);
261 if (current == NULL) {
262 fprintf(stderr, "empty document\n");
267 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
268 fprintf(stderr, "unexpected document type\n");
273 current = current->xmlChildrenNode;
274 while (current != NULL) {
275 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
276 parse_statuses(doc, current);
277 current = current->next;
284 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
287 struct bti_curl_buffer *curl_buf = userp;
288 size_t buffer_size = size * nmemb;
291 if ((!buffer) || (!buffer_size) || (!curl_buf))
294 /* add to the data we already have */
295 temp = zalloc(curl_buf->length + buffer_size + 1);
299 memcpy(temp, curl_buf->data, curl_buf->length);
300 free(curl_buf->data);
301 curl_buf->data = temp;
302 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
303 curl_buf->length += buffer_size;
304 if (curl_buf->action)
305 parse_timeline(curl_buf->data);
307 dbg("%s\n", curl_buf->data);
312 static int send_request(struct session *session)
315 char user_password[500];
317 struct bti_curl_buffer *curl_buf;
320 struct curl_httppost *formpost = NULL;
321 struct curl_httppost *lastptr = NULL;
322 struct curl_slist *slist = NULL;
327 curl_buf = bti_curl_buffer_alloc(session->action);
335 switch (session->action) {
337 snprintf(user_password, sizeof(user_password), "%s:%s",
338 session->account, session->password);
339 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
340 curl_formadd(&formpost, &lastptr,
341 CURLFORM_COPYNAME, "status",
342 CURLFORM_COPYCONTENTS, session->tweet,
345 curl_formadd(&formpost, &lastptr,
346 CURLFORM_COPYNAME, "source",
347 CURLFORM_COPYCONTENTS, "bti",
350 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
351 slist = curl_slist_append(slist, "Expect:");
352 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
354 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
355 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
356 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
360 snprintf(user_password, sizeof(user_password), "%s:%s",
361 session->account, session->password);
362 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
363 friends_uri, session->page);
364 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
365 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
369 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl, user_uri,
370 session->user, session->page);
371 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
375 snprintf(user_password, sizeof(user_password), "%s:%s",
376 session->account, session->password);
377 sprintf(endpoint, "%s%s?page=%d", session->hosturl, replies_uri, session->page);
378 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
379 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
383 sprintf(endpoint, "%s%s?page=%d", session->hosturl, public_uri, session->page);
384 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
392 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
395 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
397 dbg("user_password = %s\n", user_password);
398 dbg("data = %s\n", data);
399 dbg("proxy = %s\n", session->proxy);
401 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
402 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
403 if (!session->dry_run) {
404 res = curl_easy_perform(curl);
405 if (res && !session->bash) {
406 fprintf(stderr, "error(%d) trying to perform "
412 curl_easy_cleanup(curl);
413 if (session->action == ACTION_UPDATE)
414 curl_formfree(formpost);
415 bti_curl_buffer_free(curl_buf);
419 static void parse_configfile(struct session *session)
424 char *account = NULL;
425 char *password = NULL;
428 char *logfile = NULL;
434 /* config file is ~/.bti */
435 file = alloca(strlen(session->homedir) + 7);
437 sprintf(file, "%s/.bti", session->homedir);
439 config_file = fopen(file, "r");
441 /* No error if file does not exist or is unreadable. */
442 if (config_file == NULL)
446 ssize_t n = getline(&line, &len, config_file);
449 if (line[n - 1] == '\n')
451 /* Parse file. Format is the usual value pairs:
454 # is a comment character
456 *strchrnul(line, '#') = '\0';
460 /* Ignore blank lines. */
464 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
468 } else if (!strncasecmp(c, "password", 8) &&
472 password = strdup(c);
473 } else if (!strncasecmp(c, "host", 4) &&
478 } else if (!strncasecmp(c, "proxy", 5) &&
483 } else if (!strncasecmp(c, "logfile", 7) &&
488 } else if (!strncasecmp(c, "action", 6) &&
493 } else if (!strncasecmp(c, "user", 4) &&
498 } else if (!strncasecmp(c, "shrink-urls", 11) &&
501 if (!strncasecmp(c, "true", 4) ||
502 !strncasecmp(c, "yes", 3))
505 else if (!strncasecmp(c, "verbose", 7) &&
508 if (!strncasecmp(c, "true", 4) ||
509 !strncasecmp(c, "yes", 3))
512 } while (!feof(config_file));
515 session->password = password;
517 session->account = account;
519 if (strcasecmp(host, "twitter") == 0) {
520 session->host = HOST_TWITTER;
521 session->hosturl = strdup(twitter_host);
522 } else if (strcasecmp(host, "identica") == 0) {
523 session->host = HOST_IDENTICA;
524 session->hosturl = strdup(identica_host);
526 session->host = HOST_CUSTOM;
527 session->hosturl = strdup(host);
533 free(session->proxy);
534 session->proxy = proxy;
537 session->logfile = logfile;
539 if (strcasecmp(action, "update") == 0)
540 session->action = ACTION_UPDATE;
541 else if (strcasecmp(action, "friends") == 0)
542 session->action = ACTION_FRIENDS;
543 else if (strcasecmp(action, "user") == 0)
544 session->action = ACTION_USER;
545 else if (strcasecmp(action, "replies") == 0)
546 session->action = ACTION_REPLIES;
547 else if (strcasecmp(action, "public") == 0)
548 session->action = ACTION_PUBLIC;
550 session->action = ACTION_UNKNOWN;
554 session->user = user;
555 session->shrink_urls = shrink_urls;
557 /* Free buffer and close file. */
562 static void log_session(struct session *session, int retval)
568 /* Only log something if we have a log file set */
569 if (!session->logfile)
572 filename = alloca(strlen(session->homedir) +
573 strlen(session->logfile) + 3);
575 sprintf(filename, "%s/%s", session->homedir, session->logfile);
577 log_file = fopen(filename, "a+");
578 if (log_file == NULL)
580 switch (session->host) {
588 host = session->hosturl;
592 switch (session->action) {
595 fprintf(log_file, "%s: host=%s tweet failed\n",
596 session->time, host);
598 fprintf(log_file, "%s: host=%s tweet=%s\n",
599 session->time, host, session->tweet);
602 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
603 session->time, host);
606 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
607 session->time, host, session->user);
610 fprintf(log_file, "%s: host=%s retrieving replies\n",
611 session->time, host);
614 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
615 session->time, host);
624 static char *get_string_from_stdin(void)
629 string = zalloc(1000);
633 if (!fgets(string, 999, stdin))
635 temp = strchr(string, '\n');
640 static int find_urls(const char *tweet, int **pranges)
643 * magic obtained from
644 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
646 static const char *re_magic =
647 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
648 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
649 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
653 int ovector[10] = {0,};
654 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
655 int startoffset, tweetlen;
659 int *ranges = malloc(sizeof(int) * rbound);
661 re = pcre_compile(re_magic,
662 PCRE_NO_AUTO_CAPTURE,
663 &errptr, &erroffset, NULL);
665 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
669 tweetlen = strlen(tweet);
670 for (startoffset = 0; startoffset < tweetlen; ) {
672 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
674 if (rc == PCRE_ERROR_NOMATCH)
678 fprintf(stderr, "pcre_exec @%u: %s\n",
683 for (i = 0; i < rc; i += 2) {
684 if ((rcount+2) == rbound) {
686 ranges = realloc(ranges, sizeof(int) * rbound);
689 ranges[rcount++] = ovector[i];
690 ranges[rcount++] = ovector[i+1];
693 startoffset = ovector[1];
703 * bidirectional popen() call
705 * @param rwepipe - int array of size three
706 * @param exe - program to run
707 * @param argv - argument list
708 * @return pid or -1 on error
710 * The caller passes in an array of three integers (rwepipe), on successful
711 * execution it can then write to element 0 (stdin of exe), and read from
712 * element 1 (stdout) and 2 (stderr).
714 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
744 } else if (pid == 0) {
756 execvp(exe, (char **)argv);
776 static int pcloseRWE(int pid, int *rwepipe)
782 rc = waitpid(pid, &status, 0);
786 static char *shrink_one_url(int *rwepipe, char *big)
788 int biglen = strlen(big);
793 rc = dprintf(rwepipe[0], "%s\n", big);
797 smalllen = biglen + 128;
798 small = malloc(smalllen);
802 rc = read(rwepipe[1], small, smalllen);
803 if (rc < 0 || rc > biglen)
804 goto error_free_small;
806 if (strncmp(small, "http://", 7))
807 goto error_free_small;
810 while (smalllen && isspace(small[smalllen-1]))
811 small[--smalllen] = 0;
821 static char *shrink_urls(char *text)
828 const char *const shrink_args[] = {
834 int inlen = strlen(text);
836 dbg("before len=%u\n", inlen);
838 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
842 rcount = find_urls(text, &ranges);
846 for (i = 0; i < rcount; i += 2) {
847 int url_start = ranges[i];
848 int url_end = ranges[i+1];
849 int long_url_len = url_end - url_start;
850 char *url = strndup(text + url_start, long_url_len);
852 int not_url_len = url_start - inofs;
854 dbg("long url[%u]: %s\n", long_url_len, url);
855 url = shrink_one_url(shrink_pipe, url);
856 short_url_len = url ? strlen(url) : 0;
857 dbg("short url[%u]: %s\n", short_url_len, url);
859 if (!url || short_url_len >= long_url_len) {
860 /* The short url ended up being too long
863 strncpy(text + outofs, text + inofs,
864 not_url_len + long_url_len);
866 inofs += not_url_len + long_url_len;
867 outofs += not_url_len + long_url_len;
870 /* copy the unmodified block */
871 strncpy(text + outofs, text + inofs, not_url_len);
872 inofs += not_url_len;
873 outofs += not_url_len;
875 /* copy the new url */
876 strncpy(text + outofs, url, short_url_len);
877 inofs += long_url_len;
878 outofs += short_url_len;
884 /* copy the last block after the last match */
886 int tail = inlen - inofs;
888 strncpy(text + outofs, text + inofs, tail);
895 (void)pcloseRWE(shrink_pid, shrink_pipe);
898 dbg("after len=%u\n", outofs);
902 int main(int argc, char *argv[], char *envp[])
904 static const struct option options[] = {
905 { "debug", 0, NULL, 'd' },
906 { "verbose", 0, NULL, 'V' },
907 { "account", 1, NULL, 'a' },
908 { "password", 1, NULL, 'p' },
909 { "host", 1, NULL, 'H' },
910 { "proxy", 1, NULL, 'P' },
911 { "action", 1, NULL, 'A' },
912 { "user", 1, NULL, 'u' },
913 { "logfile", 1, NULL, 'L' },
914 { "shrink-urls", 0, NULL, 's' },
915 { "help", 0, NULL, 'h' },
916 { "bash", 0, NULL, 'b' },
917 { "dry-run", 0, NULL, 'n' },
918 { "page", 1, NULL, 'g' },
919 { "version", 0, NULL, 'v' },
922 struct session *session;
933 rl_bind_key('\t', rl_insert);
935 session = session_alloc();
937 fprintf(stderr, "no more memory...\n");
941 /* get the current time so that we can log it later */
943 session->time = strdup(ctime(&t));
944 session->time[strlen(session->time)-1] = 0x00;
946 session->homedir = strdup(getenv("HOME"));
948 curl_global_init(CURL_GLOBAL_ALL);
950 /* Set environment variables first, before reading command line options
951 * or config file values. */
952 http_proxy = getenv("http_proxy");
955 free(session->proxy);
956 session->proxy = strdup(http_proxy);
957 dbg("http_proxy = %s\n", session->proxy);
960 parse_configfile(session);
963 option = getopt_long_only(argc, argv, "dp:P:H:a:A:u:hg:snVv",
975 if (session->account)
976 free(session->account);
977 session->account = strdup(optarg);
978 dbg("account = %s\n", session->account);
981 page_nr = atoi(optarg);
982 dbg("page = %d\n", page_nr);
983 session->page = page_nr;
986 if (session->password)
987 free(session->password);
988 session->password = strdup(optarg);
989 dbg("password = %s\n", session->password);
993 free(session->proxy);
994 session->proxy = strdup(optarg);
995 dbg("proxy = %s\n", session->proxy);
998 if (strcasecmp(optarg, "update") == 0)
999 session->action = ACTION_UPDATE;
1000 else if (strcasecmp(optarg, "friends") == 0)
1001 session->action = ACTION_FRIENDS;
1002 else if (strcasecmp(optarg, "user") == 0)
1003 session->action = ACTION_USER;
1004 else if (strcasecmp(optarg, "replies") == 0)
1005 session->action = ACTION_REPLIES;
1006 else if (strcasecmp(optarg, "public") == 0)
1007 session->action = ACTION_PUBLIC;
1009 session->action = ACTION_UNKNOWN;
1010 dbg("action = %d\n", session->action);
1014 free(session->user);
1015 session->user = strdup(optarg);
1016 dbg("user = %s\n", session->user);
1019 if (session->logfile)
1020 free(session->logfile);
1021 session->logfile = strdup(optarg);
1022 dbg("logfile = %s\n", session->logfile);
1025 session->shrink_urls = 1;
1028 if (session->hosturl)
1029 free(session->hosturl);
1030 if (strcasecmp(optarg, "twitter") == 0) {
1031 session->host = HOST_TWITTER;
1032 session->hosturl = strdup(twitter_host);
1033 } else if (strcasecmp(optarg, "identica") == 0) {
1034 session->host = HOST_IDENTICA;
1035 session->hosturl = strdup(identica_host);
1037 session->host = HOST_CUSTOM;
1038 session->hosturl = strdup(optarg);
1040 dbg("host = %d\n", session->host);
1049 session->dry_run = 1;
1061 * Show the version to make it easier to determine what
1067 if (session->action == ACTION_UNKNOWN) {
1068 fprintf(stderr, "Unknown action, valid actions are:\n");
1069 fprintf(stderr, "'update', 'friends', 'public', "
1070 "'replies' or 'user'.\n");
1074 if (!session->account) {
1075 fprintf(stdout, "Enter twitter account: ");
1076 session->account = readline(NULL);
1079 if (!session->password) {
1080 fprintf(stdout, "Enter twitter password: ");
1081 session->password = readline(NULL);
1084 if (session->action == ACTION_UPDATE) {
1086 tweet = get_string_from_stdin();
1088 tweet = readline("tweet: ");
1089 if (!tweet || strlen(tweet) == 0) {
1094 if (session->shrink_urls)
1095 tweet = shrink_urls(tweet);
1097 session->tweet = zalloc(strlen(tweet) + 10);
1099 sprintf(session->tweet, "%c %s", getuid() ? '$' : '#', tweet);
1101 sprintf(session->tweet, "%s", tweet);
1104 dbg("tweet = %s\n", session->tweet);
1108 session->user = strdup(session->account);
1110 if (session->page == 0)
1112 dbg("account = %s\n", session->account);
1113 dbg("password = %s\n", session->password);
1114 dbg("host = %d\n", session->host);
1115 dbg("action = %d\n", session->action);
1117 /* fork ourself so that the main shell can get on
1118 * with it's life as we try to connect and handle everything
1120 if (session->bash) {
1123 dbg("child is %d\n", child);
1128 retval = send_request(session);
1129 if (retval && !session->bash)
1130 fprintf(stderr, "operation failed\n");
1132 log_session(session, retval);
1134 session_free(session);