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>
44 #define zalloc(size) calloc(size, 1)
46 #define dbg(format, arg...) \
49 fprintf(stdout, "bti: %s: " format , __func__ , \
92 struct bti_curl_buffer {
98 static void display_help(void)
100 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
101 fprintf(stdout, "Version: " VERSION "\n");
102 fprintf(stdout, "Usage:\n");
103 fprintf(stdout, " bti [options]\n");
104 fprintf(stdout, "options are:\n");
105 fprintf(stdout, " --account accountname\n");
106 fprintf(stdout, " --password password\n");
107 fprintf(stdout, " --action action\n");
108 fprintf(stdout, " ('update', 'friends', 'public', 'replies', "
109 "'group' or 'user')\n");
110 fprintf(stdout, " --user screenname\n");
111 fprintf(stdout, " --group groupname\n");
112 fprintf(stdout, " --proxy PROXY:PORT\n");
113 fprintf(stdout, " --host HOST\n");
114 fprintf(stdout, " --logfile logfile\n");
115 fprintf(stdout, " --shrink-urls\n");
116 fprintf(stdout, " --page PAGENUMBER\n");
117 fprintf(stdout, " --bash\n");
118 fprintf(stdout, " --debug\n");
119 fprintf(stdout, " --verbose\n");
120 fprintf(stdout, " --dry-run\n");
121 fprintf(stdout, " --version\n");
122 fprintf(stdout, " --help\n");
125 static void display_version(void)
127 fprintf(stdout, "bti - version %s\n", VERSION);
130 static struct session *session_alloc(void)
132 struct session *session;
134 session = zalloc(sizeof(*session));
140 static void session_free(struct session *session)
144 free(session->password);
145 free(session->account);
146 free(session->tweet);
147 free(session->proxy);
149 free(session->homedir);
151 free(session->group);
152 free(session->hosturl);
156 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
158 struct bti_curl_buffer *buffer;
160 buffer = zalloc(sizeof(*buffer));
164 /* start out with a data buffer of 1 byte to
165 * make the buffer fill logic simpler */
166 buffer->data = zalloc(1);
172 buffer->action = action;
176 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
184 static const char *twitter_host = "https://twitter.com/statuses";
185 static const char *identica_host = "https://identi.ca/api/statuses";
187 static const char *user_uri = "/user_timeline/";
188 static const char *update_uri = "/update.xml";
189 static const char *public_uri = "/public_timeline.xml";
190 static const char *friends_uri = "/friends_timeline.xml";
191 static const char *replies_uri = "/replies.xml";
192 static const char *group_uri = "/../laconica/groups/timeline/";
194 static CURL *curl_init(void)
198 curl = curl_easy_init();
200 fprintf(stderr, "Can not init CURL!\n");
203 /* some ssl sanity checks on the connection we are making */
204 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
205 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
209 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
211 xmlChar *text = NULL;
212 xmlChar *user = NULL;
213 xmlChar *created = NULL;
216 current = current->xmlChildrenNode;
217 while (current != NULL) {
218 if (current->type == XML_ELEMENT_NODE) {
219 if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
220 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
221 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
222 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
223 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
224 userinfo = current->xmlChildrenNode;
225 while (userinfo != NULL) {
226 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
229 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
231 userinfo = userinfo->next;
235 if (user && text && created) {
237 printf("[%s] (%.16s) %s\n",
238 user, created, text);
250 current = current->next;
256 static void parse_timeline(char *document)
261 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
262 NULL, XML_PARSE_NOERROR);
266 current = xmlDocGetRootElement(doc);
267 if (current == NULL) {
268 fprintf(stderr, "empty document\n");
273 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
274 fprintf(stderr, "unexpected document type\n");
279 current = current->xmlChildrenNode;
280 while (current != NULL) {
281 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
282 parse_statuses(doc, current);
283 current = current->next;
290 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
293 struct bti_curl_buffer *curl_buf = userp;
294 size_t buffer_size = size * nmemb;
297 if ((!buffer) || (!buffer_size) || (!curl_buf))
300 /* add to the data we already have */
301 temp = zalloc(curl_buf->length + buffer_size + 1);
305 memcpy(temp, curl_buf->data, curl_buf->length);
306 free(curl_buf->data);
307 curl_buf->data = temp;
308 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
309 curl_buf->length += buffer_size;
310 if (curl_buf->action)
311 parse_timeline(curl_buf->data);
313 dbg("%s\n", curl_buf->data);
318 static int send_request(struct session *session)
321 char user_password[500];
323 struct bti_curl_buffer *curl_buf;
326 struct curl_httppost *formpost = NULL;
327 struct curl_httppost *lastptr = NULL;
328 struct curl_slist *slist = NULL;
333 curl_buf = bti_curl_buffer_alloc(session->action);
341 switch (session->action) {
343 snprintf(user_password, sizeof(user_password), "%s:%s",
344 session->account, session->password);
345 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
346 curl_formadd(&formpost, &lastptr,
347 CURLFORM_COPYNAME, "status",
348 CURLFORM_COPYCONTENTS, session->tweet,
351 curl_formadd(&formpost, &lastptr,
352 CURLFORM_COPYNAME, "source",
353 CURLFORM_COPYCONTENTS, "bti",
356 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
357 slist = curl_slist_append(slist, "Expect:");
358 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
360 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
361 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
362 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
366 snprintf(user_password, sizeof(user_password), "%s:%s",
367 session->account, session->password);
368 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
369 friends_uri, session->page);
370 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
371 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
375 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
376 user_uri, session->user, session->page);
377 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
381 snprintf(user_password, sizeof(user_password), "%s:%s",
382 session->account, session->password);
383 sprintf(endpoint, "%s%s?page=%d", session->hosturl, replies_uri,
385 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
386 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
390 sprintf(endpoint, "%s%s?page=%d", session->hosturl, public_uri,
392 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
396 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
397 group_uri, session->group, session->page);
398 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
406 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
409 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
411 dbg("user_password = %s\n", user_password);
412 dbg("data = %s\n", data);
413 dbg("proxy = %s\n", session->proxy);
415 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
416 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
417 if (!session->dry_run) {
418 res = curl_easy_perform(curl);
419 if (res && !session->bash) {
420 fprintf(stderr, "error(%d) trying to perform "
426 curl_easy_cleanup(curl);
427 if (session->action == ACTION_UPDATE)
428 curl_formfree(formpost);
429 bti_curl_buffer_free(curl_buf);
433 static void parse_configfile(struct session *session)
438 char *account = NULL;
439 char *password = NULL;
442 char *logfile = NULL;
448 /* config file is ~/.bti */
449 file = alloca(strlen(session->homedir) + 7);
451 sprintf(file, "%s/.bti", session->homedir);
453 config_file = fopen(file, "r");
455 /* No error if file does not exist or is unreadable. */
456 if (config_file == NULL)
460 ssize_t n = getline(&line, &len, config_file);
463 if (line[n - 1] == '\n')
465 /* Parse file. Format is the usual value pairs:
468 # is a comment character
470 *strchrnul(line, '#') = '\0';
474 /* Ignore blank lines. */
478 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
482 } else if (!strncasecmp(c, "password", 8) &&
486 password = strdup(c);
487 } else if (!strncasecmp(c, "host", 4) &&
492 } else if (!strncasecmp(c, "proxy", 5) &&
497 } else if (!strncasecmp(c, "logfile", 7) &&
502 } else if (!strncasecmp(c, "action", 6) &&
507 } else if (!strncasecmp(c, "user", 4) &&
512 } else if (!strncasecmp(c, "shrink-urls", 11) &&
515 if (!strncasecmp(c, "true", 4) ||
516 !strncasecmp(c, "yes", 3))
518 } else if (!strncasecmp(c, "verbose", 7) &&
521 if (!strncasecmp(c, "true", 4) ||
522 !strncasecmp(c, "yes", 3))
525 } while (!feof(config_file));
528 session->password = password;
530 session->account = account;
532 if (strcasecmp(host, "twitter") == 0) {
533 session->host = HOST_TWITTER;
534 session->hosturl = strdup(twitter_host);
535 } else if (strcasecmp(host, "identica") == 0) {
536 session->host = HOST_IDENTICA;
537 session->hosturl = strdup(identica_host);
539 session->host = HOST_CUSTOM;
540 session->hosturl = strdup(host);
546 free(session->proxy);
547 session->proxy = proxy;
550 session->logfile = logfile;
552 if (strcasecmp(action, "update") == 0)
553 session->action = ACTION_UPDATE;
554 else if (strcasecmp(action, "friends") == 0)
555 session->action = ACTION_FRIENDS;
556 else if (strcasecmp(action, "user") == 0)
557 session->action = ACTION_USER;
558 else if (strcasecmp(action, "replies") == 0)
559 session->action = ACTION_REPLIES;
560 else if (strcasecmp(action, "public") == 0)
561 session->action = ACTION_PUBLIC;
562 else if (strcasecmp(action, "group") == 0)
563 session->action = ACTION_GROUP;
565 session->action = ACTION_UNKNOWN;
569 session->user = user;
570 session->shrink_urls = shrink_urls;
572 /* Free buffer and close file. */
577 static void log_session(struct session *session, int retval)
583 /* Only log something if we have a log file set */
584 if (!session->logfile)
587 filename = alloca(strlen(session->homedir) +
588 strlen(session->logfile) + 3);
590 sprintf(filename, "%s/%s", session->homedir, session->logfile);
592 log_file = fopen(filename, "a+");
593 if (log_file == NULL)
595 switch (session->host) {
603 host = session->hosturl;
607 switch (session->action) {
610 fprintf(log_file, "%s: host=%s tweet failed\n",
611 session->time, host);
613 fprintf(log_file, "%s: host=%s tweet=%s\n",
614 session->time, host, session->tweet);
617 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
618 session->time, host);
621 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
622 session->time, host, session->user);
625 fprintf(log_file, "%s: host=%s retrieving replies\n",
626 session->time, host);
629 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
630 session->time, host);
633 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
634 session->time, host);
643 static char *get_string_from_stdin(void)
648 string = zalloc(1000);
652 if (!fgets(string, 999, stdin))
654 temp = strchr(string, '\n');
659 void read_password(char *buf, size_t len)
668 tp.c_lflag &= (~ECHO);
669 tcsetattr(0, TCSANOW, &tp);
671 fprintf(stdout, "Enter twitter password: ");
676 fprintf(stdout, "\n");
678 tcsetattr(0, TCSANOW, &old);
680 strncpy(buf, pwd, len);
684 static int find_urls(const char *tweet, int **pranges)
687 * magic obtained from
688 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
690 static const char *re_magic =
691 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
692 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
693 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
697 int ovector[10] = {0,};
698 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
699 int startoffset, tweetlen;
703 int *ranges = malloc(sizeof(int) * rbound);
705 re = pcre_compile(re_magic,
706 PCRE_NO_AUTO_CAPTURE,
707 &errptr, &erroffset, NULL);
709 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
713 tweetlen = strlen(tweet);
714 for (startoffset = 0; startoffset < tweetlen; ) {
716 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
718 if (rc == PCRE_ERROR_NOMATCH)
722 fprintf(stderr, "pcre_exec @%u: %s\n",
727 for (i = 0; i < rc; i += 2) {
728 if ((rcount+2) == rbound) {
730 ranges = realloc(ranges, sizeof(int) * rbound);
733 ranges[rcount++] = ovector[i];
734 ranges[rcount++] = ovector[i+1];
737 startoffset = ovector[1];
747 * bidirectional popen() call
749 * @param rwepipe - int array of size three
750 * @param exe - program to run
751 * @param argv - argument list
752 * @return pid or -1 on error
754 * The caller passes in an array of three integers (rwepipe), on successful
755 * execution it can then write to element 0 (stdin of exe), and read from
756 * element 1 (stdout) and 2 (stderr).
758 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
788 } else if (pid == 0) {
800 execvp(exe, (char **)argv);
820 static int pcloseRWE(int pid, int *rwepipe)
826 rc = waitpid(pid, &status, 0);
830 static char *shrink_one_url(int *rwepipe, char *big)
832 int biglen = strlen(big);
837 rc = dprintf(rwepipe[0], "%s\n", big);
841 smalllen = biglen + 128;
842 small = malloc(smalllen);
846 rc = read(rwepipe[1], small, smalllen);
847 if (rc < 0 || rc > biglen)
848 goto error_free_small;
850 if (strncmp(small, "http://", 7))
851 goto error_free_small;
854 while (smalllen && isspace(small[smalllen-1]))
855 small[--smalllen] = 0;
865 static char *shrink_urls(char *text)
872 const char *const shrink_args[] = {
878 int inlen = strlen(text);
880 dbg("before len=%u\n", inlen);
882 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
886 rcount = find_urls(text, &ranges);
890 for (i = 0; i < rcount; i += 2) {
891 int url_start = ranges[i];
892 int url_end = ranges[i+1];
893 int long_url_len = url_end - url_start;
894 char *url = strndup(text + url_start, long_url_len);
896 int not_url_len = url_start - inofs;
898 dbg("long url[%u]: %s\n", long_url_len, url);
899 url = shrink_one_url(shrink_pipe, url);
900 short_url_len = url ? strlen(url) : 0;
901 dbg("short url[%u]: %s\n", short_url_len, url);
903 if (!url || short_url_len >= long_url_len) {
904 /* The short url ended up being too long
907 strncpy(text + outofs, text + inofs,
908 not_url_len + long_url_len);
910 inofs += not_url_len + long_url_len;
911 outofs += not_url_len + long_url_len;
914 /* copy the unmodified block */
915 strncpy(text + outofs, text + inofs, not_url_len);
916 inofs += not_url_len;
917 outofs += not_url_len;
919 /* copy the new url */
920 strncpy(text + outofs, url, short_url_len);
921 inofs += long_url_len;
922 outofs += short_url_len;
928 /* copy the last block after the last match */
930 int tail = inlen - inofs;
932 strncpy(text + outofs, text + inofs, tail);
939 (void)pcloseRWE(shrink_pid, shrink_pipe);
942 dbg("after len=%u\n", outofs);
946 int main(int argc, char *argv[], char *envp[])
948 static const struct option options[] = {
949 { "debug", 0, NULL, 'd' },
950 { "verbose", 0, NULL, 'V' },
951 { "account", 1, NULL, 'a' },
952 { "password", 1, NULL, 'p' },
953 { "host", 1, NULL, 'H' },
954 { "proxy", 1, NULL, 'P' },
955 { "action", 1, NULL, 'A' },
956 { "user", 1, NULL, 'u' },
957 { "group", 1, NULL, 'G' },
958 { "logfile", 1, NULL, 'L' },
959 { "shrink-urls", 0, NULL, 's' },
960 { "help", 0, NULL, 'h' },
961 { "bash", 0, NULL, 'b' },
962 { "dry-run", 0, NULL, 'n' },
963 { "page", 1, NULL, 'g' },
964 { "version", 0, NULL, 'v' },
967 struct session *session;
970 static char password[80];
979 rl_bind_key('\t', rl_insert);
981 session = session_alloc();
983 fprintf(stderr, "no more memory...\n");
987 /* get the current time so that we can log it later */
989 session->time = strdup(ctime(&t));
990 session->time[strlen(session->time)-1] = 0x00;
992 session->homedir = strdup(getenv("HOME"));
994 curl_global_init(CURL_GLOBAL_ALL);
996 /* Set environment variables first, before reading command line options
997 * or config file values. */
998 http_proxy = getenv("http_proxy");
1001 free(session->proxy);
1002 session->proxy = strdup(http_proxy);
1003 dbg("http_proxy = %s\n", session->proxy);
1006 parse_configfile(session);
1009 option = getopt_long_only(argc, argv, "dp:P:H:a:A:u:hg:G:snVv",
1021 if (session->account)
1022 free(session->account);
1023 session->account = strdup(optarg);
1024 dbg("account = %s\n", session->account);
1027 page_nr = atoi(optarg);
1028 dbg("page = %d\n", page_nr);
1029 session->page = page_nr;
1032 if (session->password)
1033 free(session->password);
1034 session->password = strdup(optarg);
1035 dbg("password = %s\n", session->password);
1039 free(session->proxy);
1040 session->proxy = strdup(optarg);
1041 dbg("proxy = %s\n", session->proxy);
1044 if (strcasecmp(optarg, "update") == 0)
1045 session->action = ACTION_UPDATE;
1046 else if (strcasecmp(optarg, "friends") == 0)
1047 session->action = ACTION_FRIENDS;
1048 else if (strcasecmp(optarg, "user") == 0)
1049 session->action = ACTION_USER;
1050 else if (strcasecmp(optarg, "replies") == 0)
1051 session->action = ACTION_REPLIES;
1052 else if (strcasecmp(optarg, "public") == 0)
1053 session->action = ACTION_PUBLIC;
1054 else if (strcasecmp(optarg, "group") == 0)
1055 session->action = ACTION_GROUP;
1057 session->action = ACTION_UNKNOWN;
1058 dbg("action = %d\n", session->action);
1062 free(session->user);
1063 session->user = strdup(optarg);
1064 dbg("user = %s\n", session->user);
1069 free(session->group);
1070 session->group = strdup(optarg);
1071 dbg("group = %s\n", session->group);
1074 if (session->logfile)
1075 free(session->logfile);
1076 session->logfile = strdup(optarg);
1077 dbg("logfile = %s\n", session->logfile);
1080 session->shrink_urls = 1;
1083 if (session->hosturl)
1084 free(session->hosturl);
1085 if (strcasecmp(optarg, "twitter") == 0) {
1086 session->host = HOST_TWITTER;
1087 session->hosturl = strdup(twitter_host);
1088 } else if (strcasecmp(optarg, "identica") == 0) {
1089 session->host = HOST_IDENTICA;
1090 session->hosturl = strdup(identica_host);
1092 session->host = HOST_CUSTOM;
1093 session->hosturl = strdup(optarg);
1095 dbg("host = %d\n", session->host);
1104 session->dry_run = 1;
1116 * Show the version to make it easier to determine what
1122 if (session->action == ACTION_UNKNOWN) {
1123 fprintf(stderr, "Unknown action, valid actions are:\n");
1124 fprintf(stderr, "'update', 'friends', 'public', "
1125 "'replies', 'group' or 'user'.\n");
1129 if (session->host == HOST_TWITTER && session->action == ACTION_GROUP) {
1130 fprintf(stderr, "Groups only work in Identi.ca.\n");
1134 if (session->action == ACTION_GROUP && !session->group) {
1135 fprintf(stdout, "Enter group name: ");
1136 session->group = readline(NULL);
1139 if (!session->account) {
1140 fprintf(stdout, "Enter twitter account: ");
1141 session->account = readline(NULL);
1144 if (!session->password) {
1145 read_password(password, sizeof(password));
1146 session->password = strdup(password);
1149 if (session->action == ACTION_UPDATE) {
1151 tweet = get_string_from_stdin();
1153 tweet = readline("tweet: ");
1154 if (!tweet || strlen(tweet) == 0) {
1159 if (session->shrink_urls)
1160 tweet = shrink_urls(tweet);
1162 session->tweet = zalloc(strlen(tweet) + 10);
1164 sprintf(session->tweet, "%c %s",
1165 getuid() ? '$' : '#', tweet);
1167 sprintf(session->tweet, "%s", tweet);
1170 dbg("tweet = %s\n", session->tweet);
1174 session->user = strdup(session->account);
1176 if (session->page == 0)
1178 dbg("account = %s\n", session->account);
1179 dbg("password = %s\n", session->password);
1180 dbg("host = %d\n", session->host);
1181 dbg("action = %d\n", session->action);
1183 /* fork ourself so that the main shell can get on
1184 * with it's life as we try to connect and handle everything
1186 if (session->bash) {
1189 dbg("child is %d\n", child);
1194 retval = send_request(session);
1195 if (retval && !session->bash)
1196 fprintf(stderr, "operation failed\n");
1198 log_session(session, retval);
1200 session_free(session);