rename DB_READ, DB_WRITE to AFS_READ, AFS_WRITE
[paraslash.git] / mysql_selector.c
1 /*
2  * Copyright (C) 1999-2007 Andre Noll <maan@systemlinux.org>
3  *
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  *
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  *
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 /** \file mysql_selector.c para_server's mysql-based audio file selector */
20
21 /** \cond some internal constants */
22 #define MEDIUM_BLOB_SIZE 16777220 /*  (2**24 + 4) */
23 #define BLOB_SIZE 65539 /* (2**16 + 3) */
24 /** \endcond */
25 #include "server.cmdline.h"
26 #include "server.h"
27 #include "vss.h"
28 #include "afs.h"
29 #include <mysql/mysql.h>
30 #include <mysql/mysql_version.h>
31 #include <regex.h>
32 #include "error.h"
33 #include "net.h"
34 #include "string.h"
35 #include "user_list.h"
36 #include "mysql_selector_command_list.h"
37
38 /** pointer to the shared memory area */
39 extern struct misc_meta_data *mmd;
40
41 static void *mysql_ptr = NULL;
42
43 /**
44  * contains name/replacement pairs used by s_a_r_list()
45  *
46  * \sa s_a_r()
47  */
48 struct para_macro {
49         /** the name of the macro */
50         const char *name;
51         /** the replacement text */
52         const char *replacement;
53 };
54
55 static struct para_macro macro_list[] = {
56         {       .name = "IS_N_SET",
57                 .replacement = "(data.%s != '1')"
58         }, {
59                 .name = "IS_SET",
60                 .replacement = "(data.%s = '1')"
61         }, {
62                 .name = "PICID",
63                 .replacement = "%sdata.Pic_Id"
64         }, {
65                 .name = "NAME_LIKE",
66                 .replacement = "(data.name like '%s')"
67         }, {
68                 .name = "LASTPLAYED",
69                 .replacement = "%sFLOOR((UNIX_TIMESTAMP(now())"
70                         "-UNIX_TIMESTAMP(data.Lastplayed))/60)"
71         }, {
72                 .name = "NUMPLAYED",
73                 .replacement = "%sdata.Numplayed"
74         }, {
75                 .name = NULL,
76         }
77 };
78
79 /**
80  * simple search and replace routine
81  *
82  * \param src source string
83  * \param macro_name the name of the macro
84  * \param replacement the replacement format string
85  *
86  * In \p src, replace each occurence of \p macro_name(arg) by the string
87  * determined by the \p replacement format string. \p replacement may (but
88  * needs not) contain a single string conversion specifier (%s) which gets
89  * replaced by \p arg.
90  *
91  * \return A string in which all matches in \p src are replaced, or \p NULL if
92  * an syntax error was encountered. Caller must free the result.
93  *
94  * \sa regcomp(3)
95  */
96 __must_check __malloc static char *s_a_r(const char *src, const char* macro_name,
97                 const char *replacement)
98 {
99         regex_t preg;
100         size_t  nmatch = 1;
101         regmatch_t pmatch[1];
102         int eflags = 0;
103         char *dest = NULL;
104         const char *bufptr = src;
105
106         if (!macro_name || !replacement || !src)
107                 return para_strdup(src);
108         regcomp(&preg, macro_name, 0);
109         while (regexec(&preg,  bufptr, nmatch, pmatch, eflags)
110                         != REG_NOMATCH) {
111                 char *tmp, *arg, *o_bracket, *c_bracket;
112
113                 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
114                 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
115                 if (!c_bracket)
116                         goto out;
117                 tmp = para_strdup(bufptr);
118                 tmp[pmatch[0].rm_so] = '\0';
119                 dest = para_strcat(dest, tmp);
120                 free(tmp);
121
122                 arg = para_strdup(o_bracket + 1);
123                 arg[c_bracket - o_bracket - 1] = '\0';
124                 tmp = make_message(replacement, arg);
125                 free(arg);
126                 dest = para_strcat(dest, tmp);
127                 free(tmp);
128                 bufptr = c_bracket;
129                 bufptr++;
130         }
131         dest = para_strcat(dest, bufptr);
132 //      PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
133 out:
134         regfree(&preg);
135         return dest;
136 }
137
138 /**
139  * replace a string according to a list of macros
140  *
141  * \param macro_list the array containing a macro/replacement pairs.
142  * \param src the source string
143  *
144  * This function just calls s_a_r() for each element of \p macro_list.
145  *
146  * \return \p NULL if one of the underlying calls to \p s_a_r returned \p NULL.
147  * Otherwise the completely expanded version of \p src is returned.
148  */
149 __must_check __malloc static char *s_a_r_list(struct para_macro *macro_list, char *src)
150 {
151         struct para_macro *mp = macro_list;
152         char *ret = NULL, *tmp = para_strdup(src);
153
154         while (mp->name) {
155                 ret = s_a_r(tmp, mp->name, mp->replacement);
156                 free(tmp);
157                 if (!ret) /* syntax error */
158                         return NULL;
159                 tmp = ret;
160                 mp++;
161         }
162         //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
163         return ret;
164 }
165
166 static int real_query(const char *query)
167 {
168         if (!mysql_ptr)
169                 return -E_NOTCONN;
170         PARA_DEBUG_LOG("%s\n", query);
171         if (mysql_real_query(mysql_ptr, query, strlen(query))) {
172                 PARA_ERROR_LOG("real_query error (%s)\n",
173                         mysql_error(mysql_ptr));
174                 return -E_QFAILED;
175         }
176         return 1;
177 }
178
179 /*
180  * Use open connection given by mysql_ptr to query server. Returns a
181  * result pointer on succes and NULL on errors
182  */
183 static struct MYSQL_RES *get_result(const char *query)
184 {
185         void *result;
186
187         if (real_query(query) < 0)
188                 return NULL;
189         result = mysql_store_result(mysql_ptr);
190         if (!result)
191                 PARA_ERROR_LOG("%s", "store_result error\n");
192         return result;
193 }
194 /*
195  * write input from fd to dynamically allocated char array,
196  * but maximal max_size byte. Return size.
197  */
198 static int fd2buf(int fd, char **buf_ptr, size_t max_size)
199 {
200         const size_t chunk_size = 1024;
201         size_t size = 2048;
202         char *buf = para_malloc(size * sizeof(char)), *p = buf;
203         int ret;
204
205         while ((ret = recv_bin_buffer(fd, p, chunk_size)) > 0) {
206                 p += ret;
207                 if ((p - buf) + chunk_size >= size) {
208                         char *tmp;
209
210                         size *= 2;
211                         if (size > max_size) {
212                                 ret = -E_TOOBIG;
213                                 goto out;
214                         }
215                         tmp = para_realloc(buf, size);
216                         p = (p - buf) + tmp;
217                         buf = tmp;
218                 }
219         }
220         if (ret < 0)
221                 goto out;
222         *buf_ptr = buf;
223         ret = p - buf;
224 out:
225         if (ret < 0 && buf)
226                 free(buf);
227         return ret;
228 }
229
230 static char *escape_blob(const char* old, int size)
231 {
232         char *new;
233
234         if (!mysql_ptr || size < 0)
235                 return NULL;
236         new = para_malloc(2 * size * sizeof(char) + 1);
237         mysql_real_escape_string(mysql_ptr, new, old, size);
238         return new;
239 }
240
241 static char *escape_str(const char* old)
242 {
243         return escape_blob(old, strlen(old));
244 }
245
246 static char *escaped_basename(const char *name)
247 {
248         char *esc, *bn = para_basename(name);
249
250         if (!bn)
251                 return NULL;
252         esc = escape_str(bn);
253         free(bn);
254         return esc;
255 }
256
257 /*
258  * new attribute
259  */
260 int com_na(__a_unused int fd, int argc, char *argv[])
261 {
262         char *q, *tmp;
263         int ret;
264
265         if (argc < 2)
266                 return -E_MYSQL_SYNTAX;
267         tmp = escape_str(argv[1]);
268         if (!tmp)
269                 return -E_ESCAPE;
270         q = make_message("alter table data add %s char(1) "
271                 "not null default 0", tmp);
272         free(tmp);
273         ret = real_query(q);
274         free(q);
275         return ret;
276 }
277
278 /*
279  * delete attribute
280  */
281 int com_da(__a_unused int fd, int argc, char *argv[])
282 {
283         char *q, *tmp;
284         int ret;
285
286         if (argc < 2)
287                 return -E_MYSQL_SYNTAX;
288         tmp = escape_str(argv[1]);
289         if (!tmp)
290                 return -E_ESCAPE;
291         q = make_message("alter table data drop %s", tmp);
292         free(tmp);
293         ret = real_query(q);
294         free(q);
295         return ret;
296 }
297
298 /* stradd/pic_add */
299 static int com_stradd_picadd(int fd, int argc, char *argv[])
300 {
301         char *blob = NULL, *esc_blob = NULL, *q = NULL, *tmp = NULL;
302         const char *fmt, *del_fmt;
303         int ret, stradd = strcmp(argv[0], "picadd");
304         size_t size;
305
306         if (argc < 2)
307                 return -E_MYSQL_SYNTAX;
308         if (strlen(argv[1]) >= MAXLINE - 1)
309                 return -E_NAMETOOLONG;
310         if (!mysql_ptr)
311                 return -E_NOTCONN;
312         if (stradd) {
313                 size = BLOB_SIZE;
314                 fmt = "insert into streams (name, def) values ('%s','%s')";
315                 del_fmt="delete from streams where name='%s'";
316         } else {
317                 size = MEDIUM_BLOB_SIZE;
318                 fmt = "insert into pics (name, pic) values ('%s','%s')";
319                 del_fmt="delete from pics where pic='%s'";
320         }
321         tmp = escape_str(argv[1]);
322         if (!tmp)
323                 return -E_ESCAPE;
324         q = make_message(del_fmt, tmp);
325         free(tmp);
326         ret = real_query(q);
327         free(q);
328         if (ret < 0)
329                 return ret;
330         if ((ret = send_buffer(fd, AWAITING_DATA_MSG) < 0))
331                 return ret;
332         if ((ret = fd2buf(fd, &blob, size)) < 0)
333                 return ret;
334         size = ret;
335         if (stradd)
336                 blob[size] = '\0';
337         ret = -E_ESCAPE;
338         esc_blob = escape_blob(blob, size);
339         if (!esc_blob)
340                 goto out;
341         tmp = escape_str(argv[1]);
342         if (!tmp)
343                 goto out;
344         q = make_message(fmt, tmp, esc_blob);
345         ret = real_query(q);
346 out:
347         free(blob);
348         free(esc_blob);
349         free(tmp);
350         free(q);
351         return ret;
352 }
353
354 /* stradd */
355 int com_stradd(int fd, int argc, char *argv[])
356 {
357         return com_stradd_picadd(fd, argc, argv);
358 }
359
360 /* pic_add */
361 int com_picadd(int fd, int argc, char *argv[])
362 {
363         return com_stradd_picadd(fd, argc, argv);
364 }
365
366 /*
367  * print results to fd
368  */
369 static int print_results(int fd, void *result,
370                 unsigned int top, unsigned int left,
371                 unsigned int bottom, unsigned int right)
372 {
373         unsigned int i,j;
374         int ret;
375         MYSQL_ROW row;
376
377         for (i = top; i <= bottom; i++) {
378                 row = mysql_fetch_row(result);
379                 if (!row || !row[0])
380                         return -E_NOROW;
381                 for (j = left; j <= right; j++) {
382                         ret = send_va_buffer(fd, j == left? "%s" : "\t%s",
383                                         row[j]?  row[j] : "NULL");
384                         if (ret < 0)
385                                 return ret;
386                 }
387                 ret = send_buffer(fd, "\n");
388                 if (ret < 0)
389                         return ret;
390         }
391         return 0;
392 }
393
394 /*
395  * verbatim
396  */
397 int com_verb(int fd, int argc, char *argv[])
398 {
399         void *result = NULL;
400         int ret;
401         unsigned int num_rows, num_fields;
402         char *tmp;
403
404         if (argc < 2)
405                 return -E_MYSQL_SYNTAX;
406         tmp = escape_str(argv[1]);
407         if (!tmp)
408                 return -E_ESCAPE;
409         result = get_result(tmp);
410         free(tmp);
411         if (!result)
412                 /* return success, because it's ok to have no results */
413                 return 1;
414         num_fields = mysql_field_count(mysql_ptr);
415         num_rows = mysql_num_rows(result);
416         ret = 1;
417         if (num_fields && num_rows)
418                 ret = print_results(fd, result, 0, 0, num_rows - 1,
419                         num_fields - 1);
420         mysql_free_result(result);
421         return ret;
422 }
423
424 /* returns NULL on errors or if there are no atts defined yet */
425 static void *get_all_attributes(void)
426 {
427         void *result = get_result("desc data");
428         unsigned int num_rows;
429
430         if (!result)
431                 return NULL;
432         num_rows = mysql_num_rows(result);
433         if (num_rows < 5) {
434                 mysql_free_result(result);
435                 return NULL;
436         }
437         mysql_data_seek(result, 4); /* skip Lastplayed, Numplayed... */
438         return result;
439 }
440
441 /*
442  * list all attributes
443  */
444 int com_laa(int fd, int argc, __a_unused char *argv[])
445 {
446         void *result;
447         int ret;
448
449         if (argc != 1)
450                 return -E_MYSQL_SYNTAX;
451         result = get_all_attributes();
452         if (!result)
453                 return -E_NOATTS;
454         ret = print_results(fd, result, 0, 0, mysql_num_rows(result) - 5, 0);
455         mysql_free_result(result);
456         return ret;
457 }
458
459 /*
460  * history
461  */
462 int com_hist(int fd, int argc, char *argv[])
463 {
464         int ret;
465         void *result = NULL;
466         char *q, *atts;
467         unsigned int num_rows;
468
469         if (argc > 3)
470                 return -E_MYSQL_SYNTAX;
471         if (argc > 1) {
472                 char *tmp = escape_str(argv[1]);
473                 if (!tmp)
474                         return -E_ESCAPE;
475                 atts = make_message("where %s = '1'", tmp);
476                 free(tmp);
477         } else
478                 atts = para_strdup(NULL);
479
480         q = make_message("select name, to_days(now()) - to_days(lastplayed) from "
481                 "data %s order by lastplayed", atts);
482         free(atts);
483         result = get_result(q);
484         free(q);
485         if (!result)
486                 return -E_NORESULT;
487         num_rows = mysql_num_rows(result);
488         ret = 1;
489         if (num_rows)
490                 ret = print_results(fd, result, 0, 0, num_rows - 1, 1);
491         mysql_free_result(result);
492         return ret;
493 }
494
495 /*
496  * get last num audio files
497  */
498 int com_last(int fd, int argc, char *argv[])
499 {
500         void *result = NULL;
501         char *q;
502         int num, ret;
503
504         if (argc < 2)
505                 num = 10;
506         else
507                 num = atoi(argv[1]);
508         if (!num)
509                 return -E_MYSQL_SYNTAX;
510         q = make_message("select name from data order by lastplayed desc "
511                 "limit %u", num);
512         result = get_result(q);
513         free(q);
514         if (!result)
515                 return -E_NORESULT;
516         ret = print_results(fd, result, 0, 0, mysql_num_rows(result) - 1, 0);
517         mysql_free_result(result);
518         return ret;
519 }
520
521 int com_mbox(int fd, int argc, char *argv[])
522 {
523         void *result;
524         MYSQL_ROW row;
525         int ret;
526         unsigned int num_rows, num_fields;
527         char *query = para_strdup("select concat('From foo@localhost ', "
528                 "date_format(Lastplayed, '%a %b %e %T %Y'), "
529                 "'\nReceived: from\nTo: bar\n");
530
531         ret = -E_NOATTS;
532         result = get_all_attributes();
533         if (!result)
534                 goto out;
535         ret = -E_NOROW;
536         while ((row = mysql_fetch_row(result))) {
537                 char *tmp;
538
539                 if (!row[0])
540                         goto out;
541                 tmp = make_message("%sX-Attribute-%s: ', %s, '\n", query,
542                         row[0], row[0]);
543                 free(query);
544                 query = tmp;
545         }
546         query = para_strcat(query,
547                 "From: a\n"
548                 "Subject: "
549                 "', name, '"
550                 "\n\n\n"
551                 "') from data"
552         );
553         if (argc >= 2) {
554                 char *esc = escape_str(argv[1]), *tmp;
555                 ret = -E_ESCAPE;
556                 if (!esc)
557                         goto out;
558                 tmp = make_message("%s where name LIKE '%s'", query, esc);
559                 free(esc);
560                 free(query);
561                 query = tmp;
562         }
563         mysql_free_result(result);
564         ret = -E_NORESULT;
565         result = get_result(query);
566         if (!result)
567                 goto out;
568         ret = -E_EMPTY_RESULT;
569         num_fields = mysql_field_count(mysql_ptr);
570         num_rows = mysql_num_rows(result);
571         if (!num_fields || !num_rows)
572                 goto out;
573         ret = print_results(fd, result, 0, 0, num_rows - 1, num_fields - 1);
574 out:
575         free(query);
576         if (result)
577                 mysql_free_result(result);
578         return ret;
579 }
580
581 /*
582  * get attributes by name. If verbose is not 0, this function returns a string
583  * of the form 'att1="0",att2="1"'... which is used in com_cam() for
584  * constructing a mysql update query. Otherwise the space-separated list of all
585  * attributes which are set in the audio file given by name is returned.  Never
586  * returns NULL in *NON VERBOSE* mode.
587  */
588 static char *get_atts(char *name, int verbose)
589 {
590         char *atts = NULL, *buf, *ebn;
591         void *result = NULL, *result2 = NULL;
592         MYSQL_ROW row, row2;
593         int i;
594         unsigned num_fields;
595
596         result2 = get_all_attributes();
597         if (!result2)
598                 goto out;
599         ebn = escaped_basename(name);
600         if (!ebn)
601                 goto out;
602         buf = make_message("select * from data where name='%s'", ebn);
603         free(ebn);
604         result = get_result(buf);
605         free(buf);
606         if (!result)
607                 goto out;
608         num_fields = mysql_num_fields(result);
609         if (num_fields < 5)
610                 goto out;
611         mysql_data_seek(result2, 4); /* skip Lastplayed, Numplayed... */
612         row = mysql_fetch_row(result);
613         if (!row)
614                 goto out;
615         for (i = 4; i < num_fields; i++) {
616                 int is_set = row[i] && !strcmp(row[i], "1");
617                 row2 = mysql_fetch_row(result2);
618                 if (!row2 || !row2[0])
619                         goto out;
620                 if (atts && (verbose || is_set))
621                         atts = para_strcat(atts, verbose? "," : " ");
622                 if (is_set || verbose)
623                         atts = para_strcat(atts, row2[0]);
624                 if (verbose)
625                         atts = para_strcat(atts, is_set? "=\"1\"" : "=\"0\"");
626         }
627 out:
628         if (result2)
629                 mysql_free_result(result2);
630         if (result)
631                 mysql_free_result(result);
632         if (!atts && !verbose)
633                 atts = para_strdup("(none)");
634         return atts;
635 }
636
637 /* never returns NULL in verbose mode */
638 static char *get_meta(char *name, int verbose)
639 {
640         MYSQL_ROW row;
641         void *result = NULL;
642         char *ebn, *q, *ret = NULL;
643         const char *verbose_fmt =
644                 "select concat('lastplayed: ', "
645                 "(to_days(now()) - to_days(lastplayed)),"
646                 "' day(s). numplayed: ', numplayed, "
647                 "', pic: ', pic_id) "
648                 "from data where name = '%s'";
649         /* is that really needed? */
650         const char *fmt = "select concat('lastplayed=\\'', lastplayed, "
651                 "'\\', numplayed=\\'', numplayed, "
652                 "'\\', pic_id=\\'', pic_id, '\\'') "
653                 "from data where name = '%s'";
654
655         if (!(ebn = escaped_basename(name)))
656                 goto out;
657         q = make_message(verbose? verbose_fmt : fmt, ebn);
658         free(ebn);
659         result = get_result(q);
660         free(q);
661         if (!result)
662                 goto out;
663         row = mysql_fetch_row(result);
664         if (!row || !row[0])
665                 goto out;
666         ret = para_strdup(row[0]);
667 out:
668         if (result)
669                 mysql_free_result(result);
670         if (!ret && verbose)
671                 ret = para_strdup("(not yet played)");
672         return ret;
673 }
674
675 static char *get_dir(char *name)
676 {
677         char *ret = NULL, *q, *ebn;
678         void *result;
679         MYSQL_ROW row;
680
681         if (!(ebn = escaped_basename(name)))
682                 return NULL;
683         q = make_message("select dir from dir where name = '%s'", ebn);
684         free(ebn);
685         result = get_result(q);
686         free(q);
687         if (!result)
688                 return NULL;
689         row = mysql_fetch_row(result);
690         if (row && row[0])
691                 ret = para_strdup(row[0]);
692         mysql_free_result(result);
693         return ret;
694 }
695
696 /* never returns NULL */
697 static char *get_current_stream(void)
698 {
699         char *ret;
700         MYSQL_ROW row;
701         void *result = get_result("select def from streams where "
702                 "name = 'current_stream'");
703
704         if (!result)
705                 goto err_out;
706         row = mysql_fetch_row(result);
707         if (!row || !row[0])
708                 goto err_out;
709         ret = para_strdup(row[0]);
710         mysql_free_result(result);
711         return ret;
712 err_out:
713         if (result)
714                 mysql_free_result(result);
715         return para_strdup("(none)");
716 }
717
718 /*
719  * Read stream definition of stream streamname and construct mysql
720  * query. Return NULL on errors. If streamname is NULL, use current
721  * stream. If that is also NULL, use query that selects everything.
722  * If filename is NULL, query will list everything, otherwise only
723  * the score of given file.
724  */
725 static char *get_query(char *streamname, char *filename, int with_path)
726 {
727         char *accept_opts = NULL, *deny_opts = NULL, *score = NULL;
728         char *where_clause, *order, *query;
729         char command[255] = ""; /* buffer for sscanf */
730         void *result;
731         MYSQL_ROW row;
732         char *end, *tmp;
733         char *select_clause = NULL;
734         if (!streamname)
735                 tmp = get_current_stream();
736         else {
737                 tmp = escape_str(streamname);
738                 if (!tmp)
739                         return NULL;
740         }
741         if (!strcmp(tmp, "(none)")) {
742                 free(tmp);
743                 if (filename) {
744                         char *ret, *ebn = escaped_basename(filename);
745                         if (!ebn)
746                                 return NULL;
747                         ret = make_message("select to_days(now()) - "
748                                 "to_days(lastplayed) from data "
749                                 "where name = '%s'", ebn);
750                         free(ebn);
751                         return ret;
752                 }
753                 if (with_path)
754                         return make_message(
755                                 "select concat(dir.dir, '/', dir.name) "
756                                 "from data, dir where dir.name = data.name "
757                                 "order by data.lastplayed"
758                         );
759                 return make_message(
760                         "select name from data where name is not NULL "
761                         "order by lastplayed"
762                 );
763         }
764         free(tmp);
765         query = make_message("select def from streams where name = '%s'",
766                 streamname);
767         result = get_result(query);
768         free(query);
769         query = NULL;
770         if (!result)
771                 goto out;
772         row = mysql_fetch_row(result);
773         if (!row || !row[0])
774                 goto out;
775         end = row[0];
776         while (*end) {
777                 int n;
778                 char *arg, *line = end;
779
780                 if (!(end = strchr(line, '\n')))
781                         break;
782                 *end = '\0';
783                 end++;
784                 if (sscanf(line, "%200s%n", command, &n) < 1)
785                         continue;
786                 arg = line + n;
787                 if (!strcmp(command, "accept:")) {
788                         char *tmp2 = s_a_r_list(macro_list, arg);
789                         if (accept_opts)
790                                 accept_opts = para_strcat(
791                                         accept_opts, " or ");
792                         accept_opts = para_strcat(accept_opts, tmp2);
793                         free(tmp2);
794                         continue;
795                 }
796                 if (!strcmp(command, "deny:")) {
797                         char *tmp2 = s_a_r_list(macro_list, arg);
798                         if (deny_opts)
799                                 deny_opts = para_strcat(deny_opts, " or ");
800                         deny_opts = para_strcat(deny_opts, tmp2);
801                         free(tmp2);
802                         continue;
803                 }
804                 if (!score && !strcmp(command, "score:"))
805                         score = s_a_r_list(macro_list, arg);
806         }
807         if (!score) {
808                 score = s_a_r_list(macro_list, conf.mysql_default_score_arg);
809                 if (!score)
810                         goto out;
811         }
812         if (filename) {
813                 char *ebn = escaped_basename(filename);
814                 if (!ebn)
815                         goto out;
816                 select_clause = make_message("select %s from data ", score);
817                 free(score);
818                 where_clause = make_message( "where name = '%s' ", ebn);
819                 free(ebn);
820                 order = para_strdup("");
821                 goto write_query;
822         }
823         select_clause = para_strdup(with_path?
824                 "select concat(dir.dir, '/', dir.name) from data, dir "
825                 "where dir.name = data.name "
826                 :
827                 "select name from data where name is not NULL");
828         order = make_message("order by -(%s)", score);
829         free(score);
830         if (accept_opts && deny_opts) {
831                 where_clause = make_message("and ((%s) and not (%s)) ",
832                         accept_opts, deny_opts);
833                 goto write_query;
834         }
835         if (accept_opts && !deny_opts) {
836                 where_clause = make_message("and (%s) ", accept_opts);
837                 goto write_query;
838         }
839         if (!accept_opts && deny_opts) {
840                 where_clause = make_message("and not (%s) ", deny_opts);
841                 goto write_query;
842         }
843         where_clause = para_strdup("");
844 write_query:
845         query = make_message("%s %s %s", select_clause, where_clause, order);
846         free(order);
847         free(select_clause);
848         free(where_clause);
849 out:
850         if (accept_opts)
851                 free(accept_opts);
852         if (deny_opts)
853                 free(deny_opts);
854         if (result)
855                 mysql_free_result(result);
856         return query;
857 }
858
859
860
861 /*
862  * This is called from server and from some commands. Name must not be NULL
863  * Never returns NULL.
864  */
865 static char *get_selector_info(char *name)
866 {
867         char *meta, *atts, *info, *dir, *query, *stream;
868         void *result = NULL;
869         MYSQL_ROW row = NULL;
870
871         if (!name)
872                 return para_strdup("(none)");
873         stream = get_current_stream();
874         meta = get_meta(name, 1);
875         atts = get_atts(name, 0);
876         dir = get_dir(name);
877         /* get score */
878         query = get_query(stream, name, 0); /* FIXME: pass stream == NULL instead? */
879         if (!query)
880                 goto write;
881         result = get_result(query);
882         free(query);
883         if (result)
884                 row = mysql_fetch_row(result);
885 write:
886         info = make_message("dbinfo1:dir: %s\n"
887                 "dbinfo2:stream: %s, %s, score: %s\n"
888                 "dbinfo3:%s\n",
889                 dir? dir : "(not contained in table)",
890                 stream, meta, 
891                 (result && row && row[0])? row[0] : "(no score)",
892                 atts);
893         free(dir);
894         free(meta);
895         free(atts);
896         free(stream);
897         if (result)
898                 mysql_free_result(result);
899         return info;
900 }
901
902
903 /* might return NULL */
904 static char *get_current_audio_file(void)
905 {
906         char *name;
907         mmd_lock();
908         name = para_basename(mmd->filename);
909         mmd_unlock();
910         return name;
911 }
912
913 /* list attributes / print database info */
914 static int com_la_info(int fd, int argc, char *argv[])
915 {
916         char *name = NULL, *meta = NULL, *atts = NULL, *dir = NULL;
917         int ret, com_la = strcmp(argv[0], "info");
918
919         if (argc < 2) {
920                 ret = -E_GET_AUDIO_FILE;
921                 if (!(name = get_current_audio_file()))
922                         goto out;
923                 ret = send_va_buffer(fd, "%s\n", name);
924                 if (ret < 0)
925                         goto out;
926         } else {
927                 ret = -E_ESCAPE;
928                 if (!(name = escaped_basename(argv[1])))
929                         goto out;
930         }
931         meta = get_meta(name, 1);
932         atts = get_atts(name, 0);
933         dir = get_dir(name);
934         if (com_la)
935                 ret = send_va_buffer(fd, "%s\n", atts);
936         else
937                 ret = send_va_buffer(fd, "dir: %s\n" "%s\n" "attributes: %s\n",
938                         dir? dir : "(not contained in table)", meta, atts);
939 out:
940         free(meta);
941         free(atts);
942         free(dir);
943         free(name);
944         return ret;
945 }
946
947 /* list attributes */
948 int com_la(int fd, int argc, char *argv[])
949 {
950         return com_la_info(fd, argc, argv);
951 }
952
953 /* print database info */
954 int com_info(int fd, int argc, char *argv[])
955 {
956         return com_la_info(fd, argc, argv);
957 }
958
959 static int change_stream(const char *stream)
960 {
961         char *query;
962         int ret;
963         query = make_message("update streams set def='%s' "
964                 "where name = 'current_stream'", stream);
965         ret = real_query(query);
966         free(query);
967         return ret;
968 }
969
970 static int get_pic_id_by_name(char *name)
971 {
972         char *q, *ebn;
973         void *result = NULL;
974         long unsigned ret;
975         MYSQL_ROW row;
976
977         if (!(ebn = escaped_basename(name)))
978                 return -E_ESCAPE;
979         q = make_message("select pic_id from data where name = '%s'", ebn);
980         free(ebn);
981         result = get_result(q);
982         free(q);
983         if (!result)
984                 return -E_NORESULT;
985         row = mysql_fetch_row(result);
986         ret = -E_NOROW;
987         if (row && row[0])
988                 ret = atol(row[0]);
989         mysql_free_result(result);
990         return ret;
991 }
992
993 static int remove_entry(const char *name)
994 {
995         char *q, *ebn = escaped_basename(name);
996         int ret = -E_ESCAPE;
997
998         if (!ebn)
999                 goto out;
1000         q = make_message("delete from data where name = '%s'", ebn);
1001         real_query(q); /* ignore errors */
1002         free(q);
1003         q = make_message("delete from dir where name = '%s'", ebn);
1004         real_query(q); /* ignore errors */
1005         free(q);
1006         ret = 1;
1007 out:
1008         free(ebn);
1009         return ret;
1010 }
1011
1012 static int add_entry(const char *name)
1013 {
1014         char *q, *dn, *ebn = NULL, *edn = NULL;
1015         int ret;
1016
1017         if (!name || !*name)
1018                 return -E_MYSQL_SYNTAX;
1019         ebn = escaped_basename(name);
1020         if (!ebn)
1021                 return -E_ESCAPE;
1022         ret = -E_MYSQL_SYNTAX;
1023         dn = para_dirname(name);
1024         if (!dn)
1025                 goto out;
1026         ret = -E_ESCAPE;
1027         edn = escape_str(dn);
1028         free(dn);
1029         if (!edn || !*edn)
1030                 goto out;
1031         q = make_message("insert into data (name, pic_id) values "
1032                         "('%s', '%s')", ebn, "1");
1033         ret = real_query(q);
1034 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1035         free(q);
1036         if (ret < 0)
1037                 goto out;
1038         q = make_message("insert into dir (name, dir) values "
1039                         "('%s', '%s')", ebn, edn);
1040 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1041         ret = real_query(q);
1042         free(q);
1043 out:
1044         if (ebn)
1045                 free(ebn);
1046         if (edn)
1047                 free(edn);
1048         return ret;
1049 }
1050
1051 /*
1052  * remove/add entries
1053  */
1054 static int com_rm_ne(__a_unused int fd, int argc, char *argv[])
1055 {
1056         int ne = !strcmp(argv[0], "ne");
1057         int i, ret;
1058         if (argc < 2)
1059                 return -E_MYSQL_SYNTAX;
1060         for (i = 1; i < argc; i++) {
1061                 ret = remove_entry(argv[i]);
1062                 if (ret < 0)
1063                         return ret;
1064                 if (!ne)
1065                         continue;
1066                 ret = add_entry(argv[i]);
1067                 if (ret < 0)
1068                         return ret;
1069         }
1070         return 1;
1071 }
1072
1073 /*
1074  * rm
1075  */
1076 int com_rm(int fd, int argc, char *argv[])
1077 {
1078         return com_rm_ne(fd, argc, argv);
1079 }
1080
1081 /*
1082  * ne
1083  */
1084 int com_ne(int fd, int argc, char *argv[])
1085 {
1086         return com_ne(fd, argc, argv);
1087 }
1088
1089 /*
1090  * mv: rename entry
1091  */
1092 int com_mv(__a_unused int fd, int argc, char *argv[])
1093 {
1094         char *q, *dn, *ebn1 = NULL, *ebn2 = NULL, *edn = NULL;
1095         int ret;
1096
1097         if (argc != 3)
1098                 return -E_MYSQL_SYNTAX;
1099         ret = -E_ESCAPE;
1100         ebn1 = escaped_basename(argv[1]);
1101         ebn2 = escaped_basename(argv[2]);
1102         if (!ebn1 || !ebn2 || !*ebn1 || !*ebn2)
1103                 goto out;
1104         ret = -E_MYSQL_SYNTAX;
1105         if (!strcmp(ebn1, ebn2))
1106                 goto update_dir;
1107         remove_entry(argv[2]); /* no need to escape, ignore error */
1108         q = make_message("update data set name = '%s' where name = '%s'",
1109                 ebn2, ebn1);
1110         ret = real_query(q);
1111         free(q);
1112         if (ret < 0)
1113                 goto out;
1114         ret = -E_AUDIO_FILE;
1115         if (!mysql_affected_rows(mysql_ptr))
1116                 goto out;
1117         q = make_message("update dir set name = '%s' where name = '%s'",
1118                 ebn2, ebn1);
1119         ret = real_query(q);
1120         free(q);
1121         if (ret < 0)
1122                 goto out;
1123 update_dir:
1124         ret = 1;
1125         dn = para_dirname(argv[2]);
1126         if (!dn)
1127                 goto out;
1128         ret = -E_ESCAPE;
1129         edn = escape_str(dn);
1130         free(dn);
1131         if (!edn)
1132                 goto out;
1133         ret = 1;
1134         if (!*edn)
1135                 goto out;
1136         q = make_message("update dir set dir = '%s' where name = '%s'",
1137                 edn, ebn2);
1138         ret = real_query(q);
1139         free(q);
1140 out:
1141         free(edn);
1142         free(ebn1);
1143         free(ebn2);
1144         return ret;
1145 }
1146
1147 /*
1148  * set field
1149  */
1150 static int com_set(__a_unused int fd, int argc, char *argv[])
1151 {
1152         char *q, *ebn;
1153         long unsigned id;
1154         int i, ret;
1155         const char *field = strcmp(argv[0], "picass")? "numplayed" : "pic_id";
1156
1157         if (argc < 3)
1158                 return -E_MYSQL_SYNTAX;
1159         id = atol(argv[1]);
1160         for (i = 2; i < argc; i++) {
1161                 ebn = escaped_basename(argv[i]);
1162                 if (!ebn)
1163                         return -E_ESCAPE;
1164                 q = make_message("update data set %s = %lu "
1165                                 "where name = '%s'", field, id, ebn);
1166                 free(ebn);
1167                 ret = real_query(q);
1168                 free(q);
1169                 if (ret < 0)
1170                         return ret;
1171         }
1172         return 1;
1173 }
1174
1175 /*
1176  * snp: set numplayed
1177  */
1178 int com_picass(int fd, int argc, char *argv[])
1179 {
1180         return com_set(fd, argc, argv);
1181 }
1182
1183 /*
1184  * snp: set numplayed
1185  */
1186 int com_snp(int fd, int argc, char *argv[])
1187 {
1188         return com_set(fd, argc, argv);
1189 }
1190
1191 /*
1192  * picch: change entry's name in pics table
1193  */
1194 int com_picch(__a_unused int fd, int argc, char *argv[])
1195 {
1196         int ret;
1197         long unsigned id;
1198         char *q, *tmp;
1199
1200         if (argc != 3)
1201                 return -E_MYSQL_SYNTAX;
1202         id = atol(argv[1]);
1203         ret = -E_ESCAPE;
1204         tmp = escape_str(argv[2]);
1205         if (!tmp)
1206                 return -E_ESCAPE;
1207         q = make_message("update pics set name = '%s' where id = %lu", tmp, id);
1208         free(tmp);
1209         ret = real_query(q);
1210         free(q);
1211         return ret;
1212 }
1213
1214 /*
1215  * piclist: print list of pics in db
1216  */
1217 int com_piclist(__a_unused int fd, int argc, __a_unused char *argv[])
1218 {
1219         void *result = NULL;
1220         MYSQL_ROW row;
1221         unsigned long *length;
1222         int ret;
1223
1224         if (argc != 1)
1225                 return -E_MYSQL_SYNTAX;
1226         result = get_result("select id,name,pic from pics order by id");
1227         if (!result)
1228                 return -E_NORESULT;
1229         while ((row = mysql_fetch_row(result))) {
1230                 length = mysql_fetch_lengths(result);
1231                 if (!row || !row[0] || !row[1] || !row[2])
1232                         continue;
1233                 ret = send_va_buffer(fd, "%s\t%lu\t%s\n", row[0], length[2], row[1]);
1234                 if (ret < 0)
1235                         goto out;
1236         }
1237         ret = 1;
1238 out:
1239         mysql_free_result(result);
1240         return ret;
1241 }
1242
1243 /*
1244  * picdel: delete picture from database
1245  */
1246 int com_picdel(int fd, int argc, char *argv[])
1247 {
1248         char *q;
1249         long unsigned id;
1250         my_ulonglong aff;
1251         int i, ret;
1252
1253         if (argc < 2)
1254                 return -E_MYSQL_SYNTAX;
1255         for (i = 1; i < argc; i++) {
1256                 id = atol(argv[i]);
1257                 q = make_message("delete from pics where id = %lu", id);
1258                 ret = real_query(q);
1259                 free(q);
1260                 if (ret < 0)
1261                         return ret;
1262                 aff = mysql_affected_rows(mysql_ptr);
1263                 if (!aff) {
1264                         ret = send_va_buffer(fd, "No such id: %lu\n", id);
1265                         if (ret < 0)
1266                                 return ret;
1267                         continue;
1268                 }
1269                 q = make_message("update data set pic_id = 1 where pic_id = %lu", id);
1270                 ret = real_query(q);
1271                 free(q);
1272         }
1273         return 1;
1274 }
1275 /*
1276  * pic: get picture by name or by number
1277  */
1278 int com_pic(int fd, int argc, char *argv[])
1279 {
1280         void *result = NULL;
1281         MYSQL_ROW row;
1282         unsigned long *length, id;
1283         int ret;
1284         char *q, *name = NULL;
1285
1286         if (argc < 2) {
1287                 ret = -E_GET_AUDIO_FILE;
1288                 name = get_current_audio_file();
1289         } else {
1290                 ret = -E_ESCAPE;
1291                 name = escaped_basename(argv[1]);
1292         }
1293         if (!name)
1294                 return ret;
1295         if (*name == '#')
1296                 id = atoi(name + 1);
1297         else
1298                 id = get_pic_id_by_name(name);
1299         free(name);
1300         if (id <= 0)
1301                 return id;
1302         q = make_message("select pic from pics where id = '%lu'", id);
1303         result = get_result(q);
1304         free(q);
1305         if (!result)
1306                 return -E_NORESULT;
1307         row = mysql_fetch_row(result);
1308         ret = -E_NOROW;
1309         if (!row || !row[0])
1310                 goto out;
1311         length = mysql_fetch_lengths(result);
1312         ret = send_bin_buffer(fd, row[0], *length);
1313 out:
1314         mysql_free_result(result);
1315         return ret;
1316 }
1317
1318 /* strdel */
1319 int com_strdel(__a_unused int fd, int argc, char *argv[])
1320 {
1321         char *q, *tmp;
1322         int ret;
1323
1324         if (argc < 2)
1325                 return -E_MYSQL_SYNTAX;
1326         tmp = escape_str(argv[1]);
1327         if (!tmp)
1328                 return -E_ESCAPE;
1329         q = make_message("delete from streams where name='%s'", tmp);
1330         free(tmp);
1331         ret = real_query(q);
1332         free(q);
1333         return ret;
1334 }
1335
1336 /*
1337  * ls
1338  */
1339 int com_ls(int fd, int argc, char *argv[])
1340 {
1341         char *q;
1342         void *result;
1343         int ret;
1344         unsigned int num_rows;
1345
1346         if (argc > 2)
1347                 return -E_MYSQL_SYNTAX;
1348         if (argc > 1) {
1349                 char *tmp = escape_str(argv[1]);
1350                 if (!tmp)
1351                         return -E_ESCAPE;
1352                 q = make_message("select name from data where name like '%s'",
1353                         tmp);
1354                 free(tmp);
1355         } else
1356                 q = para_strdup("select name from data");
1357         result = get_result(q);
1358         free(q);
1359         if (!result)
1360                 return -E_NORESULT;
1361         num_rows = mysql_num_rows(result);
1362         ret = 1;
1363         if (num_rows)
1364                 ret = print_results(fd, result, 0, 0, num_rows - 1, 0);
1365         mysql_free_result(result);
1366         return ret;
1367 }
1368
1369 /*
1370  * summary
1371  */
1372 int com_summary(__a_unused int fd, int argc, __a_unused char *argv[])
1373 {
1374         MYSQL_ROW row;
1375         MYSQL_ROW row2;
1376         void *result;
1377         void *result2 = NULL;
1378         const char *fmt = "select count(name) from data where %s='1'";
1379         int ret = -E_NORESULT;
1380
1381         if (argc != 1)
1382                 return -E_MYSQL_SYNTAX;
1383         result = get_all_attributes();
1384         if (!result)
1385                 goto out;
1386         while ((row = mysql_fetch_row(result))) {
1387                 char *buf;
1388
1389                 ret = -E_NOROW;
1390                 if (!row[0])
1391                         goto out;
1392                 ret = -E_NORESULT;
1393                 buf = make_message(fmt, row[0]);
1394                 result2 = get_result(buf);
1395                 free(buf);
1396                 if (!result2)
1397                         goto out;
1398                 ret = -E_NOROW;
1399                 row2 = mysql_fetch_row(result2);
1400                 if (!row2 || !row2[0])
1401                         goto out;
1402                 ret = send_va_buffer(fd, "%s\t%s\n", row[0], row2[0]);
1403                 if (ret < 0)
1404                         goto out;
1405         }
1406         ret = 1;
1407 out:
1408         if (result2)
1409                 mysql_free_result(result2);
1410         if (result)
1411                 mysql_free_result(result);
1412         return ret;
1413 }
1414
1415 static int get_numplayed(char *name)
1416 {
1417         void *result;
1418         MYSQL_ROW row;
1419         const char *fmt = "select numplayed from data where name = '%s'";
1420         char *buf = make_message(fmt, name);
1421         int ret = -E_NORESULT;
1422
1423         result = get_result(buf);
1424         free(buf);
1425         if (!result)
1426                 goto out;
1427         ret = -E_NOROW;
1428         row = mysql_fetch_row(result);
1429         if (!row || !row[0])
1430                 goto out;
1431         ret = atoi(row[0]);
1432 out:
1433         if (result)
1434                 mysql_free_result(result);
1435         return ret;
1436 }
1437
1438 static int update_audio_file(char *name)
1439 {
1440         int ret;
1441         const char *fmt1 = "update data set lastplayed = now() where name = '%s'";
1442         const char *fmt2 = "update data set numplayed = %i where name = '%s'";
1443         char *q;
1444         char *ebn = escaped_basename(name);
1445
1446         ret = -E_ESCAPE;
1447         if (!ebn)
1448                 goto out;
1449         q = make_message(fmt1, ebn);
1450         ret = real_query(q);
1451         free(q);
1452         if (ret < 0)
1453                 goto out;
1454         ret = get_numplayed(ebn);
1455         if (ret < 0)
1456                 goto out;
1457         q = make_message(fmt2, ret + 1, ebn);
1458         ret = real_query(q);
1459         free(q);
1460 out:
1461         free(ebn);
1462         return ret;
1463 }
1464
1465 /* If called as child, mmd_lock must be held */
1466 static void update_mmd(char *info)
1467 {
1468         PARA_DEBUG_LOG("%s", "updating shared memory area\n");
1469         strncpy(mmd->selector_info, info, MMD_INFO_SIZE - 1);
1470         mmd->selector_info[MMD_INFO_SIZE - 1] = '\0';
1471 }
1472
1473 static void update_audio_file_server_handler(char *name)
1474 {
1475         char *info;
1476         info = get_selector_info(name);
1477         update_mmd(info);
1478         free(info);
1479         update_audio_file(name);
1480 }
1481
1482 int com_us(__a_unused int fd, int argc, char *argv[])
1483 {
1484         char *tmp;
1485         int ret;
1486
1487         if (argc != 2)
1488                 return -E_MYSQL_SYNTAX;
1489         tmp = escape_str(argv[1]);
1490         if (!tmp)
1491                 return -E_ESCAPE;
1492         ret = update_audio_file(argv[1]);
1493         free(tmp);
1494         return ret;
1495 }
1496
1497 static void refresh_selector_info(void)
1498 {
1499         char *name = get_current_audio_file();
1500         char *info;
1501
1502         if (!name)
1503                 return;
1504         info = get_selector_info(name);
1505         free(name);
1506         mmd_lock();
1507         update_mmd(info);
1508         mmd_unlock();
1509         free(info);
1510 }
1511
1512 /* select previous / next stream */
1513 static int com_ps_ns(__a_unused int fd, int argc, char *argv[])
1514 {
1515         char *query, *stream = get_current_stream();
1516         void *result = get_result("select name from streams");
1517         MYSQL_ROW row;
1518         int match = -1, ret, i;
1519         unsigned int num_rows;
1520
1521         if (argc != 1)
1522                 return -E_MYSQL_SYNTAX;
1523         ret = -E_NORESULT;
1524         if (!result)
1525                 goto out;
1526         num_rows = mysql_num_rows(result);
1527         ret = -E_EMPTY_RESULT;
1528         if (num_rows < 2)
1529                 goto out;
1530         ret = -E_NOROW;
1531         for (i = 0; i < num_rows; i++) {
1532                 row = mysql_fetch_row(result);
1533                 if (!row || !row[0])
1534                         goto out;
1535                 if (!strcmp(row[0], "current_stream"))
1536                         continue;
1537                 if (!strcmp(row[0], stream)) {
1538                         match = i;
1539                         break;
1540                 }
1541         }
1542         ret = -E_NO_STREAM;
1543         if (match < 0)
1544                 goto out;
1545         if (!strcmp(argv[0], "ps"))
1546                 i = match > 0? match - 1 : num_rows - 1;
1547         else
1548                 i = match < num_rows - 1? match + 1 : 0;
1549         ret = -E_NOROW;
1550         mysql_data_seek(result, i);
1551         row = mysql_fetch_row(result);
1552         if (!row || !row[0])
1553                 goto out;
1554         if (!strcmp(row[0], "current_stream")) {
1555                 if (!strcmp(argv[0], "ps")) {
1556                         i = match - 2;
1557                         i = i < 0? i + num_rows : i;
1558                 } else {
1559                         i = match + 2;
1560                         i = i > num_rows - 1? i - num_rows : i;
1561                 }
1562                 mysql_data_seek(result, i);
1563                 row = mysql_fetch_row(result);
1564                 if (!row || !row[0])
1565                         goto out;
1566         }
1567         query = make_message("update streams set def='%s' where name = "
1568                 "'current_stream'", row[0]);
1569         ret = real_query(query);
1570         free(query);
1571         refresh_selector_info();
1572 out:
1573         free(stream);
1574         if (result)
1575                 mysql_free_result(result);
1576         return ret;
1577 }
1578
1579 /* select previous stream */
1580 int com_ps(int fd, int argc, char *argv[])
1581 {
1582         return com_ps_ns(fd, argc, argv);
1583 }
1584
1585 /* select next stream */
1586 int com_ns(int fd, int argc, char *argv[])
1587 {
1588         return com_ps_ns(fd, argc, argv);
1589 }
1590
1591 /* streams */
1592 int com_streams(int fd, int argc, __a_unused char *argv[])
1593 {
1594         unsigned int num_rows;
1595         int i, ret = -E_NORESULT;
1596         void *result;
1597         MYSQL_ROW row;
1598
1599         if (argc > 1 && strcmp(argv[1], "current_stream"))
1600                 return -E_MYSQL_SYNTAX;
1601         if (argc > 1) {
1602                 char *cs = get_current_stream();
1603                 ret = send_va_buffer(fd, "%s\n", cs);
1604                 free(cs);
1605                 return ret;
1606         }
1607         result = get_result("select name from streams");
1608         if (!result)
1609                 goto out;
1610         num_rows = mysql_num_rows(result);
1611         ret = 1;
1612         if (!num_rows)
1613                 goto out;
1614         ret = -E_NOROW;
1615         for (i = 0; i < num_rows; i++) {
1616                 row = mysql_fetch_row(result);
1617                 if (!row || !row[0])
1618                         goto out;
1619                 if (strcmp(row[0], "current_stream"))
1620                         send_va_buffer(fd, "%s\n", row[0]);
1621         }
1622         ret = 1;
1623 out:
1624         if (result)
1625                 mysql_free_result(result);
1626         return ret;
1627 }
1628
1629 /* query stream definition */
1630 int com_strq(int fd, int argc, char *argv[])
1631 {
1632         MYSQL_ROW row;
1633         char *query, *name;
1634         void *result;
1635         int ret;
1636
1637         if (argc < 2) {
1638                 ret = -E_GET_STREAM;
1639                 name = get_current_stream();
1640         } else {
1641                 ret = -E_ESCAPE;
1642                 name = escaped_basename(argv[1]);
1643         }
1644         if (!name)
1645                 return ret;
1646         ret = -E_NORESULT;
1647         query = make_message("select def from streams where name='%s'", name);
1648         free(name);
1649         result = get_result(query);
1650         free(query);
1651         if (!result)
1652                 goto out;
1653         ret = -E_NOROW;
1654         row = mysql_fetch_row(result);
1655         if (!row || !row[0])
1656                 goto out;
1657         /* no '\n' needed */
1658         ret = send_buffer(fd, row[0]);
1659 out:
1660         if (result)
1661                 mysql_free_result(result);
1662         return ret;
1663 }
1664
1665 /* change stream / change stream and play */
1666 static int com_cs_csp(int fd, int argc, char *argv[])
1667 {
1668         int ret, stream_change;
1669         char *query, *stream = NULL;
1670         char *old_stream = get_current_stream();
1671         int csp = !strcmp(argv[0], "csp");
1672
1673         ret = -E_MYSQL_SYNTAX;
1674         if (argc > 2)
1675                 goto out;
1676         if (argc == 1) {
1677                 if (csp)
1678                         goto out;
1679                 ret = send_va_buffer(fd, "%s\n", old_stream);
1680                 goto out;
1681         }
1682         ret = -E_GET_QUERY;
1683         /* test if stream is valid, no need to escape argv[1] */
1684         query = get_query(argv[1], NULL, 0);
1685         if (!query)
1686                 goto out;
1687         free(query);
1688         /* stream is ok */
1689         stream = escape_str(argv[1]);
1690         if (!stream)
1691                 goto out;
1692         stream_change = strcmp(stream, old_stream);
1693         if (stream_change) {
1694                 ret = change_stream(stream);
1695                 if (ret < 0)
1696                         goto out;
1697                 refresh_selector_info();
1698         }
1699         if (csp) {
1700                 mmd_lock();
1701                 mmd->new_vss_status_flags |= VSS_PLAYING;
1702                 if (stream_change)
1703                         mmd->new_vss_status_flags |= VSS_NEXT;
1704                 mmd_unlock();
1705         }
1706         ret = 1;
1707 out:
1708         free(old_stream);
1709         free(stream);
1710         return ret;
1711 }
1712
1713 /* change stream */
1714 int com_cs(int fd, int argc, char *argv[])
1715 {
1716         return com_cs_csp(fd, argc, argv);
1717 }
1718
1719 /* change stream and play */
1720 int com_csp(int fd, int argc, char *argv[])
1721 {
1722         return com_cs_csp(fd, argc, argv);
1723 }
1724
1725 /* score list / skip */
1726 static int com_sl_skip(int fd, int argc, char *argv[])
1727 {
1728         void *result = NULL;
1729         MYSQL_ROW row;
1730         int ret, i, skip = !strcmp(argv[0], "skip");
1731         char *query, *stream, *tmp;
1732         unsigned int num_rows, num;
1733
1734         if (argc < 2)
1735                 return -E_MYSQL_SYNTAX;
1736         num = atoi(argv[1]);
1737         if (!num)
1738                 return -E_MYSQL_SYNTAX;
1739         if (argc == 2) {
1740                 stream = get_current_stream();
1741                 if (!stream)
1742                         return -E_GET_STREAM;
1743         } else {
1744                 stream = escape_str(argv[2]);
1745                 if (!stream)
1746                         return -E_ESCAPE;
1747         }
1748         tmp = get_query(stream, NULL, 0);
1749         free(stream);
1750         if (!tmp)
1751                 return -E_GET_QUERY;
1752         query = make_message("%s limit %d", tmp, num);
1753         free(tmp);
1754         ret = -E_NORESULT;
1755         result = get_result(query);
1756         free(query);
1757         if (!result)
1758                 goto out;
1759         ret = -E_EMPTY_RESULT;
1760         num_rows = mysql_num_rows(result);
1761         if (!num_rows)
1762                 goto out;
1763         for (i = 0; i < num_rows && i < num; i++) {
1764                 row = mysql_fetch_row(result);
1765                 if (skip) {
1766                         send_va_buffer(fd, "Skipping %s\n", row[0]);
1767                         update_audio_file(row[0]);
1768                 } else
1769                         send_va_buffer(fd, "%s\n", row[0]? row[0]: "BUG");
1770         }
1771         ret = 1;
1772 out:
1773         if (result)
1774                 mysql_free_result(result);
1775         return ret;
1776 }
1777
1778 /* score list */
1779 int com_sl(int fd, int argc, char *argv[])
1780 {
1781         return com_sl_skip(fd, argc, argv);
1782 }
1783
1784 /* skip */
1785 int com_skip(int fd, int argc, char *argv[])
1786 {
1787         return com_sl_skip(fd, argc, argv);
1788 }
1789
1790 /*
1791  * update attributes of name
1792  */
1793 static int update_atts(int fd, char *name, char *atts)
1794 {
1795         int ret;
1796         char *ebn, *q, *old, *new = NULL;
1797
1798         if (!mysql_ptr)
1799                 return -E_NOTCONN;
1800         ebn = escaped_basename(name);
1801         if (!ebn)
1802                 return -E_ESCAPE;
1803         q = make_message("update data set %s where name = '%s'", atts, ebn);
1804         old = get_atts(ebn, 0);
1805         send_va_buffer(fd, "old: %s\n", old);
1806         free(old);
1807         ret = real_query(q);
1808         free(q);
1809         if (ret < 0)
1810                 goto out;
1811         new = get_atts(ebn, 0);
1812         ret = send_va_buffer(fd, "new: %s\n", new);
1813         free(new);
1814 out:
1815         free(ebn);
1816         return ret;
1817 }
1818
1819 /*
1820  * set attributes
1821  */
1822 int com_sa(int fd, int argc, char *argv[])
1823 {
1824         int i, ret;
1825         char *atts = NULL, *name;
1826
1827         if (argc < 2)
1828                 return -E_MYSQL_SYNTAX;
1829         for (i = 1; i < argc; i++) {
1830                 int unset = 0;
1831                 char *esc, *tmp, *p =argv[i];
1832                 int len = strlen(p);
1833
1834                 if (!len)
1835                         continue;
1836                 switch (p[len - 1]) {
1837                         case '+':
1838                                 unset = 0;
1839                                 break;
1840                         case '-':
1841                                 unset = 1;
1842                                 break;
1843                         default:
1844                                 goto no_more_atts;
1845                 }
1846                 p[len - 1] = '\0';
1847                 esc = escape_str(p);
1848                 if (!esc)
1849                         return -E_ESCAPE;
1850                 tmp = make_message("%s%s='%s'", atts? "," : "", esc,
1851                         unset? "0" : "1");
1852                 free(esc);
1853                 atts = para_strcat(atts, tmp);
1854                 free(tmp);
1855         }
1856 no_more_atts:
1857         if (!atts)
1858                 return -E_NOATTS;
1859         if (i >= argc) { /* no name given, use current af */
1860                 ret = -E_GET_AUDIO_FILE;
1861                 if (!(name = get_current_audio_file()))
1862                         goto out;
1863                 ret = update_atts(fd, name, atts);
1864                 free(name);
1865         } else {
1866                 ret = 1;
1867                 for (; argv[i] && ret >= 0; i++)
1868                         ret = update_atts(fd, argv[i], atts);
1869         }
1870         refresh_selector_info();
1871 out:
1872         free(atts);
1873         return ret;
1874 }
1875
1876 /*
1877  * copy attributes
1878  */
1879 int com_cam(int fd, int argc, char *argv[])
1880 {
1881         char *name = NULL, *meta = NULL, *atts = NULL;
1882         int i, ret;
1883
1884         if (argc < 3)
1885                 return -E_MYSQL_SYNTAX;
1886         if (!(name = escaped_basename(argv[1])))
1887                 return -E_ESCAPE;
1888         ret = -E_NOATTS;
1889         if (!(atts = get_atts(name, 1)))
1890                 goto out;
1891         ret = -E_META;
1892         if (!(meta = get_meta(name, 0)))
1893                 goto out;
1894         for (i = 2; i < argc; i++) {
1895                 char *ebn, *q;
1896                 ret = -E_ESCAPE;
1897                 if (!(ebn = escaped_basename(argv[i])))
1898                         goto out;
1899                 ret = send_va_buffer(fd, "updating %s\n", ebn);
1900                 if (ret < 0) {
1901                         free(ebn);
1902                         goto out;
1903                 }
1904                 q = make_message("update data set %s where name = '%s'",
1905                         meta, ebn);
1906                 if ((ret = update_atts(fd, ebn, atts)) >= 0)
1907                         ret = real_query(q);
1908                 free(ebn);
1909                 free(q);
1910                 if (ret < 0)
1911                         goto out;
1912         }
1913         ret = 1;
1914 out:
1915         if (name)
1916                 free(name);
1917         if (meta)
1918                 free(meta);
1919         if (atts)
1920                 free(atts);
1921         return ret;
1922 }
1923
1924 /*
1925  * verify / clean
1926  */
1927 static int com_vrfy_clean(int fd, int argc, __a_unused char *argv[])
1928 {
1929         char *query;
1930         int ret, vrfy_mode = strcmp(argv[0], "clean");
1931         void *result = NULL;
1932         unsigned int num_rows;
1933         MYSQL_ROW row;
1934         char *escaped_name;
1935
1936         if (argc != 1)
1937                 return -E_MYSQL_SYNTAX;
1938         ret = -E_NORESULT;
1939         result = get_result("select data.name from data left join dir on "
1940                 "dir.name = data.name where dir.name is NULL");
1941         if (!result)
1942                 goto out;
1943         num_rows = mysql_num_rows(result);
1944         if (!num_rows) {
1945                 ret = send_buffer(fd, "No invalid entries\n");
1946                 goto out;
1947         }
1948         if (vrfy_mode) {
1949                 send_va_buffer(fd, "found %i invalid entr%s\n", num_rows,
1950                         num_rows == 1? "y" : "ies");
1951                 ret = print_results(fd, result, 0, 0, num_rows - 1, 0);
1952                 goto out;
1953         }
1954         while ((row = mysql_fetch_row(result))) {
1955                 ret = -E_NOROW;
1956                 if (!row[0])
1957                         goto out;
1958                 ret = -E_ESCAPE;
1959                 escaped_name = escape_str(row[0]);
1960                 if (!escaped_name)
1961                         goto out;
1962                 send_va_buffer(fd, "deleting %s\n", escaped_name);
1963                 query = make_message("delete from data where name = '%s'",
1964                         escaped_name);
1965                 ret = real_query(query);
1966                 free(query);
1967                 if (ret < 0)
1968                         goto out;
1969         }
1970
1971 out:
1972         if (result)
1973                 mysql_free_result(result);
1974         return ret;
1975 }
1976
1977 /*
1978  * verify
1979  */
1980 int com_vrfy(int fd, int argc, char **argv)
1981 {
1982         return com_vrfy_clean(fd, argc, argv);
1983 }
1984
1985 /*
1986  * clean
1987  */
1988 int com_clean(int fd, int argc, char **argv)
1989 {
1990         return com_vrfy_clean(fd, argc, argv);
1991 }
1992
1993 static FILE *out_file;
1994
1995 static int mysql_write_tmp_file(const char *dir, const char *name)
1996 {
1997         int ret = -E_TMPFILE;
1998         char *msg = make_message("%s\t%s\n", dir, name);
1999         if (fputs(msg, out_file) != EOF)
2000                 ret = 1;
2001         free(msg);
2002         return ret;
2003 }
2004
2005 /*
2006  * update database
2007  */
2008 int com_upd(int fd, int argc, __a_unused char *argv[])
2009 {
2010         char *tempname = NULL, *query = NULL;
2011         int ret, out_fd = -1, num = 0;
2012         void *result = NULL;
2013         unsigned int num_rows;
2014         MYSQL_ROW row;
2015
2016         if (argc != 1)
2017                 return -E_MYSQL_SYNTAX;
2018         out_file = NULL;
2019         tempname = para_strdup("/tmp/mysql.tmp.XXXXXX");
2020         ret = para_mkstemp(tempname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2021         if (ret < 0)
2022                 goto out;
2023         out_fd = ret;
2024         out_file = fdopen(out_fd, "w");
2025         if (!out_file) {
2026                 close(out_fd);
2027                 goto out;
2028         }
2029         if (find_audio_files(conf.mysql_audio_file_dir_arg, mysql_write_tmp_file) < 0)
2030                 goto out;
2031         num = ftell(out_file);
2032         /*
2033          * we have to make sure the file hit the disk before we call
2034          * real_query
2035          */
2036         fclose(out_file);
2037         out_file = NULL;
2038         PARA_DEBUG_LOG("wrote tempfile %s (%d bytes)\n", tempname, num);
2039         if (!num)
2040                 goto out;
2041         if ((ret = real_query("delete from dir")) < 0)
2042                 goto out;
2043         query = make_message("load data infile '%s' ignore into table dir "
2044                 "fields terminated by '\t' lines terminated by '\n' "
2045                 "(dir, name)", tempname);
2046         ret = real_query(query);
2047         free(query);
2048         if (ret < 0)
2049                 goto out;
2050         result = get_result("select dir.name from dir left join data on "
2051                 "data.name = dir.name where data.name is NULL");
2052         ret = -E_NORESULT;
2053         if (!result)
2054                 goto out;
2055         num_rows = mysql_num_rows(result);
2056         if (!num_rows) {
2057                 ret = send_buffer(fd, "no new entries\n");
2058                 goto out;
2059         }
2060         while ((row = mysql_fetch_row(result))) {
2061                 char *erow;
2062                 ret = -E_NOROW;
2063                 if (!row[0])
2064                         goto out;
2065                 send_va_buffer(fd, "new entry: %s\n", row[0]);
2066                 erow = escape_str(row[0]);
2067                 if (!erow)
2068                         goto out;
2069                 query = make_message("insert into data (name, pic_id) values "
2070                         "('%s','%s')", erow, "1");
2071                 free(erow);
2072                 ret = real_query(query);
2073                 free(query);
2074                 if (ret < 0)
2075                         goto out;
2076         }
2077         ret = 1;
2078 out:
2079         if (out_fd >= 0)
2080                 unlink(tempname);
2081         free(tempname);
2082         if (out_file)
2083                 fclose(out_file);
2084         if (result)
2085                 mysql_free_result(result);
2086         return ret;
2087 }
2088
2089 static char **server_get_audio_file_list(unsigned int num)
2090 {
2091         char **list = para_malloc((num + 1) * sizeof(char *));
2092         char *tmp, *query, *stream = get_current_stream();
2093         void *result = NULL;
2094         unsigned int num_rows;
2095         int i = 0;
2096         MYSQL_ROW row;
2097
2098         tmp = get_query(stream, NULL, 1);
2099         free(stream);
2100         if (!tmp)
2101                 goto err_out;
2102         query = make_message("%s limit %d", tmp, num);
2103         free(tmp);
2104         result = get_result(query);
2105         free(query);
2106         if (!result)
2107                 goto err_out;
2108         num_rows = mysql_num_rows(result);
2109         if (!num_rows)
2110                 goto err_out;
2111         for (i = 0; i < num_rows && i < num; i++) {
2112                 row = mysql_fetch_row(result);
2113                 if (!row || !row[0])
2114                         goto err_out;
2115                 list[i] = para_strdup(row[0]);
2116         }
2117         list[i] = NULL;
2118         goto success;
2119 err_out:
2120         while (i > 0) {
2121                 i--;
2122                 free(list[i]);
2123         }
2124         free(list);
2125         list = NULL;
2126 success:
2127         if (result)
2128                 mysql_free_result(result);
2129         return list;
2130 }
2131
2132 /*
2133  * connect to mysql server, return mysql pointer on success, -E_NOTCONN
2134  * on errors. Called from parent on startup and also from com_cdb().
2135  */
2136 static int init_mysql_server(void)
2137 {
2138         char *u = conf.mysql_user_arg? conf.mysql_user_arg : para_logname();
2139
2140         mysql_ptr = mysql_init(NULL);
2141         if (!mysql_ptr) {
2142                 PARA_CRIT_LOG("%s", "mysql init error\n");
2143                 return -E_NOTCONN;
2144         }
2145         PARA_DEBUG_LOG("connecting: %s@%s:%d\n", u, conf.mysql_host_arg,
2146                 conf.mysql_port_arg);
2147         if (!conf.mysql_user_arg)
2148                 free(u);
2149         /*
2150          * If host is NULL a connection to the local host is assumed,
2151          * If user is NULL, the current user is assumed
2152          */
2153         if (!(mysql_ptr = mysql_real_connect(mysql_ptr,
2154                         conf.mysql_host_arg,
2155                         conf.mysql_user_arg,
2156                         conf.mysql_passwd_arg,
2157                         conf.mysql_database_arg,
2158                         conf.mysql_port_arg, NULL, 0))) {
2159                 PARA_CRIT_LOG("%s", "connect error\n");
2160                 return -E_NOTCONN;
2161         }
2162         PARA_INFO_LOG("%s", "success\n");
2163         return 1;
2164 }
2165
2166 /* mmd lock must be held */
2167 static void write_msg2mmd(int success)
2168 {
2169         sprintf(mmd->selector_info, "dbinfo1:%s\ndbinfo2:mysql-%s\ndbinfo3:\n",
2170                 success < 0? PARA_STRERROR(-success) :
2171                         "successfully connected to mysql server",
2172                 success < 0? "" : mysql_get_server_info(mysql_ptr));
2173 }
2174
2175 /* create database */
2176 int com_cdb(int fd, int argc, char *argv[])
2177 {
2178         char *query;
2179         int ret;
2180
2181         if (mysql_ptr) {
2182                 PARA_INFO_LOG("%s", "closing database\n");
2183                 mysql_close(mysql_ptr);
2184         }
2185         /* dont use any database */
2186         conf.mysql_database_arg = NULL; /* leak? */
2187         ret = -E_MYSQL_INIT;
2188         if (init_mysql_server() < 0 || !mysql_ptr)
2189                 goto out;
2190         if (argc < 2)
2191                 conf.mysql_database_arg = para_strdup("paraslash");
2192         else {
2193                 ret = -E_ESCAPE;
2194                 conf.mysql_database_arg = escape_str(argv[1]);
2195                 if (!conf.mysql_database_arg)
2196                         goto out;
2197         }
2198         query = make_message("create database %s", conf.mysql_database_arg);
2199         ret = real_query(query);
2200         free(query);
2201         if (ret < 0)
2202                 goto out;
2203         /* reconnect with database just created */
2204         mysql_close(mysql_ptr);
2205         ret = -E_MYSQL_INIT;
2206         if (init_mysql_server() < 0 || !mysql_ptr)
2207                 goto out;
2208         mmd_lock();
2209         write_msg2mmd(1);
2210         mmd_unlock();
2211         ret = -E_QFAILED;
2212         if (real_query("create table data (name varchar(255) binary not null "
2213                         "primary key, "
2214                         "lastplayed datetime not null default "
2215                                 "'1970-01-01', "
2216                         "numplayed int not null default 0, "
2217                         "pic_id bigint unsigned not null default 1)") < 0)
2218                 goto out;
2219         if (real_query("create table dir (name varchar(255) binary not null "
2220                         "primary key, dir varchar(255) default null)") < 0)
2221                 goto out;
2222         if (real_query("create table pics ("
2223                         "id bigint(20) unsigned not null primary key "
2224                         "auto_increment, "
2225                         "name varchar(255) binary not null, "
2226                         "pic mediumblob not null)") < 0)
2227                 goto out;
2228         if (real_query("create table streams ("
2229                         "name varchar(255) binary not null primary key, "
2230                         "def blob not null)") < 0)
2231                 goto out;
2232         if (real_query("insert into streams (name, def) values "
2233                         "('current_stream', '(none)')") < 0)
2234                 goto out;
2235         ret = send_va_buffer(fd, "successfully created database %s\n",
2236                 conf.mysql_database_arg);
2237 out:
2238         return ret;
2239 }
2240
2241 static void shutdown_connection(void)
2242 {
2243         if (mysql_ptr) {
2244                 PARA_NOTICE_LOG("%s", "shutting down mysql connection\n");
2245                 mysql_close(mysql_ptr);
2246                 mysql_ptr = NULL;
2247         }
2248 }
2249
2250 /**
2251  * the init function of the mysql-based audio file selector
2252  *
2253  * \param db pointer to the struct to initialize
2254  *
2255  * Check the command line options and initialize all function pointers of \a
2256  * db.  Connect to the mysql server and initialize the info string.
2257  *
2258  * \return This function returns success even if it could not connect
2259  * to the mysql server. This is because the connect is expected to fail
2260  * if there the paraslash database is not yet created. This gives the
2261  * user a chance to send the "cdb" to create the database.
2262  *
2263  * \sa struct audio_file_selector, misc_meta_data::selector_info,
2264  * random_selector.c
2265  */
2266 int mysql_selector_init(struct audio_file_selector *db)
2267 {
2268         int ret;
2269
2270         if (!conf.mysql_passwd_given)
2271                 return -E_NO_MYSQL_PASSWD;
2272         if (!conf.mysql_audio_file_dir_given)
2273                 return -E_NO_AF_DIR;
2274         db->name = "mysql";
2275         db->cmd_list = mysql_selector_cmds;
2276         db->get_audio_file_list = server_get_audio_file_list;
2277         db->update_audio_file = update_audio_file_server_handler;
2278         db->shutdown = shutdown_connection;
2279         ret = init_mysql_server();
2280         if (ret < 0)
2281                 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
2282         write_msg2mmd(ret);
2283         return 1;       /* return success even if connect failed to give the
2284                          * user the chance to exec com_cdb
2285                          */
2286 }