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); \
82 struct bti_curl_buffer {
88 static void display_help(void)
90 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
91 fprintf(stdout, "Version: " BTI_VERSION "\n");
92 fprintf(stdout, "Usage:\n");
93 fprintf(stdout, " bti [options]\n");
94 fprintf(stdout, "options are:\n");
95 fprintf(stdout, " --account accountname\n");
96 fprintf(stdout, " --password password\n");
97 fprintf(stdout, " --action action\n");
98 fprintf(stdout, " ('update', 'friends', 'public', 'replies' or 'user')\n");
99 fprintf(stdout, " --user screenname\n");
100 fprintf(stdout, " --proxy PROXY:PORT\n");
101 fprintf(stdout, " --host HOST\n");
102 fprintf(stdout, " --logfile logfile\n");
103 fprintf(stdout, " --shrink-urls\n");
104 fprintf(stdout, " --bash\n");
105 fprintf(stdout, " --debug\n");
106 fprintf(stdout, " --version\n");
107 fprintf(stdout, " --help\n");
110 static void display_version(void)
112 fprintf(stdout, "bti - version %s\n", BTI_VERSION);
115 static struct session *session_alloc(void)
117 struct session *session;
119 session = zalloc(sizeof(*session));
125 static void session_free(struct session *session)
129 free(session->password);
130 free(session->account);
131 free(session->tweet);
132 free(session->proxy);
134 free(session->homedir);
139 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
141 struct bti_curl_buffer *buffer;
143 buffer = zalloc(sizeof(*buffer));
147 /* start out with a data buffer of 1 byte to
148 * make the buffer fill logic simpler */
149 buffer->data = zalloc(1);
155 buffer->action = action;
159 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
167 static const char *twitter_user_url = "http://twitter.com/statuses/user_timeline/";
168 static const char *twitter_update_url = "https://twitter.com/statuses/update.xml";
169 static const char *twitter_public_url = "http://twitter.com/statuses/public_timeline.xml";
170 static const char *twitter_friends_url = "https://twitter.com/statuses/friends_timeline.xml";
171 static const char *twitter_replies_url = "http://twitter.com/statuses/replies.xml";
173 static const char *identica_user_url = "http://identi.ca/api/statuses/user_timeline/";
174 static const char *identica_update_url = "http://identi.ca/api/statuses/update.xml";
175 static const char *identica_public_url = "http://identi.ca/api/statuses/public_timeline.xml";
176 static const char *identica_friends_url = "http://identi.ca/api/statuses/friends_timeline.xml";
177 static const char *identica_replies_url = "http://identi.ca/api/statuses/replies.xml";
179 static CURL *curl_init(void)
183 curl = curl_easy_init();
185 fprintf(stderr, "Can not init CURL!\n");
188 /* some ssl sanity checks on the connection we are making */
189 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
190 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
194 void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
196 xmlChar *text = NULL;
197 xmlChar *user = NULL;
200 current = current->xmlChildrenNode;
201 while (current != NULL) {
202 if (current->type == XML_ELEMENT_NODE) {
203 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
204 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
205 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
206 userinfo = current->xmlChildrenNode;
207 while (userinfo != NULL) {
208 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
211 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
213 userinfo = userinfo->next;
217 printf("[%s] %s\n", user, text);
224 current = current->next;
230 static void parse_timeline(char *document)
234 doc = xmlReadMemory(document, strlen(document), "timeline.xml", NULL, XML_PARSE_NOERROR);
239 current = xmlDocGetRootElement(doc);
240 if (current == NULL) {
241 fprintf(stderr, "empty document\n");
246 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
247 fprintf(stderr, "unexpected document type\n");
252 current = current->xmlChildrenNode;
253 while (current != NULL) {
254 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
255 parse_statuses(doc, current);
256 current = current->next;
263 size_t curl_callback(void *buffer, size_t size, size_t nmemb, void *userp)
265 struct bti_curl_buffer *curl_buf = userp;
266 size_t buffer_size = size * nmemb;
269 if ((!buffer) || (!buffer_size) || (!curl_buf))
272 /* add to the data we already have */
273 temp = zalloc(curl_buf->length + buffer_size + 1);
277 memcpy(temp, curl_buf->data, curl_buf->length);
278 free(curl_buf->data);
279 curl_buf->data = temp;
280 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
281 curl_buf->length += buffer_size;
282 if (curl_buf->action)
283 parse_timeline(curl_buf->data);
285 dbg("%s\n", curl_buf->data);
290 static int send_request(struct session *session)
292 char user_password[500];
294 /* is there usernames longer than 22 chars? */
296 struct bti_curl_buffer *curl_buf;
299 struct curl_httppost *formpost = NULL;
300 struct curl_httppost *lastptr = NULL;
301 struct curl_slist *slist = NULL;
306 curl_buf = bti_curl_buffer_alloc(session->action);
314 switch (session->action) {
316 snprintf(user_password, sizeof(user_password), "%s:%s",
317 session->account, session->password);
318 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
319 curl_formadd(&formpost, &lastptr,
320 CURLFORM_COPYNAME, "status",
321 CURLFORM_COPYCONTENTS, session->tweet,
324 curl_formadd(&formpost, &lastptr,
325 CURLFORM_COPYNAME, "source",
326 CURLFORM_COPYCONTENTS, "bti",
329 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
330 slist = curl_slist_append(slist, "Expect:");
331 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
332 switch (session->host) {
334 curl_easy_setopt(curl, CURLOPT_URL, twitter_update_url);
337 curl_easy_setopt(curl, CURLOPT_URL, identica_update_url);
340 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
344 snprintf(user_password, sizeof(user_password), "%s:%s",
345 session->account, session->password);
346 switch (session->host) {
348 curl_easy_setopt(curl, CURLOPT_URL, twitter_friends_url);
351 curl_easy_setopt(curl, CURLOPT_URL, identica_friends_url);
354 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
358 switch (session->host) {
360 sprintf(user_url, "%s%s.xml", twitter_user_url, session->user);
361 curl_easy_setopt(curl, CURLOPT_URL, user_url);
364 sprintf(user_url, "%s%s.xml", identica_user_url, session->user);
365 curl_easy_setopt(curl, CURLOPT_URL, user_url);
371 snprintf(user_password, sizeof(user_password), "%s:%s",
372 session->account, session->password);
373 switch (session->host) {
375 curl_easy_setopt(curl, CURLOPT_URL, twitter_replies_url);
378 curl_easy_setopt(curl, CURLOPT_URL, identica_replies_url);
381 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
385 switch (session->host) {
387 curl_easy_setopt(curl, CURLOPT_URL, twitter_public_url);
390 curl_easy_setopt(curl, CURLOPT_URL, identica_public_url);
400 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
403 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
405 dbg("user_password = %s\n", user_password);
406 dbg("data = %s\n", data);
407 dbg("proxy = %s\n", session->proxy);
409 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
410 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
411 if (!session->dry_run) {
412 res = curl_easy_perform(curl);
413 if (res && !session->bash) {
414 fprintf(stderr, "error(%d) trying to perform operation\n", res);
419 curl_easy_cleanup(curl);
420 if (session->action == ACTION_UPDATE)
421 curl_formfree(formpost);
422 bti_curl_buffer_free(curl_buf);
426 static void parse_configfile(struct session *session)
431 char *account = NULL;
432 char *password = NULL;
435 char *logfile = NULL;
441 /* config file is ~/.bti */
442 file = alloca(strlen(session->homedir) + 7);
444 sprintf(file, "%s/.bti", session->homedir);
446 config_file = fopen(file, "r");
448 /* No error if file does not exist or is unreadable. */
449 if (config_file == NULL)
453 ssize_t n = getline(&line, &len, config_file);
456 if (line[n - 1] == '\n')
458 /* Parse file. Format is the usual value pairs:
461 # is a comment character
463 *strchrnul(line, '#') = '\0';
467 /* Ignore blank lines. */
471 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
475 } else if (!strncasecmp(c, "password", 8) &&
479 password = strdup(c);
480 } else if (!strncasecmp(c, "host", 4) &&
485 } else if (!strncasecmp(c, "proxy", 5) &&
490 } else if (!strncasecmp(c, "logfile", 7) &&
495 } else if (!strncasecmp(c, "action", 6) &&
500 } else if (!strncasecmp(c, "user", 4) &&
505 } else if (!strncasecmp(c, "shrink-urls", 11) &&
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 if (strcasecmp(host, "identica") == 0)
522 session->host = HOST_IDENTICA;
527 free(session->proxy);
528 session->proxy = proxy;
531 session->logfile = logfile;
533 if (strcasecmp(action, "update") == 0)
534 session->action = ACTION_UPDATE;
535 else if (strcasecmp(action, "friends") == 0)
536 session->action = ACTION_FRIENDS;
537 else if (strcasecmp(action, "user") == 0)
538 session->action = ACTION_USER;
539 else if (strcasecmp(action, "replies") == 0)
540 session->action = ACTION_REPLIES;
541 else if (strcasecmp(action, "public") == 0)
542 session->action = ACTION_PUBLIC;
544 session->action = ACTION_UNKNOWN;
548 session->user = user;
550 session->shrink_urls = shrink_urls;
552 /* Free buffer and close file. */
557 static void log_session(struct session *session, int retval)
563 /* Only log something if we have a log file set */
564 if (!session->logfile)
567 filename = alloca(strlen(session->homedir) +
568 strlen(session->logfile) + 3);
570 sprintf(filename, "%s/%s", session->homedir, session->logfile);
572 log_file = fopen(filename, "a+");
573 if (log_file == NULL)
575 switch (session->host) {
587 switch (session->action) {
590 fprintf(log_file, "%s: host=%s tweet failed\n",
591 session->time, host);
593 fprintf(log_file, "%s: host=%s tweet=%s\n",
594 session->time, host, session->tweet);
597 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
598 session->time, host);
601 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
602 session->time, host, session->user);
605 fprintf(log_file, "%s: host=%s retrieving replies\n",
606 session->time, host);
609 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
610 session->time, host);
619 static char *get_string_from_stdin(void)
624 string = zalloc(1000);
628 if (!fgets(string, 999, stdin))
630 temp = strchr(string, '\n');
635 static int find_urls(const char *tweet, int **pranges)
637 // magic obtained from http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
638 static const char *re_magic =
639 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
640 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
641 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
645 int ovector[10] = {0,};
646 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
647 int startoffset, tweetlen;
651 int *ranges = malloc(sizeof(int) * rbound);
653 re = pcre_compile(re_magic,
654 PCRE_NO_AUTO_CAPTURE,
655 &errptr, &erroffset, NULL);
657 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
661 tweetlen = strlen(tweet);
662 for (startoffset=0; startoffset<tweetlen; ) {
664 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
666 if (rc == PCRE_ERROR_NOMATCH)
670 fprintf(stderr, "pcre_exec @%u: %s\n", erroffset, errptr);
674 for (i=0; i<rc; i+=2) {
675 if ((rcount+2) == rbound) {
677 ranges = realloc(ranges, sizeof(int) * rbound);
680 ranges[rcount++] = ovector[i];
681 ranges[rcount++] = ovector[i+1];
684 startoffset = ovector[1];
694 * bidirectional popen() call
696 * @param rwepipe - int array of size three
697 * @param exe - program to run
698 * @param argv - argument list
699 * @return pid or -1 on error
701 * The caller passes in an array of three integers (rwepipe), on successful
702 * execution it can then write to element 0 (stdin of exe), and read from
703 * element 1 (stdout) and 2 (stderr).
705 static int popenRW(int *rwepipe, const char *exe, const char *const argv[])
726 if (pid > 0) { // parent
734 } else if (pid == 0) { // child
745 execvp(exe, (char**)argv);
765 static int pcloseRW(int pid, int *rwepipe)
771 rc = waitpid(pid, &status, 0);
775 static char *shrink_one_url(int *rwepipe, char *big)
777 int biglen = strlen(big);
782 rc = dprintf(rwepipe[0], "%s\n", big);
786 smalllen = biglen + 128;
787 small = malloc(smalllen);
791 rc = read(rwepipe[1], small, smalllen);
792 if (rc < 0 || rc > biglen)
793 goto error_free_small;
795 if (strncmp(small, "http://", 7))
796 goto error_free_small;
799 while (smalllen && isspace(small[smalllen-1]))
800 small[--smalllen] = 0;
810 static char *shrink_urls(char *text)
817 const char *const shrink_args[] = {
823 int inlen = strlen(text);
825 dbg("before len=%u\n", inlen);
827 shrink_pid = popenRW(shrink_pipe, shrink_args[0], shrink_args);
831 rcount = find_urls(text, &ranges);
833 for (i=0; i<rcount; i+=2) {
834 int url_start = ranges[i];
835 int url_end = ranges[i+1];
836 int long_url_len = url_end - url_start;
837 char *url = strndup(text + url_start, long_url_len);
839 int not_url_len = url_start - inofs;
841 dbg("long url[%u]: %s\n", long_url_len, url);
842 url = shrink_one_url(shrink_pipe, url);
843 short_url_len = url ? strlen(url) : 0;
844 dbg("short url[%u]: %s\n", short_url_len, url);
846 if (!url || short_url_len >= long_url_len) {
847 // the short url ended up being too long or unavailable
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;
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)pcloseRW(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 { "version", 0, NULL, 'v' },
906 struct session *session;
915 rl_bind_key('\t', rl_insert);
917 session = session_alloc();
919 fprintf(stderr, "no more memory...\n");
923 /* get the current time so that we can log it later */
925 session->time = strdup(ctime(&t));
926 session->time[strlen(session->time)-1] = 0x00;
928 session->homedir = strdup(getenv("HOME"));
930 curl_global_init(CURL_GLOBAL_ALL);
932 /* Set environment variables first, before reading command line options
933 * or config file values. */
934 http_proxy = getenv("http_proxy");
937 free(session->proxy);
938 session->proxy = strdup(http_proxy);
939 dbg("http_proxy = %s\n", session->proxy);
942 parse_configfile(session);
945 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:A:u:h",
954 if (session->account)
955 free(session->account);
956 session->account = strdup(optarg);
957 dbg("account = %s\n", session->account);
960 if (session->password)
961 free(session->password);
962 session->password = strdup(optarg);
963 dbg("password = %s\n", session->password);
967 free(session->proxy);
968 session->proxy = strdup(optarg);
969 dbg("proxy = %s\n", session->proxy);
972 if (strcasecmp(optarg, "update") == 0)
973 session->action = ACTION_UPDATE;
974 else if (strcasecmp(optarg, "friends") == 0)
975 session->action = ACTION_FRIENDS;
976 else if (strcasecmp(optarg, "user") == 0)
977 session->action = ACTION_USER;
978 else if (strcasecmp(optarg, "replies") == 0)
979 session->action = ACTION_REPLIES;
980 else if (strcasecmp(optarg, "public") == 0)
981 session->action = ACTION_PUBLIC;
983 session->action = ACTION_UNKNOWN;
984 dbg("action = %d\n", session->action);
989 session->user = strdup(optarg);
990 dbg("user = %s\n", session->user);
993 if (session->logfile)
994 free(session->logfile);
995 session->logfile = strdup(optarg);
996 dbg("logfile = %s\n", session->logfile);
999 session->shrink_urls = 1;
1002 if (strcasecmp(optarg, "twitter") == 0)
1003 session->host = HOST_TWITTER;
1004 if (strcasecmp(optarg, "identica") == 0)
1005 session->host = HOST_IDENTICA;
1006 dbg("host = %d\n", session->host);
1015 session->dry_run = 1;
1026 if (session->action == ACTION_UNKNOWN) {
1027 fprintf(stderr, "Unknown action, valid actions are:\n");
1028 fprintf(stderr, "'update', 'friends', 'public', 'replies' or 'user'.\n");
1032 if (!session->account) {
1033 fprintf(stdout, "Enter twitter account: ");
1034 session->account = readline(NULL);
1037 if (!session->password) {
1038 fprintf(stdout, "Enter twitter password: ");
1039 session->password = readline(NULL);
1042 if (session->action == ACTION_UPDATE) {
1044 tweet = get_string_from_stdin();
1046 tweet = readline("tweet: ");
1047 if (!tweet || strlen(tweet) == 0) {
1052 if (session->shrink_urls)
1053 tweet = shrink_urls(tweet);
1055 session->tweet = zalloc(strlen(tweet) + 10);
1057 sprintf(session->tweet, "$ %s", tweet);
1059 sprintf(session->tweet, "%s", tweet);
1062 dbg("tweet = %s\n", session->tweet);
1066 session->user = strdup(session->account);
1068 dbg("account = %s\n", session->account);
1069 dbg("password = %s\n", session->password);
1070 dbg("host = %d\n", session->host);
1071 dbg("action = %d\n", session->action);
1073 /* fork ourself so that the main shell can get on
1074 * with it's life as we try to connect and handle everything
1076 if (session->bash) {
1079 dbg("child is %d\n", child);
1084 retval = send_request(session);
1085 if (retval && !session->bash)
1086 fprintf(stderr, "operation failed\n");
1088 log_session(session, retval);
1090 session_free(session);