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