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 <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;
100 void *readline_handle;
101 char *(*readline)(const char *);
104 struct bti_curl_buffer {
110 static void display_help(void)
112 fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
113 fprintf(stdout, "Version: " VERSION "\n");
114 fprintf(stdout, "Usage:\n");
115 fprintf(stdout, " bti [options]\n");
116 fprintf(stdout, "options are:\n");
117 fprintf(stdout, " --account accountname\n");
118 fprintf(stdout, " --password password\n");
119 fprintf(stdout, " --action action\n");
120 fprintf(stdout, " ('update', 'friends', 'public', 'replies', "
121 "'group' or 'user')\n");
122 fprintf(stdout, " --user screenname\n");
123 fprintf(stdout, " --group groupname\n");
124 fprintf(stdout, " --proxy PROXY:PORT\n");
125 fprintf(stdout, " --host HOST\n");
126 fprintf(stdout, " --logfile logfile\n");
127 fprintf(stdout, " --config configfile\n");
128 fprintf(stdout, " --replyto ID\n");
129 fprintf(stdout, " --shrink-urls\n");
130 fprintf(stdout, " --page PAGENUMBER\n");
131 fprintf(stdout, " --bash\n");
132 fprintf(stdout, " --debug\n");
133 fprintf(stdout, " --verbose\n");
134 fprintf(stdout, " --dry-run\n");
135 fprintf(stdout, " --version\n");
136 fprintf(stdout, " --help\n");
139 static void display_version(void)
141 fprintf(stdout, "bti - version %s\n", VERSION);
144 static char *get_string(const char *name)
149 string = zalloc(1000);
153 fprintf(stdout, "%s", name);
154 if (!fgets(string, 999, stdin))
156 temp = strchr(string, '\n');
163 * Try to get a handle to a readline function from a variety of different
164 * libraries. If nothing is present on the system, then fall back to an
167 * Logic originally based off of code in the e2fsutils package in the
168 * lib/ss/get_readline.c file, which is licensed under the MIT license.
170 * This keeps us from having to relicense the bti codebase if readline
171 * ever changes its license, as there is no link-time dependancy.
172 * It is a run-time thing only, and we handle any readline-like library
173 * in the same manner, making bti not be a derivative work of any
176 static void session_readline_init(struct session *session)
178 /* Libraries we will try to use for readline/editline functionality */
179 const char *libpath = "libreadline.so.6:libreadline.so.5:"
180 "libreadline.so.4:libreadline.so:libedit.so.2:"
181 "libedit.so:libeditline.so.0:libeditline.so";
183 char *tmp, *cp, *next;
184 int (*bind_key)(int, void *);
185 void (*insert)(void);
187 /* default to internal function if we can't or won't find anything */
188 session->readline = get_string;
191 session->interactive = 1;
193 tmp = malloc(strlen(libpath)+1);
196 strcpy(tmp, libpath);
197 for (cp = tmp; cp; cp = next) {
198 next = strchr(cp, ':');
203 handle = dlopen(cp, RTLD_NOW);
205 dbg("Using %s for readline library\n", cp);
211 dbg("No readline library found.\n");
215 session->readline_handle = handle;
216 session->readline = (char *(*)(const char *))dlsym(handle, "readline");
217 if (session->readline == NULL) {
218 /* something odd happened, default back to internal stuff */
219 session->readline_handle = NULL;
220 session->readline = get_string;
225 * If we found a library, turn off filename expansion
226 * as that makes no sense from within bti.
228 bind_key = (int (*)(int, void *))dlsym(handle, "rl_bind_key");
229 insert = (void (*)(void))dlsym(handle, "rl_insert");
230 if (bind_key && insert)
231 bind_key('\t', insert);
234 static void session_readline_cleanup(struct session *session)
236 if (session->readline_handle)
237 dlclose(session->readline_handle);
240 static struct session *session_alloc(void)
242 struct session *session;
244 session = zalloc(sizeof(*session));
250 static void session_free(struct session *session)
254 free(session->replyto);
255 free(session->password);
256 free(session->account);
257 free(session->consumer_key);
258 free(session->consumer_secret);
259 free(session->access_token_key);
260 free(session->access_token_secret);
261 free(session->tweet);
262 free(session->proxy);
264 free(session->homedir);
266 free(session->group);
267 free(session->hosturl);
268 free(session->hostname);
269 free(session->configfile);
273 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
275 struct bti_curl_buffer *buffer;
277 buffer = zalloc(sizeof(*buffer));
281 /* start out with a data buffer of 1 byte to
282 * make the buffer fill logic simpler */
283 buffer->data = zalloc(1);
289 buffer->action = action;
293 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
301 static const char twitter_host[] = "http://api.twitter.com/1/statuses";
302 static const char identica_host[] = "https://identi.ca/api/statuses";
303 static const char twitter_name[] = "twitter";
304 static const char identica_name[] = "identi.ca";
306 static const char twitter_request_token_uri[] = "http://twitter.com/oauth/request_token";
307 static const char twitter_access_token_uri[] = "http://twitter.com/oauth/access_token";
308 static const char twitter_authorize_uri[] = "http://twitter.com/oauth/authorize?oauth_token=";
309 static const char identica_request_token_uri[] = "http://identi.ca/api/oauth/request_token";
310 static const char identica_access_token_uri[] = "http://identi.ca/api/oauth/access_token";
311 static const char identica_authorize_uri[] = "http://identi.ca/api/oauth/authorize?oauth_token=";
313 static const char user_uri[] = "/user_timeline/";
314 static const char update_uri[] = "/update.xml";
315 static const char public_uri[] = "/public_timeline.xml";
316 static const char friends_uri[] = "/friends_timeline.xml";
317 static const char mentions_uri[] = "/mentions.xml";
318 static const char replies_uri[] = "/replies.xml";
319 static const char group_uri[] = "/../statusnet/groups/timeline/";
321 static CURL *curl_init(void)
325 curl = curl_easy_init();
327 fprintf(stderr, "Can not init CURL!\n");
330 /* some ssl sanity checks on the connection we are making */
331 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
332 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
336 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
338 xmlChar *text = NULL;
339 xmlChar *user = NULL;
340 xmlChar *created = NULL;
344 current = current->xmlChildrenNode;
345 while (current != NULL) {
346 if (current->type == XML_ELEMENT_NODE) {
347 if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
348 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
349 if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
350 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
351 if (!xmlStrcmp(current->name, (const xmlChar *)"id"))
352 id = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
353 if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
354 userinfo = current->xmlChildrenNode;
355 while (userinfo != NULL) {
356 if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
359 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
361 userinfo = userinfo->next;
365 if (user && text && created && id) {
367 printf("[%s] {%s} (%.16s) %s\n",
368 user, id, created, text);
382 current = current->next;
388 static void parse_timeline(char *document)
393 doc = xmlReadMemory(document, strlen(document), "timeline.xml",
394 NULL, XML_PARSE_NOERROR);
398 current = xmlDocGetRootElement(doc);
399 if (current == NULL) {
400 fprintf(stderr, "empty document\n");
405 if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
406 fprintf(stderr, "unexpected document type\n");
411 current = current->xmlChildrenNode;
412 while (current != NULL) {
413 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
414 parse_statuses(doc, current);
415 current = current->next;
422 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
425 struct bti_curl_buffer *curl_buf = userp;
426 size_t buffer_size = size * nmemb;
429 if ((!buffer) || (!buffer_size) || (!curl_buf))
432 /* add to the data we already have */
433 temp = zalloc(curl_buf->length + buffer_size + 1);
437 memcpy(temp, curl_buf->data, curl_buf->length);
438 free(curl_buf->data);
439 curl_buf->data = temp;
440 memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
441 curl_buf->length += buffer_size;
442 if (curl_buf->action)
443 parse_timeline(curl_buf->data);
445 dbg("%s\n", curl_buf->data);
450 static int parse_osp_reply(const char *reply, char **token, char **secret)
455 rc = oauth_split_url_parameters(reply, &rv);
456 qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
457 if (rc == 2 || rc == 4) {
458 if (!strncmp(rv[0], "oauth_token=", 11) &&
459 !strncmp(rv[1], "oauth_token_secret=", 18)) {
461 *token = strdup(&(rv[0][12]));
463 *secret = strdup(&(rv[1][19]));
467 } else if (rc == 3) {
468 if (!strncmp(rv[1], "oauth_token=", 11) &&
469 !strncmp(rv[2], "oauth_token_secret=", 18)) {
471 *token = strdup(&(rv[1][12]));
473 *secret = strdup(&(rv[2][19]));
479 dbg("token: %s\n", *token);
480 dbg("secret: %s\n", *secret);
488 static int request_access_token(struct session *session)
490 char *post_params = NULL;
491 char *request_url = NULL;
494 char *at_secret = NULL;
495 char *verifier = NULL;
501 if (session->host == HOST_TWITTER)
502 request_url = oauth_sign_url2(
503 twitter_request_token_uri, NULL,
504 OA_HMAC, NULL, session->consumer_key,
505 session->consumer_secret, NULL, NULL);
506 else if (session->host == HOST_IDENTICA)
507 request_url = oauth_sign_url2(
508 identica_request_token_uri, NULL,
509 OA_HMAC, NULL, session->consumer_key,
510 session->consumer_secret, NULL, NULL);
511 reply = oauth_http_get(request_url, post_params);
522 if (parse_osp_reply(reply, &at_key, &at_secret))
527 fprintf(stdout, "Please open the following link in your browser, and ");
528 fprintf(stdout, "allow 'bti' to access your account. Then paste ");
529 fprintf(stdout, "back the provided PIN in here.\n");
530 if (session->host == HOST_TWITTER) {
531 fprintf(stdout, "%s%s\nPIN: ", twitter_authorize_uri, at_key);
532 verifier = session->readline(NULL);
533 sprintf(at_uri, "%s?oauth_verifier=%s",
534 twitter_access_token_uri, verifier);
535 } else if (session->host == HOST_IDENTICA) {
536 fprintf(stdout, "%s%s\nPIN: ", identica_authorize_uri, at_key);
537 verifier = session->readline(NULL);
538 sprintf(at_uri, "%s?oauth_verifier=%s",
539 identica_access_token_uri, verifier);
541 request_url = oauth_sign_url2(at_uri, NULL, OA_HMAC, NULL,
542 session->consumer_key,
543 session->consumer_secret,
545 reply = oauth_http_get(request_url, post_params);
550 if (parse_osp_reply(reply, &at_key, &at_secret))
555 fprintf(stdout, "Please put these two lines in your bti ");
556 fprintf(stdout, "configuration file (~/.bti):\n");
557 fprintf(stdout, "access_token_key=%s\n", at_key);
558 fprintf(stdout, "access_token_secret=%s\n", at_secret);
563 static int send_request(struct session *session)
566 char user_password[500];
568 struct bti_curl_buffer *curl_buf;
571 struct curl_httppost *formpost = NULL;
572 struct curl_httppost *lastptr = NULL;
573 struct curl_slist *slist = NULL;
574 char *req_url = NULL;
576 char *postarg = NULL;
577 char *escaped_tweet = NULL;
583 if (!session->hosturl)
584 session->hosturl = strdup(twitter_host);
586 if (session->no_oauth) {
587 curl_buf = bti_curl_buffer_alloc(session->action);
595 if (!session->hosturl)
596 session->hosturl = strdup(twitter_host);
598 switch (session->action) {
600 snprintf(user_password, sizeof(user_password), "%s:%s",
601 session->account, session->password);
602 snprintf(data, sizeof(data), "status=\"%s\"",
604 curl_formadd(&formpost, &lastptr,
605 CURLFORM_COPYNAME, "status",
606 CURLFORM_COPYCONTENTS, session->tweet,
609 curl_formadd(&formpost, &lastptr,
610 CURLFORM_COPYNAME, "source",
611 CURLFORM_COPYCONTENTS, "bti",
614 if (session->replyto)
615 curl_formadd(&formpost, &lastptr,
616 CURLFORM_COPYNAME, "in_reply_to_status_id",
617 CURLFORM_COPYCONTENTS, session->replyto,
620 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
621 slist = curl_slist_append(slist, "Expect:");
622 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
624 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
625 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
626 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
630 snprintf(user_password, sizeof(user_password), "%s:%s",
631 session->account, session->password);
632 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
633 friends_uri, session->page);
634 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
635 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
639 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
640 user_uri, session->user, session->page);
641 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
645 snprintf(user_password, sizeof(user_password), "%s:%s",
646 session->account, session->password);
647 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
648 replies_uri, session->page);
649 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
650 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
654 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
655 public_uri, session->page);
656 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
660 sprintf(endpoint, "%s%s%s.xml?page=%d",
661 session->hosturl, group_uri, session->group,
663 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
671 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
674 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
676 dbg("user_password = %s\n", user_password);
677 dbg("data = %s\n", data);
678 dbg("proxy = %s\n", session->proxy);
680 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
681 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
682 if (!session->dry_run) {
683 res = curl_easy_perform(curl);
684 if (res && !session->bash) {
685 fprintf(stderr, "error(%d) trying to perform "
691 curl_easy_cleanup(curl);
692 if (session->action == ACTION_UPDATE)
693 curl_formfree(formpost);
694 bti_curl_buffer_free(curl_buf);
696 switch (session->action) {
698 escaped_tweet = oauth_url_escape(session->tweet);
699 sprintf(endpoint, "%s%s?status=%s", session->hosturl,
700 update_uri, escaped_tweet);
704 sprintf(endpoint, "%s%s%s.xml?page=%d",
705 session->hosturl, user_uri, session->user,
709 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
710 mentions_uri, session->page);
713 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
714 public_uri, session->page);
717 sprintf(endpoint, "%s%s%s.xml?page=%d",
718 session->hosturl, group_uri, session->group,
722 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
723 friends_uri, session->page);
730 req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
731 NULL, session->consumer_key,
732 session->consumer_secret,
733 session->access_token_key,
734 session->access_token_secret);
735 reply = oauth_http_post(req_url, postarg);
737 req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
738 session->consumer_key,
739 session->consumer_secret,
740 session->access_token_key,
741 session->access_token_secret);
742 reply = oauth_http_get(req_url, postarg);
745 dbg("%s\n", req_url);
750 if (session->action != ACTION_UPDATE)
751 parse_timeline(reply);
756 static void parse_configfile(struct session *session)
761 char *account = NULL;
762 char *password = NULL;
763 char *consumer_key = NULL;
764 char *consumer_secret = NULL;
765 char *access_token_key = NULL;
766 char *access_token_secret = NULL;
769 char *logfile = NULL;
772 char *replyto = NULL;
775 config_file = fopen(session->configfile, "r");
777 /* No error if file does not exist or is unreadable. */
778 if (config_file == NULL)
782 ssize_t n = getline(&line, &len, config_file);
785 if (line[n - 1] == '\n')
787 /* Parse file. Format is the usual value pairs:
790 # is a comment character
792 *strchrnul(line, '#') = '\0';
796 /* Ignore blank lines. */
800 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
804 } else if (!strncasecmp(c, "password", 8) &&
808 password = strdup(c);
809 } else if (!strncasecmp(c, "consumer_key", 12) &&
813 consumer_key = strdup(c);
814 } else if (!strncasecmp(c, "consumer_secret", 15) &&
818 consumer_secret = strdup(c);
819 } else if (!strncasecmp(c, "access_token_key", 16) &&
823 access_token_key = strdup(c);
824 } else if (!strncasecmp(c, "access_token_secret", 19) &&
828 access_token_secret = strdup(c);
829 } else if (!strncasecmp(c, "host", 4) &&
834 } else if (!strncasecmp(c, "proxy", 5) &&
839 } else if (!strncasecmp(c, "logfile", 7) &&
844 } else if (!strncasecmp(c, "replyto", 7) &&
849 } else if (!strncasecmp(c, "action", 6) &&
854 } else if (!strncasecmp(c, "user", 4) &&
859 } else if (!strncasecmp(c, "shrink-urls", 11) &&
862 if (!strncasecmp(c, "true", 4) ||
863 !strncasecmp(c, "yes", 3))
865 } else if (!strncasecmp(c, "verbose", 7) &&
868 if (!strncasecmp(c, "true", 4) ||
869 !strncasecmp(c, "yes", 3))
872 } while (!feof(config_file));
875 session->password = password;
877 session->account = account;
879 session->consumer_key = consumer_key;
881 session->consumer_secret = consumer_secret;
882 if (access_token_key)
883 session->access_token_key = access_token_key;
884 if (access_token_secret)
885 session->access_token_secret = access_token_secret;
887 if (strcasecmp(host, "twitter") == 0) {
888 session->host = HOST_TWITTER;
889 session->hosturl = strdup(twitter_host);
890 session->hostname = strdup(twitter_name);
891 } else if (strcasecmp(host, "identica") == 0) {
892 session->host = HOST_IDENTICA;
893 session->hosturl = strdup(identica_host);
894 session->hostname = strdup(identica_name);
896 session->host = HOST_CUSTOM;
897 session->hosturl = strdup(host);
898 session->hostname = strdup(host);
904 free(session->proxy);
905 session->proxy = proxy;
908 session->logfile = logfile;
910 session->replyto = replyto;
912 if (strcasecmp(action, "update") == 0)
913 session->action = ACTION_UPDATE;
914 else if (strcasecmp(action, "friends") == 0)
915 session->action = ACTION_FRIENDS;
916 else if (strcasecmp(action, "user") == 0)
917 session->action = ACTION_USER;
918 else if (strcasecmp(action, "replies") == 0)
919 session->action = ACTION_REPLIES;
920 else if (strcasecmp(action, "public") == 0)
921 session->action = ACTION_PUBLIC;
922 else if (strcasecmp(action, "group") == 0)
923 session->action = ACTION_GROUP;
925 session->action = ACTION_UNKNOWN;
929 session->user = user;
930 session->shrink_urls = shrink_urls;
932 /* Free buffer and close file. */
937 static void log_session(struct session *session, int retval)
942 /* Only log something if we have a log file set */
943 if (!session->logfile)
946 filename = alloca(strlen(session->homedir) +
947 strlen(session->logfile) + 3);
949 sprintf(filename, "%s/%s", session->homedir, session->logfile);
951 log_file = fopen(filename, "a+");
952 if (log_file == NULL)
955 switch (session->action) {
958 fprintf(log_file, "%s: host=%s tweet failed\n",
959 session->time, session->hostname);
961 fprintf(log_file, "%s: host=%s tweet=%s\n",
962 session->time, session->hostname,
966 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
967 session->time, session->hostname);
970 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
971 session->time, session->hostname, session->user);
974 fprintf(log_file, "%s: host=%s retrieving replies\n",
975 session->time, session->hostname);
978 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
979 session->time, session->hostname);
982 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
983 session->time, session->hostname);
992 static char *get_string_from_stdin(void)
997 string = zalloc(1000);
1001 if (!fgets(string, 999, stdin))
1003 temp = strchr(string, '\n');
1009 static void read_password(char *buf, size_t len, char *host)
1019 tp.c_lflag &= (~ECHO);
1020 tcsetattr(0, TCSANOW, &tp);
1022 fprintf(stdout, "Enter password for %s: ", host);
1025 retval = scanf("%79s", pwd);
1027 fprintf(stdout, "\n");
1029 tcsetattr(0, TCSANOW, &old);
1031 strncpy(buf, pwd, len);
1035 static int find_urls(const char *tweet, int **pranges)
1038 * magic obtained from
1039 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
1041 static const char *re_magic =
1042 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
1043 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
1044 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
1048 int ovector[10] = {0,};
1049 const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
1050 int startoffset, tweetlen;
1054 int *ranges = malloc(sizeof(int) * rbound);
1056 re = pcre_compile(re_magic,
1057 PCRE_NO_AUTO_CAPTURE,
1058 &errptr, &erroffset, NULL);
1060 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
1064 tweetlen = strlen(tweet);
1065 for (startoffset = 0; startoffset < tweetlen; ) {
1067 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
1069 if (rc == PCRE_ERROR_NOMATCH)
1073 fprintf(stderr, "pcre_exec @%u: %s\n",
1078 for (i = 0; i < rc; i += 2) {
1079 if ((rcount+2) == rbound) {
1081 ranges = realloc(ranges, sizeof(int) * rbound);
1084 ranges[rcount++] = ovector[i];
1085 ranges[rcount++] = ovector[i+1];
1088 startoffset = ovector[1];
1098 * bidirectional popen() call
1100 * @param rwepipe - int array of size three
1101 * @param exe - program to run
1102 * @param argv - argument list
1103 * @return pid or -1 on error
1105 * The caller passes in an array of three integers (rwepipe), on successful
1106 * execution it can then write to element 0 (stdin of exe), and read from
1107 * element 1 (stdout) and 2 (stderr).
1109 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
1136 rwepipe[1] = out[0];
1137 rwepipe[2] = err[0];
1139 } else if (pid == 0) {
1151 execvp(exe, (char **)argv);
1171 static int pcloseRWE(int pid, int *rwepipe)
1177 rc = waitpid(pid, &status, 0);
1181 static char *shrink_one_url(int *rwepipe, char *big)
1183 int biglen = strlen(big);
1188 rc = dprintf(rwepipe[0], "%s\n", big);
1192 smalllen = biglen + 128;
1193 small = malloc(smalllen);
1197 rc = read(rwepipe[1], small, smalllen);
1198 if (rc < 0 || rc > biglen)
1199 goto error_free_small;
1201 if (strncmp(small, "http://", 7))
1202 goto error_free_small;
1205 while (smalllen && isspace(small[smalllen-1]))
1206 small[--smalllen] = 0;
1216 static char *shrink_urls(char *text)
1223 const char *const shrink_args[] = {
1229 int inlen = strlen(text);
1231 dbg("before len=%u\n", inlen);
1233 shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
1237 rcount = find_urls(text, &ranges);
1241 for (i = 0; i < rcount; i += 2) {
1242 int url_start = ranges[i];
1243 int url_end = ranges[i+1];
1244 int long_url_len = url_end - url_start;
1245 char *url = strndup(text + url_start, long_url_len);
1247 int not_url_len = url_start - inofs;
1249 dbg("long url[%u]: %s\n", long_url_len, url);
1250 url = shrink_one_url(shrink_pipe, url);
1251 short_url_len = url ? strlen(url) : 0;
1252 dbg("short url[%u]: %s\n", short_url_len, url);
1254 if (!url || short_url_len >= long_url_len) {
1255 /* The short url ended up being too long
1258 strncpy(text + outofs, text + inofs,
1259 not_url_len + long_url_len);
1261 inofs += not_url_len + long_url_len;
1262 outofs += not_url_len + long_url_len;
1265 /* copy the unmodified block */
1266 strncpy(text + outofs, text + inofs, not_url_len);
1267 inofs += not_url_len;
1268 outofs += not_url_len;
1270 /* copy the new url */
1271 strncpy(text + outofs, url, short_url_len);
1272 inofs += long_url_len;
1273 outofs += short_url_len;
1279 /* copy the last block after the last match */
1281 int tail = inlen - inofs;
1283 strncpy(text + outofs, text + inofs, tail);
1290 (void)pcloseRWE(shrink_pid, shrink_pipe);
1293 dbg("after len=%u\n", outofs);
1297 int main(int argc, char *argv[], char *envp[])
1299 static const struct option options[] = {
1300 { "debug", 0, NULL, 'd' },
1301 { "verbose", 0, NULL, 'V' },
1302 { "account", 1, NULL, 'a' },
1303 { "password", 1, NULL, 'p' },
1304 { "host", 1, NULL, 'H' },
1305 { "proxy", 1, NULL, 'P' },
1306 { "action", 1, NULL, 'A' },
1307 { "user", 1, NULL, 'u' },
1308 { "group", 1, NULL, 'G' },
1309 { "logfile", 1, NULL, 'L' },
1310 { "shrink-urls", 0, NULL, 's' },
1311 { "help", 0, NULL, 'h' },
1312 { "bash", 0, NULL, 'b' },
1313 { "dry-run", 0, NULL, 'n' },
1314 { "page", 1, NULL, 'g' },
1315 { "version", 0, NULL, 'v' },
1316 { "config", 1, NULL, 'c' },
1317 { "replyto", 1, NULL, 'r' },
1320 struct session *session;
1323 static char password[80];
1333 session = session_alloc();
1335 fprintf(stderr, "no more memory...\n");
1339 /* get the current time so that we can log it later */
1341 session->time = strdup(ctime(&t));
1342 session->time[strlen(session->time)-1] = 0x00;
1344 /* Get the home directory so we can try to find a config file */
1345 session->homedir = strdup(getenv("HOME"));
1347 /* set up a default config file location (traditionally ~/.bti) */
1348 session->configfile = zalloc(strlen(session->homedir) + 7);
1349 sprintf(session->configfile, "%s/.bti", session->homedir);
1351 /* Set environment variables first, before reading command line options
1352 * or config file values. */
1353 http_proxy = getenv("http_proxy");
1356 free(session->proxy);
1357 session->proxy = strdup(http_proxy);
1358 dbg("http_proxy = %s\n", session->proxy);
1361 parse_configfile(session);
1364 option = getopt_long_only(argc, argv,
1365 "dp:P:H:a:A:u:c:hg:G:sr:nVv",
1377 if (session->account)
1378 free(session->account);
1379 session->account = strdup(optarg);
1380 dbg("account = %s\n", session->account);
1383 page_nr = atoi(optarg);
1384 dbg("page = %d\n", page_nr);
1385 session->page = page_nr;
1388 session->replyto = strdup(optarg);
1389 dbg("in_reply_to_status_id = %s\n", session->replyto);
1392 if (session->password)
1393 free(session->password);
1394 session->password = strdup(optarg);
1395 dbg("password = %s\n", session->password);
1399 free(session->proxy);
1400 session->proxy = strdup(optarg);
1401 dbg("proxy = %s\n", session->proxy);
1404 if (strcasecmp(optarg, "update") == 0)
1405 session->action = ACTION_UPDATE;
1406 else if (strcasecmp(optarg, "friends") == 0)
1407 session->action = ACTION_FRIENDS;
1408 else if (strcasecmp(optarg, "user") == 0)
1409 session->action = ACTION_USER;
1410 else if (strcasecmp(optarg, "replies") == 0)
1411 session->action = ACTION_REPLIES;
1412 else if (strcasecmp(optarg, "public") == 0)
1413 session->action = ACTION_PUBLIC;
1414 else if (strcasecmp(optarg, "group") == 0)
1415 session->action = ACTION_GROUP;
1417 session->action = ACTION_UNKNOWN;
1418 dbg("action = %d\n", session->action);
1422 free(session->user);
1423 session->user = strdup(optarg);
1424 dbg("user = %s\n", session->user);
1429 free(session->group);
1430 session->group = strdup(optarg);
1431 dbg("group = %s\n", session->group);
1434 if (session->logfile)
1435 free(session->logfile);
1436 session->logfile = strdup(optarg);
1437 dbg("logfile = %s\n", session->logfile);
1440 session->shrink_urls = 1;
1443 if (session->hosturl)
1444 free(session->hosturl);
1445 if (session->hostname)
1446 free(session->hostname);
1447 if (strcasecmp(optarg, "twitter") == 0) {
1448 session->host = HOST_TWITTER;
1449 session->hosturl = strdup(twitter_host);
1450 session->hostname = strdup(twitter_name);
1451 } else if (strcasecmp(optarg, "identica") == 0) {
1452 session->host = HOST_IDENTICA;
1453 session->hosturl = strdup(identica_host);
1454 session->hostname = strdup(identica_name);
1456 session->host = HOST_CUSTOM;
1457 session->hosturl = strdup(optarg);
1458 session->hostname = strdup(optarg);
1460 dbg("host = %d\n", session->host);
1466 if (session->configfile)
1467 free(session->configfile);
1468 session->configfile = strdup(optarg);
1469 dbg("configfile = %s\n", session->configfile);
1472 * read the config file now. Yes, this could override
1473 * previously set options from the command line, but
1474 * the user asked for it...
1476 parse_configfile(session);
1482 session->dry_run = 1;
1493 session_readline_init(session);
1495 * Show the version to make it easier to determine what
1501 if (session->host == HOST_TWITTER) {
1502 if (!session->consumer_key || !session->consumer_secret) {
1503 fprintf(stderr, "Twitter no longer supuports HTTP basic authentication.\n");
1504 fprintf(stderr, "Both consumer key, and consumer secret are required");
1505 fprintf(stderr, " for bti in order to behave as an OAuth consumer.\n");
1508 if (session->action == ACTION_GROUP) {
1509 fprintf(stderr, "Groups only work in Identi.ca.\n");
1513 if (!session->consumer_key || !session->consumer_secret)
1514 session->no_oauth = 1;
1517 if (session->no_oauth) {
1518 if (!session->account) {
1519 fprintf(stdout, "Enter account for %s: ",
1521 session->account = session->readline(NULL);
1523 if (!session->password) {
1524 read_password(password, sizeof(password),
1526 session->password = strdup(password);
1529 if (!session->access_token_key ||
1530 !session->access_token_secret) {
1531 request_access_token(session);
1536 if (session->action == ACTION_UNKNOWN) {
1537 fprintf(stderr, "Unknown action, valid actions are:\n");
1538 fprintf(stderr, "'update', 'friends', 'public', "
1539 "'replies', 'group' or 'user'.\n");
1543 if (session->action == ACTION_GROUP && !session->group) {
1544 fprintf(stdout, "Enter group name: ");
1545 session->group = session->readline(NULL);
1548 if (session->action == ACTION_UPDATE) {
1549 if (session->bash || !session->interactive)
1550 tweet = get_string_from_stdin();
1552 tweet = session->readline("tweet: ");
1553 if (!tweet || strlen(tweet) == 0) {
1558 if (session->shrink_urls)
1559 tweet = shrink_urls(tweet);
1561 session->tweet = zalloc(strlen(tweet) + 10);
1563 sprintf(session->tweet, "%c %s",
1564 getuid() ? '$' : '#', tweet);
1566 sprintf(session->tweet, "%s", tweet);
1569 dbg("tweet = %s\n", session->tweet);
1572 if (session->page == 0)
1574 dbg("config file = %s\n", session->configfile);
1575 dbg("host = %d\n", session->host);
1576 dbg("action = %d\n", session->action);
1578 /* fork ourself so that the main shell can get on
1579 * with it's life as we try to connect and handle everything
1581 if (session->bash) {
1584 dbg("child is %d\n", child);
1589 retval = send_request(session);
1590 if (retval && !session->bash)
1591 fprintf(stderr, "operation failed\n");
1593 log_session(session, retval);
1595 session_readline_cleanup(session);
1596 session_free(session);