8148fabe04310739a577b99add1783de94f0f14d
[paraslash.git] / mysql_selector.c
1 /*
2  * Copyright (C) 1999-2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file mysql_selector.c para_server's mysql-based audio file selector */
8
9 /** \cond some internal constants */
10 #define MEDIUM_BLOB_SIZE 16777220 /*  (2**24 + 4) */
11 #define BLOB_SIZE 65539 /* (2**16 + 3) */
12 /** \endcond */
13 #include "server.cmdline.h"
14 #include "server.h"
15 #include "vss.h"
16 #include "afs.h"
17 #include <mysql/mysql.h>
18 #include <mysql/mysql_version.h>
19 #include <regex.h>
20 #include "error.h"
21 #include "net.h"
22 #include "string.h"
23 #include "user_list.h"
24 #include "mysql_selector_command_list.h"
25
26 /** pointer to the shared memory area */
27 extern struct misc_meta_data *mmd;
28
29 static void *mysql_ptr = NULL;
30
31 /**
32  * contains name/replacement pairs used by s_a_r_list()
33  *
34  * \sa s_a_r()
35  */
36 struct para_macro {
37         /** the name of the macro */
38         const char *name;
39         /** the replacement text */
40         const char *replacement;
41 };
42
43 static const struct para_macro mysql_macro_list[] = {
44         {       .name = "IS_N_SET",
45                 .replacement = "(data.%s != '1')"
46         }, {
47                 .name = "IS_SET",
48                 .replacement = "(data.%s = '1')"
49         }, {
50                 .name = "PICID",
51                 .replacement = "%sdata.Pic_Id"
52         }, {
53                 .name = "NAME_LIKE",
54                 .replacement = "(data.name like '%s')"
55         }, {
56                 .name = "LASTPLAYED",
57                 .replacement = "%sFLOOR((UNIX_TIMESTAMP(now())"
58                         "-UNIX_TIMESTAMP(data.Lastplayed))/60)"
59         }, {
60                 .name = "NUMPLAYED",
61                 .replacement = "%sdata.Numplayed"
62         }, {
63                 .name = NULL,
64         }
65 };
66
67 /**
68  * simple search and replace routine
69  *
70  * \param src source string
71  * \param macro_name the name of the macro
72  * \param replacement the replacement format string
73  *
74  * In \p src, replace each occurence of \p macro_name(arg) by the string
75  * determined by the \p replacement format string. \p replacement may (but
76  * needs not) contain a single string conversion specifier (%s) which gets
77  * replaced by \p arg.
78  *
79  * \return A string in which all matches in \p src are replaced, or \p NULL if
80  * an syntax error was encountered. Caller must free the result.
81  *
82  * \sa regcomp(3)
83  */
84 __must_check __malloc static char *s_a_r(const char *src, const char* macro_name,
85                 const char *replacement)
86 {
87         regex_t preg;
88         size_t  nmatch = 1;
89         regmatch_t pmatch[1];
90         int eflags = 0;
91         char *dest = NULL;
92         const char *bufptr = src;
93
94         if (!macro_name || !replacement || !src)
95                 return para_strdup(src);
96         regcomp(&preg, macro_name, 0);
97         while (regexec(&preg,  bufptr, nmatch, pmatch, eflags)
98                         != REG_NOMATCH) {
99                 char *tmp, *arg, *o_bracket, *c_bracket;
100
101                 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
102                 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
103                 if (!c_bracket)
104                         goto out;
105                 tmp = para_strdup(bufptr);
106                 tmp[pmatch[0].rm_so] = '\0';
107                 dest = para_strcat(dest, tmp);
108                 free(tmp);
109
110                 arg = para_strdup(o_bracket + 1);
111                 arg[c_bracket - o_bracket - 1] = '\0';
112                 tmp = make_message(replacement, arg);
113                 free(arg);
114                 dest = para_strcat(dest, tmp);
115                 free(tmp);
116                 bufptr = c_bracket;
117                 bufptr++;
118         }
119         dest = para_strcat(dest, bufptr);
120 //      PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
121 out:
122         regfree(&preg);
123         return dest;
124 }
125
126 /**
127  * replace a string according to a list of macros
128  *
129  * \param macro_list the array containing a macro/replacement pairs.
130  * \param src the source string
131  *
132  * This function just calls s_a_r() for each element of \p macro_list.
133  *
134  * \return \p NULL if one of the underlying calls to \p s_a_r returned \p NULL.
135  * Otherwise the completely expanded version of \p src is returned.
136  */
137 __must_check __malloc static char *s_a_r_list(const struct para_macro *macro_list,
138                 char *src)
139 {
140         const struct para_macro *mp = macro_list;
141         char *ret = NULL, *tmp = para_strdup(src);
142
143         while (mp->name) {
144                 ret = s_a_r(tmp, mp->name, mp->replacement);
145                 free(tmp);
146                 if (!ret) /* syntax error */
147                         return NULL;
148                 tmp = ret;
149                 mp++;
150         }
151         //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
152         return ret;
153 }
154
155 static int real_query(const char *query)
156 {
157         if (!mysql_ptr)
158                 return -E_NOTCONN;
159         PARA_DEBUG_LOG("%s\n", query);
160         if (mysql_real_query(mysql_ptr, query, strlen(query))) {
161                 PARA_ERROR_LOG("real_query error (%s)\n",
162                         mysql_error(mysql_ptr));
163                 return -E_QFAILED;
164         }
165         return 1;
166 }
167
168 /*
169  * Use open connection given by mysql_ptr to query server. Returns a
170  * result pointer on succes and NULL on errors
171  */
172 static struct MYSQL_RES *get_result(const char *query)
173 {
174         void *result;
175
176         if (real_query(query) < 0)
177                 return NULL;
178         result = mysql_store_result(mysql_ptr);
179         if (!result)
180                 PARA_ERROR_LOG("%s", "store_result error\n");
181         return result;
182 }
183 /*
184  * write input from fd to dynamically allocated char array,
185  * but maximal max_size byte. Return size.
186  */
187 static int fd2buf(int fd, char **buf_ptr, size_t max_size)
188 {
189         const size_t chunk_size = 1024;
190         size_t size = 2048;
191         char *buf = para_malloc(size * sizeof(char)), *p = buf;
192         int ret;
193
194         while ((ret = recv_bin_buffer(fd, p, chunk_size)) > 0) {
195                 p += ret;
196                 if ((p - buf) + chunk_size >= size) {
197                         char *tmp;
198
199                         size *= 2;
200                         if (size > max_size) {
201                                 ret = -E_TOOBIG;
202                                 goto out;
203                         }
204                         tmp = para_realloc(buf, size);
205                         p = (p - buf) + tmp;
206                         buf = tmp;
207                 }
208         }
209         if (ret < 0)
210                 goto out;
211         *buf_ptr = buf;
212         ret = p - buf;
213 out:
214         if (ret < 0 && buf)
215                 free(buf);
216         return ret;
217 }
218
219 static char *escape_blob(const char* old, size_t size)
220 {
221         char *new;
222
223         if (!mysql_ptr)
224                 return NULL;
225         new = para_malloc(2 * size * sizeof(char) + 1);
226         mysql_real_escape_string(mysql_ptr, new, old, size);
227         return new;
228 }
229
230 static char *escape_str(const char* old)
231 {
232         return escape_blob(old, strlen(old));
233 }
234
235 static char *escaped_basename(const char *name)
236 {
237         char *esc, *bn = para_basename(name);
238
239         if (!bn)
240                 return NULL;
241         esc = escape_str(bn);
242         free(bn);
243         return esc;
244 }
245
246 /*
247  * new attribute
248  */
249 int com_na(__a_unused int fd, int argc, char *argv[])
250 {
251         char *q, *tmp;
252         int ret;
253
254         if (argc < 2)
255                 return -E_MYSQL_SYNTAX;
256         tmp = escape_str(argv[1]);
257         if (!tmp)
258                 return -E_ESCAPE;
259         q = make_message("alter table data add %s char(1) "
260                 "not null default 0", tmp);
261         free(tmp);
262         ret = real_query(q);
263         free(q);
264         return ret;
265 }
266
267 /*
268  * delete attribute
269  */
270 int com_da(__a_unused int fd, int argc, char *argv[])
271 {
272         char *q, *tmp;
273         int ret;
274
275         if (argc < 2)
276                 return -E_MYSQL_SYNTAX;
277         tmp = escape_str(argv[1]);
278         if (!tmp)
279                 return -E_ESCAPE;
280         q = make_message("alter table data drop %s", tmp);
281         free(tmp);
282         ret = real_query(q);
283         free(q);
284         return ret;
285 }
286
287 /* stradd/pic_add */
288 static int com_stradd_picadd(int fd, int argc, char *argv[])
289 {
290         char *blob = NULL, *esc_blob = NULL, *q = NULL, *tmp = NULL;
291         const char *fmt, *del_fmt;
292         int ret, stradd = strcmp(argv[0], "picadd");
293         size_t size;
294
295         if (argc < 2)
296                 return -E_MYSQL_SYNTAX;
297         if (strlen(argv[1]) >= MAXLINE - 1)
298                 return -E_NAMETOOLONG;
299         if (!mysql_ptr)
300                 return -E_NOTCONN;
301         if (stradd) {
302                 size = BLOB_SIZE;
303                 fmt = "insert into streams (name, def) values ('%s','%s')";
304                 del_fmt="delete from streams where name='%s'";
305         } else {
306                 size = MEDIUM_BLOB_SIZE;
307                 fmt = "insert into pics (name, pic) values ('%s','%s')";
308                 del_fmt="delete from pics where pic='%s'";
309         }
310         tmp = escape_str(argv[1]);
311         if (!tmp)
312                 return -E_ESCAPE;
313         q = make_message(del_fmt, tmp);
314         free(tmp);
315         ret = real_query(q);
316         free(q);
317         if (ret < 0)
318                 return ret;
319         if ((ret = send_buffer(fd, AWAITING_DATA_MSG) < 0))
320                 return ret;
321         if ((ret = fd2buf(fd, &blob, size)) < 0)
322                 return ret;
323         size = ret;
324         if (stradd)
325                 blob[size] = '\0';
326         ret = -E_ESCAPE;
327         esc_blob = escape_blob(blob, size);
328         if (!esc_blob)
329                 goto out;
330         tmp = escape_str(argv[1]);
331         if (!tmp)
332                 goto out;
333         q = make_message(fmt, tmp, esc_blob);
334         ret = real_query(q);
335 out:
336         free(blob);
337         free(esc_blob);
338         free(tmp);
339         free(q);
340         return ret;
341 }
342
343 /* stradd */
344 int com_stradd(int fd, int argc, char *argv[])
345 {
346         return com_stradd_picadd(fd, argc, argv);
347 }
348
349 /* pic_add */
350 int com_picadd(int fd, int argc, char *argv[])
351 {
352         return com_stradd_picadd(fd, argc, argv);
353 }
354
355 /*
356  * print results to fd
357  */
358 static int print_results(int fd, void *result,
359                 my_ulonglong top, my_ulonglong left,
360                 my_ulonglong bottom, my_ulonglong right)
361 {
362         unsigned int i,j;
363         int ret;
364         MYSQL_ROW row;
365
366         for (i = top; i <= bottom; i++) {
367                 row = mysql_fetch_row(result);
368                 if (!row || !row[0])
369                         return -E_NOROW;
370                 for (j = left; j <= right; j++) {
371                         ret = send_va_buffer(fd, j == left? "%s" : "\t%s",
372                                         row[j]?  row[j] : "NULL");
373                         if (ret < 0)
374                                 return ret;
375                 }
376                 ret = send_buffer(fd, "\n");
377                 if (ret < 0)
378                         return ret;
379         }
380         return 0;
381 }
382
383 /*
384  * verbatim
385  */
386 int com_verb(int fd, int argc, char *argv[])
387 {
388         void *result = NULL;
389         int ret;
390         my_ulonglong num_rows, num_fields, top = 0, left = 0;
391         char *tmp;
392
393         if (argc < 2)
394                 return -E_MYSQL_SYNTAX;
395         tmp = escape_str(argv[1]);
396         if (!tmp)
397                 return -E_ESCAPE;
398         result = get_result(tmp);
399         free(tmp);
400         if (!result)
401                 /* return success, because it's ok to have no results */
402                 return 1;
403         num_fields = mysql_field_count(mysql_ptr);
404         num_rows = mysql_num_rows(result);
405         ret = 1;
406         if (num_fields && num_rows)
407                 ret = print_results(fd, result, top, left, num_rows - 1,
408                         num_fields - 1);
409         mysql_free_result(result);
410         return ret;
411 }
412
413 /* returns NULL on errors or if there are no atts defined yet */
414 static void *get_all_attributes(void)
415 {
416         void *result = get_result("desc data");
417         unsigned int num_rows;
418
419         if (!result)
420                 return NULL;
421         num_rows = mysql_num_rows(result);
422         if (num_rows < 5) {
423                 mysql_free_result(result);
424                 return NULL;
425         }
426         mysql_data_seek(result, (my_ulonglong)4); /* skip Lastplayed, Numplayed... */
427         return result;
428 }
429
430 /*
431  * list all attributes
432  */
433 int com_laa(int fd, int argc, __a_unused char *argv[])
434 {
435         void *result;
436         int ret;
437         my_ulonglong top = 0, left = 0, bottom, right = 0;
438
439         if (argc != 1)
440                 return -E_MYSQL_SYNTAX;
441         result = get_all_attributes();
442         if (!result)
443                 return -E_NOATTS;
444         bottom = mysql_num_rows(result);
445         if (bottom < 5)
446                 return -E_MYSQL_SYNTAX;
447         bottom -= 5;
448         ret = print_results(fd, result, top, left, bottom, right);
449         mysql_free_result(result);
450         return ret;
451 }
452
453 /*
454  * history
455  */
456 int com_hist(int fd, int argc, char *argv[])
457 {
458         int ret;
459         void *result = NULL;
460         char *q, *atts;
461         my_ulonglong num_rows, top = 0, left = 0, right = 1;
462
463         if (argc > 3)
464                 return -E_MYSQL_SYNTAX;
465         if (argc > 1) {
466                 char *tmp = escape_str(argv[1]);
467                 if (!tmp)
468                         return -E_ESCAPE;
469                 atts = make_message("where %s = '1'", tmp);
470                 free(tmp);
471         } else
472                 atts = para_strdup(NULL);
473
474         q = make_message("select name, to_days(now()) - to_days(lastplayed) from "
475                 "data %s order by lastplayed", atts);
476         free(atts);
477         result = get_result(q);
478         free(q);
479         if (!result)
480                 return -E_NORESULT;
481         num_rows = mysql_num_rows(result);
482         ret = 1;
483         if (num_rows)
484                 ret = print_results(fd, result, top, left, num_rows - 1, right);
485         mysql_free_result(result);
486         return ret;
487 }
488
489 /*
490  * get last num audio files
491  */
492 int com_last(int fd, int argc, char *argv[])
493 {
494         void *result = NULL;
495         char *q;
496         int num, ret;
497         my_ulonglong top = 0, left = 0, right = 0;
498
499         if (argc < 2)
500                 num = 10;
501         else
502                 num = atoi(argv[1]);
503         if (!num)
504                 return -E_MYSQL_SYNTAX;
505         q = make_message("select name from data order by lastplayed desc "
506                 "limit %u", num);
507         result = get_result(q);
508         free(q);
509         if (!result)
510                 return -E_NORESULT;
511         ret = print_results(fd, result, top, left, mysql_num_rows(result) - 1,
512                 right);
513         mysql_free_result(result);
514         return ret;
515 }
516
517 int com_mbox(int fd, int argc, char *argv[])
518 {
519         void *result;
520         MYSQL_ROW row;
521         int ret;
522         my_ulonglong num_rows, num_fields, top = 0, left = 0;
523         char *query = para_strdup("select concat('From foo@localhost ', "
524                 "date_format(Lastplayed, '%a %b %e %T %Y'), "
525                 "'\nReceived: from\nTo: bar\n");
526
527         ret = -E_NOATTS;
528         result = get_all_attributes();
529         if (!result)
530                 goto out;
531         ret = -E_NOROW;
532         while ((row = mysql_fetch_row(result))) {
533                 char *tmp;
534
535                 if (!row[0])
536                         goto out;
537                 tmp = make_message("%sX-Attribute-%s: ', %s, '\n", query,
538                         row[0], row[0]);
539                 free(query);
540                 query = tmp;
541         }
542         query = para_strcat(query,
543                 "From: a\n"
544                 "Subject: "
545                 "', name, '"
546                 "\n\n\n"
547                 "') from data"
548         );
549         if (argc >= 2) {
550                 char *esc = escape_str(argv[1]), *tmp;
551                 ret = -E_ESCAPE;
552                 if (!esc)
553                         goto out;
554                 tmp = make_message("%s where name LIKE '%s'", query, esc);
555                 free(esc);
556                 free(query);
557                 query = tmp;
558         }
559         mysql_free_result(result);
560         ret = -E_NORESULT;
561         result = get_result(query);
562         if (!result)
563                 goto out;
564         ret = -E_EMPTY_RESULT;
565         num_fields = mysql_field_count(mysql_ptr);
566         num_rows = mysql_num_rows(result);
567         if (!num_fields || !num_rows)
568                 goto out;
569         ret = print_results(fd, result, top, left, num_rows - 1,
570                 num_fields - 1);
571 out:
572         free(query);
573         if (result)
574                 mysql_free_result(result);
575         return ret;
576 }
577
578 /*
579  * get attributes by name. If verbose is not 0, this function returns a string
580  * of the form 'att1="0",att2="1"'... which is used in com_cam() for
581  * constructing a mysql update query. Otherwise the space-separated list of all
582  * attributes which are set in the audio file given by name is returned.  Never
583  * returns NULL in *NON VERBOSE* mode.
584  */
585 static char *get_atts(char *name, int verbose)
586 {
587         char *atts = NULL, *buf, *ebn;
588         void *result = NULL, *result2 = NULL;
589         MYSQL_ROW row, row2;
590         int i;
591         my_ulonglong num_fields, offset = 4; /* skip Lastplayed, Numplayed... */
592
593
594         result2 = get_all_attributes();
595         if (!result2)
596                 goto out;
597         ebn = escaped_basename(name);
598         if (!ebn)
599                 goto out;
600         buf = make_message("select * from data where name='%s'", ebn);
601         free(ebn);
602         result = get_result(buf);
603         free(buf);
604         if (!result)
605                 goto out;
606         num_fields = mysql_num_fields(result);
607         if (num_fields < 5)
608                 goto out;
609         mysql_data_seek(result2, offset);
610         row = mysql_fetch_row(result);
611         if (!row)
612                 goto out;
613         for (i = 4; i < num_fields; i++) {
614                 int is_set = row[i] && !strcmp(row[i], "1");
615                 row2 = mysql_fetch_row(result2);
616                 if (!row2 || !row2[0])
617                         goto out;
618                 if (atts && (verbose || is_set))
619                         atts = para_strcat(atts, verbose? "," : " ");
620                 if (is_set || verbose)
621                         atts = para_strcat(atts, row2[0]);
622                 if (verbose)
623                         atts = para_strcat(atts, is_set? "=\"1\"" : "=\"0\"");
624         }
625 out:
626         if (result2)
627                 mysql_free_result(result2);
628         if (result)
629                 mysql_free_result(result);
630         if (!atts && !verbose)
631                 atts = para_strdup("(none)");
632         return atts;
633 }
634
635 /* never returns NULL in verbose mode */
636 static char *get_meta(char *name, int verbose)
637 {
638         MYSQL_ROW row;
639         void *result = NULL;
640         char *ebn, *q, *ret = NULL;
641         const char *verbose_fmt =
642                 "select concat('lastplayed: ', "
643                 "(to_days(now()) - to_days(lastplayed)),"
644                 "' day(s). numplayed: ', numplayed, "
645                 "', pic: ', pic_id) "
646                 "from data where name = '%s'";
647         /* is that really needed? */
648         const char *fmt = "select concat('lastplayed=\\'', lastplayed, "
649                 "'\\', numplayed=\\'', numplayed, "
650                 "'\\', pic_id=\\'', pic_id, '\\'') "
651                 "from data where name = '%s'";
652
653         if (!(ebn = escaped_basename(name)))
654                 goto out;
655         q = make_message(verbose? verbose_fmt : fmt, ebn);
656         free(ebn);
657         result = get_result(q);
658         free(q);
659         if (!result)
660                 goto out;
661         row = mysql_fetch_row(result);
662         if (!row || !row[0])
663                 goto out;
664         ret = para_strdup(row[0]);
665 out:
666         if (result)
667                 mysql_free_result(result);
668         if (!ret && verbose)
669                 ret = para_strdup("(not yet played)");
670         return ret;
671 }
672
673 static char *get_dir(char *name)
674 {
675         char *ret = NULL, *q, *ebn;
676         void *result;
677         MYSQL_ROW row;
678
679         if (!(ebn = escaped_basename(name)))
680                 return NULL;
681         q = make_message("select dir from dir where name = '%s'", ebn);
682         free(ebn);
683         result = get_result(q);
684         free(q);
685         if (!result)
686                 return NULL;
687         row = mysql_fetch_row(result);
688         if (row && row[0])
689                 ret = para_strdup(row[0]);
690         mysql_free_result(result);
691         return ret;
692 }
693
694 /* never returns NULL */
695 static char *get_current_stream(void)
696 {
697         char *ret;
698         MYSQL_ROW row;
699         void *result = get_result("select def from streams where "
700                 "name = 'current_stream'");
701
702         if (!result)
703                 goto err_out;
704         row = mysql_fetch_row(result);
705         if (!row || !row[0])
706                 goto err_out;
707         ret = para_strdup(row[0]);
708         mysql_free_result(result);
709         return ret;
710 err_out:
711         if (result)
712                 mysql_free_result(result);
713         return para_strdup("(none)");
714 }
715
716 /*
717  * Read stream definition of stream streamname and construct mysql
718  * query. Return NULL on errors. If streamname is NULL, use current
719  * stream. If that is also NULL, use query that selects everything.
720  * If filename is NULL, query will list everything, otherwise only
721  * the score of given file.
722  */
723 static char *get_query(char *streamname, char *filename, int with_path)
724 {
725         char *accept_opts = NULL, *deny_opts = NULL, *score = NULL;
726         char *where_clause, *order, *query;
727         char command[255] = ""; /* buffer for sscanf */
728         void *result;
729         MYSQL_ROW row;
730         char *end, *tmp;
731         char *select_clause = NULL;
732         if (!streamname)
733                 tmp = get_current_stream();
734         else {
735                 tmp = escape_str(streamname);
736                 if (!tmp)
737                         return NULL;
738         }
739         if (!strcmp(tmp, "(none)")) {
740                 free(tmp);
741                 if (filename) {
742                         char *ret, *ebn = escaped_basename(filename);
743                         if (!ebn)
744                                 return NULL;
745                         ret = make_message("select to_days(now()) - "
746                                 "to_days(lastplayed) from data "
747                                 "where name = '%s'", ebn);
748                         free(ebn);
749                         return ret;
750                 }
751                 if (with_path)
752                         return make_message(
753                                 "select concat(dir.dir, '/', dir.name) "
754                                 "from data, dir where dir.name = data.name "
755                                 "order by data.lastplayed"
756                         );
757                 return make_message(
758                         "select name from data where name is not NULL "
759                         "order by lastplayed"
760                 );
761         }
762         free(tmp);
763         query = make_message("select def from streams where name = '%s'",
764                 streamname);
765         result = get_result(query);
766         free(query);
767         query = NULL;
768         if (!result)
769                 goto out;
770         row = mysql_fetch_row(result);
771         if (!row || !row[0])
772                 goto out;
773         end = row[0];
774         while (*end) {
775                 int n;
776                 char *arg, *line = end;
777
778                 if (!(end = strchr(line, '\n')))
779                         break;
780                 *end = '\0';
781                 end++;
782                 if (sscanf(line, "%200s%n", command, &n) < 1)
783                         continue;
784                 arg = line + n;
785                 if (!strcmp(command, "accept:")) {
786                         char *tmp2 = s_a_r_list(mysql_macro_list, arg);
787                         if (accept_opts)
788                                 accept_opts = para_strcat(
789                                         accept_opts, " or ");
790                         accept_opts = para_strcat(accept_opts, tmp2);
791                         free(tmp2);
792                         continue;
793                 }
794                 if (!strcmp(command, "deny:")) {
795                         char *tmp2 = s_a_r_list(mysql_macro_list, arg);
796                         if (deny_opts)
797                                 deny_opts = para_strcat(deny_opts, " or ");
798                         deny_opts = para_strcat(deny_opts, tmp2);
799                         free(tmp2);
800                         continue;
801                 }
802                 if (!score && !strcmp(command, "score:"))
803                         score = s_a_r_list(mysql_macro_list, arg);
804         }
805         if (!score) {
806                 score = s_a_r_list(mysql_macro_list, conf.mysql_default_score_arg);
807                 if (!score)
808                         goto out;
809         }
810         if (filename) {
811                 char *ebn = escaped_basename(filename);
812                 if (!ebn)
813                         goto out;
814                 select_clause = make_message("select %s from data ", score);
815                 free(score);
816                 where_clause = make_message( "where name = '%s' ", ebn);
817                 free(ebn);
818                 order = para_strdup("");
819                 goto write_query;
820         }
821         select_clause = para_strdup(with_path?
822                 "select concat(dir.dir, '/', dir.name) from data, dir "
823                 "where dir.name = data.name "
824                 :
825                 "select name from data where name is not NULL");
826         order = make_message("order by -(%s)", score);
827         free(score);
828         if (accept_opts && deny_opts) {
829                 where_clause = make_message("and ((%s) and not (%s)) ",
830                         accept_opts, deny_opts);
831                 goto write_query;
832         }
833         if (accept_opts && !deny_opts) {
834                 where_clause = make_message("and (%s) ", accept_opts);
835                 goto write_query;
836         }
837         if (!accept_opts && deny_opts) {
838                 where_clause = make_message("and not (%s) ", deny_opts);
839                 goto write_query;
840         }
841         where_clause = para_strdup("");
842 write_query:
843         query = make_message("%s %s %s", select_clause, where_clause, order);
844         free(order);
845         free(select_clause);
846         free(where_clause);
847 out:
848         if (accept_opts)
849                 free(accept_opts);
850         if (deny_opts)
851                 free(deny_opts);
852         if (result)
853                 mysql_free_result(result);
854         return query;
855 }
856
857
858
859 /*
860  * This is called from server and from some commands. Name must not be NULL
861  * Never returns NULL.
862  */
863 static char *get_selector_info(char *name)
864 {
865         char *meta, *atts, *info, *dir, *query, *stream;
866         void *result = NULL;
867         MYSQL_ROW row = NULL;
868
869         if (!name)
870                 return para_strdup("(none)");
871         stream = get_current_stream();
872         meta = get_meta(name, 1);
873         atts = get_atts(name, 0);
874         dir = get_dir(name);
875         /* get score */
876         query = get_query(stream, name, 0); /* FIXME: pass stream == NULL instead? */
877         if (!query)
878                 goto write;
879         result = get_result(query);
880         free(query);
881         if (result)
882                 row = mysql_fetch_row(result);
883 write:
884         info = make_message("dbinfo1:dir: %s\n"
885                 "dbinfo2:stream: %s, %s, score: %s\n"
886                 "dbinfo3:%s\n",
887                 dir? dir : "(not contained in table)",
888                 stream, meta, 
889                 (result && row && row[0])? row[0] : "(no score)",
890                 atts);
891         free(dir);
892         free(meta);
893         free(atts);
894         free(stream);
895         if (result)
896                 mysql_free_result(result);
897         return info;
898 }
899
900 /* might return NULL */
901 static char *get_current_audio_file(void)
902 {
903         char *name;
904         mmd_lock();
905         name = para_basename(mmd->filename);
906         mmd_unlock();
907         return name;
908 }
909
910 /* If called as child, mmd_lock must be held */
911 static void update_mmd(char *info)
912 {
913         PARA_DEBUG_LOG("%s", "updating shared memory area\n");
914         strncpy(mmd->selector_info, info, MMD_INFO_SIZE - 1);
915         mmd->selector_info[MMD_INFO_SIZE - 1] = '\0';
916 }
917
918 static void refresh_selector_info(void)
919 {
920         char *name = get_current_audio_file();
921         char *info;
922
923         if (!name)
924                 return;
925         info = get_selector_info(name);
926         free(name);
927         mmd_lock();
928         update_mmd(info);
929         mmd_unlock();
930         free(info);
931 }
932
933 /* list attributes / print database info */
934 static int com_la_info(int fd, int argc, char *argv[])
935 {
936         char *name = NULL, *meta = NULL, *atts = NULL, *dir = NULL;
937         int ret, la = strcmp(argv[0], "info");
938
939         if (argc < 2) {
940                 ret = -E_GET_AUDIO_FILE;
941                 if (!(name = get_current_audio_file()))
942                         goto out;
943                 ret = send_va_buffer(fd, "%s\n", name);
944                 if (ret < 0)
945                         goto out;
946         } else {
947                 ret = -E_ESCAPE;
948                 if (!(name = escaped_basename(argv[1])))
949                         goto out;
950         }
951         meta = get_meta(name, 1);
952         atts = get_atts(name, 0);
953         dir = get_dir(name);
954         if (la)
955                 ret = send_va_buffer(fd, "%s\n", atts);
956         else
957                 ret = send_va_buffer(fd, "dir: %s\n" "%s\n" "attributes: %s\n",
958                         dir? dir : "(not contained in table)", meta, atts);
959 out:
960         free(meta);
961         free(atts);
962         free(dir);
963         free(name);
964         return ret;
965 }
966
967 /* list attributes */
968 int com_la(int fd, int argc, char *argv[])
969 {
970         return com_la_info(fd, argc, argv);
971 }
972
973 /* print database info */
974 int com_info(int fd, int argc, char *argv[])
975 {
976         return com_la_info(fd, argc, argv);
977 }
978
979 static int change_stream(const char *stream)
980 {
981         char *query;
982         int ret;
983         query = make_message("update streams set def='%s' "
984                 "where name = 'current_stream'", stream);
985         ret = real_query(query);
986         free(query);
987         return ret;
988 }
989
990 static int get_pic_id_by_name(char *name)
991 {
992         char *q, *ebn;
993         void *result = NULL;
994         int ret;
995         MYSQL_ROW row;
996
997         if (!(ebn = escaped_basename(name)))
998                 return -E_ESCAPE;
999         q = make_message("select pic_id from data where name = '%s'", ebn);
1000         free(ebn);
1001         result = get_result(q);
1002         free(q);
1003         if (!result)
1004                 return -E_NORESULT;
1005         row = mysql_fetch_row(result);
1006         ret = -E_NOROW;
1007         if (row && row[0])
1008                 ret = atoi(row[0]);
1009         mysql_free_result(result);
1010         return ret;
1011 }
1012
1013 static int remove_entry(const char *name)
1014 {
1015         char *q, *ebn = escaped_basename(name);
1016         int ret = -E_ESCAPE;
1017
1018         if (!ebn)
1019                 goto out;
1020         q = make_message("delete from data where name = '%s'", ebn);
1021         real_query(q); /* ignore errors */
1022         free(q);
1023         q = make_message("delete from dir where name = '%s'", ebn);
1024         real_query(q); /* ignore errors */
1025         free(q);
1026         ret = 1;
1027 out:
1028         free(ebn);
1029         return ret;
1030 }
1031
1032 static int add_entry(const char *name)
1033 {
1034         char *q, *dn, *ebn = NULL, *edn = NULL;
1035         int ret;
1036
1037         if (!name || !*name)
1038                 return -E_MYSQL_SYNTAX;
1039         ebn = escaped_basename(name);
1040         if (!ebn)
1041                 return -E_ESCAPE;
1042         ret = -E_MYSQL_SYNTAX;
1043         dn = para_dirname(name);
1044         if (!dn)
1045                 goto out;
1046         ret = -E_ESCAPE;
1047         edn = escape_str(dn);
1048         free(dn);
1049         if (!edn || !*edn)
1050                 goto out;
1051         q = make_message("insert into data (name, pic_id) values "
1052                         "('%s', '%s')", ebn, "1");
1053         ret = real_query(q);
1054 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1055         free(q);
1056         if (ret < 0)
1057                 goto out;
1058         q = make_message("insert into dir (name, dir) values "
1059                         "('%s', '%s')", ebn, edn);
1060 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1061         ret = real_query(q);
1062         free(q);
1063 out:
1064         if (ebn)
1065                 free(ebn);
1066         if (edn)
1067                 free(edn);
1068         return ret;
1069 }
1070
1071 /*
1072  * remove/add entries
1073  */
1074 static int com_rm_ne(__a_unused int fd, int argc, char *argv[])
1075 {
1076         int ne = !strcmp(argv[0], "ne");
1077         int i, ret;
1078         if (argc < 2)
1079                 return -E_MYSQL_SYNTAX;
1080         for (i = 1; i < argc; i++) {
1081                 ret = remove_entry(argv[i]);
1082                 if (ret < 0)
1083                         return ret;
1084                 if (!ne)
1085                         continue;
1086                 ret = add_entry(argv[i]);
1087                 if (ret < 0)
1088                         return ret;
1089         }
1090         return 1;
1091 }
1092
1093 /*
1094  * rm
1095  */
1096 int com_rm(int fd, int argc, char *argv[])
1097 {
1098         return com_rm_ne(fd, argc, argv);
1099 }
1100
1101 /*
1102  * ne
1103  */
1104 int com_ne(int fd, int argc, char *argv[])
1105 {
1106         return com_ne(fd, argc, argv);
1107 }
1108
1109 /*
1110  * mv: rename entry
1111  */
1112 int com_mv(__a_unused int fd, int argc, char *argv[])
1113 {
1114         char *q, *dn, *ebn1 = NULL, *ebn2 = NULL, *edn = NULL;
1115         int ret;
1116
1117         if (argc != 3)
1118                 return -E_MYSQL_SYNTAX;
1119         ret = -E_ESCAPE;
1120         ebn1 = escaped_basename(argv[1]);
1121         ebn2 = escaped_basename(argv[2]);
1122         if (!ebn1 || !ebn2 || !*ebn1 || !*ebn2)
1123                 goto out;
1124         ret = -E_MYSQL_SYNTAX;
1125         if (!strcmp(ebn1, ebn2))
1126                 goto update_dir;
1127         remove_entry(argv[2]); /* no need to escape, ignore error */
1128         q = make_message("update data set name = '%s' where name = '%s'",
1129                 ebn2, ebn1);
1130         ret = real_query(q);
1131         free(q);
1132         if (ret < 0)
1133                 goto out;
1134         ret = -E_AUDIO_FILE;
1135         if (!mysql_affected_rows(mysql_ptr))
1136                 goto out;
1137         q = make_message("update dir set name = '%s' where name = '%s'",
1138                 ebn2, ebn1);
1139         ret = real_query(q);
1140         free(q);
1141         if (ret < 0)
1142                 goto out;
1143 update_dir:
1144         ret = 1;
1145         dn = para_dirname(argv[2]);
1146         if (!dn)
1147                 goto out;
1148         ret = -E_ESCAPE;
1149         edn = escape_str(dn);
1150         free(dn);
1151         if (!edn)
1152                 goto out;
1153         ret = 1;
1154         if (!*edn)
1155                 goto out;
1156         q = make_message("update dir set dir = '%s' where name = '%s'",
1157                 edn, ebn2);
1158         ret = real_query(q);
1159         free(q);
1160 out:
1161         free(edn);
1162         free(ebn1);
1163         free(ebn2);
1164         return ret;
1165 }
1166
1167 /*
1168  * set field
1169  */
1170 static int com_set(__a_unused int fd, int argc, char *argv[])
1171 {
1172         char *q, *ebn;
1173         long unsigned id;
1174         int i, ret;
1175         const char *field = strcmp(argv[0], "picass")? "numplayed" : "pic_id";
1176
1177         if (argc < 3)
1178                 return -E_MYSQL_SYNTAX;
1179         id = atol(argv[1]);
1180         for (i = 2; i < argc; i++) {
1181                 ebn = escaped_basename(argv[i]);
1182                 if (!ebn)
1183                         return -E_ESCAPE;
1184                 q = make_message("update data set %s = %lu "
1185                                 "where name = '%s'", field, id, ebn);
1186                 free(ebn);
1187                 ret = real_query(q);
1188                 free(q);
1189                 if (ret < 0)
1190                         return ret;
1191         }
1192         return 1;
1193 }
1194
1195 /*
1196  * snp: set numplayed
1197  */
1198 int com_picass(int fd, int argc, char *argv[])
1199 {
1200         return com_set(fd, argc, argv);
1201 }
1202
1203 /*
1204  * snp: set numplayed
1205  */
1206 int com_snp(int fd, int argc, char *argv[])
1207 {
1208         int ret = com_set(fd, argc, argv);
1209         if (ret >= 0)
1210                 refresh_selector_info();
1211         return ret;
1212 }
1213
1214 /*
1215  * picch: change entry's name in pics table
1216  */
1217 int com_picch(__a_unused int fd, int argc, char *argv[])
1218 {
1219         int ret;
1220         long unsigned id;
1221         char *q, *tmp;
1222
1223         if (argc != 3)
1224                 return -E_MYSQL_SYNTAX;
1225         id = atol(argv[1]);
1226         ret = -E_ESCAPE;
1227         tmp = escape_str(argv[2]);
1228         if (!tmp)
1229                 return -E_ESCAPE;
1230         q = make_message("update pics set name = '%s' where id = %lu", tmp, id);
1231         free(tmp);
1232         ret = real_query(q);
1233         free(q);
1234         return ret;
1235 }
1236
1237 /*
1238  * piclist: print list of pics in db
1239  */
1240 int com_piclist(__a_unused int fd, int argc, __a_unused char *argv[])
1241 {
1242         void *result = NULL;
1243         MYSQL_ROW row;
1244         unsigned long *length;
1245         int ret;
1246
1247         if (argc != 1)
1248                 return -E_MYSQL_SYNTAX;
1249         result = get_result("select id,name,pic from pics order by id");
1250         if (!result)
1251                 return -E_NORESULT;
1252         while ((row = mysql_fetch_row(result))) {
1253                 length = mysql_fetch_lengths(result);
1254                 if (!row || !row[0] || !row[1] || !row[2])
1255                         continue;
1256                 ret = send_va_buffer(fd, "%s\t%lu\t%s\n", row[0], length[2], row[1]);
1257                 if (ret < 0)
1258                         goto out;
1259         }
1260         ret = 1;
1261 out:
1262         mysql_free_result(result);
1263         return ret;
1264 }
1265
1266 /*
1267  * picdel: delete picture from database
1268  */
1269 int com_picdel(int fd, int argc, char *argv[])
1270 {
1271         char *q;
1272         long unsigned id;
1273         my_ulonglong aff;
1274         int i, ret;
1275
1276         if (argc < 2)
1277                 return -E_MYSQL_SYNTAX;
1278         for (i = 1; i < argc; i++) {
1279                 id = atol(argv[i]);
1280                 q = make_message("delete from pics where id = %lu", id);
1281                 ret = real_query(q);
1282                 free(q);
1283                 if (ret < 0)
1284                         return ret;
1285                 aff = mysql_affected_rows(mysql_ptr);
1286                 if (!aff) {
1287                         ret = send_va_buffer(fd, "No such id: %lu\n", id);
1288                         if (ret < 0)
1289                                 return ret;
1290                         continue;
1291                 }
1292                 q = make_message("update data set pic_id = 1 where pic_id = %lu", id);
1293                 ret = real_query(q);
1294                 free(q);
1295         }
1296         return 1;
1297 }
1298 /*
1299  * pic: get picture by name or by number
1300  */
1301 int com_pic(int fd, int argc, char *argv[])
1302 {
1303         void *result = NULL;
1304         MYSQL_ROW row;
1305         unsigned long *length, id;
1306         int ret;
1307         char *q, *name = NULL;
1308
1309         if (argc < 2) {
1310                 ret = -E_GET_AUDIO_FILE;
1311                 name = get_current_audio_file();
1312         } else {
1313                 ret = -E_ESCAPE;
1314                 name = escaped_basename(argv[1]);
1315         }
1316         if (!name)
1317                 return ret;
1318         if (*name == '#')
1319                 id = atoi(name + 1);
1320         else
1321                 id = get_pic_id_by_name(name);
1322         free(name);
1323         if (id <= 0)
1324                 return id;
1325         q = make_message("select pic from pics where id = '%lu'", id);
1326         result = get_result(q);
1327         free(q);
1328         if (!result)
1329                 return -E_NORESULT;
1330         row = mysql_fetch_row(result);
1331         ret = -E_NOROW;
1332         if (!row || !row[0])
1333                 goto out;
1334         length = mysql_fetch_lengths(result);
1335         ret = send_bin_buffer(fd, row[0], *length);
1336 out:
1337         mysql_free_result(result);
1338         return ret;
1339 }
1340
1341 /* strdel */
1342 int com_strdel(__a_unused int fd, int argc, char *argv[])
1343 {
1344         char *q, *tmp;
1345         int ret;
1346
1347         if (argc < 2)
1348                 return -E_MYSQL_SYNTAX;
1349         tmp = escape_str(argv[1]);
1350         if (!tmp)
1351                 return -E_ESCAPE;
1352         q = make_message("delete from streams where name='%s'", tmp);
1353         free(tmp);
1354         ret = real_query(q);
1355         free(q);
1356         return ret;
1357 }
1358
1359 /*
1360  * ls
1361  */
1362 int com_ls(int fd, int argc, char *argv[])
1363 {
1364         char *q;
1365         void *result;
1366         int ret;
1367         my_ulonglong num_rows, top = 0, left = 0, right = 0;
1368
1369         if (argc > 2)
1370                 return -E_MYSQL_SYNTAX;
1371         if (argc > 1) {
1372                 char *tmp = escape_str(argv[1]);
1373                 if (!tmp)
1374                         return -E_ESCAPE;
1375                 q = make_message("select name from data where name like '%s'",
1376                         tmp);
1377                 free(tmp);
1378         } else
1379                 q = para_strdup("select name from data");
1380         result = get_result(q);
1381         free(q);
1382         if (!result)
1383                 return -E_NORESULT;
1384         num_rows = mysql_num_rows(result);
1385         ret = 1;
1386         if (num_rows)
1387                 ret = print_results(fd, result, top, left, num_rows - 1, right);
1388         mysql_free_result(result);
1389         return ret;
1390 }
1391
1392 /*
1393  * summary
1394  */
1395 int com_summary(__a_unused int fd, int argc, __a_unused char *argv[])
1396 {
1397         MYSQL_ROW row;
1398         MYSQL_ROW row2;
1399         void *result;
1400         void *result2 = NULL;
1401         const char *fmt = "select count(name) from data where %s='1'";
1402         int ret = -E_NORESULT;
1403
1404         if (argc != 1)
1405                 return -E_MYSQL_SYNTAX;
1406         result = get_all_attributes();
1407         if (!result)
1408                 goto out;
1409         while ((row = mysql_fetch_row(result))) {
1410                 char *buf;
1411
1412                 ret = -E_NOROW;
1413                 if (!row[0])
1414                         goto out;
1415                 ret = -E_NORESULT;
1416                 buf = make_message(fmt, row[0]);
1417                 result2 = get_result(buf);
1418                 free(buf);
1419                 if (!result2)
1420                         goto out;
1421                 ret = -E_NOROW;
1422                 row2 = mysql_fetch_row(result2);
1423                 if (!row2 || !row2[0])
1424                         goto out;
1425                 ret = send_va_buffer(fd, "%s\t%s\n", row[0], row2[0]);
1426                 if (ret < 0)
1427                         goto out;
1428         }
1429         ret = 1;
1430 out:
1431         if (result2)
1432                 mysql_free_result(result2);
1433         if (result)
1434                 mysql_free_result(result);
1435         return ret;
1436 }
1437
1438 static int get_numplayed(char *name)
1439 {
1440         void *result;
1441         MYSQL_ROW row;
1442         const char *fmt = "select numplayed from data where name = '%s'";
1443         char *buf = make_message(fmt, name);
1444         int ret = -E_NORESULT;
1445
1446         result = get_result(buf);
1447         free(buf);
1448         if (!result)
1449                 goto out;
1450         ret = -E_NOROW;
1451         row = mysql_fetch_row(result);
1452         if (!row || !row[0])
1453                 goto out;
1454         ret = atoi(row[0]);
1455 out:
1456         if (result)
1457                 mysql_free_result(result);
1458         return ret;
1459 }
1460
1461 static int update_audio_file(char *name)
1462 {
1463         int ret;
1464         const char *fmt1 = "update data set lastplayed = now() where name = '%s'";
1465         const char *fmt2 = "update data set numplayed = %i where name = '%s'";
1466         char *q;
1467         char *ebn = escaped_basename(name);
1468
1469         ret = -E_ESCAPE;
1470         if (!ebn)
1471                 goto out;
1472         q = make_message(fmt1, ebn);
1473         ret = real_query(q);
1474         free(q);
1475         if (ret < 0)
1476                 goto out;
1477         ret = get_numplayed(ebn);
1478         if (ret < 0)
1479                 goto out;
1480         q = make_message(fmt2, ret + 1, ebn);
1481         ret = real_query(q);
1482         free(q);
1483 out:
1484         free(ebn);
1485         return ret;
1486 }
1487
1488 static void update_audio_file_server_handler(char *name)
1489 {
1490         char *info;
1491         info = get_selector_info(name);
1492         update_mmd(info);
1493         free(info);
1494         update_audio_file(name);
1495 }
1496
1497 int com_us(__a_unused int fd, int argc, char *argv[])
1498 {
1499         char *tmp;
1500         int ret;
1501
1502         if (argc != 2)
1503                 return -E_MYSQL_SYNTAX;
1504         tmp = escape_str(argv[1]);
1505         if (!tmp)
1506                 return -E_ESCAPE;
1507         ret = update_audio_file(argv[1]);
1508         free(tmp);
1509         if (ret >= 0)
1510                 refresh_selector_info();
1511         return ret;
1512 }
1513
1514 /* select previous / next stream */
1515 static int com_ps_ns(__a_unused int fd, int argc, char *argv[])
1516 {
1517         char *query, *stream = get_current_stream();
1518         void *result = get_result("select name from streams");
1519         MYSQL_ROW row;
1520         int ret;
1521         my_ulonglong num_rows, match, i;
1522
1523         ret = -E_MYSQL_SYNTAX;
1524         if (argc != 1)
1525                 goto out;
1526         ret = -E_NORESULT;
1527         if (!result)
1528                 goto out;
1529         num_rows = mysql_num_rows(result);
1530         ret = -E_EMPTY_RESULT;
1531         if (num_rows < 2)
1532                 goto out;
1533         ret = -E_NOROW;
1534         for (i = 0; i < num_rows; i++) {
1535                 row = mysql_fetch_row(result);
1536                 if (!row || !row[0])
1537                         goto out;
1538                 if (!strcmp(row[0], "current_stream"))
1539                         continue;
1540                 if (!strcmp(row[0], stream))
1541                         break;
1542         }
1543         ret = -E_NO_STREAM;
1544         if (i == num_rows)
1545                 goto out;
1546         match = i;
1547         if (!strcmp(argv[0], "ps"))
1548                 i = match > 0? match - 1 : num_rows - 1;
1549         else
1550                 i = match < num_rows - 1? match + 1 : 0;
1551         ret = -E_NOROW;
1552         mysql_data_seek(result, i);
1553         row = mysql_fetch_row(result);
1554         if (!row || !row[0])
1555                 goto out;
1556         if (!strcmp(row[0], "current_stream")) {
1557                 if (!strcmp(argv[0], "ps")) {
1558                         i = match < 2? match + num_rows - 2 : match - 2;
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         MYSQL_ROW row;
1934         char *escaped_name;
1935         my_ulonglong num_rows, top = 0, left = 0, right = 0;
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, top, left, num_rows - 1, right);
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         unsigned int port;
2141
2142         mysql_ptr = mysql_init(NULL);
2143         if (!mysql_ptr) {
2144                 PARA_CRIT_LOG("%s", "mysql init error\n");
2145                 return -E_NOTCONN;
2146         }
2147         if (conf.mysql_port_arg < 0)
2148                 return -E_MYSQL_SYNTAX;
2149         port = conf.mysql_port_arg;
2150         PARA_DEBUG_LOG("connecting: %s@%s:%d\n", u, conf.mysql_host_arg, port);
2151         if (!conf.mysql_user_arg)
2152                 free(u);
2153         /*
2154          * If host is NULL a connection to the local host is assumed,
2155          * If user is NULL, the current user is assumed
2156          */
2157         if (!(mysql_ptr = mysql_real_connect(mysql_ptr,
2158                         conf.mysql_host_arg,
2159                         conf.mysql_user_arg,
2160                         conf.mysql_passwd_arg,
2161                         conf.mysql_database_arg,
2162                         port, NULL, 0))) {
2163                 PARA_CRIT_LOG("%s", "connect error\n");
2164                 return -E_NOTCONN;
2165         }
2166         PARA_INFO_LOG("%s", "success\n");
2167         return 1;
2168 }
2169
2170 /* mmd lock must be held */
2171 static void write_msg2mmd(int success)
2172 {
2173         sprintf(mmd->selector_info, "dbinfo1:%s\ndbinfo2:mysql-%s\ndbinfo3:\n",
2174                 success < 0? PARA_STRERROR(-success) :
2175                         "successfully connected to mysql server",
2176                 success < 0? "" : mysql_get_server_info(mysql_ptr));
2177 }
2178
2179 /* create database */
2180 int com_cdb(int fd, int argc, char *argv[])
2181 {
2182         char *query;
2183         int ret;
2184
2185         if (mysql_ptr) {
2186                 PARA_INFO_LOG("%s", "closing database\n");
2187                 mysql_close(mysql_ptr);
2188         }
2189         /* dont use any database */
2190         conf.mysql_database_arg = NULL; /* leak? */
2191         ret = -E_MYSQL_INIT;
2192         if (init_mysql_server() < 0 || !mysql_ptr)
2193                 goto out;
2194         if (argc < 2)
2195                 conf.mysql_database_arg = para_strdup("paraslash");
2196         else {
2197                 ret = -E_ESCAPE;
2198                 conf.mysql_database_arg = escape_str(argv[1]);
2199                 if (!conf.mysql_database_arg)
2200                         goto out;
2201         }
2202         query = make_message("create database %s", conf.mysql_database_arg);
2203         ret = real_query(query);
2204         free(query);
2205         if (ret < 0)
2206                 goto out;
2207         /* reconnect with database just created */
2208         mysql_close(mysql_ptr);
2209         ret = -E_MYSQL_INIT;
2210         if (init_mysql_server() < 0 || !mysql_ptr)
2211                 goto out;
2212         mmd_lock();
2213         write_msg2mmd(1);
2214         mmd_unlock();
2215         ret = -E_QFAILED;
2216         if (real_query("create table data (name varchar(255) binary not null "
2217                         "primary key, "
2218                         "lastplayed datetime not null default "
2219                                 "'1970-01-01', "
2220                         "numplayed int not null default 0, "
2221                         "pic_id bigint unsigned not null default 1)") < 0)
2222                 goto out;
2223         if (real_query("create table dir (name varchar(255) binary not null "
2224                         "primary key, dir varchar(255) default null)") < 0)
2225                 goto out;
2226         if (real_query("create table pics ("
2227                         "id bigint(20) unsigned not null primary key "
2228                         "auto_increment, "
2229                         "name varchar(255) binary not null, "
2230                         "pic mediumblob not null)") < 0)
2231                 goto out;
2232         if (real_query("create table streams ("
2233                         "name varchar(255) binary not null primary key, "
2234                         "def blob not null)") < 0)
2235                 goto out;
2236         if (real_query("insert into streams (name, def) values "
2237                         "('current_stream', '(none)')") < 0)
2238                 goto out;
2239         ret = send_va_buffer(fd, "successfully created database %s\n",
2240                 conf.mysql_database_arg);
2241 out:
2242         return ret;
2243 }
2244
2245 static void shutdown_connection(void)
2246 {
2247         if (mysql_ptr) {
2248                 PARA_NOTICE_LOG("%s", "shutting down mysql connection\n");
2249                 mysql_close(mysql_ptr);
2250                 mysql_ptr = NULL;
2251         }
2252 }
2253
2254 /**
2255  * the init function of the mysql-based audio file selector
2256  *
2257  * \param db pointer to the struct to initialize
2258  *
2259  * Check the command line options and initialize all function pointers of \a
2260  * db.  Connect to the mysql server and initialize the info string.
2261  *
2262  * \return This function returns success even if it could not connect
2263  * to the mysql server. This is because the connect is expected to fail
2264  * if there the paraslash database is not yet created. This gives the
2265  * user a chance to send the "cdb" to create the database.
2266  *
2267  * \sa struct audio_file_selector, misc_meta_data::selector_info,
2268  * random_selector.c
2269  */
2270 int mysql_selector_init(struct audio_file_selector *db)
2271 {
2272         int ret;
2273
2274         if (!conf.mysql_passwd_given)
2275                 return -E_NO_MYSQL_PASSWD;
2276         if (!conf.mysql_audio_file_dir_given)
2277                 return -E_NO_AF_DIR;
2278         db->name = "mysql";
2279         db->cmd_list = mysql_selector_cmds;
2280         db->get_audio_file_list = server_get_audio_file_list;
2281         db->update_audio_file = update_audio_file_server_handler;
2282         db->shutdown = shutdown_connection;
2283         ret = init_mysql_server();
2284         if (ret < 0)
2285                 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
2286         write_msg2mmd(ret);
2287         return 1;       /* return success even if connect failed to give the
2288                          * user the chance to exec com_cdb
2289                          */
2290 }