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__ , \
79 char *consumer_secret;
80 char *access_token_key;
81 char *access_token_secret;
103 void *readline_handle;
104 char *(*readline)(const char *);
107 struct bti_curl_buffer {
113 static void display_help(void)
115 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n"
120 " --account accountname\n"
121 " --password password\n"
123 " ('update', 'friends', 'public', 'replies', or 'user')\n"
124 " --user screenname\n"
125 " --group groupname\n"
126 " --proxy PROXY:PORT\n"
128 " --logfile logfile\n"
129 " --config configfile\n"
133 " --page PAGENUMBER\n"
140 " --help\n", VERSION);
143 static void display_version(void)
145 fprintf(stdout, "bti - version %s\n", VERSION);
148 static char *get_string(const char *name)
153 string = zalloc(1000);
157 fprintf(stdout, "%s", name);
158 if (!fgets(string, 999, stdin))
160 temp = strchr(string, '\n');
167 * Try to get a handle to a readline function from a variety of different
168 * libraries. If nothing is present on the system, then fall back to an
171 * Logic originally based off of code in the e2fsutils package in the
172 * lib/ss/get_readline.c file, which is licensed under the MIT license.
174 * This keeps us from having to relicense the bti codebase if readline
175 * ever changes its license, as there is no link-time dependancy.
176 * It is a run-time thing only, and we handle any readline-like library
177 * in the same manner, making bti not be a derivative work of any
180 static void session_readline_init(struct session *session)
182 /* Libraries we will try to use for readline/editline functionality */
183 const char *libpath = "libreadline.so.6:libreadline.so.5:"
184 "libreadline.so.4:libreadline.so:libedit.so.2:"
185 "libedit.so:libeditline.so.0:libeditline.so";
187 char *tmp, *cp, *next;
188 int (*bind_key)(int, void *);
189 void (*insert)(void);
191 /* default to internal function if we can't or won't find anything */
192 session->readline = get_string;
195 session->interactive = 1;
197 tmp = malloc(strlen(libpath)+1);
200 strcpy(tmp, libpath);
201 for (cp = tmp; cp; cp = next) {
202 next = strchr(cp, ':');
207 handle = dlopen(cp, RTLD_NOW);
209 dbg("Using %s for readline library\n", cp);
215 dbg("No readline library found.\n");
219 session->readline_handle = handle;
220 session->readline = (char *(*)(const char *))dlsym(handle, "readline");
221 if (session->readline == NULL) {
222 /* something odd happened, default back to internal stuff */
223 session->readline_handle = NULL;
224 session->readline = get_string;
229 * If we found a library, turn off filename expansion
230 * as that makes no sense from within bti.
232 bind_key = (int (*)(int, void *))dlsym(handle, "rl_bind_key");
233 insert = (void (*)(void))dlsym(handle, "rl_insert");
234 if (bind_key && insert)
235 bind_key('\t', insert);
238 static void session_readline_cleanup(struct session *session)
240 if (session->readline_handle)
241 dlclose(session->readline_handle);
244 static struct session *session_alloc(void)
246 struct session *session;
248 session = zalloc(sizeof(*session));
254 static void session_free(struct session *session)
258 free(session->retweet);
259 free(session->replyto);
260 free(session->password);
261 free(session->account);
262 free(session->consumer_key);
263 free(session->consumer_secret);
264 free(session->access_token_key);
265 free(session->access_token_secret);
266 free(session->tweet);
267 free(session->proxy);
269 free(session->homedir);
271 free(session->group);
272 free(session->hosturl);
273 free(session->hostname);
274 free(session->configfile);
278 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
280 struct bti_curl_buffer *buffer;
282 buffer = zalloc(sizeof(*buffer));
286 /* start out with a data buffer of 1 byte to
287 * make the buffer fill logic simpler */
288 buffer->data = zalloc(1);
294 buffer->action = action;
298 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
306 static const char twitter_host[] = "http://api.twitter.com/1/statuses";
307 static const char identica_host[] = "https://identi.ca/api/statuses";
308 static const char twitter_name[] = "twitter";
309 static const char identica_name[] = "identi.ca";
311 static const char twitter_request_token_uri[] = "http://twitter.com/oauth/request_token";
312 static const char twitter_access_token_uri[] = "http://twitter.com/oauth/access_token";
313 static const char twitter_authorize_uri[] = "http://twitter.com/oauth/authorize?oauth_token=";
314 static const char identica_request_token_uri[] = "http://identi.ca/api/oauth/request_token?oauth_callback=oob";
315 static const char identica_access_token_uri[] = "http://identi.ca/api/oauth/access_token";
316 static const char identica_authorize_uri[] = "http://identi.ca/api/oauth/authorize?oauth_token=";
318 static const char user_uri[] = "/user_timeline/";
319 static const char update_uri[] = "/update.xml";
320 static const char public_uri[] = "/public_timeline.xml";
321 static const char friends_uri[] = "/friends_timeline.xml";
322 static const char mentions_uri[] = "/mentions.xml";
323 static const char replies_uri[] = "/replies.xml";
324 static const char retweet_uri[] = "/retweet/";
325 static const char group_uri[] = "/../statusnet/groups/timeline/";
327 static CURL *curl_init(void)
331 curl = curl_easy_init();
333 fprintf(stderr, "Can not init CURL!\n");
336 /* some ssl sanity checks on the connection we are making */
337 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
338 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
342 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
344 xmlChar *text = NULL;
345 xmlChar *user = NULL;
346 xmlChar *created = NULL;
350 current = current->xmlChildrenNode;
351 while (current != NULL) {
352 if (current->type == XML_ELEMENT_NODE) {
353 if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
354 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
355 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
356 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
357 if (!xmlStrcmp(current->name, (const xmlChar *)"id"))
358 id = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
359 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
360 userinfo = current->xmlChildrenNode;
361 while (userinfo != NULL) {
362 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
365 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
367 userinfo = userinfo->next;
371 if (user && text && created && id) {
373 printf("[%s] {%s} (%.16s) %s\n",
374 user, id, created, text);
388 current = current->next;
394 static void parse_timeline(char *document)
399 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
400 NULL, XML_PARSE_NOERROR);
404 current = xmlDocGetRootElement(doc);
405 if (current == NULL) {
406 fprintf(stderr, "empty document\n");
411 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
412 fprintf(stderr, "unexpected document type\n");
417 current = current->xmlChildrenNode;
418 while (current != NULL) {
419 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
420 parse_statuses(doc, current);
421 current = current->next;
428 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
431 struct bti_curl_buffer *curl_buf = userp;
432 size_t buffer_size = size * nmemb;
435 if ((!buffer) || (!buffer_size) || (!curl_buf))
438 /* add to the data we already have */
439 temp = zalloc(curl_buf->length + buffer_size + 1);
443 memcpy(temp, curl_buf->data, curl_buf->length);
444 free(curl_buf->data);
445 curl_buf->data = temp;
446 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
447 curl_buf->length += buffer_size;
448 if (curl_buf->action)
449 parse_timeline(curl_buf->data);
451 dbg("%s\n", curl_buf->data);
456 static int parse_osp_reply(const char *reply, char **token, char **secret)
461 rc = oauth_split_url_parameters(reply, &rv);
462 qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
463 if (rc == 2 || rc == 4) {
464 if (!strncmp(rv[0], "oauth_token=", 11) &&
465 !strncmp(rv[1], "oauth_token_secret=", 18)) {
467 *token = strdup(&(rv[0][12]));
469 *secret = strdup(&(rv[1][19]));
473 } else if (rc == 3) {
474 if (!strncmp(rv[1], "oauth_token=", 11) &&
475 !strncmp(rv[2], "oauth_token_secret=", 18)) {
477 *token = strdup(&(rv[1][12]));
479 *secret = strdup(&(rv[2][19]));
485 dbg("token: %s\n", *token);
486 dbg("secret: %s\n", *secret);
494 static int request_access_token(struct session *session)
496 char *post_params = NULL;
497 char *request_url = NULL;
500 char *at_secret = NULL;
501 char *verifier = NULL;
507 if (session->host == HOST_TWITTER)
508 request_url = oauth_sign_url2(
509 twitter_request_token_uri, NULL,
510 OA_HMAC, NULL, session->consumer_key,
511 session->consumer_secret, NULL, NULL);
512 else if (session->host == HOST_IDENTICA)
513 request_url = oauth_sign_url2(
514 identica_request_token_uri, NULL,
515 OA_HMAC, NULL, session->consumer_key,
516 session->consumer_secret, NULL, NULL);
517 reply = oauth_http_get(request_url, post_params);
528 if (parse_osp_reply(reply, &at_key, &at_secret))
534 "Please open the following link in your browser, and "
535 "allow 'bti' to access your account. Then paste "
536 "back the provided PIN in here.\n");
537 if (session->host == HOST_TWITTER) {
538 fprintf(stdout, "%s%s\nPIN: ", twitter_authorize_uri, at_key);
539 verifier = session->readline(NULL);
540 sprintf(at_uri, "%s?oauth_verifier=%s",
541 twitter_access_token_uri, verifier);
542 } else if (session->host == HOST_IDENTICA) {
543 fprintf(stdout, "%s%s\nPIN: ", identica_authorize_uri, at_key);
544 verifier = session->readline(NULL);
545 sprintf(at_uri, "%s?oauth_verifier=%s",
546 identica_access_token_uri, verifier);
548 request_url = oauth_sign_url2(at_uri, NULL, OA_HMAC, NULL,
549 session->consumer_key,
550 session->consumer_secret,
552 reply = oauth_http_get(request_url, post_params);
557 if (parse_osp_reply(reply, &at_key, &at_secret))
563 "Please put these two lines in your bti "
564 "configuration file (~/.bti):\n"
565 "access_token_key=%s\n"
566 "access_token_secret=%s\n",
572 static int send_request(struct session *session)
575 char user_password[500];
577 struct bti_curl_buffer *curl_buf;
580 struct curl_httppost *formpost = NULL;
581 struct curl_httppost *lastptr = NULL;
582 struct curl_slist *slist = NULL;
583 char *req_url = NULL;
585 char *postarg = NULL;
586 char *escaped_tweet = NULL;
592 if (!session->hosturl)
593 session->hosturl = strdup(twitter_host);
595 if (session->no_oauth) {
596 curl_buf = bti_curl_buffer_alloc(session->action);
604 if (!session->hosturl)
605 session->hosturl = strdup(twitter_host);
607 switch (session->action) {
609 snprintf(user_password, sizeof(user_password), "%s:%s",
610 session->account, session->password);
611 snprintf(data, sizeof(data), "status=\"%s\"",
613 curl_formadd(&formpost, &lastptr,
614 CURLFORM_COPYNAME, "status",
615 CURLFORM_COPYCONTENTS, session->tweet,
618 curl_formadd(&formpost, &lastptr,
619 CURLFORM_COPYNAME, "source",
620 CURLFORM_COPYCONTENTS, "bti",
623 if (session->replyto)
624 curl_formadd(&formpost, &lastptr,
625 CURLFORM_COPYNAME, "in_reply_to_status_id",
626 CURLFORM_COPYCONTENTS, session->replyto,
629 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
630 slist = curl_slist_append(slist, "Expect:");
631 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
633 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
634 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
635 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
639 snprintf(user_password, sizeof(user_password), "%s:%s",
640 session->account, session->password);
641 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
642 friends_uri, session->page);
643 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
644 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
648 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
649 user_uri, session->user, session->page);
650 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
654 snprintf(user_password, sizeof(user_password), "%s:%s",
655 session->account, session->password);
656 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
657 replies_uri, session->page);
658 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
659 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
663 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
664 public_uri, session->page);
665 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
669 sprintf(endpoint, "%s%s%s.xml?page=%d",
670 session->hosturl, group_uri, session->group,
672 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
680 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
683 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
685 dbg("user_password = %s\n", user_password);
686 dbg("data = %s\n", data);
687 dbg("proxy = %s\n", session->proxy);
689 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
690 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
691 if (!session->dry_run) {
692 res = curl_easy_perform(curl);
693 if (res && !session->background) {
694 fprintf(stderr, "error(%d) trying to perform "
700 curl_easy_cleanup(curl);
701 if (session->action == ACTION_UPDATE)
702 curl_formfree(formpost);
703 bti_curl_buffer_free(curl_buf);
705 switch (session->action) {
707 escaped_tweet = oauth_url_escape(session->tweet);
708 if (session->replyto) {
710 "%s%s?status=%s&in_reply_to_status_id=%s",
711 session->hosturl, update_uri,
712 escaped_tweet, session->replyto);
714 sprintf(endpoint, "%s%s?status=%s",
715 session->hosturl, update_uri,
722 sprintf(endpoint, "%s%s%s.xml?page=%d",
723 session->hosturl, user_uri, session->user,
727 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
728 mentions_uri, session->page);
731 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
732 public_uri, session->page);
735 sprintf(endpoint, "%s%s%s.xml?page=%d",
736 session->hosturl, group_uri, session->group,
740 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
741 friends_uri, session->page);
744 sprintf(endpoint, "%s%s%s.xml", session->hosturl,
745 retweet_uri, session->retweet);
752 dbg("%s\n", endpoint);
753 if (!session->dry_run) {
755 req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
756 NULL, session->consumer_key,
757 session->consumer_secret,
758 session->access_token_key,
759 session->access_token_secret);
760 reply = oauth_http_post(req_url, postarg);
762 req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
763 session->consumer_key,
764 session->consumer_secret,
765 session->access_token_key,
766 session->access_token_secret);
767 reply = oauth_http_get(req_url, postarg);
770 dbg("%s\n", req_url);
776 if ((session->action != ACTION_UPDATE) &&
777 (session->action != ACTION_RETWEET))
778 parse_timeline(reply);
783 static void parse_configfile(struct session *session)
788 char *account = NULL;
789 char *password = NULL;
790 char *consumer_key = NULL;
791 char *consumer_secret = NULL;
792 char *access_token_key = NULL;
793 char *access_token_secret = NULL;
796 char *logfile = NULL;
799 char *replyto = NULL;
800 char *retweet = NULL;
803 config_file = fopen(session->configfile, "r");
805 /* No error if file does not exist or is unreadable. */
806 if (config_file == NULL)
810 ssize_t n = getline(&line, &len, config_file);
813 if (line[n - 1] == '\n')
815 /* Parse file. Format is the usual value pairs:
818 # is a comment character
820 *strchrnul(line, '#') = '\0';
824 /* Ignore blank lines. */
828 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
832 } else if (!strncasecmp(c, "password", 8) &&
836 password = strdup(c);
837 } else if (!strncasecmp(c, "consumer_key", 12) &&
841 consumer_key = strdup(c);
842 } else if (!strncasecmp(c, "consumer_secret", 15) &&
846 consumer_secret = strdup(c);
847 } else if (!strncasecmp(c, "access_token_key", 16) &&
851 access_token_key = strdup(c);
852 } else if (!strncasecmp(c, "access_token_secret", 19) &&
856 access_token_secret = strdup(c);
857 } else if (!strncasecmp(c, "host", 4) &&
862 } else if (!strncasecmp(c, "proxy", 5) &&
867 } else if (!strncasecmp(c, "logfile", 7) &&
872 } else if (!strncasecmp(c, "replyto", 7) &&
877 } else if (!strncasecmp(c, "action", 6) &&
882 } else if (!strncasecmp(c, "user", 4) &&
887 } else if (!strncasecmp(c, "shrink-urls", 11) &&
890 if (!strncasecmp(c, "true", 4) ||
891 !strncasecmp(c, "yes", 3))
893 } else if (!strncasecmp(c, "verbose", 7) &&
896 if (!strncasecmp(c, "true", 4) ||
897 !strncasecmp(c, "yes", 3))
899 } else if (!strncasecmp(c,"retweet", 7) &&
905 } while (!feof(config_file));
908 session->password = password;
910 session->account = account;
912 session->consumer_key = consumer_key;
914 session->consumer_secret = consumer_secret;
915 if (access_token_key)
916 session->access_token_key = access_token_key;
917 if (access_token_secret)
918 session->access_token_secret = access_token_secret;
920 if (strcasecmp(host, "twitter") == 0) {
921 session->host = HOST_TWITTER;
922 session->hosturl = strdup(twitter_host);
923 session->hostname = strdup(twitter_name);
924 } else if (strcasecmp(host, "identica") == 0) {
925 session->host = HOST_IDENTICA;
926 session->hosturl = strdup(identica_host);
927 session->hostname = strdup(identica_name);
929 session->host = HOST_CUSTOM;
930 session->hosturl = strdup(host);
931 session->hostname = strdup(host);
937 free(session->proxy);
938 session->proxy = proxy;
941 session->logfile = logfile;
943 session->replyto = replyto;
945 session->retweet = retweet;
947 if (strcasecmp(action, "update") == 0)
948 session->action = ACTION_UPDATE;
949 else if (strcasecmp(action, "friends") == 0)
950 session->action = ACTION_FRIENDS;
951 else if (strcasecmp(action, "user") == 0)
952 session->action = ACTION_USER;
953 else if (strcasecmp(action, "replies") == 0)
954 session->action = ACTION_REPLIES;
955 else if (strcasecmp(action, "public") == 0)
956 session->action = ACTION_PUBLIC;
957 else if (strcasecmp(action, "group") == 0)
958 session->action = ACTION_GROUP;
960 session->action = ACTION_UNKNOWN;
964 session->user = user;
965 session->shrink_urls = shrink_urls;
967 /* Free buffer and close file. */
972 static void log_session(struct session *session, int retval)
977 /* Only log something if we have a log file set */
978 if (!session->logfile)
981 filename = alloca(strlen(session->homedir) +
982 strlen(session->logfile) + 3);
984 sprintf(filename, "%s/%s", session->homedir, session->logfile);
986 log_file = fopen(filename, "a+");
987 if (log_file == NULL)
990 switch (session->action) {
993 fprintf(log_file, "%s: host=%s tweet failed\n",
994 session->time, session->hostname);
996 fprintf(log_file, "%s: host=%s tweet=%s\n",
997 session->time, session->hostname,
1000 case ACTION_FRIENDS:
1001 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
1002 session->time, session->hostname);
1005 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
1006 session->time, session->hostname, session->user);
1008 case ACTION_REPLIES:
1009 fprintf(log_file, "%s: host=%s retrieving replies\n",
1010 session->time, session->hostname);
1013 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
1014 session->time, session->hostname);
1017 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
1018 session->time, session->hostname);
1027 static char *get_string_from_stdin(void)
1032 string = zalloc(1000);
1036 if (!fgets(string, 999, stdin))
1038 temp = strchr(string, '\n');
1044 static void read_password(char *buf, size_t len, char *host)
1054 tp.c_lflag &= (~ECHO);
1055 tcsetattr(0, TCSANOW, &tp);
1057 fprintf(stdout, "Enter password for %s: ", host);
1060 retval = scanf("%79s", pwd);
1062 fprintf(stdout, "\n");
1064 tcsetattr(0, TCSANOW, &old);
1066 strncpy(buf, pwd, len);
1070 static int find_urls(const char *tweet, int **pranges)
1073 * magic obtained from
1074 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
1076 static const char *re_magic =
1077 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
1078 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
1079 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
1083 int ovector[10] = {0,};
1084 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
1085 int startoffset, tweetlen;
1089 int *ranges = malloc(sizeof(int) * rbound);
1091 re = pcre_compile(re_magic,
1092 PCRE_NO_AUTO_CAPTURE,
1093 &errptr, &erroffset, NULL);
1095 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
1099 tweetlen = strlen(tweet);
1100 for (startoffset = 0; startoffset < tweetlen; ) {
1102 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
1104 if (rc == PCRE_ERROR_NOMATCH)
1108 fprintf(stderr, "pcre_exec @%u: %s\n",
1113 for (i = 0; i < rc; i += 2) {
1114 if ((rcount+2) == rbound) {
1116 ranges = realloc(ranges, sizeof(int) * rbound);
1119 ranges[rcount++] = ovector[i];
1120 ranges[rcount++] = ovector[i+1];
1123 startoffset = ovector[1];
1133 * bidirectional popen() call
1135 * @param rwepipe - int array of size three
1136 * @param exe - program to run
1137 * @param argv - argument list
1138 * @return pid or -1 on error
1140 * The caller passes in an array of three integers (rwepipe), on successful
1141 * execution it can then write to element 0 (stdin of exe), and read from
1142 * element 1 (stdout) and 2 (stderr).
1144 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
1171 rwepipe[1] = out[0];
1172 rwepipe[2] = err[0];
1174 } else if (pid == 0) {
1186 execvp(exe, (char **)argv);
1206 static int pcloseRWE(int pid, int *rwepipe)
1212 rc = waitpid(pid, &status, 0);
1216 static char *shrink_one_url(int *rwepipe, char *big)
1218 int biglen = strlen(big);
1223 rc = dprintf(rwepipe[0], "%s\n", big);
1227 smalllen = biglen + 128;
1228 small = malloc(smalllen);
1232 rc = read(rwepipe[1], small, smalllen);
1233 if (rc < 0 || rc > biglen)
1234 goto error_free_small;
1236 if (strncmp(small, "http://", 7))
1237 goto error_free_small;
1240 while (smalllen && isspace(small[smalllen-1]))
1241 small[--smalllen] = 0;
1251 static char *shrink_urls(char *text)
1258 const char *const shrink_args[] = {
1264 int inlen = strlen(text);
1266 dbg("before len=%u\n", inlen);
1268 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
1272 rcount = find_urls(text, &ranges);
1276 for (i = 0; i < rcount; i += 2) {
1277 int url_start = ranges[i];
1278 int url_end = ranges[i+1];
1279 int long_url_len = url_end - url_start;
1280 char *url = strndup(text + url_start, long_url_len);
1282 int not_url_len = url_start - inofs;
1284 dbg("long url[%u]: %s\n", long_url_len, url);
1285 url = shrink_one_url(shrink_pipe, url);
1286 short_url_len = url ? strlen(url) : 0;
1287 dbg("short url[%u]: %s\n", short_url_len, url);
1289 if (!url || short_url_len >= long_url_len) {
1290 /* The short url ended up being too long
1293 strncpy(text + outofs, text + inofs,
1294 not_url_len + long_url_len);
1296 inofs += not_url_len + long_url_len;
1297 outofs += not_url_len + long_url_len;
1300 /* copy the unmodified block */
1301 strncpy(text + outofs, text + inofs, not_url_len);
1302 inofs += not_url_len;
1303 outofs += not_url_len;
1305 /* copy the new url */
1306 strncpy(text + outofs, url, short_url_len);
1307 inofs += long_url_len;
1308 outofs += short_url_len;
1314 /* copy the last block after the last match */
1316 int tail = inlen - inofs;
1318 strncpy(text + outofs, text + inofs, tail);
1325 (void)pcloseRWE(shrink_pid, shrink_pipe);
1328 dbg("after len=%u\n", outofs);
1332 int main(int argc, char *argv[], char *envp[])
1334 static const struct option options[] = {
1335 { "debug", 0, NULL, 'd' },
1336 { "verbose", 0, NULL, 'V' },
1337 { "account", 1, NULL, 'a' },
1338 { "password", 1, NULL, 'p' },
1339 { "host", 1, NULL, 'H' },
1340 { "proxy", 1, NULL, 'P' },
1341 { "action", 1, NULL, 'A' },
1342 { "user", 1, NULL, 'u' },
1343 { "group", 1, NULL, 'G' },
1344 { "logfile", 1, NULL, 'L' },
1345 { "shrink-urls", 0, NULL, 's' },
1346 { "help", 0, NULL, 'h' },
1347 { "bash", 0, NULL, 'b' },
1348 { "background", 0, NULL, 'B' },
1349 { "dry-run", 0, NULL, 'n' },
1350 { "page", 1, NULL, 'g' },
1351 { "version", 0, NULL, 'v' },
1352 { "config", 1, NULL, 'c' },
1353 { "replyto", 1, NULL, 'r' },
1354 { "retweet", 1, NULL, 'w' },
1357 struct session *session;
1361 static char password[80];
1371 session = session_alloc();
1373 fprintf(stderr, "no more memory...\n");
1377 /* get the current time so that we can log it later */
1379 session->time = strdup(ctime(&t));
1380 session->time[strlen(session->time)-1] = 0x00;
1382 /* Get the home directory so we can try to find a config file */
1383 session->homedir = strdup(getenv("HOME"));
1385 /* set up a default config file location (traditionally ~/.bti) */
1386 session->configfile = zalloc(strlen(session->homedir) + 7);
1387 sprintf(session->configfile, "%s/.bti", session->homedir);
1389 /* Set environment variables first, before reading command line options
1390 * or config file values. */
1391 http_proxy = getenv("http_proxy");
1394 free(session->proxy);
1395 session->proxy = strdup(http_proxy);
1396 dbg("http_proxy = %s\n", session->proxy);
1399 parse_configfile(session);
1402 option = getopt_long_only(argc, argv,
1403 "dp:P:H:a:A:u:c:hg:G:sr:nVv",
1415 if (session->account)
1416 free(session->account);
1417 session->account = strdup(optarg);
1418 dbg("account = %s\n", session->account);
1421 page_nr = atoi(optarg);
1422 dbg("page = %d\n", page_nr);
1423 session->page = page_nr;
1426 session->replyto = strdup(optarg);
1427 dbg("in_reply_to_status_id = %s\n", session->replyto);
1430 session->retweet = strdup(optarg);
1431 dbg("Retweet ID = %s\n", session->retweet);
1434 if (session->password)
1435 free(session->password);
1436 session->password = strdup(optarg);
1437 dbg("password = %s\n", session->password);
1441 free(session->proxy);
1442 session->proxy = strdup(optarg);
1443 dbg("proxy = %s\n", session->proxy);
1446 if (strcasecmp(optarg, "update") == 0)
1447 session->action = ACTION_UPDATE;
1448 else if (strcasecmp(optarg, "friends") == 0)
1449 session->action = ACTION_FRIENDS;
1450 else if (strcasecmp(optarg, "user") == 0)
1451 session->action = ACTION_USER;
1452 else if (strcasecmp(optarg, "replies") == 0)
1453 session->action = ACTION_REPLIES;
1454 else if (strcasecmp(optarg, "public") == 0)
1455 session->action = ACTION_PUBLIC;
1456 else if (strcasecmp(optarg, "group") == 0)
1457 session->action = ACTION_GROUP;
1458 else if (strcasecmp(optarg,"retweet") == 0)
1459 session->action = ACTION_RETWEET;
1461 session->action = ACTION_UNKNOWN;
1462 dbg("action = %d\n", session->action);
1466 free(session->user);
1467 session->user = strdup(optarg);
1468 dbg("user = %s\n", session->user);
1473 free(session->group);
1474 session->group = strdup(optarg);
1475 dbg("group = %s\n", session->group);
1478 if (session->logfile)
1479 free(session->logfile);
1480 session->logfile = strdup(optarg);
1481 dbg("logfile = %s\n", session->logfile);
1484 session->shrink_urls = 1;
1487 if (session->hosturl)
1488 free(session->hosturl);
1489 if (session->hostname)
1490 free(session->hostname);
1491 if (strcasecmp(optarg, "twitter") == 0) {
1492 session->host = HOST_TWITTER;
1493 session->hosturl = strdup(twitter_host);
1494 session->hostname = strdup(twitter_name);
1495 } else if (strcasecmp(optarg, "identica") == 0) {
1496 session->host = HOST_IDENTICA;
1497 session->hosturl = strdup(identica_host);
1498 session->hostname = strdup(identica_name);
1500 session->host = HOST_CUSTOM;
1501 session->hosturl = strdup(optarg);
1502 session->hostname = strdup(optarg);
1504 dbg("host = %d\n", session->host);
1508 /* fall-through intended */
1510 session->background = 1;
1513 if (session->configfile)
1514 free(session->configfile);
1515 session->configfile = strdup(optarg);
1516 dbg("configfile = %s\n", session->configfile);
1519 * read the config file now. Yes, this could override
1520 * previously set options from the command line, but
1521 * the user asked for it...
1523 parse_configfile(session);
1529 session->dry_run = 1;
1540 session_readline_init(session);
1542 * Show the version to make it easier to determine what
1548 if (session->host == HOST_TWITTER) {
1549 if (!session->consumer_key || !session->consumer_secret) {
1551 "Twitter no longer supports HTTP basic authentication.\n"
1552 "Both consumer key, and consumer secret are required"
1553 " for bti in order to behave as an OAuth consumer.\n");
1556 if (session->action == ACTION_GROUP) {
1557 fprintf(stderr, "Groups only work in Identi.ca.\n");
1561 if (!session->consumer_key || !session->consumer_secret)
1562 session->no_oauth = 1;
1565 if (session->no_oauth) {
1566 if (!session->account) {
1567 fprintf(stdout, "Enter account for %s: ",
1569 session->account = session->readline(NULL);
1571 if (!session->password) {
1572 read_password(password, sizeof(password),
1574 session->password = strdup(password);
1577 if (!session->access_token_key ||
1578 !session->access_token_secret) {
1579 request_access_token(session);
1584 if (session->action == ACTION_UNKNOWN) {
1585 fprintf(stderr, "Unknown action, valid actions are:\n"
1586 "'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
1590 if (session->action == ACTION_GROUP && !session->group) {
1591 fprintf(stdout, "Enter group name: ");
1592 session->group = session->readline(NULL);
1595 if (session->action == ACTION_RETWEET) {
1596 fprintf(stdout, "Status ID to retweet: ");
1597 retweet = get_string_from_stdin();
1599 if (!retweet || strlen(retweet) == 0) {
1600 dbg("no retweet?\n");
1604 session->retweet = zalloc(strlen(retweet) + 10);
1605 sprintf(session->retweet,"%s", retweet);
1607 dbg("retweet ID = %s\n", session->retweet);
1610 if (session->action == ACTION_UPDATE) {
1611 if (session->background || !session->interactive)
1612 tweet = get_string_from_stdin();
1614 tweet = session->readline("tweet: ");
1615 if (!tweet || strlen(tweet) == 0) {
1620 if (session->shrink_urls)
1621 tweet = shrink_urls(tweet);
1623 session->tweet = zalloc(strlen(tweet) + 10);
1625 sprintf(session->tweet, "%c %s",
1626 getuid() ? '$' : '#', tweet);
1628 sprintf(session->tweet, "%s", tweet);
1631 dbg("tweet = %s\n", session->tweet);
1634 if (session->page == 0)
1636 dbg("config file = %s\n", session->configfile);
1637 dbg("host = %d\n", session->host);
1638 dbg("action = %d\n", session->action);
1640 /* fork ourself so that the main shell can get on
1641 * with it's life as we try to connect and handle everything
1643 if (session->background) {
1646 dbg("child is %d\n", child);
1651 retval = send_request(session);
1652 if (retval && !session->background)
1653 fprintf(stderr, "operation failed\n");
1655 log_session(session, retval);
1657 session_readline_cleanup(session);
1658 session_free(session);