]> ToastFreeware Gitweb - gregoa/bti.git/blob - bti.c
updated version of checkpatch.pl
[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, session->tweet);
714                 break;
715         case ACTION_FRIENDS:
716                 fprintf(log_file, "%s: host=%s retrieving friends timeline\n",
717                         session->time, session->hostname);
718                 break;
719         case ACTION_USER:
720                 fprintf(log_file, "%s: host=%s retrieving %s's timeline\n",
721                         session->time, session->hostname, session->user);
722                 break;
723         case ACTION_REPLIES:
724                 fprintf(log_file, "%s: host=%s retrieving replies\n",
725                         session->time, session->hostname);
726                 break;
727         case ACTION_PUBLIC:
728                 fprintf(log_file, "%s: host=%s retrieving public timeline\n",
729                         session->time, session->hostname);
730                 break;
731         case ACTION_GROUP:
732                 fprintf(log_file, "%s: host=%s retrieving group timeline\n",
733                         session->time, session->hostname);
734                 break;
735         default:
736                 break;
737         }
738
739         fclose(log_file);
740 }
741
742 static char *get_string_from_stdin(void)
743 {
744         char *temp;
745         char *string;
746
747         string = zalloc(1000);
748         if (!string)
749                 return NULL;
750
751         if (!fgets(string, 999, stdin))
752                 return NULL;
753         temp = strchr(string, '\n');
754         if (temp)
755                 *temp = '\0';
756         return string;
757 }
758
759 static void read_password(char *buf, size_t len, char *host)
760 {
761         char pwd[80];
762         int retval;
763         struct termios old;
764         struct termios tp;
765
766         tcgetattr(0, &tp);
767         old = tp;
768
769         tp.c_lflag &= (~ECHO);
770         tcsetattr(0, TCSANOW, &tp);
771
772         fprintf(stdout, "Enter password for %s: ", host);
773         fflush(stdout);
774         tcflow(0, TCOOFF);
775         retval = scanf("%79s", pwd);
776         tcflow(0, TCOON);
777         fprintf(stdout, "\n");
778
779         tcsetattr(0, TCSANOW, &old);
780
781         strncpy(buf, pwd, len);
782         buf[len-1] = '\0';
783 }
784
785 static int find_urls(const char *tweet, int **pranges)
786 {
787         /*
788          * magic obtained from
789          * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
790          */
791         static const char *re_magic =
792                 "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
793                 "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
794                 "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
795         pcre *re;
796         const char *errptr;
797         int erroffset;
798         int ovector[10] = {0,};
799         const size_t ovsize = sizeof(ovector)/sizeof(*ovector);
800         int startoffset, tweetlen;
801         int i, rc;
802         int rbound = 10;
803         int rcount = 0;
804         int *ranges = malloc(sizeof(int) * rbound);
805
806         re = pcre_compile(re_magic,
807                         PCRE_NO_AUTO_CAPTURE,
808                         &errptr, &erroffset, NULL);
809         if (!re) {
810                 fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
811                 exit(1);
812         }
813
814         tweetlen = strlen(tweet);
815         for (startoffset = 0; startoffset < tweetlen; ) {
816
817                 rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
818                                 ovector, ovsize);
819                 if (rc == PCRE_ERROR_NOMATCH)
820                         break;
821
822                 if (rc < 0) {
823                         fprintf(stderr, "pcre_exec @%u: %s\n",
824                                 erroffset, errptr);
825                         exit(1);
826                 }
827
828                 for (i = 0; i < rc; i += 2) {
829                         if ((rcount+2) == rbound) {
830                                 rbound *= 2;
831                                 ranges = realloc(ranges, sizeof(int) * rbound);
832                         }
833
834                         ranges[rcount++] = ovector[i];
835                         ranges[rcount++] = ovector[i+1];
836                 }
837
838                 startoffset = ovector[1];
839         }
840
841         pcre_free(re);
842
843         *pranges = ranges;
844         return rcount;
845 }
846
847 /**
848  * bidirectional popen() call
849  *
850  * @param rwepipe - int array of size three
851  * @param exe - program to run
852  * @param argv - argument list
853  * @return pid or -1 on error
854  *
855  * The caller passes in an array of three integers (rwepipe), on successful
856  * execution it can then write to element 0 (stdin of exe), and read from
857  * element 1 (stdout) and 2 (stderr).
858  */
859 static int popenRWE(int *rwepipe, const char *exe, const char *const argv[])
860 {
861         int in[2];
862         int out[2];
863         int err[2];
864         int pid;
865         int rc;
866
867         rc = pipe(in);
868         if (rc < 0)
869                 goto error_in;
870
871         rc = pipe(out);
872         if (rc < 0)
873                 goto error_out;
874
875         rc = pipe(err);
876         if (rc < 0)
877                 goto error_err;
878
879         pid = fork();
880         if (pid > 0) {
881                 /* parent */
882                 close(in[0]);
883                 close(out[1]);
884                 close(err[1]);
885                 rwepipe[0] = in[1];
886                 rwepipe[1] = out[0];
887                 rwepipe[2] = err[0];
888                 return pid;
889         } else if (pid == 0) {
890                 /* child */
891                 close(in[1]);
892                 close(out[0]);
893                 close(err[0]);
894                 close(0);
895                 rc = dup(in[0]);
896                 close(1);
897                 rc = dup(out[1]);
898                 close(2);
899                 rc = dup(err[1]);
900
901                 execvp(exe, (char **)argv);
902                 exit(1);
903         } else
904                 goto error_fork;
905
906         return pid;
907
908 error_fork:
909         close(err[0]);
910         close(err[1]);
911 error_err:
912         close(out[0]);
913         close(out[1]);
914 error_out:
915         close(in[0]);
916         close(in[1]);
917 error_in:
918         return -1;
919 }
920
921 static int pcloseRWE(int pid, int *rwepipe)
922 {
923         int rc, status;
924         close(rwepipe[0]);
925         close(rwepipe[1]);
926         close(rwepipe[2]);
927         rc = waitpid(pid, &status, 0);
928         return status;
929 }
930
931 static char *shrink_one_url(int *rwepipe, char *big)
932 {
933         int biglen = strlen(big);
934         char *small;
935         int smalllen;
936         int rc;
937
938         rc = dprintf(rwepipe[0], "%s\n", big);
939         if (rc < 0)
940                 return big;
941
942         smalllen = biglen + 128;
943         small = malloc(smalllen);
944         if (!small)
945                 return big;
946
947         rc = read(rwepipe[1], small, smalllen);
948         if (rc < 0 || rc > biglen)
949                 goto error_free_small;
950
951         if (strncmp(small, "http://", 7))
952                 goto error_free_small;
953
954         smalllen = rc;
955         while (smalllen && isspace(small[smalllen-1]))
956                         small[--smalllen] = 0;
957
958         free(big);
959         return small;
960
961 error_free_small:
962         free(small);
963         return big;
964 }
965
966 static char *shrink_urls(char *text)
967 {
968         int *ranges;
969         int rcount;
970         int i;
971         int inofs = 0;
972         int outofs = 0;
973         const char *const shrink_args[] = {
974                 "bti-shrink-urls",
975                 NULL
976         };
977         int shrink_pid;
978         int shrink_pipe[3];
979         int inlen = strlen(text);
980
981         dbg("before len=%u\n", inlen);
982
983         shrink_pid = popenRWE(shrink_pipe, shrink_args[0], shrink_args);
984         if (shrink_pid < 0)
985                 return text;
986
987         rcount = find_urls(text, &ranges);
988         if (!rcount)
989                 return text;
990
991         for (i = 0; i < rcount; i += 2) {
992                 int url_start = ranges[i];
993                 int url_end = ranges[i+1];
994                 int long_url_len = url_end - url_start;
995                 char *url = strndup(text + url_start, long_url_len);
996                 int short_url_len;
997                 int not_url_len = url_start - inofs;
998
999                 dbg("long  url[%u]: %s\n", long_url_len, url);
1000                 url = shrink_one_url(shrink_pipe, url);
1001                 short_url_len = url ? strlen(url) : 0;
1002                 dbg("short url[%u]: %s\n", short_url_len, url);
1003
1004                 if (!url || short_url_len >= long_url_len) {
1005                         /* The short url ended up being too long
1006                          * or unavailable */
1007                         if (inofs) {
1008                                 strncpy(text + outofs, text + inofs,
1009                                                 not_url_len + long_url_len);
1010                         }
1011                         inofs += not_url_len + long_url_len;
1012                         outofs += not_url_len + long_url_len;
1013
1014                 } else {
1015                         /* copy the unmodified block */
1016                         strncpy(text + outofs, text + inofs, not_url_len);
1017                         inofs += not_url_len;
1018                         outofs += not_url_len;
1019
1020                         /* copy the new url */
1021                         strncpy(text + outofs, url, short_url_len);
1022                         inofs += long_url_len;
1023                         outofs += short_url_len;
1024                 }
1025
1026                 free(url);
1027         }
1028
1029         /* copy the last block after the last match */
1030         if (inofs) {
1031                 int tail = inlen - inofs;
1032                 if (tail) {
1033                         strncpy(text + outofs, text + inofs, tail);
1034                         outofs += tail;
1035                 }
1036         }
1037
1038         free(ranges);
1039
1040         (void)pcloseRWE(shrink_pid, shrink_pipe);
1041
1042         text[outofs] = 0;
1043         dbg("after len=%u\n", outofs);
1044         return text;
1045 }
1046
1047 int main(int argc, char *argv[], char *envp[])
1048 {
1049         static const struct option options[] = {
1050                 { "debug", 0, NULL, 'd' },
1051                 { "verbose", 0, NULL, 'V' },
1052                 { "account", 1, NULL, 'a' },
1053                 { "password", 1, NULL, 'p' },
1054                 { "host", 1, NULL, 'H' },
1055                 { "proxy", 1, NULL, 'P' },
1056                 { "action", 1, NULL, 'A' },
1057                 { "user", 1, NULL, 'u' },
1058                 { "group", 1, NULL, 'G' },
1059                 { "logfile", 1, NULL, 'L' },
1060                 { "shrink-urls", 0, NULL, 's' },
1061                 { "help", 0, NULL, 'h' },
1062                 { "bash", 0, NULL, 'b' },
1063                 { "dry-run", 0, NULL, 'n' },
1064                 { "page", 1, NULL, 'g' },
1065                 { "version", 0, NULL, 'v' },
1066                 { }
1067         };
1068         struct session *session;
1069         pid_t child;
1070         char *tweet;
1071         static char password[80];
1072         int retval = 0;
1073         int option;
1074         char *http_proxy;
1075         time_t t;
1076         int page_nr;
1077
1078         debug = 0;
1079         verbose = 0;
1080
1081         session = session_alloc();
1082         if (!session) {
1083                 fprintf(stderr, "no more memory...\n");
1084                 return -1;
1085         }
1086
1087         /* get the current time so that we can log it later */
1088         time(&t);
1089         session->time = strdup(ctime(&t));
1090         session->time[strlen(session->time)-1] = 0x00;
1091
1092         session->homedir = strdup(getenv("HOME"));
1093
1094         curl_global_init(CURL_GLOBAL_ALL);
1095
1096         /* Set environment variables first, before reading command line options
1097          * or config file values. */
1098         http_proxy = getenv("http_proxy");
1099         if (http_proxy) {
1100                 if (session->proxy)
1101                         free(session->proxy);
1102                 session->proxy = strdup(http_proxy);
1103                 dbg("http_proxy = %s\n", session->proxy);
1104         }
1105
1106         parse_configfile(session);
1107
1108         while (1) {
1109                 option = getopt_long_only(argc, argv, "dp:P:H:a:A:u:hg:G:snVv",
1110                                           options, NULL);
1111                 if (option == -1)
1112                         break;
1113                 switch (option) {
1114                 case 'd':
1115                         debug = 1;
1116                         break;
1117                 case 'V':
1118                         verbose = 1;
1119                         break;
1120                 case 'a':
1121                         if (session->account)
1122                                 free(session->account);
1123                         session->account = strdup(optarg);
1124                         dbg("account = %s\n", session->account);
1125                         break;
1126                 case 'g':
1127                         page_nr = atoi(optarg);
1128                         dbg("page = %d\n", page_nr);
1129                         session->page = page_nr;
1130                         break;
1131                 case 'p':
1132                         if (session->password)
1133                                 free(session->password);
1134                         session->password = strdup(optarg);
1135                         dbg("password = %s\n", session->password);
1136                         break;
1137                 case 'P':
1138                         if (session->proxy)
1139                                 free(session->proxy);
1140                         session->proxy = strdup(optarg);
1141                         dbg("proxy = %s\n", session->proxy);
1142                         break;
1143                 case 'A':
1144                         if (strcasecmp(optarg, "update") == 0)
1145                                 session->action = ACTION_UPDATE;
1146                         else if (strcasecmp(optarg, "friends") == 0)
1147                                 session->action = ACTION_FRIENDS;
1148                         else if (strcasecmp(optarg, "user") == 0)
1149                                 session->action = ACTION_USER;
1150                         else if (strcasecmp(optarg, "replies") == 0)
1151                                 session->action = ACTION_REPLIES;
1152                         else if (strcasecmp(optarg, "public") == 0)
1153                                 session->action = ACTION_PUBLIC;
1154                         else if (strcasecmp(optarg, "group") == 0)
1155                                 session->action = ACTION_GROUP;
1156                         else
1157                                 session->action = ACTION_UNKNOWN;
1158                         dbg("action = %d\n", session->action);
1159                         break;
1160                 case 'u':
1161                         if (session->user)
1162                                 free(session->user);
1163                         session->user = strdup(optarg);
1164                         dbg("user = %s\n", session->user);
1165                         break;
1166
1167                 case 'G':
1168                         if (session->group)
1169                                 free(session->group);
1170                         session->group = strdup(optarg);
1171                         dbg("group = %s\n", session->group);
1172                         break;
1173                 case 'L':
1174                         if (session->logfile)
1175                                 free(session->logfile);
1176                         session->logfile = strdup(optarg);
1177                         dbg("logfile = %s\n", session->logfile);
1178                         break;
1179                 case 's':
1180                         session->shrink_urls = 1;
1181                         break;
1182                 case 'H':
1183                         if (session->hosturl)
1184                                 free(session->hosturl);
1185                         if (session->hostname)
1186                                 free(session->hostname);
1187                         if (strcasecmp(optarg, "twitter") == 0) {
1188                                 session->host = HOST_TWITTER;
1189                                 session->hosturl = strdup(twitter_host);
1190                                 session->hostname = strdup(twitter_name);
1191                         } else if (strcasecmp(optarg, "identica") == 0) {
1192                                 session->host = HOST_IDENTICA;
1193                                 session->hosturl = strdup(identica_host);
1194                                 session->hostname = strdup(identica_name);
1195                         } else {
1196                                 session->host = HOST_CUSTOM;
1197                                 session->hosturl = strdup(optarg);
1198                                 session->hostname = strdup(optarg);
1199                         }
1200                         dbg("host = %d\n", session->host);
1201                         break;
1202                 case 'b':
1203                         session->bash = 1;
1204                         break;
1205                 case 'h':
1206                         display_help();
1207                         goto exit;
1208                 case 'n':
1209                         session->dry_run = 1;
1210                         break;
1211                 case 'v':
1212                         display_version();
1213                         goto exit;
1214                 default:
1215                         display_help();
1216                         goto exit;
1217                 }
1218         }
1219
1220         /*
1221          * Show the version to make it easier to determine what
1222          * is going on here
1223          */
1224         if (debug)
1225                 display_version();
1226
1227         if (session->action == ACTION_UNKNOWN) {
1228                 fprintf(stderr, "Unknown action, valid actions are:\n");
1229                 fprintf(stderr, "'update', 'friends', 'public', "
1230                         "'replies', 'group' or 'user'.\n");
1231                 goto exit;
1232         }
1233
1234         if (session->host == HOST_TWITTER && session->action == ACTION_GROUP) {
1235                 fprintf(stderr, "Groups only work in Identi.ca.\n");
1236                 goto exit;
1237         }
1238
1239         if (session->action == ACTION_GROUP && !session->group) {
1240                 fprintf(stdout, "Enter group name: ");
1241                 session->group = session->readline(NULL);
1242         }
1243
1244         if (!session->account) {
1245                 fprintf(stdout, "Enter account for %s: ", session->hostname);
1246                 session->account = session->readline(NULL);
1247         }
1248
1249         if (!session->password) {
1250                 read_password(password, sizeof(password), session->hostname);
1251                 session->password = strdup(password);
1252         }
1253
1254         if (session->action == ACTION_UPDATE) {
1255                 if (session->bash || !session->interactive)
1256                         tweet = get_string_from_stdin();
1257                 else
1258                         tweet = session->readline("tweet: ");
1259                 if (!tweet || strlen(tweet) == 0) {
1260                         dbg("no tweet?\n");
1261                         return -1;
1262                 }
1263
1264                 if (session->shrink_urls)
1265                         tweet = shrink_urls(tweet);
1266
1267                 session->tweet = zalloc(strlen(tweet) + 10);
1268                 if (session->bash)
1269                         sprintf(session->tweet, "%c %s",
1270                                 getuid() ? '$' : '#', tweet);
1271                 else
1272                         sprintf(session->tweet, "%s", tweet);
1273
1274                 free(tweet);
1275                 dbg("tweet = %s\n", session->tweet);
1276         }
1277
1278         if (!session->user)
1279                 session->user = strdup(session->account);
1280
1281         if (session->page == 0)
1282                 session->page = 1;
1283         dbg("account = %s\n", session->account);
1284         dbg("password = %s\n", session->password);
1285         dbg("host = %d\n", session->host);
1286         dbg("action = %d\n", session->action);
1287
1288         /* fork ourself so that the main shell can get on
1289          * with it's life as we try to connect and handle everything
1290          */
1291         if (session->bash) {
1292                 child = fork();
1293                 if (child) {
1294                         dbg("child is %d\n", child);
1295                         exit(0);
1296                 }
1297         }
1298
1299         retval = send_request(session);
1300         if (retval && !session->bash)
1301                 fprintf(stderr, "operation failed\n");
1302
1303         log_session(session, retval);
1304 exit:
1305         session_free(session);
1306         return retval;;
1307 }