2 * Copyright (C) 2008-2010 Greg Kroah-Hartman <greg@kroah.com>
3 * Copyright (C) 2009 Bart Trojanowski <bart@jukie.net>
4 * Copyright (C) 2009-2010 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 <libxml/xmlmemory.h>
37 #include <libxml/parser.h>
38 #include <libxml/tree.h>
45 #define zalloc(size) calloc(size, 1)
47 #define dbg(format, arg...) \
50 fprintf(stdout, "bti: %s: " format , __func__ , \
78 char *consumer_secret;
79 char *access_token_key;
80 char *access_token_secret;
104 void *readline_handle;
105 char *(*readline)(const char *);
108 struct bti_curl_buffer {
110 struct session *session;
115 static void display_help(void)
117 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n"
122 " --account accountname\n"
123 " --password password\n"
125 " ('update', 'friends', 'public', 'replies', or 'user')\n"
126 " --user screenname\n"
127 " --group groupname\n"
128 " --proxy PROXY:PORT\n"
130 " --logfile logfile\n"
131 " --config configfile\n"
135 " --page PAGENUMBER\n"
142 " --help\n", VERSION);
145 static void display_version(void)
147 fprintf(stdout, "bti - version %s\n", VERSION);
150 static char *get_string(const char *name)
155 string = zalloc(1000);
159 fprintf(stdout, "%s", name);
160 if (!fgets(string, 999, stdin))
162 temp = strchr(string, '\n');
169 * Try to get a handle to a readline function from a variety of different
170 * libraries. If nothing is present on the system, then fall back to an
173 * Logic originally based off of code in the e2fsutils package in the
174 * lib/ss/get_readline.c file, which is licensed under the MIT license.
176 * This keeps us from having to relicense the bti codebase if readline
177 * ever changes its license, as there is no link-time dependancy.
178 * It is a run-time thing only, and we handle any readline-like library
179 * in the same manner, making bti not be a derivative work of any
182 static void session_readline_init(struct session *session)
184 /* Libraries we will try to use for readline/editline functionality */
185 const char *libpath = "libreadline.so.6:libreadline.so.5:"
186 "libreadline.so.4:libreadline.so:libedit.so.2:"
187 "libedit.so:libeditline.so.0:libeditline.so";
189 char *tmp, *cp, *next;
190 int (*bind_key)(int, void *);
191 void (*insert)(void);
193 /* default to internal function if we can't or won't find anything */
194 session->readline = get_string;
197 session->interactive = 1;
199 tmp = malloc(strlen(libpath)+1);
202 strcpy(tmp, libpath);
203 for (cp = tmp; cp; cp = next) {
204 next = strchr(cp, ':');
209 handle = dlopen(cp, RTLD_NOW);
211 dbg("Using %s for readline library\n", cp);
217 dbg("No readline library found.\n");
221 session->readline_handle = handle;
222 session->readline = (char *(*)(const char *))dlsym(handle, "readline");
223 if (session->readline == NULL) {
224 /* something odd happened, default back to internal stuff */
225 session->readline_handle = NULL;
226 session->readline = get_string;
231 * If we found a library, turn off filename expansion
232 * as that makes no sense from within bti.
234 bind_key = (int (*)(int, void *))dlsym(handle, "rl_bind_key");
235 insert = (void (*)(void))dlsym(handle, "rl_insert");
236 if (bind_key && insert)
237 bind_key('\t', insert);
240 static void session_readline_cleanup(struct session *session)
242 if (session->readline_handle)
243 dlclose(session->readline_handle);
246 static struct session *session_alloc(void)
248 struct session *session;
250 session = zalloc(sizeof(*session));
256 static void session_free(struct session *session)
260 free(session->retweet);
261 free(session->replyto);
262 free(session->password);
263 free(session->account);
264 free(session->consumer_key);
265 free(session->consumer_secret);
266 free(session->access_token_key);
267 free(session->access_token_secret);
268 free(session->tweet);
269 free(session->proxy);
271 free(session->homedir);
273 free(session->group);
274 free(session->hosturl);
275 free(session->hostname);
276 free(session->configfile);
280 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
282 struct bti_curl_buffer *buffer;
284 buffer = zalloc(sizeof(*buffer));
288 /* start out with a data buffer of 1 byte to
289 * make the buffer fill logic simpler */
290 buffer->data = zalloc(1);
296 buffer->action = action;
300 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
308 static const char twitter_host[] = "http://api.twitter.com/1/statuses";
309 static const char identica_host[] = "https://identi.ca/api/statuses";
310 static const char twitter_name[] = "twitter";
311 static const char identica_name[] = "identi.ca";
313 static const char twitter_request_token_uri[] = "http://twitter.com/oauth/request_token";
314 static const char twitter_access_token_uri[] = "http://twitter.com/oauth/access_token";
315 static const char twitter_authorize_uri[] = "http://twitter.com/oauth/authorize?oauth_token=";
316 static const char identica_request_token_uri[] = "http://identi.ca/api/oauth/request_token?oauth_callback=oob";
317 static const char identica_access_token_uri[] = "http://identi.ca/api/oauth/access_token";
318 static const char identica_authorize_uri[] = "http://identi.ca/api/oauth/authorize?oauth_token=";
320 static const char user_uri[] = "/user_timeline/";
321 static const char update_uri[] = "/update.xml";
322 static const char public_uri[] = "/public_timeline.xml";
323 static const char friends_uri[] = "/friends_timeline.xml";
324 static const char mentions_uri[] = "/mentions.xml";
325 static const char replies_uri[] = "/replies.xml";
326 static const char retweet_uri[] = "/retweet/";
327 static const char group_uri[] = "/../statusnet/groups/timeline/";
329 static CURL *curl_init(void)
333 curl = curl_easy_init();
335 fprintf(stderr, "Can not init CURL!\n");
338 /* some ssl sanity checks on the connection we are making */
339 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
340 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
344 static void parse_statuses(struct session *session,
345 xmlDocPtr doc, xmlNodePtr current)
347 xmlChar *text = NULL;
348 xmlChar *user = NULL;
349 xmlChar *created = NULL;
353 current = current->xmlChildrenNode;
354 while (current != NULL) {
355 if (current->type == XML_ELEMENT_NODE) {
356 if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
357 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
358 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
359 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
360 if (!xmlStrcmp(current->name, (const xmlChar *)"id"))
361 id = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
362 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
363 userinfo = current->xmlChildrenNode;
364 while (userinfo != NULL) {
365 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
368 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
370 userinfo = userinfo->next;
374 if (user && text && created && id) {
375 if (session->verbose)
376 printf("[%s] {%s} (%.16s) %s\n",
377 user, id, created, text);
391 current = current->next;
397 static void parse_timeline(char *document, struct session *session)
402 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
403 NULL, XML_PARSE_NOERROR);
407 current = xmlDocGetRootElement(doc);
408 if (current == NULL) {
409 fprintf(stderr, "empty document\n");
414 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
415 fprintf(stderr, "unexpected document type\n");
420 current = current->xmlChildrenNode;
421 while (current != NULL) {
422 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
423 parse_statuses(session, doc, current);
424 current = current->next;
431 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
434 struct bti_curl_buffer *curl_buf = userp;
435 size_t buffer_size = size * nmemb;
438 if ((!buffer) || (!buffer_size) || (!curl_buf))
441 /* add to the data we already have */
442 temp = zalloc(curl_buf->length + buffer_size + 1);
446 memcpy(temp, curl_buf->data, curl_buf->length);
447 free(curl_buf->data);
448 curl_buf->data = temp;
449 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
450 curl_buf->length += buffer_size;
451 if (curl_buf->action)
452 parse_timeline(curl_buf->data, curl_buf->session);
454 dbg("%s\n", curl_buf->data);
459 static int parse_osp_reply(const char *reply, char **token, char **secret)
464 rc = oauth_split_url_parameters(reply, &rv);
465 qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
466 if (rc == 2 || rc == 4) {
467 if (!strncmp(rv[0], "oauth_token=", 11) &&
468 !strncmp(rv[1], "oauth_token_secret=", 18)) {
470 *token = strdup(&(rv[0][12]));
472 *secret = strdup(&(rv[1][19]));
476 } else if (rc == 3) {
477 if (!strncmp(rv[1], "oauth_token=", 11) &&
478 !strncmp(rv[2], "oauth_token_secret=", 18)) {
480 *token = strdup(&(rv[1][12]));
482 *secret = strdup(&(rv[2][19]));
488 dbg("token: %s\n", *token);
489 dbg("secret: %s\n", *secret);
497 static int request_access_token(struct session *session)
499 char *post_params = NULL;
500 char *request_url = NULL;
503 char *at_secret = NULL;
504 char *verifier = NULL;
510 if (session->host == HOST_TWITTER)
511 request_url = oauth_sign_url2(
512 twitter_request_token_uri, NULL,
513 OA_HMAC, NULL, session->consumer_key,
514 session->consumer_secret, NULL, NULL);
515 else if (session->host == HOST_IDENTICA)
516 request_url = oauth_sign_url2(
517 identica_request_token_uri, NULL,
518 OA_HMAC, NULL, session->consumer_key,
519 session->consumer_secret, NULL, NULL);
520 reply = oauth_http_get(request_url, post_params);
531 if (parse_osp_reply(reply, &at_key, &at_secret))
537 "Please open the following link in your browser, and "
538 "allow 'bti' to access your account. Then paste "
539 "back the provided PIN in here.\n");
540 if (session->host == HOST_TWITTER) {
541 fprintf(stdout, "%s%s\nPIN: ", twitter_authorize_uri, at_key);
542 verifier = session->readline(NULL);
543 sprintf(at_uri, "%s?oauth_verifier=%s",
544 twitter_access_token_uri, verifier);
545 } else if (session->host == HOST_IDENTICA) {
546 fprintf(stdout, "%s%s\nPIN: ", identica_authorize_uri, at_key);
547 verifier = session->readline(NULL);
548 sprintf(at_uri, "%s?oauth_verifier=%s",
549 identica_access_token_uri, verifier);
551 request_url = oauth_sign_url2(at_uri, NULL, OA_HMAC, NULL,
552 session->consumer_key,
553 session->consumer_secret,
555 reply = oauth_http_get(request_url, post_params);
560 if (parse_osp_reply(reply, &at_key, &at_secret))
566 "Please put these two lines in your bti "
567 "configuration file (~/.bti):\n"
568 "access_token_key=%s\n"
569 "access_token_secret=%s\n",
575 static int send_request(struct session *session)
578 char user_password[500];
580 struct bti_curl_buffer *curl_buf;
583 struct curl_httppost *formpost = NULL;
584 struct curl_httppost *lastptr = NULL;
585 struct curl_slist *slist = NULL;
586 char *req_url = NULL;
588 char *postarg = NULL;
589 char *escaped_tweet = NULL;
595 if (!session->hosturl)
596 session->hosturl = strdup(twitter_host);
598 if (session->no_oauth || session->guest) {
599 curl_buf = bti_curl_buffer_alloc(session->action);
602 curl_buf->session = session;
608 if (!session->hosturl)
609 session->hosturl = strdup(twitter_host);
611 switch (session->action) {
613 snprintf(user_password, sizeof(user_password), "%s:%s",
614 session->account, session->password);
615 snprintf(data, sizeof(data), "status=\"%s\"",
617 curl_formadd(&formpost, &lastptr,
618 CURLFORM_COPYNAME, "status",
619 CURLFORM_COPYCONTENTS, session->tweet,
622 curl_formadd(&formpost, &lastptr,
623 CURLFORM_COPYNAME, "source",
624 CURLFORM_COPYCONTENTS, "bti",
627 if (session->replyto)
628 curl_formadd(&formpost, &lastptr,
629 CURLFORM_COPYNAME, "in_reply_to_status_id",
630 CURLFORM_COPYCONTENTS, session->replyto,
633 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
634 slist = curl_slist_append(slist, "Expect:");
635 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
637 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
638 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
639 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
643 snprintf(user_password, sizeof(user_password), "%s:%s",
644 session->account, session->password);
645 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
646 friends_uri, session->page);
647 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
648 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
652 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
653 user_uri, session->user, session->page);
654 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
658 snprintf(user_password, sizeof(user_password), "%s:%s",
659 session->account, session->password);
660 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
661 replies_uri, session->page);
662 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
663 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
667 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
668 public_uri, session->page);
669 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
673 sprintf(endpoint, "%s%s%s.xml?page=%d",
674 session->hosturl, group_uri, session->group,
676 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
684 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
687 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
689 dbg("user_password = %s\n", user_password);
690 dbg("data = %s\n", data);
691 dbg("proxy = %s\n", session->proxy);
693 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
694 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
695 if (!session->dry_run) {
696 res = curl_easy_perform(curl);
697 if (res && !session->background) {
698 fprintf(stderr, "error(%d) trying to perform "
704 curl_easy_cleanup(curl);
705 if (session->action == ACTION_UPDATE)
706 curl_formfree(formpost);
707 bti_curl_buffer_free(curl_buf);
709 switch (session->action) {
711 escaped_tweet = oauth_url_escape(session->tweet);
712 if (session->replyto) {
714 "%s%s?status=%s&in_reply_to_status_id=%s",
715 session->hosturl, update_uri,
716 escaped_tweet, session->replyto);
718 sprintf(endpoint, "%s%s?status=%s",
719 session->hosturl, update_uri,
726 sprintf(endpoint, "%s%s%s.xml?page=%d",
727 session->hosturl, user_uri, session->user,
731 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
732 mentions_uri, session->page);
735 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
736 public_uri, session->page);
739 sprintf(endpoint, "%s%s%s.xml?page=%d",
740 session->hosturl, group_uri, session->group,
744 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
745 friends_uri, session->page);
748 sprintf(endpoint, "%s%s%s.xml", session->hosturl,
749 retweet_uri, session->retweet);
756 dbg("%s\n", endpoint);
757 if (!session->dry_run) {
759 req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
760 NULL, session->consumer_key,
761 session->consumer_secret,
762 session->access_token_key,
763 session->access_token_secret);
764 reply = oauth_http_post(req_url, postarg);
766 req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
767 session->consumer_key,
768 session->consumer_secret,
769 session->access_token_key,
770 session->access_token_secret);
771 reply = oauth_http_get(req_url, postarg);
774 dbg("%s\n", req_url);
780 if ((session->action != ACTION_UPDATE) &&
781 (session->action != ACTION_RETWEET))
782 parse_timeline(reply, session);
787 static void parse_configfile(struct session *session)
792 char *account = NULL;
793 char *password = NULL;
794 char *consumer_key = NULL;
795 char *consumer_secret = NULL;
796 char *access_token_key = NULL;
797 char *access_token_secret = NULL;
800 char *logfile = NULL;
803 char *replyto = NULL;
804 char *retweet = NULL;
807 config_file = fopen(session->configfile, "r");
809 /* No error if file does not exist or is unreadable. */
810 if (config_file == NULL)
814 ssize_t n = getline(&line, &len, config_file);
817 if (line[n - 1] == '\n')
819 /* Parse file. Format is the usual value pairs:
822 # is a comment character
824 *strchrnul(line, '#') = '\0';
828 /* Ignore blank lines. */
832 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
836 } else if (!strncasecmp(c, "password", 8) &&
840 password = strdup(c);
841 } else if (!strncasecmp(c, "consumer_key", 12) &&
845 consumer_key = strdup(c);
846 } else if (!strncasecmp(c, "consumer_secret", 15) &&
850 consumer_secret = strdup(c);
851 } else if (!strncasecmp(c, "access_token_key", 16) &&
855 access_token_key = strdup(c);
856 } else if (!strncasecmp(c, "access_token_secret", 19) &&
860 access_token_secret = strdup(c);
861 } else if (!strncasecmp(c, "host", 4) &&
866 } else if (!strncasecmp(c, "proxy", 5) &&
871 } else if (!strncasecmp(c, "logfile", 7) &&
876 } else if (!strncasecmp(c, "replyto", 7) &&
881 } else if (!strncasecmp(c, "action", 6) &&
886 } else if (!strncasecmp(c, "user", 4) &&
891 } else if (!strncasecmp(c, "shrink-urls", 11) &&
894 if (!strncasecmp(c, "true", 4) ||
895 !strncasecmp(c, "yes", 3))
897 } else if (!strncasecmp(c, "verbose", 7) &&
900 if (!strncasecmp(c, "true", 4) ||
901 !strncasecmp(c, "yes", 3))
902 session->verbose = 1;
903 } else if (!strncasecmp(c,"retweet", 7) &&
909 } while (!feof(config_file));
912 session->password = password;
914 session->account = account;
916 session->consumer_key = consumer_key;
918 session->consumer_secret = consumer_secret;
919 if (access_token_key)
920 session->access_token_key = access_token_key;
921 if (access_token_secret)
922 session->access_token_secret = access_token_secret;
924 if (strcasecmp(host, "twitter") == 0) {
925 session->host = HOST_TWITTER;
926 session->hosturl = strdup(twitter_host);
927 session->hostname = strdup(twitter_name);
928 } else if (strcasecmp(host, "identica") == 0) {
929 session->host = HOST_IDENTICA;
930 session->hosturl = strdup(identica_host);
931 session->hostname = strdup(identica_name);
933 session->host = HOST_CUSTOM;
934 session->hosturl = strdup(host);
935 session->hostname = strdup(host);
941 free(session->proxy);
942 session->proxy = proxy;
945 session->logfile = logfile;
947 session->replyto = replyto;
949 session->retweet = retweet;
951 if (strcasecmp(action, "update") == 0)
952 session->action = ACTION_UPDATE;
953 else if (strcasecmp(action, "friends") == 0)
954 session->action = ACTION_FRIENDS;
955 else if (strcasecmp(action, "user") == 0)
956 session->action = ACTION_USER;
957 else if (strcasecmp(action, "replies") == 0)
958 session->action = ACTION_REPLIES;
959 else if (strcasecmp(action, "public") == 0)
960 session->action = ACTION_PUBLIC;
961 else if (strcasecmp(action, "group") == 0)
962 session->action = ACTION_GROUP;
964 session->action = ACTION_UNKNOWN;
968 session->user = user;
969 session->shrink_urls = shrink_urls;
971 /* Free buffer and close file. */
976 static void log_session(struct session *session, int retval)
981 /* Only log something if we have a log file set */
982 if (!session->logfile)
985 filename = alloca(strlen(session->homedir) +
986 strlen(session->logfile) + 3);
988 sprintf(filename, "%s/%s", session->homedir, session->logfile);
990 log_file = fopen(filename, "a+");
991 if (log_file == NULL)
994 switch (session->action) {
997 fprintf(log_file, "%s: host=%s tweet failed\n",
998 session->time, session->hostname);
1000 fprintf(log_file, "%s: host=%s tweet=%s\n",
1001 session->time, session->hostname,
1004 case ACTION_FRIENDS:
1005 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
1006 session->time, session->hostname);
1009 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
1010 session->time, session->hostname, session->user);
1012 case ACTION_REPLIES:
1013 fprintf(log_file, "%s: host=%s retrieving replies\n",
1014 session->time, session->hostname);
1017 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
1018 session->time, session->hostname);
1021 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
1022 session->time, session->hostname);
1031 static char *get_string_from_stdin(void)
1036 string = zalloc(1000);
1040 if (!fgets(string, 999, stdin))
1042 temp = strchr(string, '\n');
1048 static void read_password(char *buf, size_t len, char *host)
1058 tp.c_lflag &= (~ECHO);
1059 tcsetattr(0, TCSANOW, &tp);
1061 fprintf(stdout, "Enter password for %s: ", host);
1064 retval = scanf("%79s", pwd);
1066 fprintf(stdout, "\n");
1068 tcsetattr(0, TCSANOW, &old);
1070 strncpy(buf, pwd, len);
1074 static int find_urls(const char *tweet, int **pranges)
1077 * magic obtained from
1078 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
1080 static const char *re_magic =
1081 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
1082 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
1083 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
1087 int ovector[10] = {0,};
1088 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
1089 int startoffset, tweetlen;
1093 int *ranges = malloc(sizeof(int) * rbound);
1095 re = pcre_compile(re_magic,
1096 PCRE_NO_AUTO_CAPTURE,
1097 &errptr, &erroffset, NULL);
1099 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
1103 tweetlen = strlen(tweet);
1104 for (startoffset = 0; startoffset < tweetlen; ) {
1106 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
1108 if (rc == PCRE_ERROR_NOMATCH)
1112 fprintf(stderr, "pcre_exec @%u: %s\n",
1117 for (i = 0; i < rc; i += 2) {
1118 if ((rcount+2) == rbound) {
1120 ranges = realloc(ranges, sizeof(int) * rbound);
1123 ranges[rcount++] = ovector[i];
1124 ranges[rcount++] = ovector[i+1];
1127 startoffset = ovector[1];
1137 * bidirectional popen() call
1139 * @param rwepipe - int array of size three
1140 * @param exe - program to run
1141 * @param argv - argument list
1142 * @return pid or -1 on error
1144 * The caller passes in an array of three integers (rwepipe), on successful
1145 * execution it can then write to element 0 (stdin of exe), and read from
1146 * element 1 (stdout) and 2 (stderr).
1148 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
1175 rwepipe[1] = out[0];
1176 rwepipe[2] = err[0];
1178 } else if (pid == 0) {
1190 execvp(exe, (char **)argv);
1210 static int pcloseRWE(int pid, int *rwepipe)
1216 rc = waitpid(pid, &status, 0);
1220 static char *shrink_one_url(int *rwepipe, char *big)
1222 int biglen = strlen(big);
1227 rc = dprintf(rwepipe[0], "%s\n", big);
1231 smalllen = biglen + 128;
1232 small = malloc(smalllen);
1236 rc = read(rwepipe[1], small, smalllen);
1237 if (rc < 0 || rc > biglen)
1238 goto error_free_small;
1240 if (strncmp(small, "http://", 7))
1241 goto error_free_small;
1244 while (smalllen && isspace(small[smalllen-1]))
1245 small[--smalllen] = 0;
1255 static char *shrink_urls(char *text)
1262 const char *const shrink_args[] = {
1268 int inlen = strlen(text);
1270 dbg("before len=%u\n", inlen);
1272 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
1276 rcount = find_urls(text, &ranges);
1280 for (i = 0; i < rcount; i += 2) {
1281 int url_start = ranges[i];
1282 int url_end = ranges[i+1];
1283 int long_url_len = url_end - url_start;
1284 char *url = strndup(text + url_start, long_url_len);
1286 int not_url_len = url_start - inofs;
1288 dbg("long url[%u]: %s\n", long_url_len, url);
1289 url = shrink_one_url(shrink_pipe, url);
1290 short_url_len = url ? strlen(url) : 0;
1291 dbg("short url[%u]: %s\n", short_url_len, url);
1293 if (!url || short_url_len >= long_url_len) {
1294 /* The short url ended up being too long
1297 strncpy(text + outofs, text + inofs,
1298 not_url_len + long_url_len);
1300 inofs += not_url_len + long_url_len;
1301 outofs += not_url_len + long_url_len;
1304 /* copy the unmodified block */
1305 strncpy(text + outofs, text + inofs, not_url_len);
1306 inofs += not_url_len;
1307 outofs += not_url_len;
1309 /* copy the new url */
1310 strncpy(text + outofs, url, short_url_len);
1311 inofs += long_url_len;
1312 outofs += short_url_len;
1318 /* copy the last block after the last match */
1320 int tail = inlen - inofs;
1322 strncpy(text + outofs, text + inofs, tail);
1329 (void)pcloseRWE(shrink_pid, shrink_pipe);
1332 dbg("after len=%u\n", outofs);
1336 int main(int argc, char *argv[], char *envp[])
1338 static const struct option options[] = {
1339 { "debug", 0, NULL, 'd' },
1340 { "verbose", 0, NULL, 'V' },
1341 { "account", 1, NULL, 'a' },
1342 { "password", 1, NULL, 'p' },
1343 { "host", 1, NULL, 'H' },
1344 { "proxy", 1, NULL, 'P' },
1345 { "action", 1, NULL, 'A' },
1346 { "user", 1, NULL, 'u' },
1347 { "group", 1, NULL, 'G' },
1348 { "logfile", 1, NULL, 'L' },
1349 { "shrink-urls", 0, NULL, 's' },
1350 { "help", 0, NULL, 'h' },
1351 { "bash", 0, NULL, 'b' },
1352 { "background", 0, NULL, 'B' },
1353 { "dry-run", 0, NULL, 'n' },
1354 { "page", 1, NULL, 'g' },
1355 { "version", 0, NULL, 'v' },
1356 { "config", 1, NULL, 'c' },
1357 { "replyto", 1, NULL, 'r' },
1358 { "retweet", 1, NULL, 'w' },
1361 struct session *session;
1365 static char password[80];
1374 session = session_alloc();
1376 fprintf(stderr, "no more memory...\n");
1380 /* get the current time so that we can log it later */
1382 session->time = strdup(ctime(&t));
1383 session->time[strlen(session->time)-1] = 0x00;
1385 /* Get the home directory so we can try to find a config file */
1386 session->homedir = strdup(getenv("HOME"));
1388 /* set up a default config file location (traditionally ~/.bti) */
1389 session->configfile = zalloc(strlen(session->homedir) + 7);
1390 sprintf(session->configfile, "%s/.bti", session->homedir);
1392 /* Set environment variables first, before reading command line options
1393 * or config file values. */
1394 http_proxy = getenv("http_proxy");
1397 free(session->proxy);
1398 session->proxy = strdup(http_proxy);
1399 dbg("http_proxy = %s\n", session->proxy);
1402 parse_configfile(session);
1405 option = getopt_long_only(argc, argv,
1406 "dp:P:H:a:A:u:c:hg:G:sr:nVv",
1415 session->verbose = 1;
1418 if (session->account)
1419 free(session->account);
1420 session->account = strdup(optarg);
1421 dbg("account = %s\n", session->account);
1424 page_nr = atoi(optarg);
1425 dbg("page = %d\n", page_nr);
1426 session->page = page_nr;
1429 session->replyto = strdup(optarg);
1430 dbg("in_reply_to_status_id = %s\n", session->replyto);
1433 session->retweet = strdup(optarg);
1434 dbg("Retweet ID = %s\n", session->retweet);
1437 if (session->password)
1438 free(session->password);
1439 session->password = strdup(optarg);
1440 dbg("password = %s\n", session->password);
1444 free(session->proxy);
1445 session->proxy = strdup(optarg);
1446 dbg("proxy = %s\n", session->proxy);
1449 if (strcasecmp(optarg, "update") == 0)
1450 session->action = ACTION_UPDATE;
1451 else if (strcasecmp(optarg, "friends") == 0)
1452 session->action = ACTION_FRIENDS;
1453 else if (strcasecmp(optarg, "user") == 0)
1454 session->action = ACTION_USER;
1455 else if (strcasecmp(optarg, "replies") == 0)
1456 session->action = ACTION_REPLIES;
1457 else if (strcasecmp(optarg, "public") == 0)
1458 session->action = ACTION_PUBLIC;
1459 else if (strcasecmp(optarg, "group") == 0)
1460 session->action = ACTION_GROUP;
1461 else if (strcasecmp(optarg,"retweet") == 0)
1462 session->action = ACTION_RETWEET;
1464 session->action = ACTION_UNKNOWN;
1465 dbg("action = %d\n", session->action);
1469 free(session->user);
1470 session->user = strdup(optarg);
1471 dbg("user = %s\n", session->user);
1476 free(session->group);
1477 session->group = strdup(optarg);
1478 dbg("group = %s\n", session->group);
1481 if (session->logfile)
1482 free(session->logfile);
1483 session->logfile = strdup(optarg);
1484 dbg("logfile = %s\n", session->logfile);
1487 session->shrink_urls = 1;
1490 if (session->hosturl)
1491 free(session->hosturl);
1492 if (session->hostname)
1493 free(session->hostname);
1494 if (strcasecmp(optarg, "twitter") == 0) {
1495 session->host = HOST_TWITTER;
1496 session->hosturl = strdup(twitter_host);
1497 session->hostname = strdup(twitter_name);
1498 } else if (strcasecmp(optarg, "identica") == 0) {
1499 session->host = HOST_IDENTICA;
1500 session->hosturl = strdup(identica_host);
1501 session->hostname = strdup(identica_name);
1503 session->host = HOST_CUSTOM;
1504 session->hosturl = strdup(optarg);
1505 session->hostname = strdup(optarg);
1507 dbg("host = %d\n", session->host);
1511 /* fall-through intended */
1513 session->background = 1;
1516 if (session->configfile)
1517 free(session->configfile);
1518 session->configfile = strdup(optarg);
1519 dbg("configfile = %s\n", session->configfile);
1522 * read the config file now. Yes, this could override
1523 * previously set options from the command line, but
1524 * the user asked for it...
1526 parse_configfile(session);
1532 session->dry_run = 1;
1543 session_readline_init(session);
1545 * Show the version to make it easier to determine what
1551 if (session->host == HOST_TWITTER) {
1552 if (!session->consumer_key || !session->consumer_secret) {
1553 if (session->action == ACTION_USER ||
1554 session->action == ACTION_PUBLIC) {
1555 /* Some actions may still work without authentication */
1559 "Twitter no longer supports HTTP basic authentication.\n"
1560 "Both consumer key, and consumer secret are required"
1561 " for bti in order to behave as an OAuth consumer.\n");
1565 if (session->action == ACTION_GROUP) {
1566 fprintf(stderr, "Groups only work in Identi.ca.\n");
1570 if (!session->consumer_key || !session->consumer_secret)
1571 session->no_oauth = 1;
1574 if (session->no_oauth) {
1575 if (!session->account) {
1576 fprintf(stdout, "Enter account for %s: ",
1578 session->account = session->readline(NULL);
1580 if (!session->password) {
1581 read_password(password, sizeof(password),
1583 session->password = strdup(password);
1585 } else if (!session->guest) {
1586 if (!session->access_token_key ||
1587 !session->access_token_secret) {
1588 request_access_token(session);
1593 if (session->action == ACTION_UNKNOWN) {
1594 fprintf(stderr, "Unknown action, valid actions are:\n"
1595 "'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
1599 if (session->action == ACTION_GROUP && !session->group) {
1600 fprintf(stdout, "Enter group name: ");
1601 session->group = session->readline(NULL);
1604 if (session->action == ACTION_RETWEET) {
1605 fprintf(stdout, "Status ID to retweet: ");
1606 retweet = get_string_from_stdin();
1608 if (!retweet || strlen(retweet) == 0) {
1609 dbg("no retweet?\n");
1613 session->retweet = zalloc(strlen(retweet) + 10);
1614 sprintf(session->retweet,"%s", retweet);
1616 dbg("retweet ID = %s\n", session->retweet);
1619 if (session->action == ACTION_UPDATE) {
1620 if (session->background || !session->interactive)
1621 tweet = get_string_from_stdin();
1623 tweet = session->readline("tweet: ");
1624 if (!tweet || strlen(tweet) == 0) {
1629 if (session->shrink_urls)
1630 tweet = shrink_urls(tweet);
1632 session->tweet = zalloc(strlen(tweet) + 10);
1634 sprintf(session->tweet, "%c %s",
1635 getuid() ? '$' : '#', tweet);
1637 sprintf(session->tweet, "%s", tweet);
1640 dbg("tweet = %s\n", session->tweet);
1643 if (session->page == 0)
1645 dbg("config file = %s\n", session->configfile);
1646 dbg("host = %d\n", session->host);
1647 dbg("action = %d\n", session->action);
1649 /* fork ourself so that the main shell can get on
1650 * with it's life as we try to connect and handle everything
1652 if (session->background) {
1655 dbg("child is %d\n", child);
1660 retval = send_request(session);
1661 if (retval && !session->background)
1662 fprintf(stderr, "operation failed\n");
1664 log_session(session, retval);
1666 session_readline_cleanup(session);
1667 session_free(session);