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