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