e177187b7c9a36048c0b30394bb36a0c42fe1886
[gregoa/bti.git] / bti.c
1 /*
2  * Copyright (C) 2008 Greg Kroah-Hartman <greg@kroah.com>
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the
6  * Free Software Foundation version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16  */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <stddef.h>
21 #include <string.h>
22 #include <getopt.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <time.h>
28 #include <sys/stat.h>
29 #include <curl/curl.h>
30 #include <readline/readline.h>
31 #include "bti_version.h"
32
33
34 #define zalloc(size)    calloc(size, 1)
35
36 #define dbg(format, arg...)                                             \
37         do {                                                            \
38                 if (debug)                                              \
39                         printf("%s: " format , __func__ , ## arg );     \
40         } while (0)
41
42
43 static int debug = 0;
44
45 enum host {
46         HOST_TWITTER = 0,
47         HOST_IDENTICA = 1,
48 };
49
50 struct session {
51         char *password;
52         char *account;
53         char *tweet;
54         char *proxy;
55         char *time;
56         char *homedir;
57         char *logfile;
58         int bash;
59         enum host host;
60 };
61
62 struct bti_curl_buffer {
63         char *data;
64         int length;
65 };
66
67 static void display_help(void)
68 {
69         fprintf(stdout, "bti - send tweet to twitter\n");
70         fprintf(stdout, "Version: " BTI_VERSION "\n");
71         fprintf(stdout, "Usage:\n");
72         fprintf(stdout, "  bti [options]\n");
73         fprintf(stdout, "options are:\n");
74         fprintf(stdout, "  --account accountname\n");
75         fprintf(stdout, "  --password password\n");
76         fprintf(stdout, "  --proxy PROXY:PORT\n");
77         fprintf(stdout, "  --host HOST\n");
78         fprintf(stdout, "  --logfile logfile\n");
79         fprintf(stdout, "  --bash\n");
80         fprintf(stdout, "  --debug\n");
81         fprintf(stdout, "  --version\n");
82         fprintf(stdout, "  --help\n");
83 }
84
85 static void display_version(void)
86 {
87         fprintf(stdout, "bti - version %s\n", BTI_VERSION);
88 }
89
90 static char *get_string_from_stdin(void)
91 {
92         static char *string = (char *)NULL;
93         if (string) {
94                 free(string);
95                 string = (char *)NULL;
96         }
97
98         string = readline("tweet: ");
99
100         return string;
101 }
102
103 static struct session *session_alloc(void)
104 {
105         struct session *session;
106
107         session = zalloc(sizeof(*session));
108         if (!session)
109                 return NULL;
110         return session;
111 }
112
113 static void session_free(struct session *session)
114 {
115         if (!session)
116                 return;
117         free(session->password);
118         free(session->account);
119         free(session->tweet);
120         free(session->proxy);
121         free(session->time);
122         free(session->homedir);
123         free(session);
124 }
125
126 static struct bti_curl_buffer *bti_curl_buffer_alloc(void)
127 {
128         struct bti_curl_buffer *buffer;
129
130         buffer = zalloc(sizeof(*buffer));
131         if (!buffer)
132                 return NULL;
133
134         /* start out with a data buffer of 1 byte to
135          * make the buffer fill logic simpler */
136         buffer->data = zalloc(1);
137         if (!buffer->data) {
138                 free(buffer);
139                 return NULL;
140         }
141         buffer->length = 0;
142         return buffer;
143 }
144
145 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
146 {
147         if (!buffer)
148                 return;
149         free(buffer->data);
150         free(buffer);
151 }
152
153 static const char *twitter_url = "https://twitter.com/statuses/update.xml";
154 static const char *identica_url = "http://identi.ca/api/statuses/update.xml";
155
156 static CURL *curl_init(void)
157 {
158         CURL *curl;
159
160         curl = curl_easy_init();
161         if (!curl) {
162                 fprintf(stderr, "Can not init CURL!\n");
163                 return NULL;
164         }
165         /* some ssl sanity checks on the connection we are making */
166         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
167         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
168         return curl;
169 }
170
171 size_t curl_callback(void *buffer, size_t size, size_t nmemb, void *userp)
172 {
173         struct bti_curl_buffer *curl_buf = userp;
174         size_t buffer_size = size * nmemb;
175         char *temp;
176
177         if ((!buffer) || (!buffer_size) || (!curl_buf))
178                 return -EINVAL;
179
180         /* add to the data we already have */
181         temp = zalloc(curl_buf->length + buffer_size + 1);
182         if (!temp)
183                 return -ENOMEM;
184
185         memcpy(temp, curl_buf->data, curl_buf->length);
186         free(curl_buf->data);
187         curl_buf->data = temp;
188         memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
189         curl_buf->length += buffer_size;
190
191         dbg("%s\n", curl_buf->data);
192
193         return buffer_size;
194 }
195
196 static int send_tweet(struct session *session)
197 {
198         char user_password[500];
199         char data[500];
200         struct bti_curl_buffer *curl_buf;
201         CURL *curl = NULL;
202         CURLcode res;
203         struct curl_httppost *formpost = NULL;
204         struct curl_httppost *lastptr = NULL;
205         struct curl_slist *slist = NULL;
206
207         if (!session)
208                 return -EINVAL;
209
210         curl_buf = bti_curl_buffer_alloc();
211         if (!curl_buf)
212                 return -ENOMEM;
213
214         snprintf(user_password, sizeof(user_password), "%s:%s",
215                  session->account, session->password);
216         snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
217
218         curl = curl_init();
219         if (!curl)
220                 return -EINVAL;
221
222         curl_formadd(&formpost, &lastptr,
223                      CURLFORM_COPYNAME, "status",
224                      CURLFORM_COPYCONTENTS, session->tweet,
225                      CURLFORM_END);
226
227         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
228
229         switch (session->host) {
230         case HOST_TWITTER:
231                 curl_easy_setopt(curl, CURLOPT_URL, twitter_url);
232                 /*
233                  * twitter doesn't like the "Expect: 100-continue" header
234                  * anymore, so turn it off.
235                  */
236                 slist = curl_slist_append(slist, "Expect:");
237                 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
238                 break;
239         case HOST_IDENTICA:
240                 curl_easy_setopt(curl, CURLOPT_URL, identica_url);
241                 break;
242         }
243
244         if (session->proxy)
245                 curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);
246
247         if (debug)
248                 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
249         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
250
251         dbg("user_password = %s\n", user_password);
252         dbg("data = %s\n", data);
253         dbg("proxy = %s\n", session->proxy);
254
255         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
256         curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
257         res = curl_easy_perform(curl);
258         if (res && !session->bash) {
259                 fprintf(stderr, "error(%d) trying to send tweet\n", res);
260                 return -EINVAL;
261         }
262
263         curl_easy_cleanup(curl);
264         curl_formfree(formpost);
265         bti_curl_buffer_free(curl_buf);
266         return 0;
267 }
268
269 static void parse_configfile(struct session *session)
270 {
271         FILE *config_file;
272         char *line = NULL;
273         size_t len = 0;
274         char *account = NULL;
275         char *password = NULL;
276         char *host = NULL;
277         char *proxy = NULL;
278         char *logfile = NULL;
279         char *file;
280
281         /* config file is ~/.bti  */
282         file = alloca(strlen(session->homedir) + 7);
283
284         sprintf(file, "%s/.bti", session->homedir);
285
286         config_file = fopen(file, "r");
287
288         /* No error if file does not exist or is unreadable.  */
289         if (config_file == NULL)
290                 return;
291
292         do {
293                 ssize_t n = getline(&line, &len, config_file);
294                 if (n < 0)
295                         break;
296                 if (line[n - 1] == '\n')
297                         line[n - 1] = '\0';
298                 /* Parse file.  Format is the usual value pairs:
299                    account=name
300                    passwort=value
301                    # is a comment character
302                 */
303                 *strchrnul(line, '#') = '\0';
304                 char *c = line;
305                 while (isspace(*c))
306                         c++;
307                 /* Ignore blank lines.  */
308                 if (c[0] == '\0')
309                         continue;
310
311                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
312                         c += 8;
313                         if (c[0] != '\0')
314                                 account = strdup(c);
315                 } else if (!strncasecmp(c, "password", 8) &&
316                            (c[8] == '=')) {
317                         c += 9;
318                         if (c[0] != '\0')
319                                 password = strdup(c);
320                 } else if (!strncasecmp(c, "host", 4) &&
321                            (c[4] == '=')) {
322                         c += 5;
323                         if (c[0] != '\0')
324                                 host = strdup(c);
325                 } else if (!strncasecmp(c, "proxy", 5) &&
326                            (c[5] == '=')) {
327                         c += 6;
328                         if (c[0] != '\0')
329                                 proxy = strdup(c);
330                 } else if (!strncasecmp(c, "logfile", 7) &&
331                            (c[7] == '=')) {
332                         c += 8;
333                         if (c[0] != '\0')
334                                 logfile = strdup(c);
335                 }
336         } while (!feof(config_file));
337
338         if (password)
339                 session->password = password;
340         if (account)
341                 session->account = account;
342         if (host) {
343                 if (strcasecmp(host, "twitter") == 0)
344                         session->host = HOST_TWITTER;
345                 if (strcasecmp(host, "identica") == 0)
346                         session->host = HOST_IDENTICA;
347                 free(host);
348         }
349         if (proxy) {
350                 if (session->proxy)
351                         free(session->proxy);
352                 session->proxy = proxy;
353         }
354         if (logfile)
355                 session->logfile = logfile;
356
357         /* Free buffer and close file.  */
358         free(line);
359         fclose(config_file);
360 }
361
362 static void log_session(struct session *session, int retval)
363 {
364         FILE *log_file;
365         char *filename;
366         char *host;
367
368         /* Only log something if we have a log file set */
369         if (!session->logfile)
370                 return;
371
372         filename = alloca(strlen(session->homedir) +
373                           strlen(session->logfile) + 3);
374
375         sprintf(filename, "%s/%s", session->homedir, session->logfile);
376
377         log_file = fopen(filename, "a+");
378         if (log_file == NULL)
379                 return;
380         switch (session->host) {
381         case HOST_TWITTER:
382                 host = "twitter";
383                 break;
384         case HOST_IDENTICA:
385                 host = "identi.ca";
386                 break;
387         default:
388                 host = "unknown";
389                 break;
390         }
391
392         if (retval)
393                 fprintf(log_file, "%s: host=%s tweet failed\n", session->time, host);
394         else
395                 fprintf(log_file, "%s: host=%s tweet=%s\n", session->time, host, session->tweet);
396
397         fclose(log_file);
398 }
399
400 int main(int argc, char *argv[], char *envp[])
401 {
402         static const struct option options[] = {
403                 { "debug", 0, NULL, 'd' },
404                 { "account", 1, NULL, 'a' },
405                 { "password", 1, NULL, 'p' },
406                 { "host", 1, NULL, 'H' },
407                 { "proxy", 1, NULL, 'P' },
408                 { "logfile", 1, NULL, 'L' },
409                 { "help", 0, NULL, 'h' },
410                 { "bash", 0, NULL, 'b' },
411                 { "version", 0, NULL, 'v' },
412                 { }
413         };
414         struct session *session;
415         pid_t child;
416         char *tweet;
417         int retval = 0;
418         int option;
419         char *http_proxy;
420         time_t t;
421 #if 0
422         char *pwd = getenv("PWD");
423         char *dir;
424 #endif
425
426         rl_bind_key('\t', rl_insert);
427         session = session_alloc();
428         if (!session) {
429                 fprintf(stderr, "no more memory...\n");
430                 return -1;
431         }
432
433         /* get the current time so that we can log it later */
434         time(&t);
435         session->time = strdup(ctime(&t));
436         session->time[strlen(session->time)-1] = 0x00;
437
438         session->homedir = strdup(getenv("HOME"));
439
440         curl_global_init(CURL_GLOBAL_ALL);
441
442         /* Set environment variables first, before reading command line options
443          * or config file values. */
444         http_proxy = getenv("http_proxy");
445         if (http_proxy) {
446                 if (session->proxy)
447                         free(session->proxy);
448                 session->proxy = strdup(http_proxy);
449                 dbg("http_proxy = %s\n", session->proxy);
450         }
451
452         parse_configfile(session);
453
454         while (1) {
455                 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:h",
456                                           options, NULL);
457                 if (option == -1)
458                         break;
459                 switch (option) {
460                 case 'd':
461                         debug = 1;
462                         break;
463                 case 'a':
464                         if (session->account)
465                                 free(session->account);
466                         session->account = strdup(optarg);
467                         dbg("account = %s\n", session->account);
468                         break;
469                 case 'p':
470                         if (session->password)
471                                 free(session->password);
472                         session->password = strdup(optarg);
473                         dbg("password = %s\n", session->password);
474                         break;
475                 case 'P':
476                         if (session->proxy)
477                                 free(session->proxy);
478                         session->proxy = strdup(optarg);
479                         dbg("proxy = %s\n", session->proxy);
480                         break;
481                 case 'L':
482                         if (session->logfile)
483                                 free(session->logfile);
484                         session->logfile = strdup(optarg);
485                         dbg("logfile = %s\n", session->logfile);
486                         break;
487                 case 'H':
488                         if (strcasecmp(optarg, "twitter") == 0)
489                                 session->host = HOST_TWITTER;
490                         if (strcasecmp(optarg, "identica") == 0)
491                                 session->host = HOST_IDENTICA;
492                         dbg("host = %d\n", session->host);
493                         break;
494                 case 'b':
495                         session->bash= 1;
496                         break;
497                 case 'h':
498                         display_help();
499                         goto exit;
500                 case 'v':
501                         display_version();
502                         goto exit;
503                 default:
504                         display_help();
505                         goto exit;
506                 }
507         }
508
509         if (!session->account) {
510                 fprintf(stdout, "Enter twitter account: ");
511                 session->account = get_string_from_stdin();
512         }
513
514         if (!session->password) {
515                 fprintf(stdout, "Enter twitter password: ");
516                 session->password = get_string_from_stdin();
517         }
518 #if 0
519         /* get the current working directory basename */
520         if (strcmp(pwd, home) == 0)
521                 dir = "~";
522         else {
523                 dir = strrchr(pwd, '/');
524                 if (dir)
525                         dir++;
526                 else
527                         dir = "?";
528         }
529 #endif
530         tweet = get_string_from_stdin();
531         if (!tweet || strlen(tweet) == 0) {
532                 dbg("no tweet?\n");
533                 return -1;
534         }
535
536 //      session->tweet = zalloc(strlen(tweet) + strlen(dir) + 10);
537         session->tweet = zalloc(strlen(tweet) + 10);
538
539         /* if --bash is specified, add the "PWD $ " to
540          * the start of the tweet. */
541         if (session->bash)
542 //              sprintf(session->tweet, "%s $ %s", dir, tweet);
543                 sprintf(session->tweet, "$ %s", tweet);
544         else
545                 sprintf(session->tweet, "%s", tweet);
546         free(tweet);
547
548         dbg("account = %s\n", session->account);
549         dbg("password = %s\n", session->password);
550         dbg("tweet = %s\n", session->tweet);
551         dbg("host = %d\n", session->host);
552
553         /* fork ourself so that the main shell can get on
554          * with it's life as we try to connect and handle everything
555          */
556         if (session->bash) {
557                 child = fork();
558                         if (child) {
559                         dbg("child is %d\n", child);
560                         exit(0);
561                 }
562         }
563
564         retval = send_tweet(session);
565         if (retval && !session->bash)
566                 fprintf(stderr, "tweet failed\n");
567
568         log_session(session, retval);
569 exit:
570         session_free(session);
571         return retval;;
572 }