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