MiniDLNA update: 1.0.19.1 to 1.0.20
[tomato.git] / release / src / router / minidlna / upnpsoap.c
blob0eaef05b899de695af4691314c2bb5eb6b720150
1 /* MiniDLNA project
3 * http://sourceforge.net/projects/minidlna/
5 * MiniDLNA media server
6 * Copyright (C) 2008-2009 Justin Maggard
8 * This file is part of MiniDLNA.
10 * MiniDLNA is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2 as
12 * published by the Free Software Foundation.
14 * MiniDLNA is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with MiniDLNA. If not, see <http://www.gnu.org/licenses/>.
22 * Portions of the code from the MiniUPnP project:
24 * Copyright (c) 2006-2007, Thomas Bernard
25 * All rights reserved.
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions are met:
29 * * Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * * Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * * The name of the author may not be used to endorse or promote products
35 * derived from this software without specific prior written permission.
37 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
38 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
41 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
42 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
43 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
47 * POSSIBILITY OF SUCH DAMAGE.
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <sys/socket.h>
53 #include <unistd.h>
54 #include <dirent.h>
55 #include <sys/stat.h>
56 #include <sys/types.h>
57 #include <arpa/inet.h>
58 #include <netinet/in.h>
59 #include <netdb.h>
60 #include <ctype.h>
62 #include "config.h"
63 #include "upnpglobalvars.h"
64 #include "utils.h"
65 #include "upnphttp.h"
66 #include "upnpsoap.h"
67 #include "upnpreplyparse.h"
68 #include "getifaddr.h"
69 #include "scanner.h"
70 #include "sql.h"
71 #include "log.h"
73 static void
74 BuildSendAndCloseSoapResp(struct upnphttp * h,
75 const char * body, int bodylen)
77 static const char beforebody[] =
78 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
79 "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
80 "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
81 "<s:Body>";
83 static const char afterbody[] =
84 "</s:Body>"
85 "</s:Envelope>\r\n";
87 BuildHeader_upnphttp(h, 200, "OK", sizeof(beforebody) - 1
88 + sizeof(afterbody) - 1 + bodylen );
90 memcpy(h->res_buf + h->res_buflen, beforebody, sizeof(beforebody) - 1);
91 h->res_buflen += sizeof(beforebody) - 1;
93 memcpy(h->res_buf + h->res_buflen, body, bodylen);
94 h->res_buflen += bodylen;
96 memcpy(h->res_buf + h->res_buflen, afterbody, sizeof(afterbody) - 1);
97 h->res_buflen += sizeof(afterbody) - 1;
99 SendResp_upnphttp(h);
100 CloseSocket_upnphttp(h);
103 static void
104 GetSystemUpdateID(struct upnphttp * h, const char * action)
106 static const char resp[] =
107 "<u:%sResponse "
108 "xmlns:u=\"%s\">"
109 "<Id>%d</Id>"
110 "</u:%sResponse>";
112 char body[512];
113 int bodylen;
115 bodylen = snprintf(body, sizeof(body), resp,
116 action, "urn:schemas-upnp-org:service:ContentDirectory:1",
117 updateID, action);
118 BuildSendAndCloseSoapResp(h, body, bodylen);
121 static void
122 IsAuthorizedValidated(struct upnphttp * h, const char * action)
124 static const char resp[] =
125 "<u:%sResponse "
126 "xmlns:u=\"%s\">"
127 "<Result>%d</Result>"
128 "</u:%sResponse>";
130 char body[512];
131 int bodylen;
133 bodylen = snprintf(body, sizeof(body), resp,
134 action, "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1",
135 1, action);
136 BuildSendAndCloseSoapResp(h, body, bodylen);
139 static void
140 GetProtocolInfo(struct upnphttp * h, const char * action)
142 static const char resp[] =
143 "<u:%sResponse "
144 "xmlns:u=\"%s\">"
145 "<Source>"
146 RESOURCE_PROTOCOL_INFO_VALUES
147 "</Source>"
148 "<Sink></Sink>"
149 "</u:%sResponse>";
151 char * body;
152 int bodylen;
154 bodylen = asprintf(&body, resp,
155 action, "urn:schemas-upnp-org:service:ConnectionManager:1",
156 action);
157 BuildSendAndCloseSoapResp(h, body, bodylen);
158 free(body);
161 static void
162 GetSortCapabilities(struct upnphttp * h, const char * action)
164 static const char resp[] =
165 "<u:%sResponse "
166 "xmlns:u=\"%s\">"
167 "<SortCaps>"
168 "dc:title,"
169 "dc:date,"
170 "upnp:class,"
171 "upnp:originalTrackNumber"
172 "</SortCaps>"
173 "</u:%sResponse>";
175 char body[512];
176 int bodylen;
178 bodylen = snprintf(body, sizeof(body), resp,
179 action, "urn:schemas-upnp-org:service:ContentDirectory:1",
180 action);
181 BuildSendAndCloseSoapResp(h, body, bodylen);
184 static void
185 GetSearchCapabilities(struct upnphttp * h, const char * action)
187 static const char resp[] =
188 "<u:%sResponse xmlns:u=\"%s\">"
189 "<SearchCaps>"
190 "dc:creator,"
191 "dc:title,"
192 "upnp:album,"
193 "upnp:actor,"
194 "upnp:artist,"
195 "upnp:class,"
196 "upnp:genre,"
197 "@refID"
198 "</SearchCaps>"
199 "</u:%sResponse>";
201 char body[512];
202 int bodylen;
204 bodylen = snprintf(body, sizeof(body), resp,
205 action, "urn:schemas-upnp-org:service:ContentDirectory:1",
206 action);
207 BuildSendAndCloseSoapResp(h, body, bodylen);
210 static void
211 GetCurrentConnectionIDs(struct upnphttp * h, const char * action)
213 /* TODO: Use real data. - JM */
214 static const char resp[] =
215 "<u:%sResponse "
216 "xmlns:u=\"%s\">"
217 "<ConnectionIDs>0</ConnectionIDs>"
218 "</u:%sResponse>";
220 char body[512];
221 int bodylen;
223 bodylen = snprintf(body, sizeof(body), resp,
224 action, "urn:schemas-upnp-org:service:ConnectionManager:1",
225 action);
226 BuildSendAndCloseSoapResp(h, body, bodylen);
229 static void
230 GetCurrentConnectionInfo(struct upnphttp * h, const char * action)
232 /* TODO: Use real data. - JM */
233 static const char resp[] =
234 "<u:%sResponse "
235 "xmlns:u=\"%s\">"
236 "<RcsID>-1</RcsID>"
237 "<AVTransportID>-1</AVTransportID>"
238 "<ProtocolInfo></ProtocolInfo>"
239 "<PeerConnectionManager></PeerConnectionManager>"
240 "<PeerConnectionID>-1</PeerConnectionID>"
241 "<Direction>Output</Direction>"
242 "<Status>Unknown</Status>"
243 "</u:%sResponse>";
245 char body[sizeof(resp)+128];
246 int bodylen;
248 bodylen = snprintf(body, sizeof(body), resp,
249 action, "urn:schemas-upnp-org:service:ConnectionManager:1",
250 action);
251 BuildSendAndCloseSoapResp(h, body, bodylen);
254 static void
255 mime_to_ext(const char * mime, char * buf)
257 switch( *mime )
259 /* Audio extensions */
260 case 'a':
261 if( strcmp(mime+6, "mpeg") == 0 )
262 strcpy(buf, "mp3");
263 else if( strcmp(mime+6, "mp4") == 0 )
264 strcpy(buf, "m4a");
265 else if( strcmp(mime+6, "x-ms-wma") == 0 )
266 strcpy(buf, "wma");
267 else if( strcmp(mime+6, "x-flac") == 0 )
268 strcpy(buf, "flac");
269 else if( strcmp(mime+6, "flac") == 0 )
270 strcpy(buf, "flac");
271 else if( strcmp(mime+6, "x-wav") == 0 )
272 strcpy(buf, "wav");
273 else if( strncmp(mime+6, "L16", 3) == 0 )
274 strcpy(buf, "pcm");
275 else if( strcmp(mime+6, "3gpp") == 0 )
276 strcpy(buf, "3gp");
277 else if( strcmp(mime, "application/ogg") == 0 )
278 strcpy(buf, "ogg");
279 else
280 strcpy(buf, "dat");
281 break;
282 case 'v':
283 if( strcmp(mime+6, "avi") == 0 )
284 strcpy(buf, "avi");
285 else if( strcmp(mime+6, "divx") == 0 )
286 strcpy(buf, "avi");
287 else if( strcmp(mime+6, "x-msvideo") == 0 )
288 strcpy(buf, "avi");
289 else if( strcmp(mime+6, "mpeg") == 0 )
290 strcpy(buf, "mpg");
291 else if( strcmp(mime+6, "mp4") == 0 )
292 strcpy(buf, "mp4");
293 else if( strcmp(mime+6, "x-ms-wmv") == 0 )
294 strcpy(buf, "wmv");
295 else if( strcmp(mime+6, "x-matroska") == 0 )
296 strcpy(buf, "mkv");
297 else if( strcmp(mime+6, "x-mkv") == 0 )
298 strcpy(buf, "mkv");
299 else if( strcmp(mime+6, "x-flv") == 0 )
300 strcpy(buf, "flv");
301 else if( strcmp(mime+6, "vnd.dlna.mpeg-tts") == 0 )
302 strcpy(buf, "mpg");
303 else if( strcmp(mime+6, "quicktime") == 0 )
304 strcpy(buf, "mov");
305 else if( strcmp(mime+6, "3gpp") == 0 )
306 strcpy(buf, "3gp");
307 else if( strcmp(mime+6, "x-tivo-mpeg") == 0 )
308 strcpy(buf, "TiVo");
309 else
310 strcpy(buf, "dat");
311 break;
312 case 'i':
313 if( strcmp(mime+6, "jpeg") == 0 )
314 strcpy(buf, "jpg");
315 else if( strcmp(mime+6, "png") == 0 )
316 strcpy(buf, "png");
317 else
318 strcpy(buf, "dat");
319 break;
320 default:
321 strcpy(buf, "dat");
322 break;
326 #define FILTER_CHILDCOUNT 0x00000001
327 #define FILTER_DC_CREATOR 0x00000002
328 #define FILTER_DC_DATE 0x00000004
329 #define FILTER_DC_DESCRIPTION 0x00000008
330 #define FILTER_DLNA_NAMESPACE 0x00000010
331 #define FILTER_REFID 0x00000020
332 #define FILTER_RES 0x00000040
333 #define FILTER_RES_BITRATE 0x00000080
334 #define FILTER_RES_DURATION 0x00000100
335 #define FILTER_RES_NRAUDIOCHANNELS 0x00000200
336 #define FILTER_RES_RESOLUTION 0x00000400
337 #define FILTER_RES_SAMPLEFREQUENCY 0x00000800
338 #define FILTER_RES_SIZE 0x00001000
339 #define FILTER_UPNP_ACTOR 0x00002000
340 #define FILTER_UPNP_ALBUM 0x00004000
341 #define FILTER_UPNP_ALBUMARTURI 0x00008000
342 #define FILTER_UPNP_ALBUMARTURI_DLNA_PROFILEID 0x00010000
343 #define FILTER_UPNP_ARTIST 0x00020000
344 #define FILTER_UPNP_GENRE 0x00040000
345 #define FILTER_UPNP_ORIGINALTRACKNUMBER 0x00080000
346 #define FILTER_UPNP_SEARCHCLASS 0x00100000
348 static u_int32_t
349 set_filter_flags(char * filter, struct upnphttp *h)
351 char *item, *saveptr = NULL;
352 u_int32_t flags = 0;
354 if( !filter || (strlen(filter) <= 1) )
355 return 0xFFFFFFFF;
356 if( h->reqflags & FLAG_SAMSUNG )
357 flags |= FILTER_DLNA_NAMESPACE;
358 item = strtok_r(filter, ",", &saveptr);
359 while( item != NULL )
361 if( saveptr )
362 *(item-1) = ',';
363 while( isspace(*item) )
364 item++;
365 if( strcmp(item, "@childCount") == 0 )
367 flags |= FILTER_CHILDCOUNT;
369 else if( strcmp(item, "dc:creator") == 0 )
371 flags |= FILTER_DC_CREATOR;
373 else if( strcmp(item, "dc:date") == 0 )
375 flags |= FILTER_DC_DATE;
377 else if( strcmp(item, "dc:description") == 0 )
379 flags |= FILTER_DC_DESCRIPTION;
381 else if( strcmp(item, "dlna") == 0 )
383 flags |= FILTER_DLNA_NAMESPACE;
385 else if( strcmp(item, "@refID") == 0 )
387 flags |= FILTER_REFID;
389 else if( strcmp(item, "upnp:album") == 0 )
391 flags |= FILTER_UPNP_ALBUM;
393 else if( strcmp(item, "upnp:albumArtURI") == 0 )
395 flags |= FILTER_UPNP_ALBUMARTURI;
396 if( h->reqflags & FLAG_SAMSUNG )
397 flags |= FILTER_UPNP_ALBUMARTURI_DLNA_PROFILEID;
399 else if( strcmp(item, "upnp:albumArtURI@dlna:profileID") == 0 )
401 flags |= FILTER_UPNP_ALBUMARTURI;
402 flags |= FILTER_UPNP_ALBUMARTURI_DLNA_PROFILEID;
404 else if( strcmp(item, "upnp:artist") == 0 )
406 flags |= FILTER_UPNP_ARTIST;
408 else if( strcmp(item, "upnp:actor") == 0 )
410 flags |= FILTER_UPNP_ACTOR;
412 else if( strcmp(item, "upnp:genre") == 0 )
414 flags |= FILTER_UPNP_GENRE;
416 else if( strcmp(item, "upnp:originalTrackNumber") == 0 )
418 flags |= FILTER_UPNP_ORIGINALTRACKNUMBER;
420 else if( strcmp(item, "upnp:searchClass") == 0 )
422 flags |= FILTER_UPNP_SEARCHCLASS;
424 else if( strcmp(item, "res") == 0 )
426 flags |= FILTER_RES;
428 else if( (strcmp(item, "res@bitrate") == 0) ||
429 (strcmp(item, "@bitrate") == 0) ||
430 ((strcmp(item, "bitrate") == 0) && (flags & FILTER_RES)) )
432 flags |= FILTER_RES;
433 flags |= FILTER_RES_BITRATE;
435 else if( (strcmp(item, "res@duration") == 0) ||
436 (strcmp(item, "@duration") == 0) ||
437 ((strcmp(item, "duration") == 0) && (flags & FILTER_RES)) )
439 flags |= FILTER_RES;
440 flags |= FILTER_RES_DURATION;
442 else if( (strcmp(item, "res@nrAudioChannels") == 0) ||
443 (strcmp(item, "@nrAudioChannels") == 0) ||
444 ((strcmp(item, "nrAudioChannels") == 0) && (flags & FILTER_RES)) )
446 flags |= FILTER_RES;
447 flags |= FILTER_RES_NRAUDIOCHANNELS;
449 else if( (strcmp(item, "res@resolution") == 0) ||
450 (strcmp(item, "@resolution") == 0) ||
451 ((strcmp(item, "resolution") == 0) && (flags & FILTER_RES)) )
453 flags |= FILTER_RES;
454 flags |= FILTER_RES_RESOLUTION;
456 else if( (strcmp(item, "res@sampleFrequency") == 0) ||
457 (strcmp(item, "@sampleFrequency") == 0) ||
458 ((strcmp(item, "sampleFrequency") == 0) && (flags & FILTER_RES)) )
460 flags |= FILTER_RES;
461 flags |= FILTER_RES_SAMPLEFREQUENCY;
463 else if( (strcmp(item, "res@size") == 0) ||
464 (strcmp(item, "@size") == 0) ||
465 (strcmp(item, "size") == 0) )
467 flags |= FILTER_RES;
468 flags |= FILTER_RES_SIZE;
470 item = strtok_r(NULL, ",", &saveptr);
473 return flags;
476 char *
477 parse_sort_criteria(char * sortCriteria, int * error)
479 char *order = NULL;
480 char *item, *saveptr;
481 int i, ret, reverse, title_sorted = 0;
482 *error = 0;
484 if( !sortCriteria )
485 return NULL;
487 if( (item = strtok_r(sortCriteria, ",", &saveptr)) )
489 order = malloc(4096);
490 strcpy(order, "order by ");
492 for( i=0; item != NULL; i++ )
494 reverse=0;
495 if( i )
496 strcat(order, ", ");
497 if( *item == '+' )
499 item++;
501 else if( *item == '-' )
503 reverse = 1;
504 item++;
506 if( strcasecmp(item, "upnp:class") == 0 )
508 strcat(order, "o.CLASS");
510 else if( strcasecmp(item, "dc:title") == 0 )
512 strcat(order, "d.TITLE");
513 title_sorted = 1;
515 else if( strcasecmp(item, "dc:date") == 0 )
517 strcat(order, "d.DATE");
519 else if( strcasecmp(item, "upnp:originalTrackNumber") == 0 )
521 strcat(order, "d.DISC, d.TRACK");
523 else
525 printf("Unhandled SortCriteria [%s]\n", item);
526 *error = 1;
527 if( i )
529 ret = strlen(order);
530 order[ret-2] = '\0';
532 i--;
533 goto unhandled_order;
536 if( reverse )
537 strcat(order, " DESC");
538 unhandled_order:
539 item = strtok_r(NULL, ",", &saveptr);
541 if( i <= 0 )
543 free(order);
544 return NULL;
546 /* Add a "tiebreaker" sort order */
547 if( !title_sorted )
548 strcat(order, ", TITLE ASC");
550 return order;
553 inline static void
554 add_resized_res(int srcw, int srch, int reqw, int reqh, char *dlna_pn,
555 char *detailID, struct Response *args)
557 int dstw = reqw;
558 int dsth = reqh;
560 if( args->flags & FLAG_NO_RESIZE )
561 return;
563 strcatf(args->str, "&lt;res ");
564 if( args->filter & FILTER_RES_RESOLUTION )
566 dstw = reqw;
567 dsth = ((((reqw<<10)/srcw)*srch)>>10);
568 if( dsth > reqh ) {
569 dsth = reqh;
570 dstw = (((reqh<<10)/srch) * srcw>>10);
572 strcatf(args->str, "resolution=\"%dx%d\" ", dstw, dsth);
574 strcatf(args->str, "protocolInfo=\"http-get:*:image/jpeg:DLNA.ORG_PN=%s;DLNA.ORG_CI=1\"&gt;"
575 "http://%s:%d/Resized/%s.jpg?width=%d,height=%d"
576 "&lt;/res&gt;",
577 dlna_pn, lan_addr[args->iface].str, runtime_vars.port,
578 detailID, dstw, dsth);
581 inline static void
582 add_res(char *size, char *duration, char *bitrate, char *sampleFrequency,
583 char *nrAudioChannels, char *resolution, char *dlna_pn, char *mime,
584 char *detailID, char *ext, struct Response *args)
586 strcatf(args->str, "&lt;res ");
587 if( size && (args->filter & FILTER_RES_SIZE) ) {
588 strcatf(args->str, "size=\"%s\" ", size);
590 if( duration && (args->filter & FILTER_RES_DURATION) ) {
591 strcatf(args->str, "duration=\"%s\" ", duration);
593 if( bitrate && (args->filter & FILTER_RES_BITRATE) ) {
594 strcatf(args->str, "bitrate=\"%s\" ", bitrate);
596 if( sampleFrequency && (args->filter & FILTER_RES_SAMPLEFREQUENCY) ) {
597 strcatf(args->str, "sampleFrequency=\"%s\" ", sampleFrequency);
599 if( nrAudioChannels && (args->filter & FILTER_RES_NRAUDIOCHANNELS) ) {
600 strcatf(args->str, "nrAudioChannels=\"%s\" ", nrAudioChannels);
602 if( resolution && (args->filter & FILTER_RES_RESOLUTION) ) {
603 strcatf(args->str, "resolution=\"%s\" ", resolution);
605 strcatf(args->str, "protocolInfo=\"http-get:*:%s:%s\"&gt;"
606 "http://%s:%d/MediaItems/%s.%s"
607 "&lt;/res&gt;",
608 mime, dlna_pn, lan_addr[args->iface].str,
609 runtime_vars.port, detailID, ext);
612 #define SELECT_COLUMNS "SELECT o.OBJECT_ID, o.PARENT_ID, o.REF_ID, o.DETAIL_ID, o.CLASS," \
613 " d.SIZE, d.TITLE, d.DURATION, d.BITRATE, d.SAMPLERATE, d.ARTIST," \
614 " d.ALBUM, d.GENRE, d.COMMENT, d.CHANNELS, d.TRACK, d.DATE, d.RESOLUTION," \
615 " d.THUMBNAIL, d.CREATOR, d.DLNA_PN, d.MIME, d.ALBUM_ART, d.DISC "
617 static int
618 callback(void *args, int argc, char **argv, char **azColName)
620 struct Response *passed_args = (struct Response *)args;
621 char *id = argv[0], *parent = argv[1], *refID = argv[2], *detailID = argv[3], *class = argv[4], *size = argv[5], *title = argv[6],
622 *duration = argv[7], *bitrate = argv[8], *sampleFrequency = argv[9], *artist = argv[10], *album = argv[11],
623 *genre = argv[12], *comment = argv[13], *nrAudioChannels = argv[14], *track = argv[15], *date = argv[16], *resolution = argv[17],
624 *tn = argv[18], *creator = argv[19], *dlna_pn = argv[20], *mime = argv[21], *album_art = argv[22];
625 char dlna_buf[96];
626 char ext[5];
627 struct string_s *str = passed_args->str;
628 int ret = 0;
630 /* Make sure we have at least 8KB left of allocated memory to finish the response. */
631 if( str->off > (str->size - 8192) )
633 #if MAX_RESPONSE_SIZE > 0
634 if( (str->size+DEFAULT_RESP_SIZE) <= MAX_RESPONSE_SIZE )
636 #endif
637 str->data = realloc(str->data, (str->off+DEFAULT_RESP_SIZE));
638 if( str->data )
640 str->size += DEFAULT_RESP_SIZE;
641 DPRINTF(E_DEBUG, L_HTTP, "UPnP SOAP response enlarged to %d. [%d results so far]\n",
642 str->size, passed_args->returned);
644 else
646 DPRINTF(E_ERROR, L_HTTP, "UPnP SOAP response was too big, and realloc failed!\n");
647 return -1;
649 #if MAX_RESPONSE_SIZE > 0
651 else
653 DPRINTF(E_ERROR, L_HTTP, "UPnP SOAP response cut short, to not exceed the max response size [%lld]!\n", (long long int)MAX_RESPONSE_SIZE);
654 return -1;
656 #endif
658 passed_args->returned++;
660 if( dlna_pn )
661 sprintf(dlna_buf, "DLNA.ORG_PN=%s", dlna_pn);
662 else if( passed_args->flags & FLAG_DLNA )
663 strcpy(dlna_buf, dlna_no_conv);
664 else
665 strcpy(dlna_buf, "*");
667 if( strncmp(class, "item", 4) == 0 )
669 /* We may need special handling for certain MIME types */
670 if( *mime == 'v' )
672 if( passed_args->flags & FLAG_MIME_AVI_DIVX )
674 if( strcmp(mime, "video/x-msvideo") == 0 )
676 if( creator )
677 strcpy(mime+6, "divx");
678 else
679 strcpy(mime+6, "avi");
682 else if( passed_args->flags & FLAG_MIME_AVI_AVI )
684 if( strcmp(mime, "video/x-msvideo") == 0 )
686 strcpy(mime+6, "avi");
689 if( !(passed_args->flags & FLAG_DLNA) )
691 if( strcmp(mime+6, "vnd.dlna.mpeg-tts") == 0 )
693 strcpy(mime+6, "mpeg");
696 /* From what I read, Samsung TV's expect a [wrong] MIME type of x-mkv. */
697 if( passed_args->flags & FLAG_SAMSUNG )
699 if( strcmp(mime+6, "x-matroska") == 0 )
701 strcpy(mime+8, "mkv");
705 else if( *mime == 'a' )
707 if( strcmp(mime+6, "x-flac") == 0 )
709 if( passed_args->flags & FLAG_MIME_FLAC_FLAC )
711 strcpy(mime+6, "flac");
716 ret = strcatf(str, "&lt;item id=\"%s\" parentID=\"%s\" restricted=\"1\"", id, parent);
717 if( refID && (passed_args->filter & FILTER_REFID) ) {
718 ret = strcatf(str, " refID=\"%s\"", refID);
720 ret = strcatf(str, "&gt;"
721 "&lt;dc:title&gt;%s&lt;/dc:title&gt;"
722 "&lt;upnp:class&gt;object.%s&lt;/upnp:class&gt;",
723 title, class);
724 if( comment && (passed_args->filter & FILTER_DC_DESCRIPTION) ) {
725 ret = strcatf(str, "&lt;dc:description&gt;%.384s&lt;/dc:description&gt;", comment);
727 if( creator && (passed_args->filter & FILTER_DC_CREATOR) ) {
728 ret = strcatf(str, "&lt;dc:creator&gt;%s&lt;/dc:creator&gt;", creator);
730 if( date && (passed_args->filter & FILTER_DC_DATE) ) {
731 ret = strcatf(str, "&lt;dc:date&gt;%s&lt;/dc:date&gt;", date);
733 if( artist ) {
734 if( (*mime == 'v') && (passed_args->filter & FILTER_UPNP_ACTOR) ) {
735 ret = strcatf(str, "&lt;upnp:actor&gt;%s&lt;/upnp:actor&gt;", artist);
737 if( passed_args->filter & FILTER_UPNP_ARTIST ) {
738 ret = strcatf(str, "&lt;upnp:artist&gt;%s&lt;/upnp:artist&gt;", artist);
741 if( album && (passed_args->filter & FILTER_UPNP_ALBUM) ) {
742 ret = strcatf(str, "&lt;upnp:album&gt;%s&lt;/upnp:album&gt;", album);
744 if( genre && (passed_args->filter & FILTER_UPNP_GENRE) ) {
745 ret = strcatf(str, "&lt;upnp:genre&gt;%s&lt;/upnp:genre&gt;", genre);
747 if( strncmp(id, MUSIC_PLIST_ID, strlen(MUSIC_PLIST_ID)) == 0 ) {
748 track = strrchr(id, '$')+1;
750 if( track && atoi(track) && (passed_args->filter & FILTER_UPNP_ORIGINALTRACKNUMBER) ) {
751 ret = strcatf(str, "&lt;upnp:originalTrackNumber&gt;%s&lt;/upnp:originalTrackNumber&gt;", track);
753 if( album_art && atoi(album_art) )
755 /* Video and audio album art is handled differently */
756 if( *mime == 'v' && (passed_args->filter & FILTER_RES) && !(passed_args->flags & FLAG_MS_PFS) ) {
757 ret = strcatf(str, "&lt;res protocolInfo=\"http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN\"&gt;"
758 "http://%s:%d/AlbumArt/%s-%s.jpg"
759 "&lt;/res&gt;",
760 lan_addr[passed_args->iface].str, runtime_vars.port, album_art, detailID);
761 } else if( passed_args->filter & FILTER_UPNP_ALBUMARTURI ) {
762 ret = strcatf(str, "&lt;upnp:albumArtURI");
763 if( passed_args->filter & FILTER_UPNP_ALBUMARTURI_DLNA_PROFILEID ) {
764 ret = strcatf(str, " dlna:profileID=\"JPEG_TN\" xmlns:dlna=\"urn:schemas-dlna-org:metadata-1-0/\"");
766 ret = strcatf(str, "&gt;http://%s:%d/AlbumArt/%s-%s.jpg&lt;/upnp:albumArtURI&gt;",
767 lan_addr[passed_args->iface].str, runtime_vars.port, album_art, detailID);
770 if( (passed_args->flags & FLAG_MS_PFS) && *mime == 'i' ) {
771 if( passed_args->client == EMediaRoom && !album )
772 ret = strcatf(str, "&lt;upnp:album&gt;%s&lt;/upnp:album&gt;", "[No Keywords]");
774 /* EVA2000 doesn't seem to handle embedded thumbnails */
775 if( passed_args->client != ENetgearEVA2000 && tn && atoi(tn) ) {
776 ret = strcatf(str, "&lt;upnp:albumArtURI&gt;"
777 "http://%s:%d/Thumbnails/%s.jpg"
778 "&lt;/upnp:albumArtURI&gt;",
779 lan_addr[passed_args->iface].str, runtime_vars.port, detailID);
780 } else {
781 ret = strcatf(str, "&lt;upnp:albumArtURI&gt;"
782 "http://%s:%d/Resized/%s.jpg?width=160,height=160"
783 "&lt;/upnp:albumArtURI&gt;",
784 lan_addr[passed_args->iface].str, runtime_vars.port, detailID);
787 if( passed_args->filter & FILTER_RES ) {
788 mime_to_ext(mime, ext);
789 if( (passed_args->client == EFreeBox) && tn && atoi(tn) ) {
790 ret = strcatf(str, "&lt;res protocolInfo=\"http-get:*:%s:%s\"&gt;"
791 "http://%s:%d/Thumbnails/%s.jpg"
792 "&lt;/res&gt;",
793 mime, "DLNA.ORG_PN=JPEG_TN", lan_addr[passed_args->iface].str,
794 runtime_vars.port, detailID);
796 add_res(size, duration, bitrate, sampleFrequency, nrAudioChannels,
797 resolution, dlna_buf, mime, detailID, ext, passed_args);
798 if( (*mime == 'i') && (passed_args->client != EFreeBox) ) {
799 int srcw = atoi(strsep(&resolution, "x"));
800 int srch = atoi(resolution);
801 if( !dlna_pn ) {
802 add_resized_res(srcw, srch, 4096, 4096, "JPEG_LRG", detailID, passed_args);
804 if( !dlna_pn || !strncmp(dlna_pn, "JPEG_L", 6) || !strncmp(dlna_pn, "JPEG_M", 6) ) {
805 add_resized_res(srcw, srch, 640, 480, "JPEG_SM", detailID, passed_args);
807 if( tn && atoi(tn) ) {
808 ret = strcatf(str, "&lt;res protocolInfo=\"http-get:*:%s:%s\"&gt;"
809 "http://%s:%d/Thumbnails/%s.jpg"
810 "&lt;/res&gt;",
811 mime, "DLNA.ORG_PN=JPEG_TN", lan_addr[passed_args->iface].str,
812 runtime_vars.port, detailID);
815 else if( *mime == 'v' ) {
816 switch( passed_args->client ) {
817 case EToshibaTV:
818 if( dlna_pn &&
819 (strncmp(dlna_pn, "MPEG_TS_HD_NA", 13) == 0 ||
820 strncmp(dlna_pn, "MPEG_TS_SD_NA", 13) == 0 ||
821 strncmp(dlna_pn, "AVC_TS_MP_HD_AC3", 16) == 0 ||
822 strncmp(dlna_pn, "AVC_TS_HP_HD_AC3", 16) == 0))
824 sprintf(dlna_buf, "DLNA.ORG_PN=MPEG_PS_NTSC;DLNA.ORG_OP=01;DLNA.ORG_CI=0");
825 add_res(size, duration, bitrate, sampleFrequency, nrAudioChannels,
826 resolution, dlna_buf, mime, detailID, ext, passed_args);
828 break;
829 case ESonyBDP:
830 if( dlna_pn &&
831 (strncmp(dlna_pn, "AVC_TS", 6) == 0 ||
832 strncmp(dlna_pn, "MPEG_TS", 7) == 0) )
834 if( strncmp(dlna_pn, "MPEG_TS_SD_NA", 13) != 0 )
836 sprintf(dlna_buf, "DLNA.ORG_PN=MPEG_TS_SD_NA;DLNA.ORG_OP=01;DLNA.ORG_CI=0");
837 add_res(size, duration, bitrate, sampleFrequency, nrAudioChannels,
838 resolution, dlna_buf, mime, detailID, ext, passed_args);
840 if( strncmp(dlna_pn, "MPEG_TS_SD_EU", 13) != 0 )
842 sprintf(dlna_buf, "DLNA.ORG_PN=MPEG_TS_SD_EU;DLNA.ORG_OP=01;DLNA.ORG_CI=0");
843 add_res(size, duration, bitrate, sampleFrequency, nrAudioChannels,
844 resolution, dlna_buf, mime, detailID, ext, passed_args);
847 else if( (dlna_pn &&
848 (strncmp(dlna_pn, "AVC_MP4", 7) == 0 ||
849 strncmp(dlna_pn, "MPEG4_P2_MP4", 12) == 0)) ||
850 strcmp(mime+6, "x-matroska") == 0 ||
851 strcmp(mime+6, "x-msvideo") == 0 ||
852 strcmp(mime+6, "mpeg") == 0 )
854 strcpy(mime+6, "avi");
855 if( !dlna_pn || strncmp(dlna_pn, "MPEG_PS_NTSC", 12) != 0 )
857 sprintf(dlna_buf, "DLNA.ORG_PN=MPEG_PS_NTSC;DLNA.ORG_OP=01;DLNA.ORG_CI=0");
858 add_res(size, duration, bitrate, sampleFrequency, nrAudioChannels,
859 resolution, dlna_buf, mime, detailID, ext, passed_args);
861 if( !dlna_pn || strncmp(dlna_pn, "MPEG_PS_PAL", 11) != 0 )
863 sprintf(dlna_buf, "DLNA.ORG_PN=MPEG_PS_PAL;DLNA.ORG_OP=01;DLNA.ORG_CI=0");
864 add_res(size, duration, bitrate, sampleFrequency, nrAudioChannels,
865 resolution, dlna_buf, mime, detailID, ext, passed_args);
868 break;
869 case ESonyBravia:
870 /* BRAVIA KDL-##*X### series TVs do natively support AVC/AC3 in TS, but
871 require profile to be renamed (applies to _T and _ISO variants also) */
872 if( dlna_pn &&
873 (strncmp(dlna_pn, "AVC_TS_MP_SD_AC3", 16) == 0 ||
874 strncmp(dlna_pn, "AVC_TS_MP_HD_AC3", 16) == 0 ||
875 strncmp(dlna_pn, "AVC_TS_HP_HD_AC3", 16) == 0))
877 sprintf(dlna_buf, "DLNA.ORG_PN=AVC_TS_HD_50_AC3;DLNA.ORG_OP=01;DLNA.ORG_CI=0");
878 add_res(size, duration, bitrate, sampleFrequency, nrAudioChannels,
879 resolution, dlna_buf, mime, detailID, ext, passed_args);
881 break;
882 case ELGDevice:
883 if( sql_get_int_field(db, "SELECT ID from CAPTIONS where ID = '%s'", detailID) > 0 )
885 ret = strcatf(str, "&lt;res protocolInfo=\"http-get:*:text/srt:*\"&gt;"
886 "http://%s:%d/Captions/%s.srt"
887 "&lt;/res&gt;",
888 lan_addr[passed_args->iface].str, runtime_vars.port, detailID);
890 break;
891 default:
892 break;
896 ret = strcatf(str, "&lt;/item&gt;");
898 else if( strncmp(class, "container", 9) == 0 )
900 ret = strcatf(str, "&lt;container id=\"%s\" parentID=\"%s\" restricted=\"1\" ", id, parent);
901 if( passed_args->filter & FILTER_CHILDCOUNT )
903 int children;
904 ret = sql_get_int_field(db, "SELECT count(*) from OBJECTS where PARENT_ID = '%s';", id);
905 children = (ret > 0) ? ret : 0;
906 ret = strcatf(str, "childCount=\"%d\"", children);
908 /* If the client calls for BrowseMetadata on root, we have to include our "upnp:searchClass"'s, unless they're filtered out */
909 if( (passed_args->requested == 1) && (strcmp(id, "0") == 0) )
911 if( passed_args->filter & FILTER_UPNP_SEARCHCLASS )
913 ret = strcatf(str, "&gt;"
914 "&lt;upnp:searchClass includeDerived=\"1\"&gt;object.item.audioItem&lt;/upnp:searchClass&gt;"
915 "&lt;upnp:searchClass includeDerived=\"1\"&gt;object.item.imageItem&lt;/upnp:searchClass&gt;"
916 "&lt;upnp:searchClass includeDerived=\"1\"&gt;object.item.videoItem&lt;/upnp:searchClass");
919 ret = strcatf(str, "&gt;"
920 "&lt;dc:title&gt;%s&lt;/dc:title&gt;"
921 "&lt;upnp:class&gt;object.%s&lt;/upnp:class&gt;",
922 title, class);
923 if( creator && (passed_args->filter & FILTER_DC_CREATOR) ) {
924 ret = strcatf(str, "&lt;dc:creator&gt;%s&lt;/dc:creator&gt;", creator);
926 if( genre && (passed_args->filter & FILTER_UPNP_GENRE) ) {
927 ret = strcatf(str, "&lt;upnp:genre&gt;%s&lt;/upnp:genre&gt;", genre);
929 if( artist && (passed_args->filter & FILTER_UPNP_ARTIST) ) {
930 ret = strcatf(str, "&lt;upnp:artist&gt;%s&lt;/upnp:artist&gt;", artist);
932 if( album_art && atoi(album_art) && (passed_args->filter & FILTER_UPNP_ALBUMARTURI) ) {
933 ret = strcatf(str, "&lt;upnp:albumArtURI ");
934 if( passed_args->filter & FILTER_UPNP_ALBUMARTURI_DLNA_PROFILEID ) {
935 ret = strcatf(str, "dlna:profileID=\"JPEG_TN\" xmlns:dlna=\"urn:schemas-dlna-org:metadata-1-0/\"");
937 ret = strcatf(str, "&gt;http://%s:%d/AlbumArt/%s-%s.jpg&lt;/upnp:albumArtURI&gt;",
938 lan_addr[passed_args->iface].str, runtime_vars.port, album_art, detailID);
940 ret = strcatf(str, "&lt;/container&gt;");
943 return 0;
946 static void
947 BrowseContentDirectory(struct upnphttp * h, const char * action)
949 static const char resp0[] =
950 "<u:BrowseResponse "
951 "xmlns:u=\"urn:schemas-upnp-org:service:ContentDirectory:1\">"
952 "<Result>"
953 "&lt;DIDL-Lite"
954 CONTENT_DIRECTORY_SCHEMAS;
955 char *zErrMsg = 0;
956 char *sql, *ptr;
957 int ret;
958 struct Response args;
959 struct string_s str;
960 int totalMatches;
961 struct NameValueParserData data;
963 ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
964 char * ObjectID = GetValueFromNameValueList(&data, "ObjectID");
965 char * Filter = GetValueFromNameValueList(&data, "Filter");
966 char * BrowseFlag = GetValueFromNameValueList(&data, "BrowseFlag");
967 char * SortCriteria = GetValueFromNameValueList(&data, "SortCriteria");
968 char * orderBy = NULL;
969 int RequestedCount = 0;
970 int StartingIndex = 0;
971 if( (ptr = GetValueFromNameValueList(&data, "RequestedCount")) )
972 RequestedCount = atoi(ptr);
973 if( !RequestedCount )
974 RequestedCount = -1;
975 if( (ptr = GetValueFromNameValueList(&data, "StartingIndex")) )
976 StartingIndex = atoi(ptr);
977 if( !BrowseFlag || (strcmp(BrowseFlag, "BrowseDirectChildren") && strcmp(BrowseFlag, "BrowseMetadata")) )
979 SoapError(h, 402, "Invalid Args");
980 goto browse_error;
982 if( !ObjectID && !(ObjectID = GetValueFromNameValueList(&data, "ContainerID")) )
984 SoapError(h, 701, "No such object error");
985 goto browse_error;
987 memset(&args, 0, sizeof(args));
988 memset(&str, 0, sizeof(str));
990 str.data = malloc(DEFAULT_RESP_SIZE);
991 str.size = DEFAULT_RESP_SIZE;
992 str.off = sprintf(str.data, "%s", resp0);
993 /* See if we need to include DLNA namespace reference */
994 args.iface = h->iface;
995 args.filter = set_filter_flags(Filter, h);
996 if( args.filter & FILTER_DLNA_NAMESPACE )
998 ret = strcatf(&str, DLNA_NAMESPACE);
1000 strcatf(&str, "&gt;\n");
1002 args.returned = 0;
1003 args.requested = RequestedCount;
1004 args.client = h->req_client;
1005 args.flags = h->reqflags;
1006 args.str = &str;
1007 if( args.flags & FLAG_MS_PFS )
1009 if( !strchr(ObjectID, '$') && (strcmp(ObjectID, "0") != 0) )
1011 ptr = sql_get_text_field(db, "SELECT OBJECT_ID from OBJECTS"
1012 " where OBJECT_ID in "
1013 "('"MUSIC_ID"$%s', '"VIDEO_ID"$%s', '"IMAGE_ID"$%s')",
1014 ObjectID, ObjectID, ObjectID);
1015 if( ptr )
1017 ObjectID = ptr;
1018 args.flags |= FLAG_FREE_OBJECT_ID;
1022 DPRINTF(E_DEBUG, L_HTTP, "Browsing ContentDirectory:\n"
1023 " * ObjectID: %s\n"
1024 " * Count: %d\n"
1025 " * StartingIndex: %d\n"
1026 " * BrowseFlag: %s\n"
1027 " * Filter: %s\n"
1028 " * SortCriteria: %s\n",
1029 ObjectID, RequestedCount, StartingIndex,
1030 BrowseFlag, Filter, SortCriteria);
1032 if( (args.flags & FLAG_AUDIO_ONLY) && (strcmp(ObjectID, "0") == 0) )
1034 ObjectID = sqlite3_mprintf("%s", MUSIC_ID);
1035 args.flags |= FLAG_FREE_OBJECT_ID;
1038 if( strcmp(BrowseFlag+6, "Metadata") == 0 )
1040 args.requested = 1;
1041 sql = sqlite3_mprintf( SELECT_COLUMNS
1042 "from OBJECTS o left join DETAILS d on (d.ID = o.DETAIL_ID)"
1043 " where OBJECT_ID = '%s';"
1044 , ObjectID);
1045 ret = sqlite3_exec(db, sql, callback, (void *) &args, &zErrMsg);
1046 totalMatches = args.returned;
1048 else
1050 ret = sql_get_int_field(db, "SELECT count(*) from OBJECTS where PARENT_ID = '%s'", ObjectID);
1051 totalMatches = (ret > 0) ? ret : 0;
1052 ret = 0;
1053 if( SortCriteria )
1055 #ifdef __sparc__ /* Sorting takes too long on slow processors with very large containers */
1056 if( totalMatches < 10000 )
1057 #endif
1058 orderBy = parse_sort_criteria(SortCriteria, &ret);
1060 else
1062 if( strncmp(ObjectID, MUSIC_PLIST_ID, strlen(MUSIC_PLIST_ID)) == 0 )
1064 if( strcmp(ObjectID, MUSIC_PLIST_ID) == 0 )
1065 asprintf(&orderBy, "order by d.TITLE");
1066 else
1067 asprintf(&orderBy, "order by length(OBJECT_ID), OBJECT_ID");
1069 else if( args.client == ERokuSoundBridge )
1071 #ifdef __sparc__
1072 if( totalMatches < 10000 )
1073 #endif
1074 asprintf(&orderBy, "order by o.CLASS, d.DISC, d.TRACK, d.TITLE");
1077 /* If it's a DLNA client, return an error for bad sort criteria */
1078 if( (args.flags & FLAG_DLNA) && ret )
1080 SoapError(h, 709, "Unsupported or invalid sort criteria");
1081 goto browse_error;
1084 sql = sqlite3_mprintf( SELECT_COLUMNS
1085 "from OBJECTS o left join DETAILS d on (d.ID = o.DETAIL_ID)"
1086 " where PARENT_ID = '%s' %s limit %d, %d;",
1087 ObjectID, orderBy, StartingIndex, RequestedCount);
1088 DPRINTF(E_DEBUG, L_HTTP, "Browse SQL: %s\n", sql);
1089 ret = sqlite3_exec(db, sql, callback, (void *) &args, &zErrMsg);
1091 sqlite3_free(sql);
1092 if( (ret != SQLITE_OK) && (zErrMsg != NULL) )
1094 DPRINTF(E_WARN, L_HTTP, "SQL error: %s\nBAD SQL: %s\n", zErrMsg, sql);
1095 sqlite3_free(zErrMsg);
1097 /* Does the object even exist? */
1098 if( !totalMatches )
1100 ret = sql_get_int_field(db, "SELECT count(*) from OBJECTS where OBJECT_ID = '%s'", ObjectID);
1101 if( ret <= 0 )
1103 SoapError(h, 701, "No such object error");
1104 goto browse_error;
1107 ret = strcatf(&str, "&lt;/DIDL-Lite&gt;</Result>\n"
1108 "<NumberReturned>%u</NumberReturned>\n"
1109 "<TotalMatches>%u</TotalMatches>\n"
1110 "<UpdateID>%u</UpdateID>"
1111 "</u:BrowseResponse>",
1112 args.returned, totalMatches, updateID);
1113 BuildSendAndCloseSoapResp(h, str.data, str.off);
1114 browse_error:
1115 ClearNameValueList(&data);
1116 if( args.flags & FLAG_FREE_OBJECT_ID )
1117 sqlite3_free(ObjectID);
1118 free(orderBy);
1119 free(str.data);
1122 static void
1123 SearchContentDirectory(struct upnphttp * h, const char * action)
1125 static const char resp0[] =
1126 "<u:SearchResponse "
1127 "xmlns:u=\"urn:schemas-upnp-org:service:ContentDirectory:1\">"
1128 "<Result>"
1129 "&lt;DIDL-Lite"
1130 CONTENT_DIRECTORY_SCHEMAS;
1131 char *zErrMsg = 0;
1132 char *sql, *ptr;
1133 char **result;
1134 struct Response args;
1135 struct string_s str;
1136 int totalMatches = 0;
1137 int ret;
1139 struct NameValueParserData data;
1140 ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
1141 char * ContainerID = GetValueFromNameValueList(&data, "ContainerID");
1142 char * Filter = GetValueFromNameValueList(&data, "Filter");
1143 char * SearchCriteria = GetValueFromNameValueList(&data, "SearchCriteria");
1144 char * SortCriteria = GetValueFromNameValueList(&data, "SortCriteria");
1145 char * newSearchCriteria = NULL;
1146 char * orderBy = NULL;
1147 char groupBy[] = "group by DETAIL_ID";
1148 int RequestedCount = 0;
1149 int StartingIndex = 0;
1150 if( (ptr = GetValueFromNameValueList(&data, "RequestedCount")) )
1151 RequestedCount = atoi(ptr);
1152 if( !RequestedCount )
1153 RequestedCount = -1;
1154 if( (ptr = GetValueFromNameValueList(&data, "StartingIndex")) )
1155 StartingIndex = atoi(ptr);
1156 if( !ContainerID )
1158 if( !(ContainerID = GetValueFromNameValueList(&data, "ObjectID")) )
1160 SoapError(h, 701, "No such object error");
1161 goto search_error;
1164 memset(&args, 0, sizeof(args));
1165 memset(&str, 0, sizeof(str));
1167 str.data = malloc(DEFAULT_RESP_SIZE);
1168 str.size = DEFAULT_RESP_SIZE;
1169 str.off = sprintf(str.data, "%s", resp0);
1170 /* See if we need to include DLNA namespace reference */
1171 args.iface = h->iface;
1172 args.filter = set_filter_flags(Filter, h);
1173 if( args.filter & FILTER_DLNA_NAMESPACE )
1175 ret = strcatf(&str, DLNA_NAMESPACE);
1177 strcatf(&str, "&gt;\n");
1179 args.returned = 0;
1180 args.requested = RequestedCount;
1181 args.client = h->req_client;
1182 args.flags = h->reqflags;
1183 args.str = &str;
1184 if( args.flags & FLAG_MS_PFS )
1186 if( !strchr(ContainerID, '$') && (strcmp(ContainerID, "0") != 0) )
1188 ptr = sql_get_text_field(db, "SELECT OBJECT_ID from OBJECTS"
1189 " where OBJECT_ID in "
1190 "('"MUSIC_ID"$%s', '"VIDEO_ID"$%s', '"IMAGE_ID"$%s')",
1191 ContainerID, ContainerID, ContainerID);
1192 if( ptr )
1194 ContainerID = ptr;
1195 args.flags |= FLAG_FREE_OBJECT_ID;
1198 #if 0 // Looks like the 360 already does this
1199 /* Sort by track number for some containers */
1200 if( orderBy &&
1201 ((strncmp(ContainerID, MUSIC_GENRE_ID, 3) == 0) ||
1202 (strncmp(ContainerID, MUSIC_ARTIST_ID, 3) == 0) ||
1203 (strncmp(ContainerID, MUSIC_ALBUM_ID, 3) == 0)) )
1205 DPRINTF(E_DEBUG, L_HTTP, "Old sort order: %s\n", orderBy);
1206 sprintf(str_buf, "d.TRACK, ");
1207 memmove(orderBy+18, orderBy+9, strlen(orderBy)+1);
1208 memmove(orderBy+9, &str_buf, 9);
1209 DPRINTF(E_DEBUG, L_HTTP, "New sort order: %s\n", orderBy);
1211 #endif
1213 DPRINTF(E_DEBUG, L_HTTP, "Searching ContentDirectory:\n"
1214 " * ObjectID: %s\n"
1215 " * Count: %d\n"
1216 " * StartingIndex: %d\n"
1217 " * SearchCriteria: %s\n"
1218 " * Filter: %s\n"
1219 " * SortCriteria: %s\n",
1220 ContainerID, RequestedCount, StartingIndex,
1221 SearchCriteria, Filter, SortCriteria);
1223 if( strcmp(ContainerID, "0") == 0 )
1224 *ContainerID = '*';
1225 else if( strcmp(ContainerID, MUSIC_ALL_ID) == 0 )
1226 groupBy[0] = '\0';
1227 if( !SearchCriteria )
1229 newSearchCriteria = strdup("1 = 1");
1230 SearchCriteria = newSearchCriteria;
1232 else
1234 SearchCriteria = modifyString(SearchCriteria, "&quot;", "\"", 0);
1235 SearchCriteria = modifyString(SearchCriteria, "&apos;", "'", 0);
1236 SearchCriteria = modifyString(SearchCriteria, "\\\"", "\"\"", 0);
1237 SearchCriteria = modifyString(SearchCriteria, "object.", "", 0);
1238 SearchCriteria = modifyString(SearchCriteria, "derivedfrom", "like", 1);
1239 SearchCriteria = modifyString(SearchCriteria, "contains", "like", 2);
1240 SearchCriteria = modifyString(SearchCriteria, "dc:title", "d.TITLE", 0);
1241 SearchCriteria = modifyString(SearchCriteria, "dc:creator", "d.CREATOR", 0);
1242 SearchCriteria = modifyString(SearchCriteria, "upnp:class", "o.CLASS", 0);
1243 SearchCriteria = modifyString(SearchCriteria, "upnp:actor", "d.ARTIST", 0);
1244 SearchCriteria = modifyString(SearchCriteria, "upnp:artist", "d.ARTIST", 0);
1245 SearchCriteria = modifyString(SearchCriteria, "upnp:album", "d.ALBUM", 0);
1246 SearchCriteria = modifyString(SearchCriteria, "upnp:genre", "d.GENRE", 0);
1247 SearchCriteria = modifyString(SearchCriteria, "exists true", "is not NULL", 0);
1248 SearchCriteria = modifyString(SearchCriteria, "exists false", "is NULL", 0);
1249 SearchCriteria = modifyString(SearchCriteria, "@refID", "REF_ID", 0);
1250 if( strstr(SearchCriteria, "@id") )
1252 newSearchCriteria = strdup(SearchCriteria);
1253 SearchCriteria = newSearchCriteria = modifyString(newSearchCriteria, "@id", "OBJECT_ID", 0);
1255 if( strstr(SearchCriteria, "res is ") )
1257 if( !newSearchCriteria )
1258 newSearchCriteria = strdup(SearchCriteria);
1259 SearchCriteria = newSearchCriteria = modifyString(newSearchCriteria, "res is ", "MIME is ", 0);
1261 #if 0 // Does 360 need this?
1262 if( strstr(SearchCriteria, "&amp;") )
1264 if( newSearchCriteria )
1265 newSearchCriteria = modifyString(newSearchCriteria, "&amp;", "&amp;amp;", 0);
1266 else
1267 newSearchCriteria = modifyString(strdup(SearchCriteria), "&amp;", "&amp;amp;", 0);
1268 SearchCriteria = newSearchCriteria;
1270 #endif
1272 DPRINTF(E_DEBUG, L_HTTP, "Translated SearchCriteria: %s\n", SearchCriteria);
1274 sql = sqlite3_mprintf("SELECT (select count(distinct DETAIL_ID)"
1275 " from OBJECTS o left join DETAILS d on (o.DETAIL_ID = d.ID)"
1276 " where (OBJECT_ID glob '%s$*') and (%s))"
1277 " + "
1278 "(select count(*) from OBJECTS o left join DETAILS d on (o.DETAIL_ID = d.ID)"
1279 " where (OBJECT_ID = '%s') and (%s))",
1280 ContainerID, SearchCriteria, ContainerID, SearchCriteria);
1281 //DEBUG DPRINTF(E_DEBUG, L_HTTP, "Count SQL: %s\n", sql);
1282 ret = sql_get_table(db, sql, &result, NULL, NULL);
1283 sqlite3_free(sql);
1284 if( ret == SQLITE_OK )
1286 totalMatches = atoi(result[1]);
1287 sqlite3_free_table(result);
1289 else
1291 /* Must be invalid SQL, so most likely bad or unhandled search criteria. */
1292 SoapError(h, 708, "Unsupported or invalid search criteria");
1293 goto search_error;
1295 /* Does the object even exist? */
1296 if( !totalMatches )
1298 ret = sql_get_int_field(db, "SELECT count(*) from OBJECTS where OBJECT_ID = '%q'",
1299 !strcmp(ContainerID, "*")?"0":ContainerID);
1300 if( ret <= 0 )
1302 SoapError(h, 710, "No such container");
1303 goto search_error;
1306 #ifdef __sparc__ /* Sorting takes too long on slow processors with very large containers */
1307 ret = 0;
1308 if( totalMatches < 10000 )
1309 #endif
1310 orderBy = parse_sort_criteria(SortCriteria, &ret);
1311 /* If it's a DLNA client, return an error for bad sort criteria */
1312 if( (args.flags & FLAG_DLNA) && ret )
1314 SoapError(h, 709, "Unsupported or invalid sort criteria");
1315 goto search_error;
1318 sql = sqlite3_mprintf( SELECT_COLUMNS
1319 "from OBJECTS o left join DETAILS d on (d.ID = o.DETAIL_ID)"
1320 " where OBJECT_ID glob '%s$*' and (%s) %s "
1321 "%z %s"
1322 " limit %d, %d",
1323 ContainerID, SearchCriteria, groupBy,
1324 (*ContainerID == '*') ? NULL :
1325 sqlite3_mprintf("UNION ALL " SELECT_COLUMNS
1326 "from OBJECTS o left join DETAILS d on (d.ID = o.DETAIL_ID)"
1327 " where OBJECT_ID = '%s' and (%s) ", ContainerID, SearchCriteria),
1328 orderBy, StartingIndex, RequestedCount);
1329 DPRINTF(E_DEBUG, L_HTTP, "Search SQL: %s\n", sql);
1330 ret = sqlite3_exec(db, sql, callback, (void *) &args, &zErrMsg);
1331 if( (ret != SQLITE_OK) && (zErrMsg != NULL) )
1333 DPRINTF(E_WARN, L_HTTP, "SQL error: %s\nBAD SQL: %s\n", zErrMsg, sql);
1334 sqlite3_free(zErrMsg);
1336 sqlite3_free(sql);
1337 ret = strcatf(&str, "&lt;/DIDL-Lite&gt;</Result>\n"
1338 "<NumberReturned>%u</NumberReturned>\n"
1339 "<TotalMatches>%u</TotalMatches>\n"
1340 "<UpdateID>%u</UpdateID>"
1341 "</u:SearchResponse>",
1342 args.returned, totalMatches, updateID);
1343 BuildSendAndCloseSoapResp(h, str.data, str.off);
1344 search_error:
1345 ClearNameValueList(&data);
1346 if( args.flags & FLAG_FREE_OBJECT_ID )
1347 sqlite3_free(ContainerID);
1348 free(orderBy);
1349 free(newSearchCriteria);
1350 free(str.data);
1354 If a control point calls QueryStateVariable on a state variable that is not
1355 buffered in memory within (or otherwise available from) the service,
1356 the service must return a SOAP fault with an errorCode of 404 Invalid Var.
1358 QueryStateVariable remains useful as a limited test tool but may not be
1359 part of some future versions of UPnP.
1361 static void
1362 QueryStateVariable(struct upnphttp * h, const char * action)
1364 static const char resp[] =
1365 "<u:%sResponse "
1366 "xmlns:u=\"%s\">"
1367 "<return>%s</return>"
1368 "</u:%sResponse>";
1370 char body[512];
1371 int bodylen;
1372 struct NameValueParserData data;
1373 const char * var_name;
1375 ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
1376 /*var_name = GetValueFromNameValueList(&data, "QueryStateVariable"); */
1377 /*var_name = GetValueFromNameValueListIgnoreNS(&data, "varName");*/
1378 var_name = GetValueFromNameValueList(&data, "varName");
1380 DPRINTF(E_INFO, L_HTTP, "QueryStateVariable(%.40s)\n", var_name);
1382 if(!var_name)
1384 SoapError(h, 402, "Invalid Args");
1386 else if(strcmp(var_name, "ConnectionStatus") == 0)
1388 bodylen = snprintf(body, sizeof(body), resp,
1389 action, "urn:schemas-upnp-org:control-1-0",
1390 "Connected", action);
1391 BuildSendAndCloseSoapResp(h, body, bodylen);
1393 else
1395 DPRINTF(E_WARN, L_HTTP, "%s: Unknown: %s\n", action, var_name?var_name:"");
1396 SoapError(h, 404, "Invalid Var");
1399 ClearNameValueList(&data);
1402 static void
1403 SamsungGetFeatureList(struct upnphttp * h, const char * action)
1405 static const char resp[] =
1406 "<u:X_GetFeatureListResponse xmlns:u=\"urn:schemas-upnp-org:service:ContentDirectory:1\">"
1407 "<FeatureList>"
1408 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
1409 "&lt;Features xmlns=\"urn:schemas-upnp-org:av:avs\""
1410 " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
1411 " xsi:schemaLocation=\"urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd\"&gt;"
1412 "&lt;Feature name=\"samsung.com_BASICVIEW\" version=\"1\"&gt;"
1413 "&lt;container id=\"1\" type=\"object.item.audioItem\"/&gt;"
1414 "&lt;container id=\"2\" type=\"object.item.videoItem\"/&gt;"
1415 "&lt;container id=\"3\" type=\"object.item.imageItem\"/&gt;"
1416 "&lt;/Feature&gt;"
1417 "</FeatureList></u:X_GetFeatureListResponse>";
1419 BuildSendAndCloseSoapResp(h, resp, sizeof(resp));
1422 static const struct
1424 const char * methodName;
1425 void (*methodImpl)(struct upnphttp *, const char *);
1427 soapMethods[] =
1429 { "QueryStateVariable", QueryStateVariable},
1430 { "Browse", BrowseContentDirectory},
1431 { "Search", SearchContentDirectory},
1432 { "GetSearchCapabilities", GetSearchCapabilities},
1433 { "GetSortCapabilities", GetSortCapabilities},
1434 { "GetSystemUpdateID", GetSystemUpdateID},
1435 { "GetProtocolInfo", GetProtocolInfo},
1436 { "GetCurrentConnectionIDs", GetCurrentConnectionIDs},
1437 { "GetCurrentConnectionInfo", GetCurrentConnectionInfo},
1438 { "IsAuthorized", IsAuthorizedValidated},
1439 { "IsValidated", IsAuthorizedValidated},
1440 { "X_GetFeatureList", SamsungGetFeatureList},
1441 { 0, 0 }
1444 void
1445 ExecuteSoapAction(struct upnphttp * h, const char * action, int n)
1447 char * p;
1449 p = strchr(action, '#');
1450 if(p)
1452 int i = 0;
1453 int len;
1454 int methodlen;
1455 char * p2;
1456 p++;
1457 p2 = strchr(p, '"');
1458 if(p2)
1459 methodlen = p2 - p;
1460 else
1461 methodlen = n - (p - action);
1462 DPRINTF(E_DEBUG, L_HTTP, "SoapMethod: %.*s\n", methodlen, p);
1463 while(soapMethods[i].methodName)
1465 len = strlen(soapMethods[i].methodName);
1466 if(strncmp(p, soapMethods[i].methodName, len) == 0)
1468 soapMethods[i].methodImpl(h, soapMethods[i].methodName);
1469 return;
1471 i++;
1474 DPRINTF(E_WARN, L_HTTP, "SoapMethod: Unknown: %.*s\n", methodlen, p);
1477 SoapError(h, 401, "Invalid Action");
1480 /* Standard Errors:
1482 * errorCode errorDescription Description
1483 * -------- ---------------- -----------
1484 * 401 Invalid Action No action by that name at this service.
1485 * 402 Invalid Args Could be any of the following: not enough in args,
1486 * too many in args, no in arg by that name,
1487 * one or more in args are of the wrong data type.
1488 * 403 Out of Sync Out of synchronization.
1489 * 501 Action Failed May be returned in current state of service
1490 * prevents invoking that action.
1491 * 600-699 TBD Common action errors. Defined by UPnP Forum
1492 * Technical Committee.
1493 * 700-799 TBD Action-specific errors for standard actions.
1494 * Defined by UPnP Forum working committee.
1495 * 800-899 TBD Action-specific errors for non-standard actions.
1496 * Defined by UPnP vendor.
1498 void
1499 SoapError(struct upnphttp * h, int errCode, const char * errDesc)
1501 static const char resp[] =
1502 "<s:Envelope "
1503 "xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
1504 "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
1505 "<s:Body>"
1506 "<s:Fault>"
1507 "<faultcode>s:Client</faultcode>"
1508 "<faultstring>UPnPError</faultstring>"
1509 "<detail>"
1510 "<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">"
1511 "<errorCode>%d</errorCode>"
1512 "<errorDescription>%s</errorDescription>"
1513 "</UPnPError>"
1514 "</detail>"
1515 "</s:Fault>"
1516 "</s:Body>"
1517 "</s:Envelope>";
1519 char body[2048];
1520 int bodylen;
1522 DPRINTF(E_WARN, L_HTTP, "Returning UPnPError %d: %s\n", errCode, errDesc);
1523 bodylen = snprintf(body, sizeof(body), resp, errCode, errDesc);
1524 BuildResp2_upnphttp(h, 500, "Internal Server Error", body, bodylen);
1525 SendResp_upnphttp(h);
1526 CloseSocket_upnphttp(h);