chiark / gitweb /
Synchronize with disorder.dev
[disorder] / server / actions.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2008 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
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
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20 /** @file server/actions.c
21  * @brief DisOrder web actions
22  *
23  * Actions are anything that the web interface does beyond passive template
24  * expansion and inspection of state recieved from the server.  This means
25  * playing tracks, editing prefs etc but also setting extra headers e.g. to
26  * auto-refresh the playing list.
27  */
28
29 #include "disorder-cgi.h"
30
31 /** @brief Redirect to some other action or URL */
32 static void redirect(const char *url) {
33   /* By default use the 'back' argument */
34   if(!url)
35     url = cgi_get("back");
36   if(url) {
37     if(strncmp(url, "http", 4))
38       /* If the target is not a full URL assume it's the action */
39       url = cgi_makeurl(config->url, "action", url, (char *)0);
40   } else {
41     /* If back= is not set just go back to the front page */
42     url = config->url;
43   }
44   if(printf("Location: %s\n"
45             "%s\n"
46             "\n", url, dcgi_cookie_header()) < 0)
47     fatal(errno, "error writing to stdout");
48 }
49
50 /* 'playing' and 'manage' just add a Refresh: header */
51 static void act_playing(void) {
52   long refresh = config->refresh;
53   long length;
54   time_t now, fin;
55   char *url;
56   const char *action;
57
58   dcgi_lookup(DCGI_PLAYING|DCGI_QUEUE|DCGI_ENABLED|DCGI_RANDOM_ENABLED);
59   if(dcgi_playing
60      && dcgi_playing->state == playing_started /* i.e. not paused */
61      && !disorder_length(dcgi_client, dcgi_playing->track, &length)
62      && length
63      && dcgi_playing->sofar >= 0) {
64     /* Try to put the next refresh at the start of the next track. */
65     time(&now);
66     fin = now + length - dcgi_playing->sofar + config->gap;
67     if(now + refresh > fin)
68       refresh = fin - now;
69   }
70   if(dcgi_queue && dcgi_queue->state == playing_isscratch) {
71     /* next track is a scratch, don't leave more than the inter-track gap */
72     if(refresh > config->gap)
73       refresh = config->gap;
74   }
75   if(!dcgi_playing
76      && ((dcgi_queue
77           && dcgi_queue->state != playing_random)
78          || dcgi_random_enabled)
79      && dcgi_enabled) {
80     /* no track playing but playing is enabled and there is something coming
81      * up, must be in a gap */
82     if(refresh > config->gap)
83       refresh = config->gap;
84   }
85   if((action = cgi_get("action")))
86     url = cgi_makeurl(config->url, "action", action, (char *)0);
87   else
88     url = config->url;
89   if(printf("Refresh: %ld;url=%s\n",
90             refresh, url) < 0)
91     fatal(errno, "error writing to stdout");
92   dcgi_expand("playing", 1);
93 }
94
95 static void act_disable(void) {
96   if(dcgi_client)
97     disorder_disable(dcgi_client);
98   redirect(0);
99 }
100
101 static void act_enable(void) {
102   if(dcgi_client)
103     disorder_enable(dcgi_client);
104   redirect(0);
105 }
106
107 static void act_random_disable(void) {
108   if(dcgi_client)
109     disorder_random_disable(dcgi_client);
110   redirect(0);
111 }
112
113 static void act_random_enable(void) {
114   if(dcgi_client)
115     disorder_random_enable(dcgi_client);
116   redirect(0);
117 }
118
119 static void act_pause(void) {
120   if(dcgi_client)
121     disorder_pause(dcgi_client);
122   redirect(0);
123 }
124
125 static void act_resume(void) {
126   if(dcgi_client)
127     disorder_resume(dcgi_client);
128   redirect(0);
129 }
130
131 static void act_remove(void) {
132   const char *id;
133   struct queue_entry *q;
134
135   if(dcgi_client) {
136     if(!(id = cgi_get("id")))
137       error(0, "missing 'id' argument");
138     else if(!(q = dcgi_findtrack(id)))
139       error(0, "unknown queue id %s", id);
140     else switch(q->state) {
141     case playing_isscratch:
142     case playing_failed:
143     case playing_no_player:
144     case playing_ok:
145     case playing_quitting:
146     case playing_scratched:
147       error(0, "does not make sense to scratch %s", id);
148       break;
149     case playing_paused:                /* started but paused */
150     case playing_started:               /* started to play */
151       disorder_scratch(dcgi_client, id);
152       break;
153     case playing_random:                /* unplayed randomly chosen track */
154     case playing_unplayed:              /* haven't played this track yet */
155       disorder_remove(dcgi_client, id);
156       break;
157     }
158   }
159   redirect(0);
160 }
161
162 static void act_move(void) {
163   const char *id, *delta;
164   struct queue_entry *q;
165
166   if(dcgi_client) {
167     if(!(id = cgi_get("id")))
168       error(0, "missing 'id' argument");
169     else if(!(delta = cgi_get("delta")))
170       error(0, "missing 'delta' argument");
171     else if(!(q = dcgi_findtrack(id)))
172       error(0, "unknown queue id %s", id);
173     else switch(q->state) {
174     case playing_random:                /* unplayed randomly chosen track */
175     case playing_unplayed:              /* haven't played this track yet */
176       disorder_move(dcgi_client, id, atol(delta));
177       break;
178     default:
179       error(0, "does not make sense to scratch %s", id);
180       break;
181     }
182   }
183   redirect(0);
184 }
185
186 static void act_play(void) {
187   const char *track, *dir;
188   char **tracks;
189   int ntracks, n;
190   struct dcgi_entry *e;
191   
192   if(dcgi_client) {
193     if((track = cgi_get("file"))) {
194       disorder_play(dcgi_client, track);
195     } else if((dir = cgi_get("dir"))) {
196       if(disorder_files(dcgi_client, dir, 0, &tracks, &ntracks))
197         ntracks = 0;
198       e = xmalloc(ntracks * sizeof (struct dcgi_entry));
199       for(n = 0; n < ntracks; ++n) {
200         e[n].track = tracks[n];
201         e[n].sort = trackname_transform("track", tracks[n], "sort");
202         e[n].display = trackname_transform("track", tracks[n], "display");
203       }
204       qsort(e, ntracks, sizeof (struct dcgi_entry), dcgi_compare_entry);
205       for(n = 0; n < ntracks; ++n)
206         disorder_play(dcgi_client, e[n].track);
207     }
208   }
209   redirect(0);
210 }
211
212 static int clamp(int n, int min, int max) {
213   if(n < min)
214     return min;
215   if(n > max)
216     return max;
217   return n;
218 }
219
220 static void act_volume(void) {
221   const char *l, *r, *d;
222   int nd;
223
224   if(dcgi_client) {
225     if((d = cgi_get("delta"))) {
226       dcgi_lookup(DCGI_VOLUME);
227       nd = clamp(atoi(d), -255, 255);
228       disorder_set_volume(dcgi_client,
229                           clamp(dcgi_volume_left + nd, 0, 255),
230                           clamp(dcgi_volume_right + nd, 0, 255));
231     } else if((l = cgi_get("left")) && (r = cgi_get("right")))
232       disorder_set_volume(dcgi_client, atoi(l), atoi(r));
233   }
234   redirect(0);
235 }
236
237 /** @brief Expand the login template with @b @@error set to @p error
238  * @param error Error keyword
239  */
240 static void login_error(const char *error) {
241   dcgi_error_string = error;
242   dcgi_expand("login", 1);
243 }
244
245 /** @brief Log in
246  * @param username Login name
247  * @param password Password
248  * @return 0 on success, non-0 on error
249  *
250  * On error, calls login_error() to expand the login template.
251  */
252 static int login_as(const char *username, const char *password) {
253   disorder_client *c;
254
255   if(dcgi_cookie && dcgi_client)
256     disorder_revoke(dcgi_client);
257   /* We'll need a new connection as we are going to stop being guest */
258   c = disorder_new(0);
259   if(disorder_connect_user(c, username, password)) {
260     login_error("loginfailed");
261     return -1;
262   }
263   /* Generate a cookie so we can log in again later */
264   if(disorder_make_cookie(c, &dcgi_cookie)) {
265     login_error("cookiefailed");
266     return -1;
267   }
268   /* Use the new connection henceforth */
269   dcgi_client = c;
270   dcgi_lookup_reset();
271   return 0;                             /* OK */
272 }
273
274 static void act_login(void) {
275   const char *username, *password;
276
277   /* We try all this even if not connected since the subsequent connection may
278    * succeed. */
279   
280   username = cgi_get("username");
281   password = cgi_get("password");
282   if(!username
283      || !password
284      || !strcmp(username, "guest")/*bodge to avoid guest cookies*/) {
285     /* We're just visiting the login page, not performing an action at all. */
286     dcgi_expand("login", 1);
287     return;
288   }
289   if(!login_as(username, password)) {
290     /* Report the succesful login */
291     dcgi_status_string = "loginok";
292     dcgi_expand("login", 1);
293   }
294 }
295
296 static void act_logout(void) {
297   if(dcgi_client) {
298     /* Ask the server to revoke the cookie */
299     if(!disorder_revoke(dcgi_client))
300       dcgi_status_string = "logoutok";
301     else
302       dcgi_error_string = "revokefailed";
303   } else {
304     /* We can't guarantee a logout if we can't connect to the server to revoke
305      * the cookie, so we report an error.  We'll still ask the browser to
306      * forget the cookie though. */
307     dcgi_error_string = "connect";
308   }
309   /* Attempt to reconnect without the cookie */
310   dcgi_cookie = 0;
311   dcgi_login();
312   /* Back to login page, hopefuly forcing the browser to forget the cookie. */
313   dcgi_expand("login", 1);
314 }
315
316 static void act_register(void) {
317   const char *username, *password, *password2, *email;
318   char *confirm, *content_type;
319   const char *text, *encoding, *charset;
320
321   /* If we're not connected then this is a hopeless exercise */
322   if(!dcgi_client) {
323     login_error("connect");
324     return;
325   }
326
327   /* Collect arguments */
328   username = cgi_get("username");
329   password = cgi_get("password1");
330   password2 = cgi_get("password2");
331   email = cgi_get("email");
332
333   /* Verify arguments */
334   if(!username || !*username) {
335     login_error("nousername");
336     return;
337   }
338   if(!password || !*password) {
339     login_error("nopassword");
340     return;
341   }
342   if(!password2 || !*password2 || strcmp(password, password2)) {
343     login_error("passwordmismatch");
344     return;
345   }
346   if(!email || !*email) {
347     login_error("noemail");
348     return;
349   }
350   /* We could well do better address validation but for now we'll just do the
351    * minimum */
352   if(!strchr(email, '@')) {
353     login_error("bademail");
354     return;
355   }
356   if(disorder_register(dcgi_client, username, password, email, &confirm)) {
357     login_error("cannotregister");
358     return;
359   }
360   /* Send the user a mail */
361   /* TODO templatize this */
362   byte_xasprintf((char **)&text,
363                  "Welcome to DisOrder.  To active your login, please visit this URL:\n"
364                  "\n"
365                  "%s?c=%s\n", config->url, urlencodestring(confirm));
366   if(!(text = mime_encode_text(text, &charset, &encoding)))
367     fatal(0, "cannot encode email");
368   byte_xasprintf(&content_type, "text/plain;charset=%s",
369                  quote822(charset, 0));
370   sendmail("", config->mail_sender, email, "Welcome to DisOrder",
371            encoding, content_type, text); /* TODO error checking  */
372   /* We'll go back to the login page with a suitable message */
373   dcgi_status_string = "registered";
374   dcgi_expand("login", 1);
375 }
376
377 static void act_confirm(void) {
378   const char *confirmation;
379
380   /* If we're not connected then this is a hopeless exercise */
381   if(!dcgi_client) {
382     login_error("connect");
383     return;
384   }
385
386   if(!(confirmation = cgi_get("c"))) {
387     login_error("noconfirm");
388     return;
389   }
390   /* Confirm our registration */
391   if(disorder_confirm(dcgi_client, confirmation)) {
392     login_error("badconfirm");
393     return;
394   }
395   /* Get a cookie */
396   if(disorder_make_cookie(dcgi_client, &dcgi_cookie)) {
397     login_error("cookiefailed");
398     return;
399   }
400   /* Junk cached data */
401   dcgi_lookup_reset();
402   /* Report success */
403   dcgi_status_string = "confirmed";
404   dcgi_expand("login", 1);
405 }
406
407 static void act_edituser(void) {
408   const char *email = cgi_get("email"), *password = cgi_get("changepassword1");
409   const char *password2 = cgi_get("changepassword2");
410   int newpassword = 0;
411
412   /* If we're not connected then this is a hopeless exercise */
413   if(!dcgi_client) {
414     login_error("connect");
415     return;
416   }
417
418   /* Verify input */
419
420   /* If either password or password2 is set we insist they match.  If they
421    * don't we report an error. */
422   if((password && *password) || (password2 && *password2)) {
423     if(!password || !password2 || strcmp(password, password2)) {
424       login_error("passwordmismatch");
425       return;
426     }
427   } else
428     password = password2 = 0;
429   if(email && !strchr(email, '@')) {
430     login_error("bademail");
431     return;
432   }
433
434   /* Commit changes */
435   if(email) {
436     if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
437                          "email", email)) {
438       login_error("badedit");
439       return;
440     }
441   }
442   if(password) {
443     if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
444                          "password", password)) {
445       login_error("badedit");
446       return;
447     }
448     newpassword = 1;
449   }
450
451   if(newpassword) {
452     /* If we changed the password, the cookie is now invalid, so we must log
453      * back in. */
454     if(login_as(disorder_user(dcgi_client), password))
455       return;
456   }
457   /* Report success */
458   dcgi_status_string = "edited";
459   dcgi_expand("login", 1);
460 }
461
462 static void act_reminder(void) {
463   const char *const username = cgi_get("username");
464
465   /* If we're not connected then this is a hopeless exercise */
466   if(!dcgi_client) {
467     login_error("connect");
468     return;
469   }
470
471   if(!username || !*username) {
472     login_error("nousername");
473     return;
474   }
475   if(disorder_reminder(dcgi_client, username)) {
476     login_error("reminderfailed");
477     return;
478   }
479   /* Report success */
480   dcgi_status_string = "reminded";
481   dcgi_expand("login", 1);
482 }
483
484 /** @brief Table of actions */
485 static const struct action {
486   /** @brief Action name */
487   const char *name;
488   /** @brief Action handler */
489   void (*handler)(void);
490 } actions[] = {
491   { "confirm", act_confirm },
492   { "disable", act_disable },
493   { "edituser", act_edituser },
494   { "enable", act_enable },
495   { "login", act_login },
496   { "logout", act_logout },
497   { "manage", act_playing },
498   { "move", act_move },
499   { "pause", act_pause },
500   { "play", act_play },
501   { "playing", act_playing },
502   { "randomdisable", act_random_disable },
503   { "randomenable", act_random_enable },
504   { "register", act_register },
505   { "reminder", act_reminder },
506   { "remove", act_remove },
507   { "resume", act_resume },
508   { "volume", act_volume },
509 };
510
511 /** @brief Check that an action name is valid
512  * @param name Action
513  * @return 1 if valid, 0 if not
514  */
515 static int dcgi_valid_action(const char *name) {
516   int c;
517
518   /* First character must be letter or digit (this also requires there to _be_
519    * a first character) */
520   if(!isalnum((unsigned char)*name))
521     return 0;
522   /* Only letters, digits, '.' and '-' allowed */
523   while((c = (unsigned char)*name++)) {
524     if(!(isalnum(c)
525          || c == '.'
526          || c == '_'))
527       return 0;
528   }
529   return 1;
530 }
531
532 /** @brief Expand a template
533  * @param name Base name of template, or NULL to consult CGI args
534  * @param header True to write header
535  */
536 void dcgi_expand(const char *name, int header) {
537   const char *p, *found;
538
539   /* Parse macros first */
540   if((found = mx_find("macros.tmpl")))
541     mx_expand_file(found, sink_discard(), 0);
542   /* For unknown actions check that they aren't evil */
543   if(!dcgi_valid_action(name))
544     fatal(0, "invalid action name '%s'", name);
545   byte_xasprintf((char **)&p, "%s.tmpl", name);
546   if(!(found = mx_find(p)))
547     fatal(errno, "cannot find %s", p);
548   if(header) {
549     if(printf("Content-Type: text/html\n"
550               "%s\n"
551               "\n", dcgi_cookie_header()) < 0)
552       fatal(errno, "error writing to stdout");
553   }
554   if(mx_expand_file(found, sink_stdio("stdout", stdout), 0) == -1
555      || fflush(stdout) < 0)
556     fatal(errno, "error writing to stdout");
557 }
558
559 /** @brief Execute a web action
560  * @param action Action to perform, or NULL to consult CGI args
561  *
562  * If no recognized action is specified then 'playing' is assumed.
563  */
564 void dcgi_action(const char *action) {
565   int n;
566
567   /* Consult CGI args if caller had no view */
568   if(!action)
569     action = cgi_get("action");
570   /* Pick a default if nobody cares at all */
571   if(!action) {
572     /* We allow URLs which are just c=... in order to keep confirmation URLs,
573      * which are user-facing, as short as possible.  Actually we could lose the
574      * c= for this... */
575     if(cgi_get("c"))
576       action = "confirm";
577     else
578       action = "playing";
579     /* Make sure 'action' is always set */
580     cgi_set("action", action);
581   }
582   if((n = TABLE_FIND(actions, struct action, name, action)) >= 0)
583     /* Its a known action */
584     actions[n].handler();
585   else {
586     /* Just expand the template */
587     dcgi_expand(action, 1/*header*/);
588   }
589 }
590
591 /** @brief Generate an error page */
592 void dcgi_error(const char *key) {
593   dcgi_error_string = xstrdup(key);
594   dcgi_expand("error", 1);
595 }
596
597 /*
598 Local Variables:
599 c-basic-offset:2
600 comment-column:40
601 fill-column:79
602 indent-tabs-mode:nil
603 End:
604 */