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