2 * Copyright (C) 1999-2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file mysql_selector.c para_server's mysql-based audio file selector */
9 /** \cond some internal constants */
10 #define MEDIUM_BLOB_SIZE 16777220 /* (2**24 + 4) */
11 #define BLOB_SIZE 65539 /* (2**16 + 3) */
15 #include "server.cmdline.h"
19 #include "afs_common.h"
20 #include <mysql/mysql.h>
21 #include <mysql/mysql_version.h>
27 #include "user_list.h"
28 #include "mysql_selector_command_list.h"
31 /** pointer to the shared memory area */
32 extern struct misc_meta_data *mmd;
34 static void *mysql_ptr = NULL;
35 static int mysql_lock;
38 * contains name/replacement pairs used by s_a_r_list()
43 /** the name of the macro */
45 /** the replacement text */
46 const char *replacement;
49 static const struct para_macro mysql_macro_list[] = {
51 .replacement = "(data.%s != '1')"
54 .replacement = "(data.%s = '1')"
57 .replacement = "%sdata.Pic_Id"
60 .replacement = "(data.name like '%s')"
63 .replacement = "%sFLOOR((UNIX_TIMESTAMP(now())"
64 "-UNIX_TIMESTAMP(data.Lastplayed))/60)"
67 .replacement = "%sdata.Numplayed"
74 * Simple search and replace routine.
76 * \param src Source String.
77 * \param macro_name The name of the macro.
78 * \param replacement The replacement format string.
80 * In \p src, replace each occurence of \p macro_name(arg) by the string
81 * determined by the \p replacement format string. \p replacement may (but
82 * needs not) contain a single string conversion specifier (%s) which gets
85 * \return A string in which all matches in \p src are replaced, or \p NULL if
86 * an error was encountered. Caller must free the result.
90 __must_check __malloc static char *s_a_r(const char *src, const char* macro_name,
91 const char *replacement)
98 const char *bufptr = src;
100 if (!macro_name || !replacement || !src)
101 return para_strdup(src);
102 if (regcomp(&preg, macro_name, 0) != 0)
104 while (regexec(&preg, bufptr, nmatch, pmatch, eflags)
106 char *tmp, *arg, *o_bracket, *c_bracket;
108 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
109 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
112 tmp = para_strdup(bufptr);
113 tmp[pmatch[0].rm_so] = '\0';
114 dest = para_strcat(dest, tmp);
117 arg = para_strdup(o_bracket + 1);
118 arg[c_bracket - o_bracket - 1] = '\0';
119 tmp = make_message(replacement, arg);
121 dest = para_strcat(dest, tmp);
126 dest = para_strcat(dest, bufptr);
127 // PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
134 * replace a string according to a list of macros
136 * \param macro_list the array containing a macro/replacement pairs.
137 * \param src the source string
139 * This function just calls s_a_r() for each element of \p macro_list.
141 * \return \p NULL if one of the underlying calls to \p s_a_r returned \p NULL.
142 * Otherwise the completely expanded version of \p src is returned.
144 __must_check __malloc static char *s_a_r_list(const struct para_macro *macro_list,
147 const struct para_macro *mp = macro_list;
148 char *ret = NULL, *tmp = para_strdup(src);
151 ret = s_a_r(tmp, mp->name, mp->replacement);
153 if (!ret) /* syntax error */
158 //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
162 static int lockless_real_query(const char *query)
166 PARA_DEBUG_LOG("%s\n", query);
167 if (mysql_real_query(mysql_ptr, query, strlen(query))) {
168 PARA_ERROR_LOG("real_query error (%s)\n",
169 mysql_error(mysql_ptr));
175 static int real_query(const char *query)
179 mutex_lock(mysql_lock);
180 ret = lockless_real_query(query);
181 mutex_unlock(mysql_lock);
186 * Use open connection given by mysql_ptr to query server. Returns a
187 * result pointer on succes and NULL on errors
189 static struct MYSQL_RES *get_result(const char *query)
193 mutex_lock(mysql_lock);
194 if (lockless_real_query(query) < 0)
196 result = mysql_store_result(mysql_ptr);
198 PARA_ERROR_LOG("%s", "store_result error\n");
200 mutex_unlock(mysql_lock);
204 * write input from fd to dynamically allocated char array,
205 * but maximal max_size byte. Return size.
207 static int fd2buf(int fd, char **buf_ptr, size_t max_size)
209 const size_t chunk_size = 1024;
211 char *buf = para_malloc(size * sizeof(char)), *p = buf;
214 while ((ret = recv_bin_buffer(fd, p, chunk_size)) > 0) {
216 if ((p - buf) + chunk_size >= size) {
220 if (size > max_size) {
224 tmp = para_realloc(buf, size);
239 static char *escape_blob(const char* old, size_t size)
245 new = para_malloc(2 * size * sizeof(char) + 1);
246 mysql_real_escape_string(mysql_ptr, new, old, size);
250 static char *escape_str(const char* old)
252 return escape_blob(old, strlen(old));
255 static char *escaped_basename(const char *name)
257 char *esc, *bn = para_basename(name);
261 esc = escape_str(bn);
269 int com_na(__a_unused int fd, int argc, char * const * argv)
275 return -E_MYSQL_SYNTAX;
276 tmp = escape_str(argv[1]);
279 q = make_message("alter table data add %s char(1) "
280 "not null default 0", tmp);
290 int com_da(__a_unused int fd, int argc, char * const * argv)
296 return -E_MYSQL_SYNTAX;
297 tmp = escape_str(argv[1]);
300 q = make_message("alter table data drop %s", tmp);
308 static int com_stradd_picadd(int fd, int argc, char * const * argv)
310 char *blob = NULL, *esc_blob = NULL, *q = NULL, *tmp = NULL;
311 const char *fmt, *del_fmt;
312 int ret, stradd = strcmp(argv[0], "picadd");
316 return -E_MYSQL_SYNTAX;
317 if (strlen(argv[1]) >= MAXLINE - 1)
318 return -E_NAMETOOLONG;
323 fmt = "insert into streams (name, def) values ('%s','%s')";
324 del_fmt="delete from streams where name='%s'";
326 size = MEDIUM_BLOB_SIZE;
327 fmt = "insert into pics (name, pic) values ('%s','%s')";
328 del_fmt="delete from pics where pic='%s'";
330 tmp = escape_str(argv[1]);
333 q = make_message(del_fmt, tmp);
339 if ((ret = send_buffer(fd, AWAITING_DATA_MSG) < 0))
341 if ((ret = fd2buf(fd, &blob, size)) < 0)
347 esc_blob = escape_blob(blob, size);
350 tmp = escape_str(argv[1]);
353 q = make_message(fmt, tmp, esc_blob);
364 int com_stradd(int fd, int argc, char * const * argv)
366 return com_stradd_picadd(fd, argc, argv);
370 int com_picadd(int fd, int argc, char * const * argv)
372 return com_stradd_picadd(fd, argc, argv);
376 * print results to fd
378 static int print_results(int fd, void *result,
379 my_ulonglong top, my_ulonglong left,
380 my_ulonglong bottom, my_ulonglong right)
386 for (i = top; i <= bottom; i++) {
387 row = mysql_fetch_row(result);
390 for (j = left; j <= right; j++) {
391 ret = send_va_buffer(fd, j == left? "%s" : "\t%s",
392 row[j]? row[j] : "NULL");
396 ret = send_buffer(fd, "\n");
406 int com_verb(int fd, int argc, char * const * argv)
410 my_ulonglong num_rows, num_fields, top = 0, left = 0;
414 return -E_MYSQL_SYNTAX;
415 tmp = escape_str(argv[1]);
418 result = get_result(tmp);
421 /* return success, because it's ok to have no results */
423 num_fields = mysql_field_count(mysql_ptr);
424 num_rows = mysql_num_rows(result);
426 if (num_fields && num_rows)
427 ret = print_results(fd, result, top, left, num_rows - 1,
429 mysql_free_result(result);
433 /* returns NULL on errors or if there are no atts defined yet */
434 static void *get_all_attributes(void)
436 void *result = get_result("desc data");
437 unsigned int num_rows;
441 num_rows = mysql_num_rows(result);
443 mysql_free_result(result);
446 mysql_data_seek(result, (my_ulonglong)4); /* skip Lastplayed, Numplayed... */
451 * list all attributes
453 int com_laa(int fd, int argc, __a_unused char * const * argv)
457 my_ulonglong top = 0, left = 0, bottom, right = 0;
460 return -E_MYSQL_SYNTAX;
461 result = get_all_attributes();
464 bottom = mysql_num_rows(result);
466 return -E_MYSQL_SYNTAX;
468 ret = print_results(fd, result, top, left, bottom, right);
469 mysql_free_result(result);
476 int com_hist(int fd, int argc, char * const * argv)
481 my_ulonglong num_rows, top = 0, left = 0, right = 1;
484 return -E_MYSQL_SYNTAX;
486 char *tmp = escape_str(argv[1]);
489 atts = make_message("where %s = '1'", tmp);
492 atts = para_strdup(NULL);
494 q = make_message("select name, to_days(now()) - to_days(lastplayed) from "
495 "data %s order by lastplayed", atts);
497 result = get_result(q);
501 num_rows = mysql_num_rows(result);
504 ret = print_results(fd, result, top, left, num_rows - 1, right);
505 mysql_free_result(result);
510 * get last num audio files
512 int com_last(int fd, int argc, char * const * argv)
517 my_ulonglong top = 0, left = 0, right = 0;
524 return -E_MYSQL_SYNTAX;
525 q = make_message("select name from data order by lastplayed desc "
527 result = get_result(q);
531 ret = print_results(fd, result, top, left, mysql_num_rows(result) - 1,
533 mysql_free_result(result);
537 int com_mbox(int fd, int argc, char * const * argv)
542 my_ulonglong num_rows, num_fields, top = 0, left = 0;
543 char *query = para_strdup("select concat('From foo@localhost ', "
544 "date_format(Lastplayed, '%a %b %e %T %Y'), "
545 "'\nReceived: from\nTo: bar\n");
548 result = get_all_attributes();
552 while ((row = mysql_fetch_row(result))) {
557 tmp = make_message("%sX-Attribute-%s: ', %s, '\n", query,
562 query = para_strcat(query,
570 char *esc = escape_str(argv[1]), *tmp;
574 tmp = make_message("%s where name LIKE '%s'", query, esc);
579 mysql_free_result(result);
581 result = get_result(query);
584 ret = -E_EMPTY_RESULT;
585 num_fields = mysql_field_count(mysql_ptr);
586 num_rows = mysql_num_rows(result);
587 if (!num_fields || !num_rows)
589 ret = print_results(fd, result, top, left, num_rows - 1,
594 mysql_free_result(result);
599 * get attributes by name. If verbose is not 0, this function returns a string
600 * of the form 'att1="0",att2="1"'... which is used in com_cam() for
601 * constructing a mysql update query. Otherwise the space-separated list of all
602 * attributes which are set in the audio file given by name is returned. Never
603 * returns NULL in *NON VERBOSE* mode.
605 static char *get_atts(char *name, int verbose)
607 char *atts = NULL, *buf, *ebn;
608 void *result = NULL, *result2 = NULL;
611 my_ulonglong num_fields, offset = 4; /* skip Lastplayed, Numplayed... */
614 result2 = get_all_attributes();
617 ebn = escaped_basename(name);
620 buf = make_message("select * from data where name='%s'", ebn);
622 result = get_result(buf);
626 num_fields = mysql_num_fields(result);
629 mysql_data_seek(result2, offset);
630 row = mysql_fetch_row(result);
633 for (i = 4; i < num_fields; i++) {
634 int is_set = row[i] && !strcmp(row[i], "1");
635 row2 = mysql_fetch_row(result2);
636 if (!row2 || !row2[0])
638 if (atts && (verbose || is_set))
639 atts = para_strcat(atts, verbose? "," : " ");
640 if (is_set || verbose)
641 atts = para_strcat(atts, row2[0]);
643 atts = para_strcat(atts, is_set? "=\"1\"" : "=\"0\"");
647 mysql_free_result(result2);
649 mysql_free_result(result);
650 if (!atts && !verbose)
651 atts = para_strdup("(none)");
655 /* never returns NULL in verbose mode */
656 static char *get_meta(char *name, int verbose)
660 char *ebn, *q, *ret = NULL;
661 const char *verbose_fmt =
662 "select concat('lastplayed: ', "
663 "(to_days(now()) - to_days(lastplayed)),"
664 "' day(s). numplayed: ', numplayed, "
665 "', pic: ', pic_id) "
666 "from data where name = '%s'";
667 /* is that really needed? */
668 const char *fmt = "select concat('lastplayed=\\'', lastplayed, "
669 "'\\', numplayed=\\'', numplayed, "
670 "'\\', pic_id=\\'', pic_id, '\\'') "
671 "from data where name = '%s'";
673 if (!(ebn = escaped_basename(name)))
675 q = make_message(verbose? verbose_fmt : fmt, ebn);
677 result = get_result(q);
681 row = mysql_fetch_row(result);
684 ret = para_strdup(row[0]);
687 mysql_free_result(result);
689 ret = para_strdup("(not yet played)");
693 static char *get_dir(char *name)
695 char *ret = NULL, *q, *ebn;
699 if (!(ebn = escaped_basename(name)))
701 q = make_message("select dir from dir where name = '%s'", ebn);
703 result = get_result(q);
707 row = mysql_fetch_row(result);
709 ret = para_strdup(row[0]);
710 mysql_free_result(result);
714 /* never returns NULL */
715 static char *get_current_stream(void)
719 void *result = get_result("select def from streams where "
720 "name = 'current_stream'");
724 row = mysql_fetch_row(result);
727 ret = para_strdup(row[0]);
728 mysql_free_result(result);
732 mysql_free_result(result);
733 return para_strdup("(none)");
737 * Read stream definition of stream streamname and construct mysql
738 * query. Return NULL on errors. If streamname is NULL, use current
739 * stream. If that is also NULL, use query that selects everything.
740 * If filename is NULL, query will list everything, otherwise only
741 * the score of given file.
743 static char *get_query(const char *streamname, char *filename, int with_path)
745 char *accept_opts = NULL, *deny_opts = NULL, *score = NULL;
746 char *where_clause, *order, *query;
747 char command[255] = ""; /* buffer for sscanf */
751 char *select_clause = NULL;
753 tmp = get_current_stream();
755 tmp = escape_str(streamname);
759 if (!strcmp(tmp, "(none)")) {
762 char *ret, *ebn = escaped_basename(filename);
765 ret = make_message("select to_days(now()) - "
766 "to_days(lastplayed) from data "
767 "where name = '%s'", ebn);
773 "select concat(dir.dir, '/', dir.name) "
774 "from data, dir where dir.name = data.name "
775 "order by data.lastplayed"
778 "select name from data where name is not NULL "
779 "order by lastplayed"
783 query = make_message("select def from streams where name = '%s'",
785 result = get_result(query);
790 row = mysql_fetch_row(result);
796 char *arg, *line = end;
798 if (!(end = strchr(line, '\n')))
802 if (sscanf(line, "%200s%n", command, &n) < 1)
805 if (!strcmp(command, "accept:")) {
806 char *tmp2 = s_a_r_list(mysql_macro_list, arg);
808 accept_opts = para_strcat(
809 accept_opts, " or ");
810 accept_opts = para_strcat(accept_opts, tmp2);
814 if (!strcmp(command, "deny:")) {
815 char *tmp2 = s_a_r_list(mysql_macro_list, arg);
817 deny_opts = para_strcat(deny_opts, " or ");
818 deny_opts = para_strcat(deny_opts, tmp2);
822 if (!score && !strcmp(command, "score:"))
823 score = s_a_r_list(mysql_macro_list, arg);
826 score = s_a_r_list(mysql_macro_list, conf.mysql_default_score_arg);
831 char *ebn = escaped_basename(filename);
834 select_clause = make_message("select %s from data ", score);
836 where_clause = make_message( "where name = '%s' ", ebn);
838 order = para_strdup("");
841 select_clause = para_strdup(with_path?
842 "select concat(dir.dir, '/', dir.name) from data, dir "
843 "where dir.name = data.name "
845 "select name from data where name is not NULL");
846 order = make_message("order by -(%s)", score);
848 if (accept_opts && deny_opts) {
849 where_clause = make_message("and ((%s) and not (%s)) ",
850 accept_opts, deny_opts);
853 if (accept_opts && !deny_opts) {
854 where_clause = make_message("and (%s) ", accept_opts);
857 if (!accept_opts && deny_opts) {
858 where_clause = make_message("and not (%s) ", deny_opts);
861 where_clause = para_strdup("");
863 query = make_message("%s %s %s", select_clause, where_clause, order);
873 mysql_free_result(result);
880 * This is called from server and from some commands. Name must not be NULL
881 * Never returns NULL.
883 static char *get_selector_info(char *name)
885 char *meta, *atts, *info, *dir, *query, *stream;
887 MYSQL_ROW row = NULL;
890 return para_strdup("(none)");
891 stream = get_current_stream();
892 meta = get_meta(name, 1);
893 atts = get_atts(name, 0);
896 query = get_query(stream, name, 0); /* FIXME: pass stream == NULL instead? */
899 result = get_result(query);
902 row = mysql_fetch_row(result);
904 info = make_message("dbinfo1:dir: %s\n"
905 "dbinfo2:stream: %s, %s, score: %s\n"
907 dir? dir : "(not contained in table)",
909 (result && row && row[0])? row[0] : "(no score)",
916 mysql_free_result(result);
920 /* might return NULL */
921 static char *get_current_audio_file(void)
925 name = para_basename(mmd->filename);
930 /* If called as child, mmd_lock must be held */
931 static void update_mmd(char *info)
933 PARA_DEBUG_LOG("%s", "updating shared memory area\n");
934 strncpy(mmd->selector_info, info, MMD_INFO_SIZE - 1);
935 mmd->selector_info[MMD_INFO_SIZE - 1] = '\0';
938 static void refresh_selector_info(void)
940 char *name = get_current_audio_file();
945 info = get_selector_info(name);
953 /* list attributes / print database info */
954 static int com_la_info(int fd, int argc, char * const * argv)
956 char *name = NULL, *meta = NULL, *atts = NULL, *dir = NULL;
957 int ret, la = strcmp(argv[0], "info");
960 ret = -E_GET_AUDIO_FILE;
961 if (!(name = get_current_audio_file()))
963 ret = send_va_buffer(fd, "%s\n", name);
968 if (!(name = escaped_basename(argv[1])))
971 meta = get_meta(name, 1);
972 atts = get_atts(name, 0);
975 ret = send_va_buffer(fd, "%s\n", atts);
977 ret = send_va_buffer(fd, "dir: %s\n" "%s\n" "attributes: %s\n",
978 dir? dir : "(not contained in table)", meta, atts);
987 /* list attributes */
988 int com_la(int fd, int argc, char * const * argv)
990 return com_la_info(fd, argc, argv);
993 /* print database info */
994 int com_info(int fd, int argc, char * const * argv)
996 return com_la_info(fd, argc, argv);
999 static int change_stream(const char *stream)
1003 query = make_message("update streams set def='%s' "
1004 "where name = 'current_stream'", stream);
1005 ret = real_query(query);
1010 static int get_pic_id_by_name(char *name)
1013 void *result = NULL;
1017 if (!(ebn = escaped_basename(name)))
1019 q = make_message("select pic_id from data where name = '%s'", ebn);
1021 result = get_result(q);
1025 row = mysql_fetch_row(result);
1029 mysql_free_result(result);
1033 static int remove_entry(const char *name)
1035 char *q, *ebn = escaped_basename(name);
1036 int ret = -E_ESCAPE;
1040 q = make_message("delete from data where name = '%s'", ebn);
1041 real_query(q); /* ignore errors */
1043 q = make_message("delete from dir where name = '%s'", ebn);
1044 real_query(q); /* ignore errors */
1052 static int add_entry(const char *name)
1054 char *q, *dn, *ebn = NULL, *edn = NULL;
1057 if (!name || !*name)
1058 return -E_MYSQL_SYNTAX;
1059 ebn = escaped_basename(name);
1062 ret = -E_MYSQL_SYNTAX;
1063 dn = para_dirname(name);
1067 edn = escape_str(dn);
1071 q = make_message("insert into data (name, pic_id) values "
1072 "('%s', '%s')", ebn, "1");
1073 ret = real_query(q);
1074 // ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1078 q = make_message("insert into dir (name, dir) values "
1079 "('%s', '%s')", ebn, edn);
1080 // ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1081 ret = real_query(q);
1092 * remove/add entries
1094 static int com_rm_ne(__a_unused int fd, int argc, char * const * argv)
1096 int ne = !strcmp(argv[0], "ne");
1099 return -E_MYSQL_SYNTAX;
1100 for (i = 1; i < argc; i++) {
1101 ret = remove_entry(argv[i]);
1106 ret = add_entry(argv[i]);
1116 int com_rm(int fd, int argc, char * const * argv)
1118 return com_rm_ne(fd, argc, argv);
1124 int com_ne(int fd, int argc, char * const * argv)
1126 return com_ne(fd, argc, argv);
1132 int com_mv(__a_unused int fd, int argc, char * const * argv)
1134 char *q, *dn, *ebn1 = NULL, *ebn2 = NULL, *edn = NULL;
1138 return -E_MYSQL_SYNTAX;
1140 ebn1 = escaped_basename(argv[1]);
1141 ebn2 = escaped_basename(argv[2]);
1142 if (!ebn1 || !ebn2 || !*ebn1 || !*ebn2)
1144 ret = -E_MYSQL_SYNTAX;
1145 if (!strcmp(ebn1, ebn2))
1147 remove_entry(argv[2]); /* no need to escape, ignore error */
1148 q = make_message("update data set name = '%s' where name = '%s'",
1150 ret = real_query(q);
1154 ret = -E_AUDIO_FILE;
1155 if (!mysql_affected_rows(mysql_ptr))
1157 q = make_message("update dir set name = '%s' where name = '%s'",
1159 ret = real_query(q);
1165 dn = para_dirname(argv[2]);
1169 edn = escape_str(dn);
1176 q = make_message("update dir set dir = '%s' where name = '%s'",
1178 ret = real_query(q);
1190 static int com_set(__a_unused int fd, int argc, char * const * argv)
1195 const char *field = strcmp(argv[0], "picass")? "numplayed" : "pic_id";
1198 return -E_MYSQL_SYNTAX;
1200 for (i = 2; i < argc; i++) {
1201 ebn = escaped_basename(argv[i]);
1204 q = make_message("update data set %s = %lu "
1205 "where name = '%s'", field, id, ebn);
1207 ret = real_query(q);
1216 * snp: set numplayed
1218 int com_picass(int fd, int argc, char * const * argv)
1220 return com_set(fd, argc, argv);
1224 * snp: set numplayed
1226 int com_snp(int fd, int argc, char * const * argv)
1228 int ret = com_set(fd, argc, argv);
1230 refresh_selector_info();
1235 * picch: change entry's name in pics table
1237 int com_picch(__a_unused int fd, int argc, char * const * argv)
1244 return -E_MYSQL_SYNTAX;
1247 tmp = escape_str(argv[2]);
1250 q = make_message("update pics set name = '%s' where id = %lu", tmp, id);
1252 ret = real_query(q);
1258 * piclist: print list of pics in db
1260 int com_piclist(__a_unused int fd, int argc, __a_unused char * const * argv)
1262 void *result = NULL;
1264 unsigned long *length;
1268 return -E_MYSQL_SYNTAX;
1269 result = get_result("select id,name,pic from pics order by id");
1272 while ((row = mysql_fetch_row(result))) {
1273 length = mysql_fetch_lengths(result);
1274 if (!row || !row[0] || !row[1] || !row[2])
1276 ret = send_va_buffer(fd, "%s\t%lu\t%s\n", row[0], length[2], row[1]);
1282 mysql_free_result(result);
1287 * picdel: delete picture from database
1289 int com_picdel(int fd, int argc, char * const * argv)
1297 return -E_MYSQL_SYNTAX;
1298 for (i = 1; i < argc; i++) {
1300 q = make_message("delete from pics where id = %lu", id);
1301 ret = real_query(q);
1305 aff = mysql_affected_rows(mysql_ptr);
1307 ret = send_va_buffer(fd, "No such id: %lu\n", id);
1312 q = make_message("update data set pic_id = 1 where pic_id = %lu", id);
1313 ret = real_query(q);
1319 * pic: get picture by name or by number
1321 int com_pic(int fd, int argc, char * const * argv)
1323 void *result = NULL;
1325 unsigned long *length, id;
1327 char *q, *name = NULL;
1330 ret = -E_GET_AUDIO_FILE;
1331 name = get_current_audio_file();
1334 name = escaped_basename(argv[1]);
1339 id = atoi(name + 1);
1341 id = get_pic_id_by_name(name);
1345 q = make_message("select pic from pics where id = '%lu'", id);
1346 result = get_result(q);
1350 row = mysql_fetch_row(result);
1352 if (!row || !row[0])
1354 length = mysql_fetch_lengths(result);
1355 ret = send_bin_buffer(fd, row[0], *length);
1357 mysql_free_result(result);
1362 int com_strdel(__a_unused int fd, int argc, char * const * argv)
1368 return -E_MYSQL_SYNTAX;
1369 tmp = escape_str(argv[1]);
1372 q = make_message("delete from streams where name='%s'", tmp);
1374 ret = real_query(q);
1382 int com_ls(int fd, int argc, char * const * argv)
1387 my_ulonglong num_rows, top = 0, left = 0, right = 0;
1390 return -E_MYSQL_SYNTAX;
1392 char *tmp = escape_str(argv[1]);
1395 q = make_message("select name from data where name like '%s'",
1399 q = para_strdup("select name from data");
1400 result = get_result(q);
1404 num_rows = mysql_num_rows(result);
1407 ret = print_results(fd, result, top, left, num_rows - 1, right);
1408 mysql_free_result(result);
1415 int com_summary(__a_unused int fd, int argc, __a_unused char * const * argv)
1420 void *result2 = NULL;
1421 const char *fmt = "select count(name) from data where %s='1'";
1422 int ret = -E_NORESULT;
1425 return -E_MYSQL_SYNTAX;
1426 result = get_all_attributes();
1429 while ((row = mysql_fetch_row(result))) {
1436 buf = make_message(fmt, row[0]);
1437 result2 = get_result(buf);
1442 row2 = mysql_fetch_row(result2);
1443 if (!row2 || !row2[0])
1445 ret = send_va_buffer(fd, "%s\t%s\n", row[0], row2[0]);
1452 mysql_free_result(result2);
1454 mysql_free_result(result);
1458 static int get_numplayed(char *name)
1462 const char *fmt = "select numplayed from data where name = '%s'";
1463 char *buf = make_message(fmt, name);
1464 int ret = -E_NORESULT;
1466 result = get_result(buf);
1471 row = mysql_fetch_row(result);
1472 if (!row || !row[0])
1477 mysql_free_result(result);
1481 static int update_audio_file(const char *name)
1484 const char *fmt1 = "update data set lastplayed = now() where name = '%s'";
1485 const char *fmt2 = "update data set numplayed = %i where name = '%s'";
1487 char *ebn = escaped_basename(name);
1492 q = make_message(fmt1, ebn);
1493 ret = real_query(q);
1497 ret = get_numplayed(ebn);
1500 q = make_message(fmt2, ret + 1, ebn);
1501 ret = real_query(q);
1508 static void update_audio_file_server_handler(char *name)
1511 info = get_selector_info(name);
1514 update_audio_file(name);
1517 int com_us(__a_unused int fd, int argc, char * const * argv)
1523 return -E_MYSQL_SYNTAX;
1524 tmp = escape_str(argv[1]);
1527 ret = update_audio_file(argv[1]);
1530 refresh_selector_info();
1534 /* select previous / next stream */
1535 static int com_ps_ns(__a_unused int fd, int argc, char * const * argv)
1537 char *query, *stream = get_current_stream();
1538 void *result = get_result("select name from streams");
1541 my_ulonglong num_rows, match, i;
1543 ret = -E_MYSQL_SYNTAX;
1549 num_rows = mysql_num_rows(result);
1550 ret = -E_EMPTY_RESULT;
1554 for (i = 0; i < num_rows; i++) {
1555 row = mysql_fetch_row(result);
1556 if (!row || !row[0])
1558 if (!strcmp(row[0], "current_stream"))
1560 if (!strcmp(row[0], stream))
1567 if (!strcmp(argv[0], "ps"))
1568 i = match > 0? match - 1 : num_rows - 1;
1570 i = match < num_rows - 1? match + 1 : 0;
1572 mysql_data_seek(result, i);
1573 row = mysql_fetch_row(result);
1574 if (!row || !row[0])
1576 if (!strcmp(row[0], "current_stream")) {
1577 if (!strcmp(argv[0], "ps")) {
1578 i = match < 2? match + num_rows - 2 : match - 2;
1581 i = i > num_rows - 1? i - num_rows : i;
1583 mysql_data_seek(result, i);
1584 row = mysql_fetch_row(result);
1585 if (!row || !row[0])
1588 query = make_message("update streams set def='%s' where name = "
1589 "'current_stream'", row[0]);
1590 ret = real_query(query);
1592 refresh_selector_info();
1596 mysql_free_result(result);
1600 /* select previous stream */
1601 int com_ps(int fd, int argc, char * const * argv)
1603 return com_ps_ns(fd, argc, argv);
1606 /* select next stream */
1607 int com_ns(int fd, int argc, char * const * argv)
1609 return com_ps_ns(fd, argc, argv);
1613 int com_streams(int fd, int argc, __a_unused char * const * argv)
1615 unsigned int num_rows;
1616 int i, ret = -E_NORESULT;
1620 if (argc > 1 && strcmp(argv[1], "current_stream"))
1621 return -E_MYSQL_SYNTAX;
1623 char *cs = get_current_stream();
1624 ret = send_va_buffer(fd, "%s\n", cs);
1628 result = get_result("select name from streams");
1631 num_rows = mysql_num_rows(result);
1636 for (i = 0; i < num_rows; i++) {
1637 row = mysql_fetch_row(result);
1638 if (!row || !row[0])
1640 if (strcmp(row[0], "current_stream"))
1641 send_va_buffer(fd, "%s\n", row[0]);
1646 mysql_free_result(result);
1650 /* query stream definition */
1651 int com_strq(int fd, int argc, char * const * argv)
1659 ret = -E_GET_STREAM;
1660 name = get_current_stream();
1663 name = escaped_basename(argv[1]);
1668 query = make_message("select def from streams where name='%s'", name);
1670 result = get_result(query);
1675 row = mysql_fetch_row(result);
1676 if (!row || !row[0])
1678 /* no '\n' needed */
1679 ret = send_buffer(fd, row[0]);
1682 mysql_free_result(result);
1686 /* change stream / change stream and play */
1687 static int com_cs_csp(int fd, int argc, char * const * argv)
1689 int ret, stream_change;
1690 char *query, *stream = NULL;
1691 char *old_stream = get_current_stream();
1692 int csp = !strcmp(argv[0], "csp");
1694 ret = -E_MYSQL_SYNTAX;
1700 ret = send_va_buffer(fd, "%s\n", old_stream);
1704 /* test if stream is valid, no need to escape argv[1] */
1705 query = get_query(argv[1], NULL, 0);
1710 stream = escape_str(argv[1]);
1713 stream_change = strcmp(stream, old_stream);
1714 if (stream_change) {
1715 ret = change_stream(stream);
1718 refresh_selector_info();
1722 mmd->new_vss_status_flags |= VSS_PLAYING;
1724 mmd->new_vss_status_flags |= VSS_NEXT;
1735 int com_cs(int fd, int argc, char * const * argv)
1737 return com_cs_csp(fd, argc, argv);
1740 /* change stream and play */
1741 int com_csp(int fd, int argc, char * const * argv)
1743 return com_cs_csp(fd, argc, argv);
1746 /* score list / skip */
1747 static int com_sl_skip(int fd, int argc, char * const * argv)
1749 void *result = NULL;
1751 int ret, i, skip = !strcmp(argv[0], "skip");
1752 char *query, *stream, *tmp;
1753 unsigned int num_rows, num;
1756 return -E_MYSQL_SYNTAX;
1757 num = atoi(argv[1]);
1759 return -E_MYSQL_SYNTAX;
1761 stream = get_current_stream();
1763 return -E_GET_STREAM;
1765 stream = escape_str(argv[2]);
1769 tmp = get_query(stream, NULL, 0);
1772 return -E_GET_QUERY;
1773 query = make_message("%s limit %d", tmp, num);
1776 result = get_result(query);
1780 ret = -E_EMPTY_RESULT;
1781 num_rows = mysql_num_rows(result);
1784 for (i = 0; i < num_rows && i < num; i++) {
1785 row = mysql_fetch_row(result);
1787 send_va_buffer(fd, "Skipping %s\n", row[0]);
1788 update_audio_file(row[0]);
1790 send_va_buffer(fd, "%s\n", row[0]? row[0]: "BUG");
1795 mysql_free_result(result);
1800 int com_sl(int fd, int argc, char * const * argv)
1802 return com_sl_skip(fd, argc, argv);
1806 int com_skip(int fd, int argc, char * const * argv)
1808 return com_sl_skip(fd, argc, argv);
1812 * update attributes of name
1814 static int update_atts(int fd, const char *name, char *atts)
1817 char *ebn, *q, *old, *new = NULL;
1821 ebn = escaped_basename(name);
1824 q = make_message("update data set %s where name = '%s'", atts, ebn);
1825 old = get_atts(ebn, 0);
1826 send_va_buffer(fd, "old: %s\n", old);
1828 ret = real_query(q);
1832 new = get_atts(ebn, 0);
1833 ret = send_va_buffer(fd, "new: %s\n", new);
1843 int com_sa(int fd, int argc, char * const * argv)
1846 char *atts = NULL, *name;
1849 return -E_MYSQL_SYNTAX;
1850 for (i = 1; i < argc; i++) {
1852 char *esc, *tmp, *p;
1853 int len = strlen(argv[i]);
1857 switch (argv[i][len - 1]) {
1867 p = para_strdup(argv[i]);
1869 esc = escape_str(p);
1873 tmp = make_message("%s%s='%s'", atts? "," : "", esc,
1876 atts = para_strcat(atts, tmp);
1882 if (i >= argc) { /* no name given, use current af */
1883 ret = -E_GET_AUDIO_FILE;
1884 if (!(name = get_current_audio_file()))
1886 ret = update_atts(fd, name, atts);
1890 for (; argv[i] && ret >= 0; i++)
1891 ret = update_atts(fd, argv[i], atts);
1893 refresh_selector_info();
1902 int com_cam(int fd, int argc, char * const * argv)
1904 char *name = NULL, *meta = NULL, *atts = NULL;
1908 return -E_MYSQL_SYNTAX;
1909 if (!(name = escaped_basename(argv[1])))
1912 if (!(atts = get_atts(name, 1)))
1915 if (!(meta = get_meta(name, 0)))
1917 for (i = 2; i < argc; i++) {
1920 if (!(ebn = escaped_basename(argv[i])))
1922 ret = send_va_buffer(fd, "updating %s\n", ebn);
1927 q = make_message("update data set %s where name = '%s'",
1929 if ((ret = update_atts(fd, ebn, atts)) >= 0)
1930 ret = real_query(q);
1950 static int com_vrfy_clean(int fd, int argc, __a_unused char * const * argv)
1953 int ret, vrfy_mode = strcmp(argv[0], "clean");
1954 void *result = NULL;
1957 my_ulonglong num_rows, top = 0, left = 0, right = 0;
1960 return -E_MYSQL_SYNTAX;
1962 result = get_result("select data.name from data left join dir on "
1963 "dir.name = data.name where dir.name is NULL");
1966 num_rows = mysql_num_rows(result);
1968 ret = send_buffer(fd, "No invalid entries\n");
1972 send_va_buffer(fd, "found %lli invalid entr%s\n", num_rows,
1973 num_rows == 1? "y" : "ies");
1974 ret = print_results(fd, result, top, left, num_rows - 1, right);
1977 while ((row = mysql_fetch_row(result))) {
1982 escaped_name = escape_str(row[0]);
1985 send_va_buffer(fd, "deleting %s\n", escaped_name);
1986 query = make_message("delete from data where name = '%s'",
1988 ret = real_query(query);
1996 mysql_free_result(result);
2003 int com_vrfy(int fd, int argc, char * const * argv)
2005 return com_vrfy_clean(fd, argc, argv);
2011 int com_clean(int fd, int argc, char * const * argv)
2013 return com_vrfy_clean(fd, argc, argv);
2016 static FILE *out_file;
2018 static int mysql_write_tmp_file(const char *dir, const char *name)
2020 int ret = -E_TMPFILE;
2021 char *msg = make_message("%s\t%s\n", dir, name);
2022 if (fputs(msg, out_file) != EOF)
2031 int com_upd(int fd, int argc, __a_unused char * const * argv)
2033 char *tempname = NULL, *query = NULL;
2034 int ret, out_fd = -1, num = 0;
2035 void *result = NULL;
2036 unsigned int num_rows;
2040 return -E_MYSQL_SYNTAX;
2042 tempname = para_strdup("/tmp/mysql.tmp.XXXXXX");
2043 ret = para_mkstemp(tempname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2047 out_file = fdopen(out_fd, "w");
2052 if (find_audio_files(conf.mysql_audio_file_dir_arg, mysql_write_tmp_file) < 0)
2054 num = ftell(out_file);
2056 * we have to make sure the file hit the disk before we call
2061 PARA_DEBUG_LOG("wrote tempfile %s (%d bytes)\n", tempname, num);
2064 if ((ret = real_query("delete from dir")) < 0)
2066 query = make_message("load data infile '%s' ignore into table dir "
2067 "fields terminated by '\t' lines terminated by '\n' "
2068 "(dir, name)", tempname);
2069 ret = real_query(query);
2073 result = get_result("select dir.name from dir left join data on "
2074 "data.name = dir.name where data.name is NULL");
2078 num_rows = mysql_num_rows(result);
2080 ret = send_buffer(fd, "no new entries\n");
2083 while ((row = mysql_fetch_row(result))) {
2088 send_va_buffer(fd, "new entry: %s\n", row[0]);
2089 erow = escape_str(row[0]);
2092 query = make_message("insert into data (name, pic_id) values "
2093 "('%s','%s')", erow, "1");
2095 ret = real_query(query);
2108 mysql_free_result(result);
2112 static char **server_get_audio_file_list(unsigned int num)
2114 char **list = para_malloc((num + 1) * sizeof(char *));
2115 char *tmp, *query, *stream = get_current_stream();
2116 void *result = NULL;
2117 unsigned int num_rows;
2121 tmp = get_query(stream, NULL, 1);
2125 query = make_message("%s limit %d", tmp, num);
2127 result = get_result(query);
2131 num_rows = mysql_num_rows(result);
2134 for (i = 0; i < num_rows && i < num; i++) {
2135 row = mysql_fetch_row(result);
2136 if (!row || !row[0])
2138 list[i] = para_strdup(row[0]);
2151 mysql_free_result(result);
2156 * connect to mysql server, return mysql pointer on success, -E_NOTCONN
2157 * on errors. Called from parent on startup and also from com_cdb().
2159 static int init_mysql_server(void)
2161 char *u = conf.mysql_user_arg? conf.mysql_user_arg : para_logname();
2164 mysql_ptr = mysql_init(NULL);
2166 PARA_CRIT_LOG("%s", "mysql init error\n");
2169 if (conf.mysql_port_arg < 0)
2170 return -E_MYSQL_SYNTAX;
2171 port = conf.mysql_port_arg;
2172 PARA_DEBUG_LOG("connecting: %s@%s:%d\n", u, conf.mysql_host_arg, port);
2173 if (!conf.mysql_user_arg)
2176 * If host is NULL a connection to the local host is assumed,
2177 * If user is NULL, the current user is assumed
2179 if (!(mysql_ptr = mysql_real_connect(mysql_ptr,
2180 conf.mysql_host_arg,
2181 conf.mysql_user_arg,
2182 conf.mysql_passwd_arg,
2183 conf.mysql_database_arg,
2185 PARA_CRIT_LOG("%s", "connect error\n");
2188 PARA_INFO_LOG("%s", "success\n");
2192 /* mmd lock must be held */
2193 static void write_msg2mmd(int success)
2195 sprintf(mmd->selector_info, "dbinfo1:%s\ndbinfo2:mysql-%s\ndbinfo3:\n",
2196 success < 0? PARA_STRERROR(-success) :
2197 "successfully connected to mysql server",
2198 success < 0? "" : mysql_get_server_info(mysql_ptr));
2201 /* create database */
2202 int com_cdb(int fd, int argc, char * const * argv)
2208 PARA_INFO_LOG("%s", "closing database\n");
2209 mysql_close(mysql_ptr);
2211 /* dont use any database */
2212 conf.mysql_database_arg = NULL; /* leak? */
2213 ret = -E_MYSQL_INIT;
2214 if (init_mysql_server() < 0 || !mysql_ptr)
2217 conf.mysql_database_arg = para_strdup("paraslash");
2220 conf.mysql_database_arg = escape_str(argv[1]);
2221 if (!conf.mysql_database_arg)
2224 query = make_message("create database %s", conf.mysql_database_arg);
2225 ret = real_query(query);
2229 /* reconnect with database just created */
2230 mysql_close(mysql_ptr);
2231 ret = -E_MYSQL_INIT;
2232 if (init_mysql_server() < 0 || !mysql_ptr)
2238 if (real_query("create table data (name varchar(255) binary not null "
2240 "lastplayed datetime not null default "
2242 "numplayed int not null default 0, "
2243 "pic_id bigint unsigned not null default 1)") < 0)
2245 if (real_query("create table dir (name varchar(255) binary not null "
2246 "primary key, dir varchar(255) default null)") < 0)
2248 if (real_query("create table pics ("
2249 "id bigint(20) unsigned not null primary key "
2251 "name varchar(255) binary not null, "
2252 "pic mediumblob not null)") < 0)
2254 if (real_query("create table streams ("
2255 "name varchar(255) binary not null primary key, "
2256 "def blob not null)") < 0)
2258 if (real_query("insert into streams (name, def) values "
2259 "('current_stream', '(none)')") < 0)
2261 ret = send_va_buffer(fd, "successfully created database %s\n",
2262 conf.mysql_database_arg);
2267 static void shutdown_connection(void)
2272 PARA_NOTICE_LOG("%s", "shutting down mysql connection\n");
2273 mysql_close(mysql_ptr);
2277 ret = mutex_destroy(mysql_lock);
2279 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
2285 * the init function of the mysql-based audio file selector
2287 * \param db pointer to the struct to initialize
2289 * Check the command line options and initialize all function pointers of \a
2290 * db. Connect to the mysql server and initialize the info string.
2292 * \return This function returns success even if it could not connect
2293 * to the mysql server. This is because the connect is expected to fail
2294 * if there the paraslash database is not yet created. This gives the
2295 * user a chance to send the "cdb" to create the database.
2297 * \sa struct audio_file_selector, misc_meta_data::selector_info,
2300 int mysql_selector_init(struct audio_file_selector *db)
2304 if (!conf.mysql_passwd_given)
2305 return -E_NO_MYSQL_PASSWD;
2306 if (!conf.mysql_audio_file_dir_given)
2307 return -E_NO_AF_DIR;
2309 db->cmd_list = mysql_selector_cmds;
2310 db->get_audio_file_list = server_get_audio_file_list;
2311 db->update_audio_file = update_audio_file_server_handler;
2312 db->shutdown = shutdown_connection;
2317 ret = init_mysql_server();
2319 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
2321 return 1; /* return success even if connect failed to give the
2322 * user the chance to exec com_cdb