2 * Copyright (C) 1999-2007 Andre Noll <maan@systemlinux.org>
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.
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.
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.
19 /** \file mysql_selector.c para_server's mysql-based audio file selector */
21 /** \cond some internal constants */
22 #define MEDIUM_BLOB_SIZE 16777220 /* (2**24 + 4) */
23 #define BLOB_SIZE 65539 /* (2**16 + 3) */
25 #include "server.cmdline.h"
29 #include <mysql/mysql.h>
30 #include <mysql/mysql_version.h>
35 #include "user_list.h"
36 #include "mysql_selector_command_list.h"
38 /** pointer to the shared memory area */
39 extern struct misc_meta_data *mmd;
41 static void *mysql_ptr = NULL;
44 * contains name/replacement pairs used by s_a_r_list()
49 /** the name of the macro */
51 /** the replacement text */
52 const char *replacement;
55 static const struct para_macro mysql_macro_list[] = {
57 .replacement = "(data.%s != '1')"
60 .replacement = "(data.%s = '1')"
63 .replacement = "%sdata.Pic_Id"
66 .replacement = "(data.name like '%s')"
69 .replacement = "%sFLOOR((UNIX_TIMESTAMP(now())"
70 "-UNIX_TIMESTAMP(data.Lastplayed))/60)"
73 .replacement = "%sdata.Numplayed"
80 * simple search and replace routine
82 * \param src source string
83 * \param macro_name the name of the macro
84 * \param replacement the replacement format string
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
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.
96 __must_check __malloc static char *s_a_r(const char *src, const char* macro_name,
97 const char *replacement)
101 regmatch_t pmatch[1];
104 const char *bufptr = src;
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)
111 char *tmp, *arg, *o_bracket, *c_bracket;
113 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
114 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
117 tmp = para_strdup(bufptr);
118 tmp[pmatch[0].rm_so] = '\0';
119 dest = para_strcat(dest, tmp);
122 arg = para_strdup(o_bracket + 1);
123 arg[c_bracket - o_bracket - 1] = '\0';
124 tmp = make_message(replacement, arg);
126 dest = para_strcat(dest, tmp);
131 dest = para_strcat(dest, bufptr);
132 // PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
139 * replace a string according to a list of macros
141 * \param macro_list the array containing a macro/replacement pairs.
142 * \param src the source string
144 * This function just calls s_a_r() for each element of \p macro_list.
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.
149 __must_check __malloc static char *s_a_r_list(const struct para_macro *macro_list,
152 const struct para_macro *mp = macro_list;
153 char *ret = NULL, *tmp = para_strdup(src);
156 ret = s_a_r(tmp, mp->name, mp->replacement);
158 if (!ret) /* syntax error */
163 //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
167 static int real_query(const char *query)
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));
181 * Use open connection given by mysql_ptr to query server. Returns a
182 * result pointer on succes and NULL on errors
184 static struct MYSQL_RES *get_result(const char *query)
188 if (real_query(query) < 0)
190 result = mysql_store_result(mysql_ptr);
192 PARA_ERROR_LOG("%s", "store_result error\n");
196 * write input from fd to dynamically allocated char array,
197 * but maximal max_size byte. Return size.
199 static int fd2buf(int fd, char **buf_ptr, size_t max_size)
201 const size_t chunk_size = 1024;
203 char *buf = para_malloc(size * sizeof(char)), *p = buf;
206 while ((ret = recv_bin_buffer(fd, p, chunk_size)) > 0) {
208 if ((p - buf) + chunk_size >= size) {
212 if (size > max_size) {
216 tmp = para_realloc(buf, size);
231 static char *escape_blob(const char* old, int size)
235 if (!mysql_ptr || size < 0)
237 new = para_malloc(2 * size * sizeof(char) + 1);
238 mysql_real_escape_string(mysql_ptr, new, old, size);
242 static char *escape_str(const char* old)
244 return escape_blob(old, strlen(old));
247 static char *escaped_basename(const char *name)
249 char *esc, *bn = para_basename(name);
253 esc = escape_str(bn);
261 int com_na(__a_unused int fd, int argc, char *argv[])
267 return -E_MYSQL_SYNTAX;
268 tmp = escape_str(argv[1]);
271 q = make_message("alter table data add %s char(1) "
272 "not null default 0", tmp);
282 int com_da(__a_unused int fd, int argc, char *argv[])
288 return -E_MYSQL_SYNTAX;
289 tmp = escape_str(argv[1]);
292 q = make_message("alter table data drop %s", tmp);
300 static int com_stradd_picadd(int fd, int argc, char *argv[])
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");
308 return -E_MYSQL_SYNTAX;
309 if (strlen(argv[1]) >= MAXLINE - 1)
310 return -E_NAMETOOLONG;
315 fmt = "insert into streams (name, def) values ('%s','%s')";
316 del_fmt="delete from streams where name='%s'";
318 size = MEDIUM_BLOB_SIZE;
319 fmt = "insert into pics (name, pic) values ('%s','%s')";
320 del_fmt="delete from pics where pic='%s'";
322 tmp = escape_str(argv[1]);
325 q = make_message(del_fmt, tmp);
331 if ((ret = send_buffer(fd, AWAITING_DATA_MSG) < 0))
333 if ((ret = fd2buf(fd, &blob, size)) < 0)
339 esc_blob = escape_blob(blob, size);
342 tmp = escape_str(argv[1]);
345 q = make_message(fmt, tmp, esc_blob);
356 int com_stradd(int fd, int argc, char *argv[])
358 return com_stradd_picadd(fd, argc, argv);
362 int com_picadd(int fd, int argc, char *argv[])
364 return com_stradd_picadd(fd, argc, argv);
368 * print results to fd
370 static int print_results(int fd, void *result,
371 unsigned int top, unsigned int left,
372 unsigned int bottom, unsigned int right)
378 for (i = top; i <= bottom; i++) {
379 row = mysql_fetch_row(result);
382 for (j = left; j <= right; j++) {
383 ret = send_va_buffer(fd, j == left? "%s" : "\t%s",
384 row[j]? row[j] : "NULL");
388 ret = send_buffer(fd, "\n");
398 int com_verb(int fd, int argc, char *argv[])
402 unsigned int num_rows, num_fields;
406 return -E_MYSQL_SYNTAX;
407 tmp = escape_str(argv[1]);
410 result = get_result(tmp);
413 /* return success, because it's ok to have no results */
415 num_fields = mysql_field_count(mysql_ptr);
416 num_rows = mysql_num_rows(result);
418 if (num_fields && num_rows)
419 ret = print_results(fd, result, 0, 0, num_rows - 1,
421 mysql_free_result(result);
425 /* returns NULL on errors or if there are no atts defined yet */
426 static void *get_all_attributes(void)
428 void *result = get_result("desc data");
429 unsigned int num_rows;
433 num_rows = mysql_num_rows(result);
435 mysql_free_result(result);
438 mysql_data_seek(result, 4); /* skip Lastplayed, Numplayed... */
443 * list all attributes
445 int com_laa(int fd, int argc, __a_unused char *argv[])
451 return -E_MYSQL_SYNTAX;
452 result = get_all_attributes();
455 ret = print_results(fd, result, 0, 0, mysql_num_rows(result) - 5, 0);
456 mysql_free_result(result);
463 int com_hist(int fd, int argc, char *argv[])
468 unsigned int num_rows;
471 return -E_MYSQL_SYNTAX;
473 char *tmp = escape_str(argv[1]);
476 atts = make_message("where %s = '1'", tmp);
479 atts = para_strdup(NULL);
481 q = make_message("select name, to_days(now()) - to_days(lastplayed) from "
482 "data %s order by lastplayed", atts);
484 result = get_result(q);
488 num_rows = mysql_num_rows(result);
491 ret = print_results(fd, result, 0, 0, num_rows - 1, 1);
492 mysql_free_result(result);
497 * get last num audio files
499 int com_last(int fd, int argc, char *argv[])
510 return -E_MYSQL_SYNTAX;
511 q = make_message("select name from data order by lastplayed desc "
513 result = get_result(q);
517 ret = print_results(fd, result, 0, 0, mysql_num_rows(result) - 1, 0);
518 mysql_free_result(result);
522 int com_mbox(int fd, int argc, char *argv[])
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");
533 result = get_all_attributes();
537 while ((row = mysql_fetch_row(result))) {
542 tmp = make_message("%sX-Attribute-%s: ', %s, '\n", query,
547 query = para_strcat(query,
555 char *esc = escape_str(argv[1]), *tmp;
559 tmp = make_message("%s where name LIKE '%s'", query, esc);
564 mysql_free_result(result);
566 result = get_result(query);
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)
574 ret = print_results(fd, result, 0, 0, num_rows - 1, num_fields - 1);
578 mysql_free_result(result);
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.
589 static char *get_atts(char *name, int verbose)
591 char *atts = NULL, *buf, *ebn;
592 void *result = NULL, *result2 = NULL;
597 result2 = get_all_attributes();
600 ebn = escaped_basename(name);
603 buf = make_message("select * from data where name='%s'", ebn);
605 result = get_result(buf);
609 num_fields = mysql_num_fields(result);
612 mysql_data_seek(result2, 4); /* skip Lastplayed, Numplayed... */
613 row = mysql_fetch_row(result);
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])
621 if (atts && (verbose || is_set))
622 atts = para_strcat(atts, verbose? "," : " ");
623 if (is_set || verbose)
624 atts = para_strcat(atts, row2[0]);
626 atts = para_strcat(atts, is_set? "=\"1\"" : "=\"0\"");
630 mysql_free_result(result2);
632 mysql_free_result(result);
633 if (!atts && !verbose)
634 atts = para_strdup("(none)");
638 /* never returns NULL in verbose mode */
639 static char *get_meta(char *name, int verbose)
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'";
656 if (!(ebn = escaped_basename(name)))
658 q = make_message(verbose? verbose_fmt : fmt, ebn);
660 result = get_result(q);
664 row = mysql_fetch_row(result);
667 ret = para_strdup(row[0]);
670 mysql_free_result(result);
672 ret = para_strdup("(not yet played)");
676 static char *get_dir(char *name)
678 char *ret = NULL, *q, *ebn;
682 if (!(ebn = escaped_basename(name)))
684 q = make_message("select dir from dir where name = '%s'", ebn);
686 result = get_result(q);
690 row = mysql_fetch_row(result);
692 ret = para_strdup(row[0]);
693 mysql_free_result(result);
697 /* never returns NULL */
698 static char *get_current_stream(void)
702 void *result = get_result("select def from streams where "
703 "name = 'current_stream'");
707 row = mysql_fetch_row(result);
710 ret = para_strdup(row[0]);
711 mysql_free_result(result);
715 mysql_free_result(result);
716 return para_strdup("(none)");
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.
726 static char *get_query(char *streamname, char *filename, int with_path)
728 char *accept_opts = NULL, *deny_opts = NULL, *score = NULL;
729 char *where_clause, *order, *query;
730 char command[255] = ""; /* buffer for sscanf */
734 char *select_clause = NULL;
736 tmp = get_current_stream();
738 tmp = escape_str(streamname);
742 if (!strcmp(tmp, "(none)")) {
745 char *ret, *ebn = escaped_basename(filename);
748 ret = make_message("select to_days(now()) - "
749 "to_days(lastplayed) from data "
750 "where name = '%s'", ebn);
756 "select concat(dir.dir, '/', dir.name) "
757 "from data, dir where dir.name = data.name "
758 "order by data.lastplayed"
761 "select name from data where name is not NULL "
762 "order by lastplayed"
766 query = make_message("select def from streams where name = '%s'",
768 result = get_result(query);
773 row = mysql_fetch_row(result);
779 char *arg, *line = end;
781 if (!(end = strchr(line, '\n')))
785 if (sscanf(line, "%200s%n", command, &n) < 1)
788 if (!strcmp(command, "accept:")) {
789 char *tmp2 = s_a_r_list(mysql_macro_list, arg);
791 accept_opts = para_strcat(
792 accept_opts, " or ");
793 accept_opts = para_strcat(accept_opts, tmp2);
797 if (!strcmp(command, "deny:")) {
798 char *tmp2 = s_a_r_list(mysql_macro_list, arg);
800 deny_opts = para_strcat(deny_opts, " or ");
801 deny_opts = para_strcat(deny_opts, tmp2);
805 if (!score && !strcmp(command, "score:"))
806 score = s_a_r_list(mysql_macro_list, arg);
809 score = s_a_r_list(mysql_macro_list, conf.mysql_default_score_arg);
814 char *ebn = escaped_basename(filename);
817 select_clause = make_message("select %s from data ", score);
819 where_clause = make_message( "where name = '%s' ", ebn);
821 order = para_strdup("");
824 select_clause = para_strdup(with_path?
825 "select concat(dir.dir, '/', dir.name) from data, dir "
826 "where dir.name = data.name "
828 "select name from data where name is not NULL");
829 order = make_message("order by -(%s)", score);
831 if (accept_opts && deny_opts) {
832 where_clause = make_message("and ((%s) and not (%s)) ",
833 accept_opts, deny_opts);
836 if (accept_opts && !deny_opts) {
837 where_clause = make_message("and (%s) ", accept_opts);
840 if (!accept_opts && deny_opts) {
841 where_clause = make_message("and not (%s) ", deny_opts);
844 where_clause = para_strdup("");
846 query = make_message("%s %s %s", select_clause, where_clause, order);
856 mysql_free_result(result);
863 * This is called from server and from some commands. Name must not be NULL
864 * Never returns NULL.
866 static char *get_selector_info(char *name)
868 char *meta, *atts, *info, *dir, *query, *stream;
870 MYSQL_ROW row = NULL;
873 return para_strdup("(none)");
874 stream = get_current_stream();
875 meta = get_meta(name, 1);
876 atts = get_atts(name, 0);
879 query = get_query(stream, name, 0); /* FIXME: pass stream == NULL instead? */
882 result = get_result(query);
885 row = mysql_fetch_row(result);
887 info = make_message("dbinfo1:dir: %s\n"
888 "dbinfo2:stream: %s, %s, score: %s\n"
890 dir? dir : "(not contained in table)",
892 (result && row && row[0])? row[0] : "(no score)",
899 mysql_free_result(result);
904 /* might return NULL */
905 static char *get_current_audio_file(void)
909 name = para_basename(mmd->filename);
914 /* list attributes / print database info */
915 static int com_la_info(int fd, int argc, char *argv[])
917 char *name = NULL, *meta = NULL, *atts = NULL, *dir = NULL;
918 int ret, la = strcmp(argv[0], "info");
921 ret = -E_GET_AUDIO_FILE;
922 if (!(name = get_current_audio_file()))
924 ret = send_va_buffer(fd, "%s\n", name);
929 if (!(name = escaped_basename(argv[1])))
932 meta = get_meta(name, 1);
933 atts = get_atts(name, 0);
936 ret = send_va_buffer(fd, "%s\n", atts);
938 ret = send_va_buffer(fd, "dir: %s\n" "%s\n" "attributes: %s\n",
939 dir? dir : "(not contained in table)", meta, atts);
948 /* list attributes */
949 int com_la(int fd, int argc, char *argv[])
951 return com_la_info(fd, argc, argv);
954 /* print database info */
955 int com_info(int fd, int argc, char *argv[])
957 return com_la_info(fd, argc, argv);
960 static int change_stream(const char *stream)
964 query = make_message("update streams set def='%s' "
965 "where name = 'current_stream'", stream);
966 ret = real_query(query);
971 static int get_pic_id_by_name(char *name)
978 if (!(ebn = escaped_basename(name)))
980 q = make_message("select pic_id from data where name = '%s'", ebn);
982 result = get_result(q);
986 row = mysql_fetch_row(result);
990 mysql_free_result(result);
994 static int remove_entry(const char *name)
996 char *q, *ebn = escaped_basename(name);
1001 q = make_message("delete from data where name = '%s'", ebn);
1002 real_query(q); /* ignore errors */
1004 q = make_message("delete from dir where name = '%s'", ebn);
1005 real_query(q); /* ignore errors */
1013 static int add_entry(const char *name)
1015 char *q, *dn, *ebn = NULL, *edn = NULL;
1018 if (!name || !*name)
1019 return -E_MYSQL_SYNTAX;
1020 ebn = escaped_basename(name);
1023 ret = -E_MYSQL_SYNTAX;
1024 dn = para_dirname(name);
1028 edn = escape_str(dn);
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);
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);
1053 * remove/add entries
1055 static int com_rm_ne(__a_unused int fd, int argc, char *argv[])
1057 int ne = !strcmp(argv[0], "ne");
1060 return -E_MYSQL_SYNTAX;
1061 for (i = 1; i < argc; i++) {
1062 ret = remove_entry(argv[i]);
1067 ret = add_entry(argv[i]);
1077 int com_rm(int fd, int argc, char *argv[])
1079 return com_rm_ne(fd, argc, argv);
1085 int com_ne(int fd, int argc, char *argv[])
1087 return com_ne(fd, argc, argv);
1093 int com_mv(__a_unused int fd, int argc, char *argv[])
1095 char *q, *dn, *ebn1 = NULL, *ebn2 = NULL, *edn = NULL;
1099 return -E_MYSQL_SYNTAX;
1101 ebn1 = escaped_basename(argv[1]);
1102 ebn2 = escaped_basename(argv[2]);
1103 if (!ebn1 || !ebn2 || !*ebn1 || !*ebn2)
1105 ret = -E_MYSQL_SYNTAX;
1106 if (!strcmp(ebn1, ebn2))
1108 remove_entry(argv[2]); /* no need to escape, ignore error */
1109 q = make_message("update data set name = '%s' where name = '%s'",
1111 ret = real_query(q);
1115 ret = -E_AUDIO_FILE;
1116 if (!mysql_affected_rows(mysql_ptr))
1118 q = make_message("update dir set name = '%s' where name = '%s'",
1120 ret = real_query(q);
1126 dn = para_dirname(argv[2]);
1130 edn = escape_str(dn);
1137 q = make_message("update dir set dir = '%s' where name = '%s'",
1139 ret = real_query(q);
1151 static int com_set(__a_unused int fd, int argc, char *argv[])
1156 const char *field = strcmp(argv[0], "picass")? "numplayed" : "pic_id";
1159 return -E_MYSQL_SYNTAX;
1161 for (i = 2; i < argc; i++) {
1162 ebn = escaped_basename(argv[i]);
1165 q = make_message("update data set %s = %lu "
1166 "where name = '%s'", field, id, ebn);
1168 ret = real_query(q);
1177 * snp: set numplayed
1179 int com_picass(int fd, int argc, char *argv[])
1181 return com_set(fd, argc, argv);
1185 * snp: set numplayed
1187 int com_snp(int fd, int argc, char *argv[])
1189 return com_set(fd, argc, argv);
1193 * picch: change entry's name in pics table
1195 int com_picch(__a_unused int fd, int argc, char *argv[])
1202 return -E_MYSQL_SYNTAX;
1205 tmp = escape_str(argv[2]);
1208 q = make_message("update pics set name = '%s' where id = %lu", tmp, id);
1210 ret = real_query(q);
1216 * piclist: print list of pics in db
1218 int com_piclist(__a_unused int fd, int argc, __a_unused char *argv[])
1220 void *result = NULL;
1222 unsigned long *length;
1226 return -E_MYSQL_SYNTAX;
1227 result = get_result("select id,name,pic from pics order by id");
1230 while ((row = mysql_fetch_row(result))) {
1231 length = mysql_fetch_lengths(result);
1232 if (!row || !row[0] || !row[1] || !row[2])
1234 ret = send_va_buffer(fd, "%s\t%lu\t%s\n", row[0], length[2], row[1]);
1240 mysql_free_result(result);
1245 * picdel: delete picture from database
1247 int com_picdel(int fd, int argc, char *argv[])
1255 return -E_MYSQL_SYNTAX;
1256 for (i = 1; i < argc; i++) {
1258 q = make_message("delete from pics where id = %lu", id);
1259 ret = real_query(q);
1263 aff = mysql_affected_rows(mysql_ptr);
1265 ret = send_va_buffer(fd, "No such id: %lu\n", id);
1270 q = make_message("update data set pic_id = 1 where pic_id = %lu", id);
1271 ret = real_query(q);
1277 * pic: get picture by name or by number
1279 int com_pic(int fd, int argc, char *argv[])
1281 void *result = NULL;
1283 unsigned long *length, id;
1285 char *q, *name = NULL;
1288 ret = -E_GET_AUDIO_FILE;
1289 name = get_current_audio_file();
1292 name = escaped_basename(argv[1]);
1297 id = atoi(name + 1);
1299 id = get_pic_id_by_name(name);
1303 q = make_message("select pic from pics where id = '%lu'", id);
1304 result = get_result(q);
1308 row = mysql_fetch_row(result);
1310 if (!row || !row[0])
1312 length = mysql_fetch_lengths(result);
1313 ret = send_bin_buffer(fd, row[0], *length);
1315 mysql_free_result(result);
1320 int com_strdel(__a_unused int fd, int argc, char *argv[])
1326 return -E_MYSQL_SYNTAX;
1327 tmp = escape_str(argv[1]);
1330 q = make_message("delete from streams where name='%s'", tmp);
1332 ret = real_query(q);
1340 int com_ls(int fd, int argc, char *argv[])
1345 unsigned int num_rows;
1348 return -E_MYSQL_SYNTAX;
1350 char *tmp = escape_str(argv[1]);
1353 q = make_message("select name from data where name like '%s'",
1357 q = para_strdup("select name from data");
1358 result = get_result(q);
1362 num_rows = mysql_num_rows(result);
1365 ret = print_results(fd, result, 0, 0, num_rows - 1, 0);
1366 mysql_free_result(result);
1373 int com_summary(__a_unused int fd, int argc, __a_unused char *argv[])
1378 void *result2 = NULL;
1379 const char *fmt = "select count(name) from data where %s='1'";
1380 int ret = -E_NORESULT;
1383 return -E_MYSQL_SYNTAX;
1384 result = get_all_attributes();
1387 while ((row = mysql_fetch_row(result))) {
1394 buf = make_message(fmt, row[0]);
1395 result2 = get_result(buf);
1400 row2 = mysql_fetch_row(result2);
1401 if (!row2 || !row2[0])
1403 ret = send_va_buffer(fd, "%s\t%s\n", row[0], row2[0]);
1410 mysql_free_result(result2);
1412 mysql_free_result(result);
1416 static int get_numplayed(char *name)
1420 const char *fmt = "select numplayed from data where name = '%s'";
1421 char *buf = make_message(fmt, name);
1422 int ret = -E_NORESULT;
1424 result = get_result(buf);
1429 row = mysql_fetch_row(result);
1430 if (!row || !row[0])
1435 mysql_free_result(result);
1439 static int update_audio_file(char *name)
1442 const char *fmt1 = "update data set lastplayed = now() where name = '%s'";
1443 const char *fmt2 = "update data set numplayed = %i where name = '%s'";
1445 char *ebn = escaped_basename(name);
1450 q = make_message(fmt1, ebn);
1451 ret = real_query(q);
1455 ret = get_numplayed(ebn);
1458 q = make_message(fmt2, ret + 1, ebn);
1459 ret = real_query(q);
1466 /* If called as child, mmd_lock must be held */
1467 static void update_mmd(char *info)
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';
1474 static void update_audio_file_server_handler(char *name)
1477 info = get_selector_info(name);
1480 update_audio_file(name);
1483 int com_us(__a_unused int fd, int argc, char *argv[])
1489 return -E_MYSQL_SYNTAX;
1490 tmp = escape_str(argv[1]);
1493 ret = update_audio_file(argv[1]);
1498 static void refresh_selector_info(void)
1500 char *name = get_current_audio_file();
1505 info = get_selector_info(name);
1513 /* select previous / next stream */
1514 static int com_ps_ns(__a_unused int fd, int argc, char *argv[])
1516 char *query, *stream = get_current_stream();
1517 void *result = get_result("select name from streams");
1519 int match = -1, ret, i;
1520 unsigned int num_rows;
1523 return -E_MYSQL_SYNTAX;
1527 num_rows = mysql_num_rows(result);
1528 ret = -E_EMPTY_RESULT;
1532 for (i = 0; i < num_rows; i++) {
1533 row = mysql_fetch_row(result);
1534 if (!row || !row[0])
1536 if (!strcmp(row[0], "current_stream"))
1538 if (!strcmp(row[0], stream)) {
1546 if (!strcmp(argv[0], "ps"))
1547 i = match > 0? match - 1 : num_rows - 1;
1549 i = match < num_rows - 1? match + 1 : 0;
1551 mysql_data_seek(result, i);
1552 row = mysql_fetch_row(result);
1553 if (!row || !row[0])
1555 if (!strcmp(row[0], "current_stream")) {
1556 if (!strcmp(argv[0], "ps")) {
1558 i = i < 0? i + num_rows : i;
1561 i = i > num_rows - 1? i - num_rows : i;
1563 mysql_data_seek(result, i);
1564 row = mysql_fetch_row(result);
1565 if (!row || !row[0])
1568 query = make_message("update streams set def='%s' where name = "
1569 "'current_stream'", row[0]);
1570 ret = real_query(query);
1572 refresh_selector_info();
1576 mysql_free_result(result);
1580 /* select previous stream */
1581 int com_ps(int fd, int argc, char *argv[])
1583 return com_ps_ns(fd, argc, argv);
1586 /* select next stream */
1587 int com_ns(int fd, int argc, char *argv[])
1589 return com_ps_ns(fd, argc, argv);
1593 int com_streams(int fd, int argc, __a_unused char *argv[])
1595 unsigned int num_rows;
1596 int i, ret = -E_NORESULT;
1600 if (argc > 1 && strcmp(argv[1], "current_stream"))
1601 return -E_MYSQL_SYNTAX;
1603 char *cs = get_current_stream();
1604 ret = send_va_buffer(fd, "%s\n", cs);
1608 result = get_result("select name from streams");
1611 num_rows = mysql_num_rows(result);
1616 for (i = 0; i < num_rows; i++) {
1617 row = mysql_fetch_row(result);
1618 if (!row || !row[0])
1620 if (strcmp(row[0], "current_stream"))
1621 send_va_buffer(fd, "%s\n", row[0]);
1626 mysql_free_result(result);
1630 /* query stream definition */
1631 int com_strq(int fd, int argc, char *argv[])
1639 ret = -E_GET_STREAM;
1640 name = get_current_stream();
1643 name = escaped_basename(argv[1]);
1648 query = make_message("select def from streams where name='%s'", name);
1650 result = get_result(query);
1655 row = mysql_fetch_row(result);
1656 if (!row || !row[0])
1658 /* no '\n' needed */
1659 ret = send_buffer(fd, row[0]);
1662 mysql_free_result(result);
1666 /* change stream / change stream and play */
1667 static int com_cs_csp(int fd, int argc, char *argv[])
1669 int ret, stream_change;
1670 char *query, *stream = NULL;
1671 char *old_stream = get_current_stream();
1672 int csp = !strcmp(argv[0], "csp");
1674 ret = -E_MYSQL_SYNTAX;
1680 ret = send_va_buffer(fd, "%s\n", old_stream);
1684 /* test if stream is valid, no need to escape argv[1] */
1685 query = get_query(argv[1], NULL, 0);
1690 stream = escape_str(argv[1]);
1693 stream_change = strcmp(stream, old_stream);
1694 if (stream_change) {
1695 ret = change_stream(stream);
1698 refresh_selector_info();
1702 mmd->new_vss_status_flags |= VSS_PLAYING;
1704 mmd->new_vss_status_flags |= VSS_NEXT;
1715 int com_cs(int fd, int argc, char *argv[])
1717 return com_cs_csp(fd, argc, argv);
1720 /* change stream and play */
1721 int com_csp(int fd, int argc, char *argv[])
1723 return com_cs_csp(fd, argc, argv);
1726 /* score list / skip */
1727 static int com_sl_skip(int fd, int argc, char *argv[])
1729 void *result = NULL;
1731 int ret, i, skip = !strcmp(argv[0], "skip");
1732 char *query, *stream, *tmp;
1733 unsigned int num_rows, num;
1736 return -E_MYSQL_SYNTAX;
1737 num = atoi(argv[1]);
1739 return -E_MYSQL_SYNTAX;
1741 stream = get_current_stream();
1743 return -E_GET_STREAM;
1745 stream = escape_str(argv[2]);
1749 tmp = get_query(stream, NULL, 0);
1752 return -E_GET_QUERY;
1753 query = make_message("%s limit %d", tmp, num);
1756 result = get_result(query);
1760 ret = -E_EMPTY_RESULT;
1761 num_rows = mysql_num_rows(result);
1764 for (i = 0; i < num_rows && i < num; i++) {
1765 row = mysql_fetch_row(result);
1767 send_va_buffer(fd, "Skipping %s\n", row[0]);
1768 update_audio_file(row[0]);
1770 send_va_buffer(fd, "%s\n", row[0]? row[0]: "BUG");
1775 mysql_free_result(result);
1780 int com_sl(int fd, int argc, char *argv[])
1782 return com_sl_skip(fd, argc, argv);
1786 int com_skip(int fd, int argc, char *argv[])
1788 return com_sl_skip(fd, argc, argv);
1792 * update attributes of name
1794 static int update_atts(int fd, char *name, char *atts)
1797 char *ebn, *q, *old, *new = NULL;
1801 ebn = escaped_basename(name);
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);
1808 ret = real_query(q);
1812 new = get_atts(ebn, 0);
1813 ret = send_va_buffer(fd, "new: %s\n", new);
1823 int com_sa(int fd, int argc, char *argv[])
1826 char *atts = NULL, *name;
1829 return -E_MYSQL_SYNTAX;
1830 for (i = 1; i < argc; i++) {
1832 char *esc, *tmp, *p =argv[i];
1833 int len = strlen(p);
1837 switch (p[len - 1]) {
1848 esc = escape_str(p);
1851 tmp = make_message("%s%s='%s'", atts? "," : "", esc,
1854 atts = para_strcat(atts, tmp);
1860 if (i >= argc) { /* no name given, use current af */
1861 ret = -E_GET_AUDIO_FILE;
1862 if (!(name = get_current_audio_file()))
1864 ret = update_atts(fd, name, atts);
1868 for (; argv[i] && ret >= 0; i++)
1869 ret = update_atts(fd, argv[i], atts);
1871 refresh_selector_info();
1880 int com_cam(int fd, int argc, char *argv[])
1882 char *name = NULL, *meta = NULL, *atts = NULL;
1886 return -E_MYSQL_SYNTAX;
1887 if (!(name = escaped_basename(argv[1])))
1890 if (!(atts = get_atts(name, 1)))
1893 if (!(meta = get_meta(name, 0)))
1895 for (i = 2; i < argc; i++) {
1898 if (!(ebn = escaped_basename(argv[i])))
1900 ret = send_va_buffer(fd, "updating %s\n", ebn);
1905 q = make_message("update data set %s where name = '%s'",
1907 if ((ret = update_atts(fd, ebn, atts)) >= 0)
1908 ret = real_query(q);
1928 static int com_vrfy_clean(int fd, int argc, __a_unused char *argv[])
1931 int ret, vrfy_mode = strcmp(argv[0], "clean");
1932 void *result = NULL;
1933 unsigned int num_rows;
1938 return -E_MYSQL_SYNTAX;
1940 result = get_result("select data.name from data left join dir on "
1941 "dir.name = data.name where dir.name is NULL");
1944 num_rows = mysql_num_rows(result);
1946 ret = send_buffer(fd, "No invalid entries\n");
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);
1955 while ((row = mysql_fetch_row(result))) {
1960 escaped_name = escape_str(row[0]);
1963 send_va_buffer(fd, "deleting %s\n", escaped_name);
1964 query = make_message("delete from data where name = '%s'",
1966 ret = real_query(query);
1974 mysql_free_result(result);
1981 int com_vrfy(int fd, int argc, char **argv)
1983 return com_vrfy_clean(fd, argc, argv);
1989 int com_clean(int fd, int argc, char **argv)
1991 return com_vrfy_clean(fd, argc, argv);
1994 static FILE *out_file;
1996 static int mysql_write_tmp_file(const char *dir, const char *name)
1998 int ret = -E_TMPFILE;
1999 char *msg = make_message("%s\t%s\n", dir, name);
2000 if (fputs(msg, out_file) != EOF)
2009 int com_upd(int fd, int argc, __a_unused char *argv[])
2011 char *tempname = NULL, *query = NULL;
2012 int ret, out_fd = -1, num = 0;
2013 void *result = NULL;
2014 unsigned int num_rows;
2018 return -E_MYSQL_SYNTAX;
2020 tempname = para_strdup("/tmp/mysql.tmp.XXXXXX");
2021 ret = para_mkstemp(tempname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2025 out_file = fdopen(out_fd, "w");
2030 if (find_audio_files(conf.mysql_audio_file_dir_arg, mysql_write_tmp_file) < 0)
2032 num = ftell(out_file);
2034 * we have to make sure the file hit the disk before we call
2039 PARA_DEBUG_LOG("wrote tempfile %s (%d bytes)\n", tempname, num);
2042 if ((ret = real_query("delete from dir")) < 0)
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);
2051 result = get_result("select dir.name from dir left join data on "
2052 "data.name = dir.name where data.name is NULL");
2056 num_rows = mysql_num_rows(result);
2058 ret = send_buffer(fd, "no new entries\n");
2061 while ((row = mysql_fetch_row(result))) {
2066 send_va_buffer(fd, "new entry: %s\n", row[0]);
2067 erow = escape_str(row[0]);
2070 query = make_message("insert into data (name, pic_id) values "
2071 "('%s','%s')", erow, "1");
2073 ret = real_query(query);
2086 mysql_free_result(result);
2090 static char **server_get_audio_file_list(unsigned int num)
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;
2099 tmp = get_query(stream, NULL, 1);
2103 query = make_message("%s limit %d", tmp, num);
2105 result = get_result(query);
2109 num_rows = mysql_num_rows(result);
2112 for (i = 0; i < num_rows && i < num; i++) {
2113 row = mysql_fetch_row(result);
2114 if (!row || !row[0])
2116 list[i] = para_strdup(row[0]);
2129 mysql_free_result(result);
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().
2137 static int init_mysql_server(void)
2139 char *u = conf.mysql_user_arg? conf.mysql_user_arg : para_logname();
2141 mysql_ptr = mysql_init(NULL);
2143 PARA_CRIT_LOG("%s", "mysql init error\n");
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)
2151 * If host is NULL a connection to the local host is assumed,
2152 * If user is NULL, the current user is assumed
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");
2163 PARA_INFO_LOG("%s", "success\n");
2167 /* mmd lock must be held */
2168 static void write_msg2mmd(int success)
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));
2176 /* create database */
2177 int com_cdb(int fd, int argc, char *argv[])
2183 PARA_INFO_LOG("%s", "closing database\n");
2184 mysql_close(mysql_ptr);
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)
2192 conf.mysql_database_arg = para_strdup("paraslash");
2195 conf.mysql_database_arg = escape_str(argv[1]);
2196 if (!conf.mysql_database_arg)
2199 query = make_message("create database %s", conf.mysql_database_arg);
2200 ret = real_query(query);
2204 /* reconnect with database just created */
2205 mysql_close(mysql_ptr);
2206 ret = -E_MYSQL_INIT;
2207 if (init_mysql_server() < 0 || !mysql_ptr)
2213 if (real_query("create table data (name varchar(255) binary not null "
2215 "lastplayed datetime not null default "
2217 "numplayed int not null default 0, "
2218 "pic_id bigint unsigned not null default 1)") < 0)
2220 if (real_query("create table dir (name varchar(255) binary not null "
2221 "primary key, dir varchar(255) default null)") < 0)
2223 if (real_query("create table pics ("
2224 "id bigint(20) unsigned not null primary key "
2226 "name varchar(255) binary not null, "
2227 "pic mediumblob not null)") < 0)
2229 if (real_query("create table streams ("
2230 "name varchar(255) binary not null primary key, "
2231 "def blob not null)") < 0)
2233 if (real_query("insert into streams (name, def) values "
2234 "('current_stream', '(none)')") < 0)
2236 ret = send_va_buffer(fd, "successfully created database %s\n",
2237 conf.mysql_database_arg);
2242 static void shutdown_connection(void)
2245 PARA_NOTICE_LOG("%s", "shutting down mysql connection\n");
2246 mysql_close(mysql_ptr);
2252 * the init function of the mysql-based audio file selector
2254 * \param db pointer to the struct to initialize
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.
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.
2264 * \sa struct audio_file_selector, misc_meta_data::selector_info,
2267 int mysql_selector_init(struct audio_file_selector *db)
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;
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();
2282 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
2284 return 1; /* return success even if connect failed to give the
2285 * user the chance to exec com_cdb