29599f50cf5fd4004e625a53f904c607ec4de7c3
[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 <sys/stat.h>
28 #include <curl/curl.h>
29 #include "bti_version.h"
30
31
32 #define zalloc(size)    calloc(size, 1)
33
34 #define dbg(format, arg...)                                             \
35         do {                                                            \
36                 if (debug)                                              \
37                         printf("%s: " format , __func__ , ## arg );     \
38         } while (0)
39
40
41 static int debug = 0;
42
43 struct session {
44         char *password;
45         char *account;
46         char *tweet;
47         int clean;
48 };
49
50 struct bti_curl_buffer {
51         char *data;
52         int length;
53 };
54
55 static void display_help(void)
56 {
57         fprintf(stdout, "bti - send tweet to twitter\n");
58         fprintf(stdout, "Version: " BTI_VERSION "\n");
59         fprintf(stdout, "Usage:\n");
60         fprintf(stdout, "  bti [options]\n");
61         fprintf(stdout, "options are:\n");
62         fprintf(stdout, "  --account accountname\n");
63         fprintf(stdout, "  --password password\n");
64         fprintf(stdout, "  --bash\n");
65         fprintf(stdout, "  --quiet\n");
66         fprintf(stdout, "  --debug\n");
67         fprintf(stdout, "  --help\n");
68 }
69
70 static char *get_string_from_stdin(void)
71 {
72         char *temp;
73         char *string;
74
75         string = zalloc(100);
76         if (!string)
77                 return NULL;
78
79         if (!fgets(string, 99, stdin))
80                 return NULL;
81         temp = strchr(string, '\n');
82         *temp = '\0';
83         return string;
84 }
85
86 static struct session *session_alloc(void)
87 {
88         struct session *session;
89
90         session = zalloc(sizeof(*session));
91         if (!session)
92                 return NULL;
93         return session;
94 }
95
96 static void session_free(struct session *session)
97 {
98         if (!session)
99                 return;
100         free(session->password);
101         free(session->account);
102         free(session->tweet);
103         free(session);
104 }
105
106 static struct bti_curl_buffer *bti_curl_buffer_alloc(void)
107 {
108         struct bti_curl_buffer *buffer;
109
110         buffer = zalloc(sizeof(*buffer));
111         if (!buffer)
112                 return NULL;
113
114         /* start out with a data buffer of 1 byte to
115          * make the buffer fill logic simpler */
116         buffer->data = zalloc(1);
117         if (!buffer->data) {
118                 free(buffer);
119                 return NULL;
120         }
121         buffer->length = 0;
122         return buffer;
123 }
124
125 static void bti_curl_buffer_free(struct bti_curl_buffer *buffer)
126 {
127         if (!buffer)
128                 return;
129         free(buffer->data);
130         free(buffer);
131 }
132
133 static const char *twitter_url = "https://twitter.com/statuses/update.xml";
134
135 static CURL *curl_init(void)
136 {
137         CURL *curl;
138
139         curl = curl_easy_init();
140         if (!curl) {
141                 fprintf(stderr, "Can not init CURL!\n");
142                 return NULL;
143         }
144         /* some ssl sanity checks on the connection we are making */
145         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
146         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
147         return curl;
148 }
149
150 size_t curl_callback(void *buffer, size_t size, size_t nmemb, void *userp)
151 {
152         struct bti_curl_buffer *curl_buf = userp;
153         size_t buffer_size = size * nmemb;
154         char *temp;
155
156         if ((!buffer) || (!buffer_size) || (!curl_buf))
157                 return -EINVAL;
158
159         /* add to the data we already have */
160         temp = zalloc(curl_buf->length + buffer_size + 1);
161         if (!temp)
162                 return -ENOMEM;
163
164         memcpy(temp, curl_buf->data, curl_buf->length);
165         free(curl_buf->data);
166         curl_buf->data = temp;
167         memcpy(&curl_buf->data[curl_buf->length], (char *)buffer, buffer_size);
168         curl_buf->length += buffer_size;
169
170         dbg("%s\n", curl_buf->data);
171
172         return buffer_size;
173 }
174
175 static int send_tweet(struct session *session)
176 {
177         char user_password[500];
178         char data[500];
179         struct bti_curl_buffer *curl_buf;
180         CURL *curl = NULL;
181         CURLcode res;
182         struct curl_httppost *formpost = NULL;
183         struct curl_httppost *lastptr = NULL;
184
185         if (!session)
186                 return -EINVAL;
187
188         curl_buf = bti_curl_buffer_alloc();
189         if (!curl_buf)
190                 return -ENOMEM;
191
192         snprintf(user_password, sizeof(user_password), "%s:%s",
193                  session->account, session->password);
194         snprintf(data, sizeof(data), "status=\"%s\"", session->tweet);
195
196         curl = curl_init();
197         if (!curl)
198                 return -EINVAL;
199
200         curl_formadd(&formpost, &lastptr,
201                      CURLFORM_COPYNAME, "status",
202                      CURLFORM_COPYCONTENTS, session->tweet,
203                      CURLFORM_END);
204
205         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
206         curl_easy_setopt(curl, CURLOPT_URL, twitter_url);
207         if (debug)
208                 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
209         curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
210
211         dbg("user_password = %s\n", user_password);
212         dbg("data = %s\n", data);
213
214         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
215         curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
216         res = curl_easy_perform(curl);
217         if (res) {
218                 printf("error(%d) trying to send tweet\n", res);
219                 return -EINVAL;
220         }
221
222         curl_easy_cleanup(curl);
223         curl_formfree(formpost);
224         bti_curl_buffer_free(curl_buf);
225         return 0;
226 }
227
228 static void parse_configfile(struct session *session)
229 {
230         FILE *config_file;
231         char *line = NULL;
232         size_t len = 0;
233         char *account = NULL;
234         char *password = NULL;
235         char *file;
236         char *home = getenv("HOME");
237
238         /* config file is ~/.bti  */
239         file = alloca(strlen(home) + 7);
240
241         sprintf(file, "%s/.bti", home);
242
243         config_file = fopen(file, "r");
244
245         /* No error if file does not exist or is unreadable.  */
246         if (config_file == NULL)
247                 return;
248
249         do {
250                 ssize_t n = getline(&line, &len, config_file);
251                 if (n < 0)
252                         break;
253                 if (line[n - 1] == '\n')
254                         line[n - 1] = '\0';
255                 /* Parse file.  Format is the usual value pairs:
256                    account=name
257                    passwort=value
258                    # is a comment character
259                 */
260                 *strchrnul(line, '#') = '\0';
261                 char *c = line;
262                 while (isspace(*c))
263                         c++;
264                 /* Ignore blank lines.  */
265                 if (c[0] == '\0')
266                         continue;
267
268                 if (!strncasecmp(c, "account", 7) && (c[7] == '=')) {
269                         c += 8;
270                         if (c[0] != '\0')
271                                 account = strdup(c);
272                 } else if (!strncasecmp(c, "password", 8) &&
273                            (c[8] == '=')) {
274                         c += 9;
275                         if (c[0] != '\0')
276                                 password = strdup(c);
277                 }
278         } while (!feof(config_file));
279
280         if (password)
281                 session->password = password;
282         if (account)
283                 session->account= account;
284
285         /* Free buffer and close file.  */
286         free(line);
287         fclose(config_file);
288 }
289
290 int main(int argc, char *argv[], char *envp[])
291 {
292         static const struct option options[] = {
293                 { "debug", 0, NULL, 'd' },
294                 { "account", 1, NULL, 'a' },
295                 { "password", 1, NULL, 'p' },
296                 { "help", 0, NULL, 'h' },
297                 { "clean", 0, NULL, 'c' },
298                 { "version", 0, NULL, 'v' },
299                 { }
300         };
301         struct session *session;
302         pid_t child;
303         char *tweet;
304         int retval;
305         int option;
306         char *home = getenv("HOME");
307         char *pwd = getenv("PWD");
308         char *dir;
309
310         session = session_alloc();
311         if (!session) {
312                 fprintf(stderr, "no more memory...\n");
313                 return -1;
314         }
315
316         curl_global_init(CURL_GLOBAL_ALL);
317         parse_configfile(session);
318
319         while (1) {
320                 option = getopt_long_only(argc, argv, "dqe:p:a:h",
321                                           options, NULL);
322                 if (option == -1)
323                         break;
324                 switch (option) {
325                 case 'd':
326                         debug = 1;
327                         break;
328                 case 'a':
329                         if (session->account)
330                                 free(session->account);
331                         session->account = strdup(optarg);
332                         dbg("account = %s\n", session->account);
333                         break;
334                 case 'p':
335                         if (session->password)
336                                 free(session->password);
337                         session->password = strdup(optarg);
338                         dbg("password = %s\n", session->password);
339                         break;
340                 case 'c':
341                         session->clean = 1;
342                         break;
343                 case 'h':
344                         display_help();
345                         goto exit;
346                 case 'v':
347                         display_version();
348                         goto exit;
349                 default:
350                         display_help();
351                         goto exit;
352                 }
353         }
354
355         if (!session->account) {
356                 fprintf(stdout, "Enter twitter account: ");
357                 session->account = get_string_from_stdin();
358         }
359
360         if (!session->password) {
361                 fprintf(stdout, "Enter twitter password: ");
362                 session->password = get_string_from_stdin();
363         }
364
365         if (strcmp(pwd, home) == 0)
366                 dir = "~";
367         else {
368                 dir = strrchr(pwd, '/');
369                 if (dir)
370                         dir++;
371                 else
372                         dir = "?";
373         }
374
375         /* Add the "PWD $ " to the start of the tweet to show it is
376          * coming from a shell unless --clean is specified. */
377         tweet = get_string_from_stdin();
378         if (strlen(tweet) == 0) {
379                 dbg("no tweet?\n");
380                 return -1;
381         }
382
383         session->tweet = zalloc(strlen(tweet) + strlen(dir) + 10);
384         if (session->clean)
385                 sprintf(session->tweet, "%s", tweet);
386         else
387                 sprintf(session->tweet, "%s $ %s", dir, tweet);
388         free(tweet);
389
390         dbg("account = %s\n", session->account);
391         dbg("password = %s\n", session->password);
392         dbg("tweet = %s\n", session->tweet);
393
394         /* fork ourself so that the main shell can get on
395          * with it's life as we try to connect and handle everything
396          */
397         child = fork();
398         if (child) {
399                 dbg("child is %d\n", child);
400                 exit(0);
401         }
402
403         retval = send_tweet(session);
404         if (retval) {
405                 fprintf(stderr, "tweet failed\n");
406                 return -1;
407         }
408
409         session_free(session);
410 exit:
411         return 0;
412 }