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