Add documentation about how to send me patches
[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 "bti_version.h"
31
32
33 #define zalloc(size)    calloc(size, 1)
34
35 #define dbg(format, arg...)                                             \
36         do {                                                            \
37                 if (debug)                                              \
38                         printf("%s: " format , __func__ , ## arg );     \
39         } while (0)
40
41
42 static int debug = 0;
43
44 enum host {
45         HOST_TWITTER = 0,
46         HOST_IDENTICA = 1,
47 };
48
49 struct session {
50         char *password;
51         char *account;
52         char *tweet;
53         char *proxy;
54         char *time;
55         char *homedir;
56         int bash;
57         enum host host;
58 };
59
60 struct bti_curl_buffer {
61         char *data;
62         int length;
63 };
64
65 static void display_help(void)
66 {
67         fprintf(stdout, "bti - send tweet to twitter\n");
68         fprintf(stdout, "Version: " BTI_VERSION "\n");
69         fprintf(stdout, "Usage:\n");
70         fprintf(stdout, "  bti [options]\n");
71         fprintf(stdout, "options are:\n");
72         fprintf(stdout, "  --account accountname\n");
73         fprintf(stdout, "  --password password\n");
74         fprintf(stdout, "  --proxy PROXY:PORT\n");
75         fprintf(stdout, "  --host HOST\n");
76         fprintf(stdout, "  --bash\n");
77         fprintf(stdout, "  --debug\n");
78         fprintf(stdout, "  --version\n");
79         fprintf(stdout, "  --help\n");
80 }
81
82 static void display_version(void)
83 {
84         fprintf(stdout, "bti - version %s\n", BTI_VERSION);
85 }
86
87 static char *get_string_from_stdin(void)
88 {
89         char *temp;
90         char *string;
91
92         string = zalloc(1000);
93         if (!string)
94                 return NULL;
95
96         if (!fgets(string, 999, stdin))
97                 return NULL;
98         temp = strchr(string, '\n');
99         *temp = '\0';
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 *file;
279
280         /* config file is ~/.bti  */
281         file = alloca(strlen(session->homedir) + 7);
282
283         sprintf(file, "%s/.bti", session->homedir);
284
285         config_file = fopen(file, "r");
286
287         /* No error if file does not exist or is unreadable.  */
288         if (config_file == NULL)
289                 return;
290
291         do {
292                 ssize_t n = getline(&line, &len, config_file);
293                 if (n < 0)
294                         break;
295                 if (line[n - 1] == '\n')
296                         line[n - 1] = '\0';
297                 /* Parse file.  Format is the usual value pairs:
298                    account=name
299                    passwort=value
300                    # is a comment character
301                 */
302                 *strchrnul(line, '#') = '\0';
303                 char *c = line;
304                 while (isspace(*c))
305                         c++;
306                 /* Ignore blank lines.  */
307                 if (c[0] == '\0')
308                         continue;
309
310                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
311                         c += 8;
312                         if (c[0] != '\0')
313                                 account = strdup(c);
314                 } else if (!strncasecmp(c, "password", 8) &&
315                            (c[8] == '=')) {
316                         c += 9;
317                         if (c[0] != '\0')
318                                 password = strdup(c);
319                 } else if (!strncasecmp(c, "host", 4) &&
320                            (c[4] == '=')) {
321                         c += 5;
322                         if (c[0] != '\0')
323                                 host = strdup(c);
324                 } else if (!strncasecmp(c, "proxy", 5) &&
325                            (c[5] == '=')) {
326                         c += 6;
327                         if (c[0] != '\0')
328                                 proxy = strdup(c);
329                 }
330         } while (!feof(config_file));
331
332         if (password)
333                 session->password = password;
334         if (account)
335                 session->account = account;
336         if (host) {
337                 if (strcasecmp(host, "twitter") == 0)
338                         session->host = HOST_TWITTER;
339                 if (strcasecmp(host, "identica") == 0)
340                         session->host = HOST_IDENTICA;
341                 free(host);
342         }
343         if (proxy) {
344                 if (session->proxy)
345                         free(session->proxy);
346                 session->proxy = proxy;
347         }
348
349         /* Free buffer and close file.  */
350         free(line);
351         fclose(config_file);
352 }
353
354 static void log_session(struct session *session, int retval)
355 {
356         FILE *log_file;
357         char *filename;
358         char *host;
359
360         /* logfile is ~/.bti.log  */
361         filename = alloca(strlen(session->homedir) + 10);
362
363         sprintf(filename, "%s/.bti.log", session->homedir);
364
365         log_file = fopen(filename, "a+");
366         if (log_file == NULL)
367                 return;
368         switch (session->host) {
369         case HOST_TWITTER:
370                 host = "twitter";
371                 break;
372         case HOST_IDENTICA:
373                 host = "identi.ca";
374                 break;
375         default:
376                 host = "unknown";
377                 break;
378         }
379
380         if (retval)
381                 fprintf(log_file, "%s: host=%s tweet failed\n", session->time, host);
382         else
383                 fprintf(log_file, "%s: host=%s tweet=%s\n", session->time, host, session->tweet);
384
385         fclose(log_file);
386 }
387
388 int main(int argc, char *argv[], char *envp[])
389 {
390         static const struct option options[] = {
391                 { "debug", 0, NULL, 'd' },
392                 { "account", 1, NULL, 'a' },
393                 { "password", 1, NULL, 'p' },
394                 { "host", 1, NULL, 'H' },
395                 { "proxy", 1, NULL, 'P' },
396                 { "help", 0, NULL, 'h' },
397                 { "bash", 0, NULL, 'b' },
398                 { "version", 0, NULL, 'v' },
399                 { }
400         };
401         struct session *session;
402         pid_t child;
403         char *tweet;
404         int retval = 0;
405         int option;
406         char *http_proxy;
407         time_t t;
408 #if 0
409         char *pwd = getenv("PWD");
410         char *dir;
411 #endif
412
413         session = session_alloc();
414         if (!session) {
415                 fprintf(stderr, "no more memory...\n");
416                 return -1;
417         }
418
419         /* get the current time so that we can log it later */
420         time(&t);
421         session->time = strdup(ctime(&t));
422         session->time[strlen(session->time)-1] = 0x00;
423
424         session->homedir = strdup(getenv("HOME"));
425
426         curl_global_init(CURL_GLOBAL_ALL);
427
428         /* Set environment variables first, before reading command line options
429          * or config file values. */
430         http_proxy = getenv("http_proxy");
431         if (http_proxy) {
432                 if (session->proxy)
433                         free(session->proxy);
434                 session->proxy = strdup(http_proxy);
435                 dbg("http_proxy = %s\n", session->proxy);
436         }
437
438         parse_configfile(session);
439
440         while (1) {
441                 option = getopt_long_only(argc, argv, "dqe:p:P:H:a:h",
442                                           options, NULL);
443                 if (option == -1)
444                         break;
445                 switch (option) {
446                 case 'd':
447                         debug = 1;
448                         break;
449                 case 'a':
450                         if (session->account)
451                                 free(session->account);
452                         session->account = strdup(optarg);
453                         dbg("account = %s\n", session->account);
454                         break;
455                 case 'p':
456                         if (session->password)
457                                 free(session->password);
458                         session->password = strdup(optarg);
459                         dbg("password = %s\n", session->password);
460                         break;
461                 case 'P':
462                         if (session->proxy)
463                                 free(session->proxy);
464                         session->proxy = strdup(optarg);
465                         dbg("proxy = %s\n", session->proxy);
466                         break;
467                 case 'H':
468                         if (strcasecmp(optarg, "twitter") == 0)
469                                 session->host = HOST_TWITTER;
470                         if (strcasecmp(optarg, "identica") == 0)
471                                 session->host = HOST_IDENTICA;
472                         dbg("host = %d\n", session->host);
473                         break;
474                 case 'b':
475                         session->bash= 1;
476                         break;
477                 case 'h':
478                         display_help();
479                         goto exit;
480                 case 'v':
481                         display_version();
482                         goto exit;
483                 default:
484                         display_help();
485                         goto exit;
486                 }
487         }
488
489         if (!session->account) {
490                 fprintf(stdout, "Enter twitter account: ");
491                 session->account = get_string_from_stdin();
492         }
493
494         if (!session->password) {
495                 fprintf(stdout, "Enter twitter password: ");
496                 session->password = get_string_from_stdin();
497         }
498 #if 0
499         /* get the current working directory basename */
500         if (strcmp(pwd, home) == 0)
501                 dir = "~";
502         else {
503                 dir = strrchr(pwd, '/');
504                 if (dir)
505                         dir++;
506                 else
507                         dir = "?";
508         }
509 #endif
510         tweet = get_string_from_stdin();
511         if (!tweet || strlen(tweet) == 0) {
512                 dbg("no tweet?\n");
513                 return -1;
514         }
515
516 //      session->tweet = zalloc(strlen(tweet) + strlen(dir) + 10);
517         session->tweet = zalloc(strlen(tweet) + 10);
518
519         /* if --bash is specified, add the "PWD $ " to
520          * the start of the tweet. */
521         if (session->bash)
522 //              sprintf(session->tweet, "%s $ %s", dir, tweet);
523                 sprintf(session->tweet, "$ %s", tweet);
524         else
525                 sprintf(session->tweet, "%s", tweet);
526         free(tweet);
527
528         dbg("account = %s\n", session->account);
529         dbg("password = %s\n", session->password);
530         dbg("tweet = %s\n", session->tweet);
531         dbg("host = %d\n", session->host);
532
533         /* fork ourself so that the main shell can get on
534          * with it's life as we try to connect and handle everything
535          */
536         if (session->bash) {
537                 child = fork();
538                         if (child) {
539                         dbg("child is %d\n", child);
540                         exit(0);
541                 }
542         }
543
544         retval = send_tweet(session);
545         if (retval && !session->bash)
546                 fprintf(stderr, "tweet failed\n");
547
548         log_session(session, retval);
549 exit:
550         session_free(session);
551         return retval;;
552 }