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