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