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