]> ToastFreeware Gitweb - gregoa/bti.git/blob - bti.c
e2b57c050b478a24c5a4782b4608382ae2606202
[gregoa/bti.git] / bti.c
1 /*
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>
5  *
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.
9  *
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.
14  *
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.
18  */
19
20 #define _GNU_SOURCE
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stddef.h>
25 #include <string.h>
26 #include <getopt.h>
27 #include <errno.h>
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <time.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <curl/curl.h>
36 #include <libxml/xmlmemory.h>
37 #include <libxml/parser.h>
38 #include <libxml/tree.h>
39 #include <pcre.h>
40 #include <termios.h>
41 #include <dlfcn.h>
42 #include <oauth.h>
43
44
45 #define zalloc(size)    calloc(size, 1)
46
47 #define dbg(format, arg...)                                             \
48         do {                                                            \
49                 if (debug)                                              \
50                         fprintf(stdout, "bti: %s: " format , __func__ , \
51                                 ## arg);                                \
52         } while (0)
53
54
55 static int debug;
56 static int verbose;
57
58 enum host {
59         HOST_TWITTER  = 0,
60         HOST_IDENTICA = 1,
61         HOST_CUSTOM   = 2
62 };
63
64 enum action {
65         ACTION_UPDATE  = 0,
66         ACTION_FRIENDS = 1,
67         ACTION_USER    = 2,
68         ACTION_REPLIES = 4,
69         ACTION_PUBLIC  = 8,
70         ACTION_GROUP   = 16,
71         ACTION_UNKNOWN = 32
72 };
73
74 struct session {
75         char *password;
76         char *account;
77         char *consumer_key;
78         char *consumer_secret;
79         char *access_token_key;
80         char *access_token_secret;
81         char *tweet;
82         char *proxy;
83         char *time;
84         char *homedir;
85         char *logfile;
86         char *user;
87         char *group;
88         char *hosturl;
89         char *hostname;
90         char *configfile;
91         int bash;
92         int interactive;
93         int shrink_urls;
94         int dry_run;
95         int page;
96         int no_oauth;
97         enum host host;
98         enum action action;
99         void *readline_handle;
100         char *(*readline)(const char *);
101 };
102
103 struct bti_curl_buffer {
104         char *data;
105         enum action action;
106         int length;
107 };
108
109 static void display_help(void)
110 {
111         fprintf(stdout, "bti - send tweet to twitter or identi.ca\n");
112         fprintf(stdout, "Version: " VERSION "\n");
113         fprintf(stdout, "Usage:\n");
114         fprintf(stdout, "  bti [options]\n");
115         fprintf(stdout, "options are:\n");
116         fprintf(stdout, "  --account accountname\n");
117         fprintf(stdout, "  --password password\n");
118         fprintf(stdout, "  --action action\n");
119         fprintf(stdout, "    ('update', 'friends', 'public', 'replies', "
120                 "'group' or 'user')\n");
121         fprintf(stdout, "  --user screenname\n");
122         fprintf(stdout, "  --group groupname\n");
123         fprintf(stdout, "  --proxy PROXY:PORT\n");
124         fprintf(stdout, "  --host HOST\n");
125         fprintf(stdout, "  --logfile logfile\n");
126         fprintf(stdout, "  --config configfile\n");
127         fprintf(stdout, "  --shrink-urls\n");
128         fprintf(stdout, "  --page PAGENUMBER\n");
129         fprintf(stdout, "  --bash\n");
130         fprintf(stdout, "  --debug\n");
131         fprintf(stdout, "  --verbose\n");
132         fprintf(stdout, "  --dry-run\n");
133         fprintf(stdout, "  --version\n");
134         fprintf(stdout, "  --help\n");
135 }
136
137 static void display_version(void)
138 {
139         fprintf(stdout, "bti - version %s\n", VERSION);
140 }
141
142 static char *get_string(const char *name)
143 {
144         char *temp;
145         char *string;
146
147         string = zalloc(1000);
148         if (!string)
149                 exit(1);
150         if (name != NULL)
151                 fprintf(stdout, "%s", name);
152         if (!fgets(string, 999, stdin))
153                 return NULL;
154         temp = strchr(string, '\n');
155         if (temp)
156                 *temp = '\0';
157         return string;
158 }
159
160 /*
161  * Try to get a handle to a readline function from a variety of different
162  * libraries.  If nothing is present on the system, then fall back to an
163  * internal one.
164  *
165  * Logic originally based off of code in the e2fsutils package in the
166  * lib/ss/get_readline.c file, which is licensed under the MIT license.
167  *
168  * This keeps us from having to relicense the bti codebase if readline
169  * ever changes its license, as there is no link-time dependancy.
170  * It is a run-time thing only, and we handle any readline-like library
171  * in the same manner, making bti not be a derivative work of any
172  * other program.
173  */
174 static void session_readline_init(struct session *session)
175 {
176         /* Libraries we will try to use for readline/editline functionality */
177         const char *libpath = "libreadline.so.6:libreadline.so.5:"
178                                 "libreadline.so.4:libreadline.so:libedit.so.2:"
179                                 "libedit.so:libeditline.so.0:libeditline.so";
180         void *handle = NULL;
181         char *tmp, *cp, *next;
182         int (*bind_key)(int, void *);
183         void (*insert)(void);
184
185         /* default to internal function if we can't or won't find anything */
186         session->readline = get_string;
187         if (!isatty(0))
188                 return;
189         session->interactive = 1;
190
191         tmp = malloc(strlen(libpath)+1);
192         if (!tmp)
193                 return;
194         strcpy(tmp, libpath);
195         for (cp = tmp; cp; cp = next) {
196                 next = strchr(cp, ':');
197                 if (next)
198                         *next++ = 0;
199                 if (*cp == 0)
200                         continue;
201                 handle = dlopen(cp, RTLD_NOW);
202                 if (handle) {
203                         dbg("Using %s for readline library\n", cp);
204                         break;
205                 }
206         }
207         free(tmp);
208         if (!handle) {
209                 dbg("No readline library found.\n");
210                 return;
211         }
212
213         session->readline_handle = handle;
214         session->readline = (char *(*)(const char *))dlsym(handle, "readline");
215         if (session->readline == NULL) {
216                 /* something odd happened, default back to internal stuff */
217                 session->readline_handle = NULL;
218                 session->readline = get_string;
219                 return;
220         }
221
222         /*
223          * If we found a library, turn off filename expansion
224          * as that makes no sense from within bti.
225          */
226         bind_key = (int (*)(int, void *))dlsym(handle, "rl_bind_key");
227         insert = (void (*)(void))dlsym(handle, "rl_insert");
228         if (bind_key && insert)
229                 bind_key('\t', insert);
230 }
231
232 static void session_readline_cleanup(struct session *session)
233 {
234         if (session->readline_handle)
235                 dlclose(session->readline_handle);
236 }
237
238 static struct session *session_alloc(void)
239 {
240         struct session *session;
241
242         session = zalloc(sizeof(*session));
243         if (!session)
244                 return NULL;
245         return session;
246 }
247
248 static void session_free(struct session *session)
249 {
250         if (!session)
251                 return;
252         free(session->password);
253         free(session->account);
254         free(session->consumer_key);
255         free(session->consumer_secret);
256         free(session->access_token_key);
257         free(session->access_token_secret);
258         free(session->tweet);
259         free(session->proxy);
260         free(session->time);
261         free(session->homedir);
262         free(session->user);
263         free(session->group);
264         free(session->hosturl);
265         free(session->hostname);
266         free(session->configfile);
267         free(session);
268 }
269
270 static struct bti_curl_buffer *bti_curl_buffer_alloc(enum action action)
271 {
272         struct bti_curl_buffer *buffer;
273
274         buffer = zalloc(sizeof(*buffer));
275         if (!buffer)
276                 return NULL;
277
278         /* start out with a data buffer of 1 byte to
279          * make the buffer fill logic simpler */
280         buffer->data = zalloc(1);
281         if (!buffer->data) {
282                 free(buffer);
283                 return NULL;
284         }
285         buffer->length = 0;
286         buffer->action = action;
287         return buffer;
288 }
289
290 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
291 {
292         if (!buffer)
293                 return;
294         free(buffer->data);
295         free(buffer);
296 }
297
298 static const char *twitter_host  = "http://api.twitter.com/1/statuses";
299 static const char *identica_host = "https://identi.ca/api/statuses";
300 static const char *twitter_name  = "twitter";
301 static const char *identica_name = "identi.ca";
302
303 static const char *twitter_request_token_uri  = "http://twitter.com/oauth/request_token";
304 static const char *twitter_access_token_uri   = "http://twitter.com/oauth/access_token";
305 static const char *twitter_authorize_uri      = "http://twitter.com/oauth/authorize?oauth_token=";
306 static const char *identica_request_token_uri = "http://identi.ca/api/oauth/request_token";
307 static const char *identica_access_token_uri  = "http://identi.ca/api/oauth/access_token";
308 static const char *identica_authorize_uri     = "http://identi.ca/api/oauth/authorize?oauth_token=";
309
310 static const char *user_uri    = "/user_timeline/";
311 static const char *update_uri  = "/update.xml";
312 static const char *public_uri  = "/public_timeline.xml";
313 static const char *friends_uri = "/friends_timeline.xml";
314 static const char *mentions_uri = "/mentions.xml";
315 static const char *replies_uri = "/replies.xml";
316 static const char *group_uri = "/../statusnet/groups/timeline/";
317
318 static CURL *curl_init(void)
319 {
320         CURL *curl;
321
322         curl = curl_easy_init();
323         if (!curl) {
324                 fprintf(stderr, "Can not init CURL!\n");
325                 return NULL;
326         }
327         /* some ssl sanity checks on the connection we are making */
328         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
329         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
330         return curl;
331 }
332
333 static void parse_statuses(xmlDocPtr doc, xmlNodePtr current)
334 {
335         xmlChar *text = NULL;
336         xmlChar *user = NULL;
337         xmlChar *created = NULL;
338         xmlNodePtr userinfo;
339
340         current = current->xmlChildrenNode;
341         while (current != NULL) {
342                 if (current->type == XML_ELEMENT_NODE) {
343                         if (!xmlStrcmp(current->name, (const xmlChar *)"created_at"))
344                                 created = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
345                         if (!xmlStrcmp(current->name, (const xmlChar *)"text"))
346                                 text = xmlNodeListGetString(doc, current->xmlChildrenNode, 1);
347                         if (!xmlStrcmp(current->name, (const xmlChar *)"user")) {
348                                 userinfo = current->xmlChildrenNode;
349                                 while (userinfo != NULL) {
350                                         if ((!xmlStrcmp(userinfo->name, (const xmlChar *)"screen_name"))) {
351                                                 if (user)
352                                                         xmlFree(user);
353                                                 user = xmlNodeListGetString(doc, userinfo->xmlChildrenNode, 1);
354                                         }
355                                         userinfo = userinfo->next;
356                                 }
357                         }
358
359                         if (user && text && created) {
360                                 if (verbose)
361                                         printf("[%s] (%.16s) %s\n",
362                                                 user, created, text);
363                                 else
364                                         printf("[%s] %s\n",
365                                                 user, text);
366                                 xmlFree(user);
367                                 xmlFree(text);
368                                 xmlFree(created);
369                                 user = NULL;
370                                 text = NULL;
371                                 created = NULL;
372                         }
373                 }
374                 current = current->next;
375         }
376
377         return;
378 }
379
380 static void parse_timeline(char *document)
381 {
382         xmlDocPtr doc;
383         xmlNodePtr current;
384
385         doc = xmlReadMemory(document, strlen(document), "timeline.xml",
386                             NULL, XML_PARSE_NOERROR);
387         if (doc == NULL)
388                 return;
389
390         current = xmlDocGetRootElement(doc);
391         if (current == NULL) {
392                 fprintf(stderr, "empty document\n");
393                 xmlFreeDoc(doc);
394                 return;
395         }
396
397         if (xmlStrcmp(current->name, (const xmlChar *) "statuses")) {
398                 fprintf(stderr, "unexpected document type\n");
399                 xmlFreeDoc(doc);
400                 return;
401         }
402
403         current = current->xmlChildrenNode;
404         while (current != NULL) {
405                 if ((!xmlStrcmp(current->name, (const xmlChar *)"status")))
406                         parse_statuses(doc, current);
407                 current = current->next;
408         }
409         xmlFreeDoc(doc);
410
411         return;
412 }
413
414 static size_t curl_callback(void *buffer, size_t size, size_t nmemb,
415                             void *userp)
416 {
417         struct bti_curl_buffer *curl_buf = userp;
418         size_t buffer_size = size * nmemb;
419         char *temp;
420
421         if ((!buffer) || (!buffer_size) || (!curl_buf))
422                 return -EINVAL;
423
424         /* add to the data we already have */
425         temp = zalloc(curl_buf->length + buffer_size + 1);
426         if (!temp)
427                 return -ENOMEM;
428
429         memcpy(temp, curl_buf->data, curl_buf->length);
430         free(curl_buf->data);
431         curl_buf->data = temp;
432         memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
433         curl_buf->length += buffer_size;
434         if (curl_buf->action)
435                 parse_timeline(curl_buf->data);
436
437         dbg("%s\n", curl_buf->data);
438
439         return buffer_size;
440 }
441
442 static int parse_osp_reply(const char *reply, char **token, char **secret)
443 {
444         int rc;
445         int retval = 1;
446         char **rv = NULL;
447         rc = oauth_split_url_parameters(reply, &rv);
448         qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
449         if (rc == 2 || rc == 4) {
450                 if (!strncmp(rv[0],"oauth_token=",11) && !strncmp(rv[1],"oauth_token_secret=",18)) {
451                         if (token)
452                                 *token =strdup(&(rv[0][12]));
453                         if (secret)
454                                 *secret=strdup(&(rv[1][19]));
455
456                         retval = 0;
457                 }
458         } else if (rc == 3) {
459                 if (!strncmp(rv[1],"oauth_token=",11) && !strncmp(rv[2],"oauth_token_secret=",18)) {
460                         if (token)
461                                 *token =strdup(&(rv[1][12]));
462                         if (secret)
463                                 *secret=strdup(&(rv[2][19]));
464
465                         retval = 0;
466                 }
467         }
468
469         dbg("token: %s\n", *token);
470         dbg("secret: %s\n", *secret);
471
472         if (rv)
473                 free(rv);
474
475         return retval;
476 }
477         
478
479 static int request_access_token(struct session *session)
480 {
481         char *post_params = NULL;
482         char *request_url = NULL;
483         char *reply    = NULL;
484         char *at_key      = NULL;
485         char *at_secret   = NULL;
486         char *verifier    = NULL;
487         char at_uri[90];
488
489         if (!session)
490                 return -EINVAL;
491
492         if (session->host == HOST_TWITTER)
493                 request_url = oauth_sign_url2(
494                                 twitter_request_token_uri, NULL,
495                                 OA_HMAC, NULL, session->consumer_key,
496                                 session->consumer_secret, NULL, NULL);
497         else if (session->host == HOST_IDENTICA)
498                 request_url = oauth_sign_url2(
499                                 identica_request_token_uri, NULL,
500                                 OA_HMAC, NULL, session->consumer_key,
501                                 session->consumer_secret, NULL, NULL);
502         reply = oauth_http_get(request_url, post_params);
503
504         if (request_url)
505                 free(request_url);
506
507         if (post_params)
508                 free(post_params);
509
510         if (!reply)
511                 return 1;
512
513         if (parse_osp_reply(reply, &at_key, &at_secret))
514                 return 1;
515
516         free(reply);
517
518         fprintf(stdout, "Please open the following link in your browser, and ");
519         fprintf(stdout, "allow 'bti' to access your account. Then paste ");
520         fprintf(stdout, "back the provided PIN in here.\n");
521         if (session->host == HOST_TWITTER) {
522                 fprintf(stdout, "%s%s\nPIN: ", twitter_authorize_uri, at_key);
523                 verifier = session->readline(NULL);
524                 sprintf(at_uri, "%s?oauth_verifier=%s", twitter_access_token_uri, verifier);
525         } else if (session->host == HOST_IDENTICA) {
526                 fprintf(stdout, "%s%s\nPIN: ", identica_authorize_uri, at_key);
527                 verifier = session->readline(NULL);
528                 sprintf(at_uri, "%s?oauth_verifier=%s", identica_access_token_uri, verifier);
529         }
530         request_url = oauth_sign_url2(at_uri, NULL, OA_HMAC, NULL,
531                         session->consumer_key, session->consumer_secret, at_key,
532                         at_secret);
533         reply = oauth_http_get(request_url, post_params);
534
535         if (!reply)
536                 return 1;
537
538         if (parse_osp_reply(reply, &at_key, &at_secret))
539                 return 1;
540
541         free(reply);
542
543         fprintf(stdout, "Please put these two lines in your bti configuration ");
544         fprintf(stdout, "file (~/.bti):\n");
545         fprintf(stdout, "access_token_key=%s\n", at_key);
546         fprintf(stdout, "access_token_secret=%s\n", at_secret);
547
548         return 0;
549 }
550
551 static int send_request(struct session *session)
552 {
553         char endpoint[500];
554         char user_password[500];
555         char data[500];
556         struct bti_curl_buffer *curl_buf;
557         CURL *curl = NULL;
558         CURLcode res;
559         struct curl_httppost *formpost = NULL;
560         struct curl_httppost *lastptr = NULL;
561         struct curl_slist *slist = NULL;
562         char *req_url = NULL;
563         char *reply = NULL;
564         char *postarg = NULL;
565         int is_post = 0;
566
567         if (!session)
568                 return -EINVAL;
569
570         if (!session->hosturl)
571                 session->hosturl = strdup(twitter_host);
572
573         if (session->no_oauth) {
574                 curl_buf = bti_curl_buffer_alloc(session->action);
575                 if (!curl_buf)
576                         return -ENOMEM;
577
578                 curl = curl_init();
579                 if (!curl)
580                         return -EINVAL;
581
582                 if (!session->hosturl)
583                         session->hosturl = strdup(twitter_host);
584
585                 switch (session->action) {
586                         case ACTION_UPDATE:
587                                 snprintf(user_password, sizeof(user_password), "%s:%s",
588                                                 session->account, session->password);
589                                 snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
590                                 curl_formadd(&formpost, &lastptr,
591                                                 CURLFORM_COPYNAME, "status",
592                                                 CURLFORM_COPYCONTENTS, session->tweet,
593                                                 CURLFORM_END);
594
595                                 curl_formadd(&formpost, &lastptr,
596                                                 CURLFORM_COPYNAME, "source",
597                                                 CURLFORM_COPYCONTENTS, "bti",
598                                                 CURLFORM_END);
599
600                                 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
601                                 slist = curl_slist_append(slist, "Expect:");
602                                 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
603
604                                 sprintf(endpoint, "%s%s", session->hosturl, update_uri);
605                                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
606                                 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
607
608                                 break;
609                         case ACTION_FRIENDS:
610                                 snprintf(user_password, sizeof(user_password), "%s:%s",
611                                                 session->account, session->password);
612                                 sprintf(endpoint, "%s%s?page=%d", session->hosturl,
613                                                 friends_uri, session->page);
614                                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
615                                 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
616
617                                 break;
618                         case ACTION_USER:
619                                 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
620                                                 user_uri, session->user, session->page);
621                                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
622
623                                 break;
624                         case ACTION_REPLIES:
625                                 snprintf(user_password, sizeof(user_password), "%s:%s",
626                                                 session->account, session->password);
627                                 sprintf(endpoint, "%s%s?page=%d", session->hosturl, replies_uri,
628                                                 session->page);
629                                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
630                                 curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
631
632                                 break;
633                         case ACTION_PUBLIC:
634                                 sprintf(endpoint, "%s%s?page=%d", session->hosturl, public_uri,
635                                                 session->page);
636                                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
637
638                                 break;
639                         case ACTION_GROUP:
640                                 sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
641                                                 group_uri, session->group, session->page);
642                                 curl_easy_setopt(curl, CURLOPT_URL, endpoint);
643
644                                 break;
645                         default:
646                                 break;
647                 }
648
649                 if (session->proxy)
650                         curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
651
652                 if (debug)
653                         curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
654
655                 dbg("user_password = %s\n", user_password);
656                 dbg("data = %s\n", data);
657                 dbg("proxy = %s\n", session->proxy);
658
659                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
660                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
661                 if (!session->dry_run) {
662                         res = curl_easy_perform(curl);
663                         if (res && !session->bash) {
664                                 fprintf(stderr, "error(%d) trying to perform "
665                                                 "operation\n", res);
666                                 return -EINVAL;
667                         }
668                 }
669
670                 curl_easy_cleanup(curl);
671                 if (session->action == ACTION_UPDATE)
672                         curl_formfree(formpost);
673                 bti_curl_buffer_free(curl_buf);
674         } else {
675                 switch (session->action) {
676                         case ACTION_UPDATE:
677                                 sprintf(endpoint,
678                                                 "%s%s?status=%s",
679                                                 session->hosturl, update_uri, session->tweet);
680                                 is_post = 1;
681                                 break;
682                         case ACTION_USER:
683                                 sprintf(endpoint, "%s%s%s.xml?page=%d",
684                                                 session->hosturl, user_uri,
685                                                 session->user, session->page);
686                                 break;
687                         case ACTION_REPLIES:
688                                 sprintf(endpoint, "%s%s?page=%d",
689                                                 session->hosturl, mentions_uri, session->page);
690                                 break;
691                         case ACTION_PUBLIC:
692                                 sprintf(endpoint, "%s%s?page=%d",
693                                                 session->hosturl, public_uri, session->page);
694                                 break;
695                         case ACTION_GROUP:
696                                 sprintf(endpoint, "%s%s%s.xml?page=%d",
697                                                 session->hosturl, group_uri,
698                                                 session->group, session->page);
699                                 break;
700                         case ACTION_FRIENDS:
701                                 sprintf(endpoint, "%s%s?page=%d",
702                                                 session->hosturl, friends_uri, session->page);
703                                 break;
704                         default:
705                                 break;
706                 }
707
708                 if (is_post) {
709                         req_url = oauth_sign_url2(
710                                         endpoint, &postarg, OA_HMAC, NULL,
711                                         session->consumer_key, session->consumer_secret,
712                                         session->access_token_key, session->access_token_secret
713                                         );
714                         reply = oauth_http_post(req_url, postarg);
715                 } else {
716                         req_url = oauth_sign_url2(
717                                         endpoint, NULL, OA_HMAC, NULL,
718                                         session->consumer_key, session->consumer_secret,
719                                         session->access_token_key, session->access_token_secret
720                                         );
721                         reply = oauth_http_get(req_url, postarg);
722                 }
723
724                 dbg("%s\n", req_url);
725                 dbg("%s\n", reply);
726                 if (req_url)
727                         free(req_url);
728
729                 if (session->action != ACTION_UPDATE)
730                         parse_timeline(reply);
731         }
732         return 0;
733 }
734
735 static void parse_configfile(struct session *session)
736 {
737         FILE *config_file;
738         char *line = NULL;
739         size_t len = 0;
740         char *account = NULL;
741         char *password = NULL;
742         char *consumer_key = NULL;
743         char *consumer_secret = NULL;
744         char *access_token_key = NULL;
745         char *access_token_secret = NULL;
746         char *host = NULL;
747         char *proxy = NULL;
748         char *logfile = NULL;
749         char *action = NULL;
750         char *user = NULL;
751         int shrink_urls = 0;
752
753         config_file = fopen(session->configfile, "r");
754
755         /* No error if file does not exist or is unreadable.  */
756         if (config_file == NULL)
757                 return;
758
759         do {
760                 ssize_t n = getline(&line, &len, config_file);
761                 if (n < 0)
762                         break;
763                 if (line[n - 1] == '\n')
764                         line[n - 1] = '\0';
765                 /* Parse file.  Format is the usual value pairs:
766                    account=name
767                    passwort=value
768                    # is a comment character
769                 */
770                 *strchrnul(line, '#') = '\0';
771                 char *c = line;
772                 while (isspace(*c))
773                         c++;
774                 /* Ignore blank lines.  */
775                 if (c[0] == '\0')
776                         continue;
777
778                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
779                         c += 8;
780                         if (c[0] != '\0')
781                                 account = strdup(c);
782                 } else if (!strncasecmp(c, "password", 8) &&
783                            (c[8] == '=')) {
784                         c += 9;
785                         if (c[0] != '\0')
786                                 password = strdup(c);
787                 } else if (!strncasecmp(c, "consumer_key", 12) &&
788                            (c[12] == '=')) {
789                         c += 13;
790                         if (c[0] != '\0')
791                                 consumer_key = strdup(c);
792                 } else if (!strncasecmp(c, "consumer_secret", 15) &&
793                            (c[15] == '=')) {
794                         c += 16;
795                         if (c[0] != '\0')
796                                 consumer_secret = strdup(c);
797                 } else if (!strncasecmp(c, "access_token_key", 16) &&
798                            (c[16] == '=')) {
799                         c += 17;
800                         if (c[0] != '\0')
801                                 access_token_key = strdup(c);
802                 } else if (!strncasecmp(c, "access_token_secret", 19) &&
803                            (c[19] == '=')) {
804                         c += 20;
805                         if (c[0] != '\0')
806                                 access_token_secret = strdup(c);
807                 } else if (!strncasecmp(c, "host", 4) &&
808                            (c[4] == '=')) {
809                         c += 5;
810                         if (c[0] != '\0')
811                                 host = strdup(c);
812                 } else if (!strncasecmp(c, "proxy", 5) &&
813                            (c[5] == '=')) {
814                         c += 6;
815                         if (c[0] != '\0')
816                                 proxy = strdup(c);
817                 } else if (!strncasecmp(c, "logfile", 7) &&
818                            (c[7] == '=')) {
819                         c += 8;
820                         if (c[0] != '\0')
821                                 logfile = strdup(c);
822                 } else if (!strncasecmp(c, "action", 6) &&
823                            (c[6] == '=')) {
824                         c += 7;
825                         if (c[0] != '\0')
826                                 action = strdup(c);
827                 } else if (!strncasecmp(c, "user", 4) &&
828                                 (c[4] == '=')) {
829                         c += 5;
830                         if (c[0] != '\0')
831                                 user = strdup(c);
832                 } else if (!strncasecmp(c, "shrink-urls", 11) &&
833                                 (c[11] == '=')) {
834                         c += 12;
835                         if (!strncasecmp(c, "true", 4) ||
836                                         !strncasecmp(c, "yes", 3))
837                                 shrink_urls = 1;
838                 } else if (!strncasecmp(c, "verbose", 7) &&
839                                 (c[7] == '=')) {
840                         c += 8;
841                         if (!strncasecmp(c, "true", 4) ||
842                                         !strncasecmp(c, "yes", 3))
843                                 verbose = 1;
844                 }
845         } while (!feof(config_file));
846
847         if (password)
848                 session->password = password;
849         if (account)
850                 session->account = account;
851         if (consumer_key)
852                 session->consumer_key = consumer_key;
853         if (consumer_secret)
854                 session->consumer_secret = consumer_secret;
855         if (access_token_key)
856                 session->access_token_key = access_token_key;
857         if (access_token_secret)
858                 session->access_token_secret = access_token_secret;
859         if (host) {
860                 if (strcasecmp(host, "twitter") == 0) {
861                         session->host = HOST_TWITTER;
862                         session->hosturl = strdup(twitter_host);
863                         session->hostname = strdup(twitter_name);
864                 } else if (strcasecmp(host, "identica") == 0) {
865                         session->host = HOST_IDENTICA;
866                         session->hosturl = strdup(identica_host);
867                         session->hostname = strdup(identica_name);
868                 } else {
869                         session->host = HOST_CUSTOM;
870                         session->hosturl = strdup(host);
871                         session->hostname = strdup(host);
872                 }
873                 free(host);
874         }
875         if (proxy) {
876                 if (session->proxy)
877                         free(session->proxy);
878                 session->proxy = proxy;
879         }
880         if (logfile)
881                 session->logfile = logfile;
882         if (action) {
883                 if (strcasecmp(action, "update") == 0)
884                         session->action = ACTION_UPDATE;
885                 else if (strcasecmp(action, "friends") == 0)
886                         session->action = ACTION_FRIENDS;
887                 else if (strcasecmp(action, "user") == 0)
888                         session->action = ACTION_USER;
889                 else if (strcasecmp(action, "replies") == 0)
890                         session->action = ACTION_REPLIES;
891                 else if (strcasecmp(action, "public") == 0)
892                         session->action = ACTION_PUBLIC;
893                 else if (strcasecmp(action, "group") == 0)
894                         session->action = ACTION_GROUP;
895                 else
896                         session->action = ACTION_UNKNOWN;
897                 free(action);
898         }
899         if (user)
900                 session->user = user;
901         session->shrink_urls = shrink_urls;
902
903         /* Free buffer and close file.  */
904         free(line);
905         fclose(config_file);
906 }
907
908 static void log_session(struct session *session, int retval)
909 {
910         FILE *log_file;
911         char *filename;
912
913         /* Only log something if we have a log file set */
914         if (!session->logfile)
915                 return;
916
917         filename = alloca(strlen(session->homedir) +
918                           strlen(session->logfile) + 3);
919
920         sprintf(filename, "%s/%s", session->homedir, session->logfile);
921
922         log_file = fopen(filename, "a+");
923         if (log_file == NULL)
924                 return;
925
926         switch (session->action) {
927         case ACTION_UPDATE:
928                 if (retval)
929                         fprintf(log_file, "%s: host=%s tweet failed\n",
930                                 session->time, session->hostname);
931                 else
932                         fprintf(log_file, "%s: host=%s tweet=%s\n",
933                                 session->time, session->hostname,
934                                 session->tweet);
935                 break;
936         case ACTION_FRIENDS:
937                 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
938                         session->time, session->hostname);
939                 break;
940         case ACTION_USER:
941                 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
942                         session->time, session->hostname, session->user);
943                 break;
944         case ACTION_REPLIES:
945                 fprintf(log_file, "%s: host=%s retrieving replies\n",
946                         session->time, session->hostname);
947                 break;
948         case ACTION_PUBLIC:
949                 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
950                         session->time, session->hostname);
951                 break;
952         case ACTION_GROUP:
953                 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
954                         session->time, session->hostname);
955                 break;
956         default:
957                 break;
958         }
959
960         fclose(log_file);
961 }
962
963 static char *get_string_from_stdin(void)
964 {
965         char *temp;
966         char *string;
967
968         string = zalloc(1000);
969         if (!string)
970                 return NULL;
971
972         if (!fgets(string, 999, stdin))
973                 return NULL;
974         temp = strchr(string, '\n');
975         if (temp)
976                 *temp = '\0';
977         return string;
978 }
979
980 static void read_password(char *buf, size_t len, char *host)
981 {
982         char pwd[80];
983         int retval;
984         struct termios old;
985         struct termios tp;
986
987         tcgetattr(0, &tp);
988         old = tp;
989
990         tp.c_lflag &= (~ECHO);
991         tcsetattr(0, TCSANOW, &tp);
992
993         fprintf(stdout, "Enter password for %s: ", host);
994         fflush(stdout);
995         tcflow(0, TCOOFF);
996         retval = scanf("%79s", pwd);
997         tcflow(0, TCOON);
998         fprintf(stdout, "\n");
999
1000         tcsetattr(0, TCSANOW, &old);
1001
1002         strncpy(buf, pwd, len);
1003         buf[len-1] = '\0';
1004 }
1005
1006 static int find_urls(const char *tweet, int **pranges)
1007 {
1008         /*
1009          * magic obtained from
1010          * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
1011          */
1012         static const char *re_magic =
1013                 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
1014                 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
1015                 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
1016         pcre *re;
1017         const char *errptr;
1018         int erroffset;
1019         int ovector[10] = {0,};
1020         const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
1021         int startoffset, tweetlen;
1022         int i, rc;
1023         int rbound = 10;
1024         int rcount = 0;
1025         int *ranges = malloc(sizeof(int) * rbound);
1026
1027         re = pcre_compile(re_magic,
1028                         PCRE_NO_AUTO_CAPTURE,
1029                         &errptr, &erroffset, NULL);
1030         if (!re) {
1031                 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
1032                 exit(1);
1033         }
1034
1035         tweetlen = strlen(tweet);
1036         for (startoffset = 0; startoffset < tweetlen; ) {
1037
1038                 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
1039                                 ovector, ovsize);
1040                 if (rc == PCRE_ERROR_NOMATCH)
1041                         break;
1042
1043                 if (rc < 0) {
1044                         fprintf(stderr, "pcre_exec @%u: %s\n",
1045                                 erroffset, errptr);
1046                         exit(1);
1047                 }
1048
1049                 for (i = 0; i < rc; i += 2) {
1050                         if ((rcount+2) == rbound) {
1051                                 rbound *= 2;
1052                                 ranges = realloc(ranges, sizeof(int) * rbound);
1053                         }
1054
1055                         ranges[rcount++] = ovector[i];
1056                         ranges[rcount++] = ovector[i+1];
1057                 }
1058
1059                 startoffset = ovector[1];
1060         }
1061
1062         pcre_free(re);
1063
1064         *pranges = ranges;
1065         return rcount;
1066 }
1067
1068 /**
1069  * bidirectional popen() call
1070  *
1071  * @param rwepipe - int array of size three
1072  * @param exe - program to run
1073  * @param argv - argument list
1074  * @return pid or -1 on error
1075  *
1076  * The caller passes in an array of three integers (rwepipe), on successful
1077  * execution it can then write to element 0 (stdin of exe), and read from
1078  * element 1 (stdout) and 2 (stderr).
1079  */
1080 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
1081 {
1082         int in[2];
1083         int out[2];
1084         int err[2];
1085         int pid;
1086         int rc;
1087
1088         rc = pipe(in);
1089         if (rc < 0)
1090                 goto error_in;
1091
1092         rc = pipe(out);
1093         if (rc < 0)
1094                 goto error_out;
1095
1096         rc = pipe(err);
1097         if (rc < 0)
1098                 goto error_err;
1099
1100         pid = fork();
1101         if (pid > 0) {
1102                 /* parent */
1103                 close(in[0]);
1104                 close(out[1]);
1105                 close(err[1]);
1106                 rwepipe[0] = in[1];
1107                 rwepipe[1] = out[0];
1108                 rwepipe[2] = err[0];
1109                 return pid;
1110         } else if (pid == 0) {
1111                 /* child */
1112                 close(in[1]);
1113                 close(out[0]);
1114                 close(err[0]);
1115                 close(0);
1116                 rc = dup(in[0]);
1117                 close(1);
1118                 rc = dup(out[1]);
1119                 close(2);
1120                 rc = dup(err[1]);
1121
1122                 execvp(exe, (char **)argv);
1123                 exit(1);
1124         } else
1125                 goto error_fork;
1126
1127         return pid;
1128
1129 error_fork:
1130         close(err[0]);
1131         close(err[1]);
1132 error_err:
1133         close(out[0]);
1134         close(out[1]);
1135 error_out:
1136         close(in[0]);
1137         close(in[1]);
1138 error_in:
1139         return -1;
1140 }
1141
1142 static int pcloseRWE(int pid, int *rwepipe)
1143 {
1144         int rc, status;
1145         close(rwepipe[0]);
1146         close(rwepipe[1]);
1147         close(rwepipe[2]);
1148         rc = waitpid(pid, &status, 0);
1149         return status;
1150 }
1151
1152 static char *shrink_one_url(int *rwepipe, char *big)
1153 {
1154         int biglen = strlen(big);
1155         char *small;
1156         int smalllen;
1157         int rc;
1158
1159         rc = dprintf(rwepipe[0], "%s\n", big);
1160         if (rc < 0)
1161                 return big;
1162
1163         smalllen = biglen + 128;
1164         small = malloc(smalllen);
1165         if (!small)
1166                 return big;
1167
1168         rc = read(rwepipe[1], small, smalllen);
1169         if (rc < 0 || rc > biglen)
1170                 goto error_free_small;
1171
1172         if (strncmp(small, "http://", 7))
1173                 goto error_free_small;
1174
1175         smalllen = rc;
1176         while (smalllen && isspace(small[smalllen-1]))
1177                         small[--smalllen] = 0;
1178
1179         free(big);
1180         return small;
1181
1182 error_free_small:
1183         free(small);
1184         return big;
1185 }
1186
1187 static char *shrink_urls(char *text)
1188 {
1189         int *ranges;
1190         int rcount;
1191         int i;
1192         int inofs = 0;
1193         int outofs = 0;
1194         const char *const shrink_args[] = {
1195                 "bti-shrink-urls",
1196                 NULL
1197         };
1198         int shrink_pid;
1199         int shrink_pipe[3];
1200         int inlen = strlen(text);
1201
1202         dbg("before len=%u\n", inlen);
1203
1204         shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
1205         if (shrink_pid < 0)
1206                 return text;
1207
1208         rcount = find_urls(text, &ranges);
1209         if (!rcount)
1210                 return text;
1211
1212         for (i = 0; i < rcount; i += 2) {
1213                 int url_start = ranges[i];
1214                 int url_end = ranges[i+1];
1215                 int long_url_len = url_end - url_start;
1216                 char *url = strndup(text + url_start, long_url_len);
1217                 int short_url_len;
1218                 int not_url_len = url_start - inofs;
1219
1220                 dbg("long  url[%u]: %s\n", long_url_len, url);
1221                 url = shrink_one_url(shrink_pipe, url);
1222                 short_url_len = url ? strlen(url) : 0;
1223                 dbg("short url[%u]: %s\n", short_url_len, url);
1224
1225                 if (!url || short_url_len >= long_url_len) {
1226                         /* The short url ended up being too long
1227                          * or unavailable */
1228                         if (inofs) {
1229                                 strncpy(text + outofs, text + inofs,
1230                                                 not_url_len + long_url_len);
1231                         }
1232                         inofs += not_url_len + long_url_len;
1233                         outofs += not_url_len + long_url_len;
1234
1235                 } else {
1236                         /* copy the unmodified block */
1237                         strncpy(text + outofs, text + inofs, not_url_len);
1238                         inofs += not_url_len;
1239                         outofs += not_url_len;
1240
1241                         /* copy the new url */
1242                         strncpy(text + outofs, url, short_url_len);
1243                         inofs += long_url_len;
1244                         outofs += short_url_len;
1245                 }
1246
1247                 free(url);
1248         }
1249
1250         /* copy the last block after the last match */
1251         if (inofs) {
1252                 int tail = inlen - inofs;
1253                 if (tail) {
1254                         strncpy(text + outofs, text + inofs, tail);
1255                         outofs += tail;
1256                 }
1257         }
1258
1259         free(ranges);
1260
1261         (void)pcloseRWE(shrink_pid, shrink_pipe);
1262
1263         text[outofs] = 0;
1264         dbg("after len=%u\n", outofs);
1265         return text;
1266 }
1267
1268 int main(int argc, char *argv[], char *envp[])
1269 {
1270         static const struct option options[] = {
1271                 { "debug", 0, NULL, 'd' },
1272                 { "verbose", 0, NULL, 'V' },
1273                 { "host", 1, NULL, 'H' },
1274                 { "proxy", 1, NULL, 'P' },
1275                 { "action", 1, NULL, 'A' },
1276                 { "user", 1, NULL, 'u' },
1277                 { "group", 1, NULL, 'G' },
1278                 { "logfile", 1, NULL, 'L' },
1279                 { "shrink-urls", 0, NULL, 's' },
1280                 { "help", 0, NULL, 'h' },
1281                 { "bash", 0, NULL, 'b' },
1282                 { "dry-run", 0, NULL, 'n' },
1283                 { "page", 1, NULL, 'g' },
1284                 { "version", 0, NULL, 'v' },
1285                 { "config", 1, NULL, 'c' },
1286                 { }
1287         };
1288         struct session *session;
1289         pid_t child;
1290         char *tweet;
1291         static char password[80];
1292         int retval = 0;
1293         int option;
1294         char *http_proxy;
1295         time_t t;
1296         int page_nr;
1297
1298         debug = 0;
1299         verbose = 0;
1300
1301         session = session_alloc();
1302         if (!session) {
1303                 fprintf(stderr, "no more memory...\n");
1304                 return -1;
1305         }
1306
1307         /* get the current time so that we can log it later */
1308         time(&t);
1309         session->time = strdup(ctime(&t));
1310         session->time[strlen(session->time)-1] = 0x00;
1311
1312         /* Get the home directory so we can try to find a config file */
1313         session->homedir = strdup(getenv("HOME"));
1314
1315         /* set up a default config file location (traditionally ~/.bti) */
1316         session->configfile = zalloc(strlen(session->homedir) + 7);
1317         sprintf(session->configfile, "%s/.bti", session->homedir);
1318
1319         /* Set environment variables first, before reading command line options
1320          * or config file values. */
1321         http_proxy = getenv("http_proxy");
1322         if (http_proxy) {
1323                 if (session->proxy)
1324                         free(session->proxy);
1325                 session->proxy = strdup(http_proxy);
1326                 dbg("http_proxy = %s\n", session->proxy);
1327         }
1328
1329         parse_configfile(session);
1330
1331         while (1) {
1332                 option = getopt_long_only(argc, argv, "dp:P:H:a:A:u:c:hg:G:snVv",
1333                                           options, NULL);
1334                 if (option == -1)
1335                         break;
1336                 switch (option) {
1337                 case 'd':
1338                         debug = 1;
1339                         break;
1340                 case 'V':
1341                         verbose = 1;
1342                         break;
1343                 case 'g':
1344                         page_nr = atoi(optarg);
1345                         dbg("page = %d\n", page_nr);
1346                         session->page = page_nr;
1347                         break;
1348                 case 'P':
1349                         if (session->proxy)
1350                                 free(session->proxy);
1351                         session->proxy = strdup(optarg);
1352                         dbg("proxy = %s\n", session->proxy);
1353                         break;
1354                 case 'A':
1355                         if (strcasecmp(optarg, "update") == 0)
1356                                 session->action = ACTION_UPDATE;
1357                         else if (strcasecmp(optarg, "friends") == 0)
1358                                 session->action = ACTION_FRIENDS;
1359                         else if (strcasecmp(optarg, "user") == 0)
1360                                 session->action = ACTION_USER;
1361                         else if (strcasecmp(optarg, "replies") == 0)
1362                                 session->action = ACTION_REPLIES;
1363                         else if (strcasecmp(optarg, "public") == 0)
1364                                 session->action = ACTION_PUBLIC;
1365                         else if (strcasecmp(optarg, "group") == 0)
1366                                 session->action = ACTION_GROUP;
1367                         else
1368                                 session->action = ACTION_UNKNOWN;
1369                         dbg("action = %d\n", session->action);
1370                         break;
1371                 case 'u':
1372                         if (session->user)
1373                                 free(session->user);
1374                         session->user = strdup(optarg);
1375                         dbg("user = %s\n", session->user);
1376                         break;
1377
1378                 case 'G':
1379                         if (session->group)
1380                                 free(session->group);
1381                         session->group = strdup(optarg);
1382                         dbg("group = %s\n", session->group);
1383                         break;
1384                 case 'L':
1385                         if (session->logfile)
1386                                 free(session->logfile);
1387                         session->logfile = strdup(optarg);
1388                         dbg("logfile = %s\n", session->logfile);
1389                         break;
1390                 case 's':
1391                         session->shrink_urls = 1;
1392                         break;
1393                 case 'H':
1394                         if (session->hosturl)
1395                                 free(session->hosturl);
1396                         if (session->hostname)
1397                                 free(session->hostname);
1398                         if (strcasecmp(optarg, "twitter") == 0) {
1399                                 session->host = HOST_TWITTER;
1400                                 session->hosturl = strdup(twitter_host);
1401                                 session->hostname = strdup(twitter_name);
1402                         } else if (strcasecmp(optarg, "identica") == 0) {
1403                                 session->host = HOST_IDENTICA;
1404                                 session->hosturl = strdup(identica_host);
1405                                 session->hostname = strdup(identica_name);
1406                         } else {
1407                                 session->host = HOST_CUSTOM;
1408                                 session->hosturl = strdup(optarg);
1409                                 session->hostname = strdup(optarg);
1410                         }
1411                         dbg("host = %d\n", session->host);
1412                         break;
1413                 case 'b':
1414                         session->bash = 1;
1415                         break;
1416                 case 'c':
1417                         if (session->configfile)
1418                                 free(session->configfile);
1419                         session->configfile = strdup(optarg);
1420                         dbg("configfile = %s\n", session->configfile);
1421
1422                         /*
1423                          * read the config file now.  Yes, this could override previously
1424                          * set options from the command line, but the user asked for it...
1425                          */
1426                         parse_configfile(session);
1427                         break;
1428                 case 'h':
1429                         display_help();
1430                         goto exit;
1431                 case 'n':
1432                         session->dry_run = 1;
1433                         break;
1434                 case 'v':
1435                         display_version();
1436                         goto exit;
1437                 default:
1438                         display_help();
1439                         goto exit;
1440                 }
1441         }
1442
1443         session_readline_init(session);
1444         /*
1445          * Show the version to make it easier to determine what
1446          * is going on here
1447          */
1448         if (debug)
1449                 display_version();
1450
1451         if (session->host == HOST_TWITTER) {
1452                 if (!session->consumer_key || !session->consumer_secret) {
1453                         fprintf(stderr, "Twitter no longer supuports HTTP basic authentication.\n");
1454                         fprintf(stderr, "Both consumer key, and consumer secret are required");
1455                         fprintf(stderr, " for bti in order to behave as an OAuth consumer.\n");
1456                         goto exit;
1457                 }
1458                 if (session->action == ACTION_GROUP) {
1459                         fprintf(stderr, "Groups only work in Identi.ca.\n");
1460                         goto exit;
1461                 }
1462         } else {
1463                 if (!session->consumer_key || !session->consumer_secret) {
1464                         session->no_oauth = 1;
1465                 }
1466         }
1467         
1468         if (session->no_oauth) {
1469                 if (!session->account) {
1470                         fprintf(stdout, "Enter account for %s: ", session->hostname);
1471                         session->account = session->readline(NULL);
1472                 }
1473                 if (!session->password) {
1474                         read_password(password, sizeof(password), session->hostname);
1475                         session->password = strdup(password);
1476                 }
1477         } else {
1478                 if (!session->access_token_key || !session->access_token_secret) {
1479                         request_access_token(session);
1480                         goto exit;
1481                 } 
1482         }
1483
1484         if (session->action == ACTION_UNKNOWN) {
1485                 fprintf(stderr, "Unknown action, valid actions are:\n");
1486                 fprintf(stderr, "'update', 'friends', 'public', "
1487                         "'replies', 'group' or 'user'.\n");
1488                 goto exit;
1489         }
1490
1491         if (session->action == ACTION_GROUP && !session->group) {
1492                 fprintf(stdout, "Enter group name: ");
1493                 session->group = session->readline(NULL);
1494         }
1495
1496         if (session->action == ACTION_UPDATE) {
1497                 if (session->bash || !session->interactive)
1498                         tweet = get_string_from_stdin();
1499                 else
1500                         tweet = session->readline("tweet: ");
1501                 if (!tweet || strlen(tweet) == 0) {
1502                         dbg("no tweet?\n");
1503                         return -1;
1504                 }
1505
1506                 if (session->shrink_urls)
1507                         tweet = shrink_urls(tweet);
1508
1509                 session->tweet = zalloc(strlen(tweet) + 10);
1510                 if (session->bash)
1511                         sprintf(session->tweet, "%c %s",
1512                                 getuid() ? '$' : '#', tweet);
1513                 else
1514                         sprintf(session->tweet, "%s", tweet);
1515
1516                 free(tweet);
1517                 dbg("tweet = %s\n", session->tweet);
1518         }
1519
1520         if (session->page == 0)
1521                 session->page = 1;
1522         dbg("config file = %s\n", session->configfile);
1523         dbg("host = %d\n", session->host);
1524         dbg("action = %d\n", session->action);
1525
1526         /* fork ourself so that the main shell can get on
1527          * with it's life as we try to connect and handle everything
1528          */
1529         if (session->bash) {
1530                 child = fork();
1531                 if (child) {
1532                         dbg("child is %d\n", child);
1533                         exit(0);
1534                 }
1535         }
1536
1537         retval = send_request(session);
1538         if (retval && !session->bash)
1539                 fprintf(stderr, "operation failed\n");
1540
1541         log_session(session, retval);
1542 exit:
1543         session_readline_cleanup(session);
1544         session_free(session);
1545         return retval;;
1546 }