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__ , \
88 struct bti_curl_buffer {
94 static void display_help(void)
96 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
97 fprintf(stdout, "Version: " VERSION "\n");
98 fprintf(stdout, "Usage:\n");
99 fprintf(stdout, " bti [options]\n");
100 fprintf(stdout, "options are:\n");
101 fprintf(stdout, " --account accountname\n");
102 fprintf(stdout, " --password password\n");
103 fprintf(stdout, " --action action\n");
104 fprintf(stdout, " ('update', 'friends', 'public', 'replies' "
106 fprintf(stdout, " --user screenname\n");
107 fprintf(stdout, " --proxy PROXY:PORT\n");
108 fprintf(stdout, " --host HOST\n");
109 fprintf(stdout, " --logfile logfile\n");
110 fprintf(stdout, " --shrink-urls\n");
111 fprintf(stdout, " --page PAGENUMBER\n");
112 fprintf(stdout, " --bash\n");
113 fprintf(stdout, " --debug\n");
114 fprintf(stdout, " --verbose\n");
115 fprintf(stdout, " --dry-run\n");
116 fprintf(stdout, " --version\n");
117 fprintf(stdout, " --help\n");
120 static void display_version(void)
122 fprintf(stdout, "bti - version %s\n", VERSION);
125 static struct session *session_alloc(void)
127 struct session *session;
129 session = zalloc(sizeof(*session));
135 static void session_free(struct session *session)
139 free(session->password);
140 free(session->account);
141 free(session->tweet);
142 free(session->proxy);
144 free(session->homedir);
146 free(session->hosturl);
150 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
152 struct bti_curl_buffer *buffer;
154 buffer = zalloc(sizeof(*buffer));
158 /* start out with a data buffer of 1 byte to
159 * make the buffer fill logic simpler */
160 buffer->data = zalloc(1);
166 buffer->action = action;
170 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
178 static const char *twitter_host = "https://twitter.com/statuses";
179 static const char *identica_host = "https://identi.ca/api/statuses";
181 static const char *user_uri = "/user_timeline/";
182 static const char *update_uri = "/update.xml";
183 static const char *public_uri = "/public_timeline.xml";
184 static const char *friends_uri = "/friends_timeline.xml";
185 static const char *replies_uri = "/replies.xml";
187 static CURL *curl_init(void)
191 curl = curl_easy_init();
193 fprintf(stderr, "Can not init CURL!\n");
196 /* some ssl sanity checks on the connection we are making */
197 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
198 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
202 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
204 xmlChar *text = NULL;
205 xmlChar *user = NULL;
206 xmlChar *created = NULL;
209 current = current->xmlChildrenNode;
210 while (current != NULL) {
211 if (current->type == XML_ELEMENT_NODE) {
212 if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
213 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
214 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
215 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
216 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
217 userinfo = current->xmlChildrenNode;
218 while (userinfo != NULL) {
219 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
222 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
224 userinfo = userinfo->next;
228 if (user && text && created) {
230 printf("[%s] (%.16s) %s\n",
231 user, created, text);
243 current = current->next;
249 static void parse_timeline(char *document)
254 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
255 NULL, XML_PARSE_NOERROR);
259 current = xmlDocGetRootElement(doc);
260 if (current == NULL) {
261 fprintf(stderr, "empty document\n");
266 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
267 fprintf(stderr, "unexpected document type\n");
272 current = current->xmlChildrenNode;
273 while (current != NULL) {
274 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
275 parse_statuses(doc, current);
276 current = current->next;
283 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
286 struct bti_curl_buffer *curl_buf = userp;
287 size_t buffer_size = size * nmemb;
290 if ((!buffer) || (!buffer_size) || (!curl_buf))
293 /* add to the data we already have */
294 temp = zalloc(curl_buf->length + buffer_size + 1);
298 memcpy(temp, curl_buf->data, curl_buf->length);
299 free(curl_buf->data);
300 curl_buf->data = temp;
301 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
302 curl_buf->length += buffer_size;
303 if (curl_buf->action)
304 parse_timeline(curl_buf->data);
306 dbg("%s\n", curl_buf->data);
311 static int send_request(struct session *session)
314 char user_password[500];
316 struct bti_curl_buffer *curl_buf;
319 struct curl_httppost *formpost = NULL;
320 struct curl_httppost *lastptr = NULL;
321 struct curl_slist *slist = NULL;
326 curl_buf = bti_curl_buffer_alloc(session->action);
334 switch (session->action) {
336 snprintf(user_password, sizeof(user_password), "%s:%s",
337 session->account, session->password);
338 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
339 curl_formadd(&formpost, &lastptr,
340 CURLFORM_COPYNAME, "status",
341 CURLFORM_COPYCONTENTS, session->tweet,
344 curl_formadd(&formpost, &lastptr,
345 CURLFORM_COPYNAME, "source",
346 CURLFORM_COPYCONTENTS, "bti",
349 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
350 slist = curl_slist_append(slist, "Expect:");
351 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
353 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
354 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
355 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
359 snprintf(user_password, sizeof(user_password), "%s:%s",
360 session->account, session->password);
361 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
362 friends_uri, session->page);
363 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
364 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
368 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl, user_uri,
369 session->user, session->page);
370 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
374 snprintf(user_password, sizeof(user_password), "%s:%s",
375 session->account, session->password);
376 sprintf(endpoint, "%s%s?page=%d", session->hosturl, replies_uri, session->page);
377 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
378 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
382 sprintf(endpoint, "%s%s?page=%d", session->hosturl, public_uri, session->page);
383 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
391 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
394 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
396 dbg("user_password = %s\n", user_password);
397 dbg("data = %s\n", data);
398 dbg("proxy = %s\n", session->proxy);
400 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
401 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
402 if (!session->dry_run) {
403 res = curl_easy_perform(curl);
404 if (res && !session->bash) {
405 fprintf(stderr, "error(%d) trying to perform "
411 curl_easy_cleanup(curl);
412 if (session->action == ACTION_UPDATE)
413 curl_formfree(formpost);
414 bti_curl_buffer_free(curl_buf);
418 static void parse_configfile(struct session *session)
423 char *account = NULL;
424 char *password = NULL;
427 char *logfile = NULL;
433 /* config file is ~/.bti */
434 file = alloca(strlen(session->homedir) + 7);
436 sprintf(file, "%s/.bti", session->homedir);
438 config_file = fopen(file, "r");
440 /* No error if file does not exist or is unreadable. */
441 if (config_file == NULL)
445 ssize_t n = getline(&line, &len, config_file);
448 if (line[n - 1] == '\n')
450 /* Parse file. Format is the usual value pairs:
453 # is a comment character
455 *strchrnul(line, '#') = '\0';
459 /* Ignore blank lines. */
463 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
467 } else if (!strncasecmp(c, "password", 8) &&
471 password = strdup(c);
472 } else if (!strncasecmp(c, "host", 4) &&
477 } else if (!strncasecmp(c, "proxy", 5) &&
482 } else if (!strncasecmp(c, "logfile", 7) &&
487 } else if (!strncasecmp(c, "action", 6) &&
492 } else if (!strncasecmp(c, "user", 4) &&
497 } else if (!strncasecmp(c, "shrink-urls", 11) &&
500 if (!strncasecmp(c, "true", 4) ||
501 !strncasecmp(c, "yes", 3))
504 else if (!strncasecmp(c, "verbose", 7) &&
507 if (!strncasecmp(c, "true", 4) ||
508 !strncasecmp(c, "yes", 3))
511 } while (!feof(config_file));
514 session->password = password;
516 session->account = account;
518 if (strcasecmp(host, "twitter") == 0) {
519 session->host = HOST_TWITTER;
520 session->hosturl = strdup(twitter_host);
521 } else if (strcasecmp(host, "identica") == 0) {
522 session->host = HOST_IDENTICA;
523 session->hosturl = strdup(identica_host);
525 session->host = HOST_CUSTOM;
526 session->hosturl = strdup(host);
532 free(session->proxy);
533 session->proxy = proxy;
536 session->logfile = logfile;
538 if (strcasecmp(action, "update") == 0)
539 session->action = ACTION_UPDATE;
540 else if (strcasecmp(action, "friends") == 0)
541 session->action = ACTION_FRIENDS;
542 else if (strcasecmp(action, "user") == 0)
543 session->action = ACTION_USER;
544 else if (strcasecmp(action, "replies") == 0)
545 session->action = ACTION_REPLIES;
546 else if (strcasecmp(action, "public") == 0)
547 session->action = ACTION_PUBLIC;
549 session->action = ACTION_UNKNOWN;
553 session->user = user;
554 session->shrink_urls = shrink_urls;
556 /* Free buffer and close file. */
561 static void log_session(struct session *session, int retval)
567 /* Only log something if we have a log file set */
568 if (!session->logfile)
571 filename = alloca(strlen(session->homedir) +
572 strlen(session->logfile) + 3);
574 sprintf(filename, "%s/%s", session->homedir, session->logfile);
576 log_file = fopen(filename, "a+");
577 if (log_file == NULL)
579 switch (session->host) {
587 host = session->hosturl;
591 switch (session->action) {
594 fprintf(log_file, "%s: host=%s tweet failed\n",
595 session->time, host);
597 fprintf(log_file, "%s: host=%s tweet=%s\n",
598 session->time, host, session->tweet);
601 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
602 session->time, host);
605 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
606 session->time, host, session->user);
609 fprintf(log_file, "%s: host=%s retrieving replies\n",
610 session->time, host);
613 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
614 session->time, host);
623 static char *get_string_from_stdin(void)
628 string = zalloc(1000);
632 if (!fgets(string, 999, stdin))
634 temp = strchr(string, '\n');
639 static int find_urls(const char *tweet, int **pranges)
642 * magic obtained from
643 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
645 static const char *re_magic =
646 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
647 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
648 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
652 int ovector[10] = {0,};
653 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
654 int startoffset, tweetlen;
658 int *ranges = malloc(sizeof(int) * rbound);
660 re = pcre_compile(re_magic,
661 PCRE_NO_AUTO_CAPTURE,
662 &errptr, &erroffset, NULL);
664 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
668 tweetlen = strlen(tweet);
669 for (startoffset = 0; startoffset < tweetlen; ) {
671 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
673 if (rc == PCRE_ERROR_NOMATCH)
677 fprintf(stderr, "pcre_exec @%u: %s\n",
682 for (i = 0; i < rc; i += 2) {
683 if ((rcount+2) == rbound) {
685 ranges = realloc(ranges, sizeof(int) * rbound);
688 ranges[rcount++] = ovector[i];
689 ranges[rcount++] = ovector[i+1];
692 startoffset = ovector[1];
702 * bidirectional popen() call
704 * @param rwepipe - int array of size three
705 * @param exe - program to run
706 * @param argv - argument list
707 * @return pid or -1 on error
709 * The caller passes in an array of three integers (rwepipe), on successful
710 * execution it can then write to element 0 (stdin of exe), and read from
711 * element 1 (stdout) and 2 (stderr).
713 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
743 } else if (pid == 0) {
755 execvp(exe, (char **)argv);
775 static int pcloseRWE(int pid, int *rwepipe)
781 rc = waitpid(pid, &status, 0);
785 static char *shrink_one_url(int *rwepipe, char *big)
787 int biglen = strlen(big);
792 rc = dprintf(rwepipe[0], "%s\n", big);
796 smalllen = biglen + 128;
797 small = malloc(smalllen);
801 rc = read(rwepipe[1], small, smalllen);
802 if (rc < 0 || rc > biglen)
803 goto error_free_small;
805 if (strncmp(small, "http://", 7))
806 goto error_free_small;
809 while (smalllen && isspace(small[smalllen-1]))
810 small[--smalllen] = 0;
820 static char *shrink_urls(char *text)
827 const char *const shrink_args[] = {
833 int inlen = strlen(text);
835 dbg("before len=%u\n", inlen);
837 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
841 rcount = find_urls(text, &ranges);
845 for (i = 0; i < rcount; i += 2) {
846 int url_start = ranges[i];
847 int url_end = ranges[i+1];
848 int long_url_len = url_end - url_start;
849 char *url = strndup(text + url_start, long_url_len);
851 int not_url_len = url_start - inofs;
853 dbg("long url[%u]: %s\n", long_url_len, url);
854 url = shrink_one_url(shrink_pipe, url);
855 short_url_len = url ? strlen(url) : 0;
856 dbg("short url[%u]: %s\n", short_url_len, url);
858 if (!url || short_url_len >= long_url_len) {
859 /* The short url ended up being too long
862 strncpy(text + outofs, text + inofs,
863 not_url_len + long_url_len);
865 inofs += not_url_len + long_url_len;
866 outofs += not_url_len + long_url_len;
869 /* copy the unmodified block */
870 strncpy(text + outofs, text + inofs, not_url_len);
871 inofs += not_url_len;
872 outofs += not_url_len;
874 /* copy the new url */
875 strncpy(text + outofs, url, short_url_len);
876 inofs += long_url_len;
877 outofs += short_url_len;
883 /* copy the last block after the last match */
885 int tail = inlen - inofs;
887 strncpy(text + outofs, text + inofs, tail);
894 (void)pcloseRWE(shrink_pid, shrink_pipe);
897 dbg("after len=%u\n", outofs);
901 int main(int argc, char *argv[], char *envp[])
903 static const struct option options[] = {
904 { "debug", 0, NULL, 'd' },
905 { "verbose", 0, NULL, 'V' },
906 { "account", 1, NULL, 'a' },
907 { "password", 1, NULL, 'p' },
908 { "host", 1, NULL, 'H' },
909 { "proxy", 1, NULL, 'P' },
910 { "action", 1, NULL, 'A' },
911 { "user", 1, NULL, 'u' },
912 { "logfile", 1, NULL, 'L' },
913 { "shrink-urls", 0, NULL, 's' },
914 { "help", 0, NULL, 'h' },
915 { "bash", 0, NULL, 'b' },
916 { "dry-run", 0, NULL, 'n' },
917 { "page", 1, NULL, 'g' },
918 { "version", 0, NULL, 'v' },
921 struct session *session;
932 rl_bind_key('\t', rl_insert);
934 session = session_alloc();
936 fprintf(stderr, "no more memory...\n");
940 /* get the current time so that we can log it later */
942 session->time = strdup(ctime(&t));
943 session->time[strlen(session->time)-1] = 0x00;
945 session->homedir = strdup(getenv("HOME"));
947 curl_global_init(CURL_GLOBAL_ALL);
949 /* Set environment variables first, before reading command line options
950 * or config file values. */
951 http_proxy = getenv("http_proxy");
954 free(session->proxy);
955 session->proxy = strdup(http_proxy);
956 dbg("http_proxy = %s\n", session->proxy);
959 parse_configfile(session);
962 option = getopt_long_only(argc, argv, "dp:P:H:a:A:u:hg:snVv",
974 if (session->account)
975 free(session->account);
976 session->account = strdup(optarg);
977 dbg("account = %s\n", session->account);
980 page_nr = atoi(optarg);
981 dbg("page = %d\n", page_nr);
982 session->page = page_nr;
985 if (session->password)
986 free(session->password);
987 session->password = strdup(optarg);
988 dbg("password = %s\n", session->password);
992 free(session->proxy);
993 session->proxy = strdup(optarg);
994 dbg("proxy = %s\n", session->proxy);
997 if (strcasecmp(optarg, "update") == 0)
998 session->action = ACTION_UPDATE;
999 else if (strcasecmp(optarg, "friends") == 0)
1000 session->action = ACTION_FRIENDS;
1001 else if (strcasecmp(optarg, "user") == 0)
1002 session->action = ACTION_USER;
1003 else if (strcasecmp(optarg, "replies") == 0)
1004 session->action = ACTION_REPLIES;
1005 else if (strcasecmp(optarg, "public") == 0)
1006 session->action = ACTION_PUBLIC;
1008 session->action = ACTION_UNKNOWN;
1009 dbg("action = %d\n", session->action);
1013 free(session->user);
1014 session->user = strdup(optarg);
1015 dbg("user = %s\n", session->user);
1018 if (session->logfile)
1019 free(session->logfile);
1020 session->logfile = strdup(optarg);
1021 dbg("logfile = %s\n", session->logfile);
1024 session->shrink_urls = 1;
1027 if (session->hosturl)
1028 free(session->hosturl);
1029 if (strcasecmp(optarg, "twitter") == 0) {
1030 session->host = HOST_TWITTER;
1031 session->hosturl = strdup(twitter_host);
1032 } else if (strcasecmp(optarg, "identica") == 0) {
1033 session->host = HOST_IDENTICA;
1034 session->hosturl = strdup(identica_host);
1036 session->host = HOST_CUSTOM;
1037 session->hosturl = strdup(optarg);
1039 dbg("host = %d\n", session->host);
1048 session->dry_run = 1;
1060 * Show the version to make it easier to determine what
1066 if (session->action == ACTION_UNKNOWN) {
1067 fprintf(stderr, "Unknown action, valid actions are:\n");
1068 fprintf(stderr, "'update', 'friends', 'public', "
1069 "'replies' or 'user'.\n");
1073 if (!session->account) {
1074 fprintf(stdout, "Enter twitter account: ");
1075 session->account = readline(NULL);
1078 if (!session->password) {
1079 fprintf(stdout, "Enter twitter password: ");
1080 session->password = readline(NULL);
1083 if (session->action == ACTION_UPDATE) {
1085 tweet = get_string_from_stdin();
1087 tweet = readline("tweet: ");
1088 if (!tweet || strlen(tweet) == 0) {
1093 if (session->shrink_urls)
1094 tweet = shrink_urls(tweet);
1096 session->tweet = zalloc(strlen(tweet) + 10);
1098 sprintf(session->tweet, "%c %s", getuid() ? '$' : '#', tweet);
1100 sprintf(session->tweet, "%s", tweet);
1103 dbg("tweet = %s\n", session->tweet);
1107 session->user = strdup(session->account);
1109 if (session->page == 0)
1111 dbg("account = %s\n", session->account);
1112 dbg("password = %s\n", session->password);
1113 dbg("host = %d\n", session->host);
1114 dbg("action = %d\n", session->action);
1116 /* fork ourself so that the main shell can get on
1117 * with it's life as we try to connect and handle everything
1119 if (session->bash) {
1122 dbg("child is %d\n", child);
1127 retval = send_request(session);
1128 if (retval && !session->bash)
1129 fprintf(stderr, "operation failed\n");
1131 log_session(session, retval);
1133 session_free(session);