Merge branch 'minidlna' into tomato-ND-USBmod
[tomato.git] / release / src / router / minidlna / upnphttp.c
blobc7b527e4a0f3d5bff88e664df37e4276943cd2d1
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 <stdlib.h>
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <sys/types.h>
54 #include <sys/socket.h>
55 #include <sys/param.h>
56 #include <ctype.h>
57 #include "config.h"
58 #include "upnphttp.h"
59 #include "upnpdescgen.h"
60 #include "minidlnapath.h"
61 #include "upnpsoap.h"
62 #include "upnpevents.h"
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <fcntl.h>
67 #include <errno.h>
68 #include <sys/sendfile.h>
69 #include <arpa/inet.h>
71 #include "upnpglobalvars.h"
72 #include "utils.h"
73 #include "getifaddr.h"
74 #include "image_utils.h"
75 #include "log.h"
76 #include "sql.h"
77 #include <libexif/exif-loader.h>
78 #ifdef TIVO_SUPPORT
79 #include "tivo_utils.h"
80 #include "tivo_commands.h"
81 #endif
82 #define MAX_BUFFER_SIZE 4194304 // 4MB -- Too much?
83 //#define MAX_BUFFER_SIZE 2147483647 // 2GB -- Too much?
84 #define MIN_BUFFER_SIZE 65536
86 #include "icons.c"
88 struct upnphttp *
89 New_upnphttp(int s)
91 struct upnphttp * ret;
92 if(s<0)
93 return NULL;
94 ret = (struct upnphttp *)malloc(sizeof(struct upnphttp));
95 if(ret == NULL)
96 return NULL;
97 memset(ret, 0, sizeof(struct upnphttp));
98 ret->socket = s;
99 return ret;
102 void
103 CloseSocket_upnphttp(struct upnphttp * h)
105 if(close(h->socket) < 0)
107 DPRINTF(E_ERROR, L_HTTP, "CloseSocket_upnphttp: close(%d): %s\n", h->socket, strerror(errno));
109 h->socket = -1;
110 h->state = 100;
113 void
114 Delete_upnphttp(struct upnphttp * h)
116 if(h)
118 if(h->socket >= 0)
119 CloseSocket_upnphttp(h);
120 if(h->req_buf)
121 free(h->req_buf);
122 if(h->res_buf)
123 free(h->res_buf);
124 free(h);
129 SearchClientCache(struct in_addr addr)
131 int i;
132 for( i=0; i<CLIENT_CACHE_SLOTS; i++ )
134 if( clients[i].addr.s_addr == addr.s_addr )
136 /* Invalidate this client cache if it's older than 1 hour */
137 if( (time(NULL) - clients[i].age) > 3600 )
139 unsigned char mac[6];
140 if( get_remote_mac(addr, mac) == 0 &&
141 memcmp(mac, clients[i].mac, 6) == 0 )
143 /* Same MAC as last time when we were able to identify the client,
144 * so extend the timeout by another hour. */
145 clients[i].age = time(NULL);
147 else
149 memset(&clients[i], 0, sizeof(struct client_cache_s));
150 return -1;
153 DPRINTF(E_DEBUG, L_HTTP, "Client found in cache. [type %d/entry %d]\n", clients[i].type, i);
154 return i;
157 return -1;
160 /* parse HttpHeaders of the REQUEST */
161 static void
162 ParseHttpHeaders(struct upnphttp * h)
164 char * line;
165 char * colon;
166 char * p;
167 int n;
168 line = h->req_buf;
169 /* TODO : check if req_buf, contentoff are ok */
170 while(line < (h->req_buf + h->req_contentoff))
172 colon = strchr(line, ':');
173 if(colon)
175 if(strncasecmp(line, "Content-Length", 14)==0)
177 p = colon;
178 while(*p < '0' || *p > '9')
179 p++;
180 h->req_contentlen = atoi(p);
182 else if(strncasecmp(line, "SOAPAction", 10)==0)
184 p = colon;
185 n = 0;
186 while(*p == ':' || *p == ' ' || *p == '\t')
187 p++;
188 while(p[n]>=' ')
190 n++;
192 if((p[0] == '"' && p[n-1] == '"')
193 || (p[0] == '\'' && p[n-1] == '\''))
195 p++; n -= 2;
197 h->req_soapAction = p;
198 h->req_soapActionLen = n;
200 else if(strncasecmp(line, "Callback", 8)==0)
202 p = colon;
203 while(*p != '<' && *p != '\r' )
204 p++;
205 n = 0;
206 while(p[n] != '>' && p[n] != '\r' )
207 n++;
208 h->req_Callback = p + 1;
209 h->req_CallbackLen = MAX(0, n - 1);
211 else if(strncasecmp(line, "SID", 3)==0)
213 //zqiu: fix bug for test 4.0.5
214 //Skip extra headers like "SIDHEADER: xxxxxx xxx"
215 for(p=line+3;p<colon;p++)
217 if(!isspace(*p))
219 p = NULL; //unexpected header
220 break;
223 if(p) {
224 p = colon + 1;
225 while(isspace(*p))
226 p++;
227 n = 0;
228 while(!isspace(p[n]))
229 n++;
230 h->req_SID = p;
231 h->req_SIDLen = n;
234 /* Timeout: Seconds-nnnn */
235 /* TIMEOUT
236 Recommended. Requested duration until subscription expires,
237 either number of seconds or infinite. Recommendation
238 by a UPnP Forum working committee. Defined by UPnP vendor.
239 Consists of the keyword "Second-" followed (without an
240 intervening space) by either an integer or the keyword "infinite". */
241 else if(strncasecmp(line, "Timeout", 7)==0)
243 p = colon + 1;
244 while(isspace(*p))
245 p++;
246 if(strncasecmp(p, "Second-", 7)==0) {
247 h->req_Timeout = atoi(p+7);
250 // Range: bytes=xxx-yyy
251 else if(strncasecmp(line, "Range", 5)==0)
253 p = colon + 1;
254 while(isspace(*p))
255 p++;
256 if(strncasecmp(p, "bytes=", 6)==0) {
257 h->reqflags |= FLAG_RANGE;
258 h->req_RangeEnd = atoll(index(p+6, '-')+1);
259 h->req_RangeStart = atoll(p+6);
260 DPRINTF(E_DEBUG, L_HTTP, "Range Start-End: %lld - %lld\n",
261 h->req_RangeStart, h->req_RangeEnd?h->req_RangeEnd:-1);
264 else if(strncasecmp(line, "Host", 4)==0)
266 h->reqflags |= FLAG_HOST;
268 else if(strncasecmp(line, "User-Agent", 10)==0)
270 /* Skip client detection if we already detected it. */
271 if( h->req_client )
272 goto next_header;
273 p = colon + 1;
274 while(isspace(*p))
275 p++;
276 if(strncasecmp(p, "Xbox/", 5)==0)
278 h->req_client = EXbox;
279 h->reqflags |= FLAG_MIME_AVI_AVI;
280 h->reqflags |= FLAG_MS_PFS;
282 else if(strncmp(p, "PLAYSTATION", 11)==0)
284 h->req_client = EPS3;
285 h->reqflags |= FLAG_DLNA;
286 h->reqflags |= FLAG_MIME_AVI_DIVX;
288 else if(strncmp(p, "SamsungWiselinkPro", 18)==0 ||
289 strncmp(p, "SEC_HHP_", 8)==0)
291 h->req_client = ESamsungTV;
292 h->reqflags |= FLAG_DLNA;
293 h->reqflags |= FLAG_NO_RESIZE;
294 //h->reqflags |= FLAG_MIME_AVI_DIVX;
296 else if(strstrc(p, "bridgeCo-DMP/3", '\r'))
298 h->req_client = EDenonReceiver;
299 h->reqflags |= FLAG_DLNA;
301 else if(strstrc(p, "fbxupnpav/", '\r'))
303 h->req_client = EFreeBox;
305 else if(strncmp(p, "SMP8634", 7)==0)
307 h->req_client = EPopcornHour;
308 h->reqflags |= FLAG_MIME_FLAC_FLAC;
310 else if(strstrc(p, "Microsoft-IPTV-Client", '\r'))
312 h->req_client = EMediaRoom;
313 h->reqflags |= FLAG_MS_PFS;
315 else if(strstrc(p, "DLNADOC/1.50", '\r'))
317 h->req_client = EStandardDLNA150;
318 h->reqflags |= FLAG_DLNA;
319 h->reqflags |= FLAG_MIME_AVI_AVI;
322 else if(strncasecmp(line, "X-AV-Client-Info", 16)==0)
324 /* Skip client detection if we already detected it. */
325 if( h->req_client && h->req_client < EStandardDLNA150 )
326 goto next_header;
327 p = colon + 1;
328 while(isspace(*p))
329 p++;
330 if(strstrc(p, "PLAYSTATION 3", '\r'))
332 h->req_client = EPS3;
333 h->reqflags |= FLAG_DLNA;
334 h->reqflags |= FLAG_MIME_AVI_DIVX;
336 /* X-AV-Client-Info: av=5.0; cn="Sony Corporation"; mn="Blu-ray Disc Player"; mv="2.0" */
337 /* X-AV-Client-Info: av=5.0; cn="Sony Corporation"; mn="BLU-RAY HOME THEATRE SYSTEM"; mv="2.0"; */
338 /* Sony SMP-100 needs the same treatment as their BDP-S370 */
339 /* X-AV-Client-Info: av=5.0; cn="Sony Corporation"; mn="Media Player"; mv="2.0" */
340 else if(strstrc(p, "Blu-ray Disc Player", '\r') ||
341 strstrc(p, "BLU-RAY HOME THEATRE SYSTEM", '\r') ||
342 strstrc(p, "Media Player", '\r'))
344 h->req_client = ESonyBDP;
345 h->reqflags |= FLAG_DLNA;
348 else if(strncasecmp(line, "Transfer-Encoding", 17)==0)
350 p = colon + 1;
351 while(isspace(*p))
352 p++;
353 if(strncasecmp(p, "chunked", 7)==0)
355 h->reqflags |= FLAG_CHUNKED;
358 else if(strncasecmp(line, "getcontentFeatures.dlna.org", 27)==0)
360 p = colon + 1;
361 while(isspace(*p))
362 p++;
363 if( (*p != '1') || !isspace(p[1]) )
364 h->reqflags |= FLAG_INVALID_REQ;
366 else if(strncasecmp(line, "TimeSeekRange.dlna.org", 22)==0)
368 h->reqflags |= FLAG_TIMESEEK;
370 else if(strncasecmp(line, "PlaySpeed.dlna.org", 18)==0)
372 h->reqflags |= FLAG_PLAYSPEED;
374 else if(strncasecmp(line, "realTimeInfo.dlna.org", 21)==0)
376 h->reqflags |= FLAG_REALTIMEINFO;
378 else if(strncasecmp(line, "transferMode.dlna.org", 21)==0)
380 p = colon + 1;
381 while(isspace(*p))
382 p++;
383 if(strncasecmp(p, "Streaming", 9)==0)
385 h->reqflags |= FLAG_XFERSTREAMING;
387 if(strncasecmp(p, "Interactive", 11)==0)
389 h->reqflags |= FLAG_XFERINTERACTIVE;
391 if(strncasecmp(p, "Background", 10)==0)
393 h->reqflags |= FLAG_XFERBACKGROUND;
396 else if(strncasecmp(line, "getCaptionInfo.sec", 18)==0)
398 h->reqflags |= FLAG_CAPTION;
401 next_header:
402 while(!(line[0] == '\r' && line[1] == '\n'))
403 line++;
404 line += 2;
406 if( h->reqflags & FLAG_CHUNKED )
408 char *endptr;
409 h->req_chunklen = -1;
410 if( h->req_buflen <= h->req_contentoff )
411 return;
412 while( (line < (h->req_buf + h->req_buflen)) &&
413 (h->req_chunklen = strtol(line, &endptr, 16)) &&
414 (endptr != line) )
416 while(!(endptr[0] == '\r' && endptr[1] == '\n'))
418 endptr++;
420 line = endptr+h->req_chunklen+2;
423 if( endptr == line )
425 h->req_chunklen = -1;
426 return;
429 /* If the client type wasn't found, search the cache.
430 * This is done because a lot of clients like to send a
431 * different User-Agent with different types of requests. */
432 n = SearchClientCache(h->clientaddr);
433 if( h->req_client )
435 /* Add this client to the cache if it's not there already. */
436 if( n < 0 )
438 for( n=0; n<CLIENT_CACHE_SLOTS; n++ )
440 if( clients[n].addr.s_addr )
441 continue;
442 get_remote_mac(h->clientaddr, clients[n].mac);
443 clients[n].addr = h->clientaddr;
444 DPRINTF(E_DEBUG, L_HTTP, "Added client [%d/%s/%02X:%02X:%02X:%02X:%02X:%02X] to cache slot %d.\n",
445 h->req_client, inet_ntoa(clients[n].addr),
446 clients[n].mac[0], clients[n].mac[1], clients[n].mac[2],
447 clients[n].mac[3], clients[n].mac[4], clients[n].mac[5], n);
448 break;
451 else if( (n < EStandardDLNA150) && (h->req_client == EStandardDLNA150) )
453 /* If we know the client and our new detection is generic, use our cached info */
454 h->reqflags |= clients[n].flags;
455 h->req_client = clients[n].type;
456 return;
458 clients[n].type = h->req_client;
459 clients[n].flags = h->reqflags & 0xFFF00000;
460 clients[n].age = time(NULL);
462 else if( n >= 0 )
464 h->reqflags |= clients[n].flags;
465 h->req_client = clients[n].type;
469 /* very minimalistic 400 error message */
470 static void
471 Send400(struct upnphttp * h)
473 static const char body400[] =
474 "<HTML><HEAD><TITLE>400 Bad Request</TITLE></HEAD>"
475 "<BODY><H1>Bad Request</H1>The request is invalid"
476 " for this HTTP version.</BODY></HTML>\r\n";
477 h->respflags = FLAG_HTML;
478 BuildResp2_upnphttp(h, 400, "Bad Request",
479 body400, sizeof(body400) - 1);
480 SendResp_upnphttp(h);
481 CloseSocket_upnphttp(h);
484 /* very minimalistic 404 error message */
485 static void
486 Send404(struct upnphttp * h)
488 static const char body404[] =
489 "<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD>"
490 "<BODY><H1>Not Found</H1>The requested URL was not found"
491 " on this server.</BODY></HTML>\r\n";
492 h->respflags = FLAG_HTML;
493 BuildResp2_upnphttp(h, 404, "Not Found",
494 body404, sizeof(body404) - 1);
495 SendResp_upnphttp(h);
496 CloseSocket_upnphttp(h);
499 /* very minimalistic 406 error message */
500 static void
501 Send406(struct upnphttp * h)
503 static const char body406[] =
504 "<HTML><HEAD><TITLE>406 Not Acceptable</TITLE></HEAD>"
505 "<BODY><H1>Not Acceptable</H1>An unsupported operation"
506 " was requested.</BODY></HTML>\r\n";
507 h->respflags = FLAG_HTML;
508 BuildResp2_upnphttp(h, 406, "Not Acceptable",
509 body406, sizeof(body406) - 1);
510 SendResp_upnphttp(h);
511 CloseSocket_upnphttp(h);
514 /* very minimalistic 416 error message */
515 static void
516 Send416(struct upnphttp * h)
518 static const char body416[] =
519 "<HTML><HEAD><TITLE>416 Requested Range Not Satisfiable</TITLE></HEAD>"
520 "<BODY><H1>Requested Range Not Satisfiable</H1>The requested range"
521 " was outside the file's size.</BODY></HTML>\r\n";
522 h->respflags = FLAG_HTML;
523 BuildResp2_upnphttp(h, 416, "Requested Range Not Satisfiable",
524 body416, sizeof(body416) - 1);
525 SendResp_upnphttp(h);
526 CloseSocket_upnphttp(h);
529 /* very minimalistic 500 error message */
530 static void
531 Send500(struct upnphttp * h)
533 static const char body500[] =
534 "<HTML><HEAD><TITLE>500 Internal Server Error</TITLE></HEAD>"
535 "<BODY><H1>Internal Server Error</H1>Server encountered "
536 "and Internal Error.</BODY></HTML>\r\n";
537 h->respflags = FLAG_HTML;
538 BuildResp2_upnphttp(h, 500, "Internal Server Errror",
539 body500, sizeof(body500) - 1);
540 SendResp_upnphttp(h);
541 CloseSocket_upnphttp(h);
544 /* very minimalistic 501 error message */
545 void
546 Send501(struct upnphttp * h)
548 static const char body501[] =
549 "<HTML><HEAD><TITLE>501 Not Implemented</TITLE></HEAD>"
550 "<BODY><H1>Not Implemented</H1>The HTTP Method "
551 "is not implemented by this server.</BODY></HTML>\r\n";
552 h->respflags = FLAG_HTML;
553 BuildResp2_upnphttp(h, 501, "Not Implemented",
554 body501, sizeof(body501) - 1);
555 SendResp_upnphttp(h);
556 CloseSocket_upnphttp(h);
559 static const char *
560 findendheaders(const char * s, int len)
562 while(len-->0)
564 if(s[0]=='\r' && s[1]=='\n' && s[2]=='\r' && s[3]=='\n')
565 return s;
566 s++;
568 return NULL;
571 /* Sends the description generated by the parameter */
572 static void
573 sendXMLdesc(struct upnphttp * h, char * (f)(int *))
575 char * desc;
576 int len;
577 desc = f(&len);
578 if(!desc)
580 DPRINTF(E_ERROR, L_HTTP, "Failed to generate XML description\n");
581 Send500(h);
582 free(desc);
583 return;
585 else
587 BuildResp_upnphttp(h, desc, len);
589 SendResp_upnphttp(h);
590 CloseSocket_upnphttp(h);
591 free(desc);
594 /* ProcessHTTPPOST_upnphttp()
595 * executes the SOAP query if it is possible */
596 static void
597 ProcessHTTPPOST_upnphttp(struct upnphttp * h)
599 if((h->req_buflen - h->req_contentoff) >= h->req_contentlen)
601 if(h->req_soapAction)
603 /* we can process the request */
604 DPRINTF(E_DEBUG, L_HTTP, "SOAPAction: %.*s\n", h->req_soapActionLen, h->req_soapAction);
605 ExecuteSoapAction(h,
606 h->req_soapAction,
607 h->req_soapActionLen);
609 else
611 static const char err400str[] =
612 "<html><body>Bad request</body></html>";
613 DPRINTF(E_WARN, L_HTTP, "No SOAPAction in HTTP headers");
614 h->respflags = FLAG_HTML;
615 BuildResp2_upnphttp(h, 400, "Bad Request",
616 err400str, sizeof(err400str) - 1);
617 SendResp_upnphttp(h);
618 CloseSocket_upnphttp(h);
621 else
623 /* waiting for remaining data */
624 h->state = 1;
628 static void
629 ProcessHTTPSubscribe_upnphttp(struct upnphttp * h, const char * path)
631 const char * sid;
632 DPRINTF(E_DEBUG, L_HTTP, "ProcessHTTPSubscribe %s\n", path);
633 DPRINTF(E_DEBUG, L_HTTP, "Callback '%.*s' Timeout=%d\n",
634 h->req_CallbackLen, h->req_Callback, h->req_Timeout);
635 DPRINTF(E_DEBUG, L_HTTP, "SID '%.*s'\n", h->req_SIDLen, h->req_SID);
636 if(!h->req_Callback && !h->req_SID) {
637 /* Missing or invalid CALLBACK : 412 Precondition Failed.
638 * If CALLBACK header is missing or does not contain a valid HTTP URL,
639 * the publisher must respond with HTTP error 412 Precondition Failed*/
640 BuildResp2_upnphttp(h, 412, "Precondition Failed", 0, 0);
641 SendResp_upnphttp(h);
642 CloseSocket_upnphttp(h);
643 } else {
644 /* - add to the subscriber list
645 * - respond HTTP/x.x 200 OK
646 * - Send the initial event message */
647 /* Server:, SID:; Timeout: Second-(xx|infinite) */
648 if(h->req_Callback) {
649 sid = upnpevents_addSubscriber(path, h->req_Callback,
650 h->req_CallbackLen, h->req_Timeout);
651 h->respflags = FLAG_TIMEOUT;
652 if(sid) {
653 DPRINTF(E_DEBUG, L_HTTP, "generated sid=%s\n", sid);
654 h->respflags |= FLAG_SID;
655 h->req_SID = sid;
656 h->req_SIDLen = strlen(sid);
658 BuildResp_upnphttp(h, 0, 0);
659 } else {
660 /* subscription renew */
661 /* Invalid SID
662 412 Precondition Failed. If a SID does not correspond to a known,
663 un-expired subscription, the publisher must respond
664 with HTTP error 412 Precondition Failed. */
665 if(renewSubscription(h->req_SID, h->req_SIDLen, h->req_Timeout) < 0) {
666 BuildResp2_upnphttp(h, 412, "Precondition Failed", 0, 0);
667 } else {
668 /* A DLNA device must enforce a 5 minute timeout */
669 h->respflags = FLAG_TIMEOUT;
670 h->req_Timeout = 300;
671 h->respflags |= FLAG_SID;
672 BuildResp_upnphttp(h, 0, 0);
675 SendResp_upnphttp(h);
676 CloseSocket_upnphttp(h);
680 static void
681 ProcessHTTPUnSubscribe_upnphttp(struct upnphttp * h, const char * path)
683 DPRINTF(E_DEBUG, L_HTTP, "ProcessHTTPUnSubscribe %s\n", path);
684 DPRINTF(E_DEBUG, L_HTTP, "SID '%.*s'\n", h->req_SIDLen, h->req_SID);
685 /* Remove from the list */
686 if(upnpevents_removeSubscriber(h->req_SID, h->req_SIDLen) < 0) {
687 BuildResp2_upnphttp(h, 412, "Precondition Failed", 0, 0);
688 } else {
689 BuildResp_upnphttp(h, 0, 0);
691 SendResp_upnphttp(h);
692 CloseSocket_upnphttp(h);
695 /* Parse and process Http Query
696 * called once all the HTTP headers have been received. */
697 static void
698 ProcessHttpQuery_upnphttp(struct upnphttp * h)
700 char HttpCommand[16];
701 char HttpUrl[512];
702 char * HttpVer;
703 char * p;
704 int i;
705 p = h->req_buf;
706 if(!p)
707 return;
708 for(i = 0; i<15 && *p != ' ' && *p != '\r'; i++)
709 HttpCommand[i] = *(p++);
710 HttpCommand[i] = '\0';
711 while(*p==' ')
712 p++;
713 if(strncmp(p, "http://", 7) == 0)
715 p = p+7;
716 while(*p!='/')
717 p++;
719 for(i = 0; i<511 && *p != ' ' && *p != '\r'; i++)
720 HttpUrl[i] = *(p++);
721 HttpUrl[i] = '\0';
722 while(*p==' ')
723 p++;
724 HttpVer = h->HttpVer;
725 for(i = 0; i<15 && *p != '\r'; i++)
726 HttpVer[i] = *(p++);
727 HttpVer[i] = '\0';
728 /*DPRINTF(E_INFO, L_HTTP, "HTTP REQUEST : %s %s (%s)\n",
729 HttpCommand, HttpUrl, HttpVer);*/
730 ParseHttpHeaders(h);
732 /* see if we need to wait for remaining data */
733 if( (h->reqflags & FLAG_CHUNKED) )
735 if( h->req_chunklen )
737 h->state = 2;
738 return;
740 char *chunkstart, *chunk, *endptr, *endbuf;
741 chunk = endbuf = chunkstart = h->req_buf + h->req_contentoff;
743 while( (h->req_chunklen = strtol(chunk, &endptr, 16)) && (endptr != chunk) )
745 while(!(endptr[0] == '\r' && endptr[1] == '\n'))
747 endptr++;
749 endptr += 2;
751 memmove(endbuf, endptr, h->req_chunklen);
753 endbuf += h->req_chunklen;
754 chunk = endptr + h->req_chunklen;
756 h->req_contentlen = endbuf - chunkstart;
757 h->req_buflen = endbuf - h->req_buf;
758 h->state = 100;
761 DPRINTF(E_DEBUG, L_HTTP, "HTTP REQUEST: %.*s\n", h->req_buflen, h->req_buf);
762 if(strcmp("POST", HttpCommand) == 0)
764 h->req_command = EPost;
765 ProcessHTTPPOST_upnphttp(h);
767 else if((strcmp("GET", HttpCommand) == 0) || (strcmp("HEAD", HttpCommand) == 0))
769 if( ((strcmp(h->HttpVer, "HTTP/1.1")==0) && !(h->reqflags & FLAG_HOST)) || (h->reqflags & FLAG_INVALID_REQ) )
771 DPRINTF(E_WARN, L_HTTP, "Invalid request, responding ERROR 400. (No Host specified in HTTP headers?)\n");
772 Send400(h);
773 return;
775 #if 1 /* 7.3.33.4 */
776 else if( ((h->reqflags & FLAG_TIMESEEK) || (h->reqflags & FLAG_PLAYSPEED)) &&
777 !(h->reqflags & FLAG_RANGE) )
779 DPRINTF(E_WARN, L_HTTP, "DLNA %s requested, responding ERROR 406\n",
780 h->reqflags&FLAG_TIMESEEK ? "TimeSeek" : "PlaySpeed");
781 Send406(h);
782 return;
784 #endif
785 else if(strcmp("GET", HttpCommand) == 0)
787 h->req_command = EGet;
789 else
791 h->req_command = EHead;
793 if(strcmp(ROOTDESC_PATH, HttpUrl) == 0)
795 /* If it's a Xbox360, we might need a special friendly_name to be recognized */
796 if( (h->req_client == EXbox) && !strchr(friendly_name, ':') )
798 strncat(friendly_name, ": 1", FRIENDLYNAME_MAX_LEN-4);
799 sendXMLdesc(h, genRootDesc);
800 friendly_name[strlen(friendly_name)-3] = '\0';
802 else
804 sendXMLdesc(h, genRootDesc);
807 else if(strcmp(CONTENTDIRECTORY_PATH, HttpUrl) == 0)
809 sendXMLdesc(h, genContentDirectory);
811 else if(strcmp(CONNECTIONMGR_PATH, HttpUrl) == 0)
813 sendXMLdesc(h, genConnectionManager);
815 else if(strcmp(X_MS_MEDIARECEIVERREGISTRAR_PATH, HttpUrl) == 0)
817 sendXMLdesc(h, genX_MS_MediaReceiverRegistrar);
819 else if(strncmp(HttpUrl, "/MediaItems/", 12) == 0)
821 SendResp_dlnafile(h, HttpUrl+12);
822 CloseSocket_upnphttp(h);
824 else if(strncmp(HttpUrl, "/Thumbnails/", 12) == 0)
826 SendResp_thumbnail(h, HttpUrl+12);
828 else if(strncmp(HttpUrl, "/AlbumArt/", 10) == 0)
830 SendResp_albumArt(h, HttpUrl+10);
831 CloseSocket_upnphttp(h);
833 #ifdef TIVO_SUPPORT
834 else if(strncmp(HttpUrl, "/TiVoConnect", 12) == 0)
836 if( GETFLAG(TIVO_MASK) )
838 if( *(HttpUrl+12) == '?' )
840 ProcessTiVoCommand(h, HttpUrl+13);
842 else
844 printf("Invalid TiVo request! %s\n", HttpUrl+12);
845 Send404(h);
848 else
850 printf("TiVo request with out TiVo support enabled! %s\n", HttpUrl+12);
851 Send404(h);
854 #endif
855 else if(strncmp(HttpUrl, "/Resized/", 9) == 0)
857 SendResp_resizedimg(h, HttpUrl+9);
858 CloseSocket_upnphttp(h);
860 else if(strncmp(HttpUrl, "/icons/", 7) == 0)
862 SendResp_icon(h, HttpUrl+7);
863 CloseSocket_upnphttp(h);
865 else if(strncmp(HttpUrl, "/Captions/", 10) == 0)
867 SendResp_caption(h, HttpUrl+10);
868 CloseSocket_upnphttp(h);
870 else
872 DPRINTF(E_WARN, L_HTTP, "%s not found, responding ERROR 404\n", HttpUrl);
873 Send404(h);
876 else if(strcmp("SUBSCRIBE", HttpCommand) == 0)
878 h->req_command = ESubscribe;
879 ProcessHTTPSubscribe_upnphttp(h, HttpUrl);
881 else if(strcmp("UNSUBSCRIBE", HttpCommand) == 0)
883 h->req_command = EUnSubscribe;
884 ProcessHTTPUnSubscribe_upnphttp(h, HttpUrl);
886 else
888 DPRINTF(E_WARN, L_HTTP, "Unsupported HTTP Command %s\n", HttpCommand);
889 Send501(h);
894 void
895 Process_upnphttp(struct upnphttp * h)
897 char buf[2048];
898 int n;
899 if(!h)
900 return;
901 switch(h->state)
903 case 0:
904 n = recv(h->socket, buf, 2048, 0);
905 if(n<0)
907 DPRINTF(E_ERROR, L_HTTP, "recv (state0): %s\n", strerror(errno));
908 h->state = 100;
910 else if(n==0)
912 DPRINTF(E_WARN, L_HTTP, "HTTP Connection closed unexpectedly\n");
913 h->state = 100;
915 else
917 const char * endheaders;
918 /* if 1st arg of realloc() is null,
919 * realloc behaves the same as malloc() */
920 h->req_buf = (char *)realloc(h->req_buf, n + h->req_buflen + 1);
921 memcpy(h->req_buf + h->req_buflen, buf, n);
922 h->req_buflen += n;
923 h->req_buf[h->req_buflen] = '\0';
924 /* search for the string "\r\n\r\n" */
925 endheaders = findendheaders(h->req_buf, h->req_buflen);
926 if(endheaders)
928 h->req_contentoff = endheaders - h->req_buf + 4;
929 h->req_contentlen = h->req_buflen - h->req_contentoff;
930 ProcessHttpQuery_upnphttp(h);
933 break;
934 case 1:
935 case 2:
936 n = recv(h->socket, buf, 2048, 0);
937 if(n<0)
939 DPRINTF(E_ERROR, L_HTTP, "recv (state%d): %s\n", h->state, strerror(errno));
940 h->state = 100;
942 else if(n==0)
944 DPRINTF(E_WARN, L_HTTP, "HTTP Connection closed unexpectedly\n");
945 h->state = 100;
947 else
949 /*fwrite(buf, 1, n, stdout);*/ /* debug */
950 h->req_buf = (char *)realloc(h->req_buf, n + h->req_buflen);
951 memcpy(h->req_buf + h->req_buflen, buf, n);
952 h->req_buflen += n;
953 if((h->req_buflen - h->req_contentoff) >= h->req_contentlen)
955 /* Need the struct to point to the realloc'd memory locations */
956 if( h->state == 1 )
958 ParseHttpHeaders(h);
959 ProcessHTTPPOST_upnphttp(h);
961 else if( h->state == 2 )
963 ProcessHttpQuery_upnphttp(h);
967 break;
968 default:
969 DPRINTF(E_WARN, L_HTTP, "Unexpected state: %d\n", h->state);
973 static const char httpresphead[] =
974 "%s %d %s\r\n"
975 "Content-Type: %s\r\n"
976 "Connection: close\r\n"
977 "Content-Length: %d\r\n"
978 "Server: " MINIDLNA_SERVER_STRING "\r\n"
979 // "Accept-Ranges: bytes\r\n"
980 ; /*"\r\n";*/
982 "<?xml version=\"1.0\"?>\n"
983 "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
984 "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
985 "<s:Body>"
987 "</s:Body>"
988 "</s:Envelope>";
990 /* with response code and response message
991 * also allocate enough memory */
993 void
994 BuildHeader_upnphttp(struct upnphttp * h, int respcode,
995 const char * respmsg,
996 int bodylen)
998 int templen;
999 if(!h->res_buf)
1001 templen = sizeof(httpresphead) + 192 + bodylen;
1002 h->res_buf = (char *)malloc(templen);
1003 h->res_buf_alloclen = templen;
1005 h->res_buflen = snprintf(h->res_buf, h->res_buf_alloclen,
1006 //httpresphead, h->HttpVer,
1007 httpresphead, "HTTP/1.1",
1008 respcode, respmsg,
1009 (h->respflags&FLAG_HTML)?"text/html":"text/xml; charset=\"utf-8\"",
1010 bodylen);
1011 /* Additional headers */
1012 if(h->respflags & FLAG_TIMEOUT) {
1013 h->res_buflen += snprintf(h->res_buf + h->res_buflen,
1014 h->res_buf_alloclen - h->res_buflen,
1015 "Timeout: Second-");
1016 if(h->req_Timeout) {
1017 h->res_buflen += snprintf(h->res_buf + h->res_buflen,
1018 h->res_buf_alloclen - h->res_buflen,
1019 "%d\r\n", h->req_Timeout);
1020 } else {
1021 h->res_buflen += snprintf(h->res_buf + h->res_buflen,
1022 h->res_buf_alloclen - h->res_buflen,
1023 "300\r\n");
1024 //JM DLNA must force to 300 - "infinite\r\n");
1027 if(h->respflags & FLAG_SID) {
1028 h->res_buflen += snprintf(h->res_buf + h->res_buflen,
1029 h->res_buf_alloclen - h->res_buflen,
1030 "SID: %.*s\r\n", h->req_SIDLen, h->req_SID);
1032 #if 0 // DLNA
1033 char szTime[30];
1034 time_t curtime = time(NULL);
1035 strftime(szTime, 30,"%a, %d %b %Y %H:%M:%S GMT" , gmtime(&curtime));
1036 h->res_buflen += snprintf(h->res_buf + h->res_buflen,
1037 h->res_buf_alloclen - h->res_buflen,
1038 "Date: %s\r\n", szTime);
1039 h->res_buflen += snprintf(h->res_buf + h->res_buflen,
1040 h->res_buf_alloclen - h->res_buflen,
1041 "contentFeatures.dlna.org: \r\n");
1042 h->res_buflen += snprintf(h->res_buf + h->res_buflen,
1043 h->res_buf_alloclen - h->res_buflen,
1044 "EXT:\r\n");
1045 #endif
1046 h->res_buf[h->res_buflen++] = '\r';
1047 h->res_buf[h->res_buflen++] = '\n';
1048 if(h->res_buf_alloclen < (h->res_buflen + bodylen))
1050 h->res_buf = (char *)realloc(h->res_buf, (h->res_buflen + bodylen));
1051 h->res_buf_alloclen = h->res_buflen + bodylen;
1055 void
1056 BuildResp2_upnphttp(struct upnphttp * h, int respcode,
1057 const char * respmsg,
1058 const char * body, int bodylen)
1060 BuildHeader_upnphttp(h, respcode, respmsg, bodylen);
1061 if( h->req_command == EHead )
1062 return;
1063 if(body)
1064 memcpy(h->res_buf + h->res_buflen, body, bodylen);
1065 h->res_buflen += bodylen;
1068 /* responding 200 OK ! */
1069 void
1070 BuildResp_upnphttp(struct upnphttp * h,
1071 const char * body, int bodylen)
1073 BuildResp2_upnphttp(h, 200, "OK", body, bodylen);
1076 void
1077 SendResp_upnphttp(struct upnphttp * h)
1079 int n;
1080 DPRINTF(E_DEBUG, L_HTTP, "HTTP RESPONSE: %.*s\n", h->res_buflen, h->res_buf);
1081 n = send(h->socket, h->res_buf, h->res_buflen, 0);
1082 if(n<0)
1084 DPRINTF(E_ERROR, L_HTTP, "send(res_buf): %s\n", strerror(errno));
1086 else if(n < h->res_buflen)
1088 /* TODO : handle correctly this case */
1089 DPRINTF(E_ERROR, L_HTTP, "send(res_buf): %d bytes sent (out of %d)\n",
1090 n, h->res_buflen);
1095 send_data(struct upnphttp * h, char * header, size_t size, int flags)
1097 int n;
1099 n = send(h->socket, header, size, flags);
1100 if(n<0)
1102 DPRINTF(E_ERROR, L_HTTP, "send(res_buf): %s\n", strerror(errno));
1104 else if(n < h->res_buflen)
1106 /* TODO : handle correctly this case */
1107 DPRINTF(E_ERROR, L_HTTP, "send(res_buf): %d bytes sent (out of %d)\n",
1108 n, h->res_buflen);
1110 else
1112 return 0;
1114 return 1;
1117 void
1118 send_file(struct upnphttp * h, int sendfd, off_t offset, off_t end_offset)
1120 off_t send_size;
1121 off_t ret;
1122 char *buf = NULL;
1123 int try_sendfile = 1;
1125 while( offset < end_offset )
1127 if( try_sendfile )
1129 send_size = ( ((end_offset - offset) < MAX_BUFFER_SIZE) ? (end_offset - offset + 1) : MAX_BUFFER_SIZE);
1130 ret = sendfile(h->socket, sendfd, &offset, send_size);
1131 if( ret == -1 )
1133 DPRINTF(E_DEBUG, L_HTTP, "sendfile error :: error no. %d [%s]\n", errno, strerror(errno));
1134 /* If sendfile isn't supported on the filesystem, don't bother trying to use it again. */
1135 if( errno == EOVERFLOW )
1136 try_sendfile = 0;
1137 else if( errno != EAGAIN )
1138 break;
1140 else
1142 //DPRINTF(E_DEBUG, L_HTTP, "sent %lld bytes to %d. offset is now %lld.\n", ret, h->socket, offset);
1143 continue;
1146 /* Fall back to regular I/O */
1147 if( !buf )
1148 buf = malloc(MIN_BUFFER_SIZE);
1149 send_size = ( ((end_offset - offset) < MIN_BUFFER_SIZE) ? (end_offset - offset + 1) : MIN_BUFFER_SIZE);
1150 lseek(sendfd, offset, SEEK_SET);
1151 ret = read(sendfd, buf, send_size);
1152 if( ret == -1 ) {
1153 DPRINTF(E_DEBUG, L_HTTP, "read error :: error no. %d [%s]\n", errno, strerror(errno));
1154 if( errno != EAGAIN )
1155 break;
1157 ret = write(h->socket, buf, ret);
1158 if( ret == -1 ) {
1159 DPRINTF(E_DEBUG, L_HTTP, "write error :: error no. %d [%s]\n", errno, strerror(errno));
1160 if( errno != EAGAIN )
1161 break;
1163 offset+=ret;
1165 if( buf )
1166 free(buf);
1169 void
1170 SendResp_icon(struct upnphttp * h, char * icon)
1172 char * header;
1173 char * data;
1174 int size, ret;
1175 char mime[12];
1176 char date[30];
1177 time_t curtime = time(NULL);
1179 if( strcmp(icon, "sm.png") == 0 )
1181 DPRINTF(E_DEBUG, L_HTTP, "Sending small PNG icon\n");
1182 data = (char *)png_sm;
1183 size = sizeof(png_sm)-1;
1184 strcpy(mime, "image/png");
1186 else if( strcmp(icon, "lrg.png") == 0 )
1188 DPRINTF(E_DEBUG, L_HTTP, "Sending large PNG icon\n");
1189 data = (char *)png_lrg;
1190 size = sizeof(png_lrg)-1;
1191 strcpy(mime, "image/png");
1193 else if( strcmp(icon, "sm.jpg") == 0 )
1195 DPRINTF(E_DEBUG, L_HTTP, "Sending small JPEG icon\n");
1196 data = (char *)jpeg_sm;
1197 size = sizeof(jpeg_sm)-1;
1198 strcpy(mime, "image/jpeg");
1200 else if( strcmp(icon, "lrg.jpg") == 0 )
1202 DPRINTF(E_DEBUG, L_HTTP, "Sending large JPEG icon\n");
1203 data = (char *)jpeg_lrg;
1204 size = sizeof(jpeg_lrg)-1;
1205 strcpy(mime, "image/jpeg");
1207 else
1209 DPRINTF(E_WARN, L_HTTP, "Invalid icon request: %s\n", icon);
1210 Send404(h);
1211 return;
1215 strftime(date, 30,"%a, %d %b %Y %H:%M:%S GMT" , gmtime(&curtime));
1216 ret = asprintf(&header, "HTTP/1.1 200 OK\r\n"
1217 "Content-Type: %s\r\n"
1218 "Content-Length: %d\r\n"
1219 "Connection: close\r\n"
1220 "Date: %s\r\n"
1221 "Server: " MINIDLNA_SERVER_STRING "\r\n\r\n",
1222 mime, size, date);
1224 if( (send_data(h, header, ret, MSG_MORE) == 0) && (h->req_command != EHead) )
1226 send_data(h, data, size, 0);
1228 free(header);
1231 void
1232 SendResp_albumArt(struct upnphttp * h, char * object)
1234 char header[1500];
1235 char sql_buf[256];
1236 char **result;
1237 int rows = 0;
1238 char *path;
1239 char *dash;
1240 char date[30];
1241 time_t curtime = time(NULL);
1242 off_t offset = 0, size;
1243 int sendfh;
1245 memset(header, 0, 1500);
1247 if( h->reqflags & FLAG_XFERSTREAMING || h->reqflags & FLAG_RANGE )
1249 DPRINTF(E_WARN, L_HTTP, "Client tried to specify transferMode as Streaming with an image!\n");
1250 Send406(h);
1251 return;
1254 dash = strchr(object, '-');
1255 if( dash )
1256 *dash = '\0';
1257 sprintf(sql_buf, "SELECT PATH from ALBUM_ART where ID = %s", object);
1258 sql_get_table(db, sql_buf, &result, &rows, NULL);
1259 if( !rows )
1261 DPRINTF(E_WARN, L_HTTP, "ALBUM_ART ID %s not found, responding ERROR 404\n", object);
1262 Send404(h);
1263 goto error;
1265 path = result[1];
1266 DPRINTF(E_INFO, L_HTTP, "Serving album art ID: %s [%s]\n", object, path);
1268 if( access(path, F_OK) == 0 )
1270 strftime(date, 30,"%a, %d %b %Y %H:%M:%S GMT" , gmtime(&curtime));
1272 sendfh = open(path, O_RDONLY);
1273 if( sendfh < 0 ) {
1274 DPRINTF(E_ERROR, L_HTTP, "Error opening %s\n", path);
1275 goto error;
1277 size = lseek(sendfh, 0, SEEK_END);
1278 lseek(sendfh, 0, SEEK_SET);
1280 sprintf(header, "HTTP/1.1 200 OK\r\n"
1281 "Content-Type: image/jpeg\r\n"
1282 "Content-Length: %jd\r\n"
1283 "Connection: close\r\n"
1284 "Date: %s\r\n"
1285 "EXT:\r\n"
1286 "realTimeInfo.dlna.org: DLNA.ORG_TLAG=*\r\n"
1287 "contentFeatures.dlna.org: DLNA.ORG_PN=JPEG_TN\r\n"
1288 "Server: " MINIDLNA_SERVER_STRING "\r\n",
1289 size, date);
1291 if( h->reqflags & FLAG_XFERBACKGROUND )
1293 strcat(header, "transferMode.dlna.org: Background\r\n\r\n");
1295 else //if( h->reqflags & FLAG_XFERINTERACTIVE )
1297 strcat(header, "transferMode.dlna.org: Interactive\r\n\r\n");
1301 if( (send_data(h, header, strlen(header), MSG_MORE) == 0) && (h->req_command != EHead) && (sendfh > 0) )
1303 send_file(h, sendfh, offset, size);
1305 close(sendfh);
1307 error:
1308 sqlite3_free_table(result);
1311 void
1312 SendResp_caption(struct upnphttp * h, char * object)
1314 char header[1500];
1315 char sql_buf[256];
1316 char **result;
1317 int rows = 0;
1318 char *path;
1319 char date[30];
1320 time_t curtime = time(NULL);
1321 off_t offset = 0, size;
1322 int sendfh, ret;
1324 memset(header, 0, 1500);
1326 strip_ext(object);
1327 sprintf(sql_buf, "SELECT PATH from CAPTIONS where ID = %s", object);
1328 sql_get_table(db, sql_buf, &result, &rows, NULL);
1329 if( !rows )
1331 DPRINTF(E_WARN, L_HTTP, "CAPTION ID %s not found, responding ERROR 404\n", object);
1332 Send404(h);
1333 goto error;
1335 path = result[1];
1336 DPRINTF(E_INFO, L_HTTP, "Serving caption ID: %s [%s]\n", object, path);
1338 if( access(path, F_OK) != 0 )
1339 goto error;
1341 strftime(date, 30,"%a, %d %b %Y %H:%M:%S GMT" , gmtime(&curtime));
1342 sendfh = open(path, O_RDONLY);
1343 if( sendfh < 0 ) {
1344 DPRINTF(E_ERROR, L_HTTP, "Error opening %s\n", path);
1345 goto error;
1347 size = lseek(sendfh, 0, SEEK_END);
1348 lseek(sendfh, 0, SEEK_SET);
1350 ret = snprintf(header, sizeof(header), "HTTP/1.1 200 OK\r\n"
1351 "Content-Type: smi/caption\r\n"
1352 "Content-Length: %jd\r\n"
1353 "Connection: close\r\n"
1354 "Date: %s\r\n"
1355 "EXT:\r\n"
1356 "Server: " MINIDLNA_SERVER_STRING "\r\n\r\n",
1357 size, date);
1359 if( (send_data(h, header, ret, MSG_MORE) == 0) && (h->req_command != EHead) && (sendfh > 0) )
1361 send_file(h, sendfh, offset, size);
1363 close(sendfh);
1365 error:
1366 sqlite3_free_table(result);
1369 void
1370 SendResp_thumbnail(struct upnphttp * h, char * object)
1372 char header[1500];
1373 char sql_buf[256];
1374 char **result;
1375 int rows = 0;
1376 char *path;
1377 char date[30];
1378 time_t curtime = time(NULL);
1379 ExifData *ed;
1380 ExifLoader *l;
1382 memset(header, 0, 1500);
1384 if( h->reqflags & FLAG_XFERSTREAMING || h->reqflags & FLAG_RANGE )
1386 DPRINTF(E_WARN, L_HTTP, "Client tried to specify transferMode as Streaming with an image!\n");
1387 Send406(h);
1388 return;
1391 strip_ext(object);
1392 sprintf(sql_buf, "SELECT PATH from DETAILS where ID = '%s'", object);
1393 sql_get_table(db, sql_buf, &result, &rows, NULL);
1394 if( !rows )
1396 DPRINTF(E_WARN, L_HTTP, "%s not found, responding ERROR 404\n", object);
1397 Send404(h);
1398 goto error;
1400 path = result[1];
1401 DPRINTF(E_INFO, L_HTTP, "Serving thumbnail for ObjectId: %s [%s]\n", object, path);
1403 if( access(path, F_OK) == 0 )
1405 strftime(date, 30,"%a, %d %b %Y %H:%M:%S GMT" , gmtime(&curtime));
1407 l = exif_loader_new();
1408 exif_loader_write_file(l, path);
1409 ed = exif_loader_get_data(l);
1410 exif_loader_unref(l);
1412 if( !ed || !ed->size )
1414 Send404(h);
1415 if( ed )
1416 exif_data_unref(ed);
1417 goto error;
1419 sprintf(header, "HTTP/1.1 200 OK\r\n"
1420 "Content-Type: image/jpeg\r\n"
1421 "Content-Length: %d\r\n"
1422 "Connection: close\r\n"
1423 "Date: %s\r\n"
1424 "EXT:\r\n"
1425 "realTimeInfo.dlna.org: DLNA.ORG_TLAG=*\r\n"
1426 "contentFeatures.dlna.org: DLNA.ORG_PN=JPEG_TN\r\n"
1427 "Server: " MINIDLNA_SERVER_STRING "\r\n",
1428 ed->size, date);
1430 if( h->reqflags & FLAG_XFERBACKGROUND )
1432 strcat(header, "transferMode.dlna.org: Background\r\n\r\n");
1434 else //if( h->reqflags & FLAG_XFERINTERACTIVE )
1436 strcat(header, "transferMode.dlna.org: Interactive\r\n\r\n");
1439 if( (send_data(h, header, strlen(header), MSG_MORE) == 0) && (h->req_command != EHead) )
1441 send_data(h, (char *)ed->data, ed->size, 0);
1443 exif_data_unref(ed);
1445 CloseSocket_upnphttp(h);
1446 error:
1447 sqlite3_free_table(result);
1450 void
1451 SendResp_resizedimg(struct upnphttp * h, char * object)
1453 char header[1500];
1454 char str_buf[256];
1455 char **result;
1456 char date[30];
1457 char dlna_pn[4];
1458 time_t curtime = time(NULL);
1459 int width=640, height=480, dstw, dsth, rotation, size;
1460 long srcw, srch;
1461 unsigned char * data = NULL;
1462 char *path, *file_path;
1463 char *resolution, *tn;
1464 char *key, *val;
1465 char *saveptr=NULL, *item=NULL;
1466 char *pixelshape=NULL;
1467 sqlite_int64 id;
1468 int rows=0, chunked=0, ret;
1469 #ifdef __sparc__
1470 ExifData *ed;
1471 ExifLoader *l;
1472 #endif
1473 image *imsrc = NULL, *imdst = NULL;
1474 int scale = 1;
1476 id = strtoll(object, NULL, 10);
1477 sprintf(str_buf, "SELECT PATH, RESOLUTION, THUMBNAIL from DETAILS where ID = '%lld'", id);
1478 ret = sql_get_table(db, str_buf, &result, &rows, NULL);
1479 if( (ret != SQLITE_OK) )
1481 DPRINTF(E_ERROR, L_HTTP, "Didn't find valid file for %lld!\n", id);
1482 Send500(h);
1483 return;
1485 if( !rows || (access(result[3], F_OK) != 0) )
1487 DPRINTF(E_WARN, L_HTTP, "%s not found, responding ERROR 404\n", object);
1488 sqlite3_free_table(result);
1489 Send404(h);
1490 return;
1492 #if USE_FORK
1493 pid_t newpid = 0;
1494 newpid = fork();
1495 if( newpid )
1496 goto resized_error;
1497 #endif
1498 file_path = result[3];
1499 resolution = result[4];
1500 tn = result[5];
1501 srcw = strtol(resolution, &saveptr, 10);
1502 srch = strtol(saveptr+1, NULL, 10);
1504 path = strdup(object);
1505 if( strtok_r(path, "?", &saveptr) )
1507 item = strtok_r(NULL, "&,", &saveptr);
1509 while( item != NULL )
1511 #ifdef TIVO_SUPPORT
1512 decodeString(item, 1);
1513 #endif
1514 val = item;
1515 key = strsep(&val, "=");
1516 DPRINTF(E_DEBUG, L_GENERAL, "%s: %s\n", key, val);
1517 if( strcasecmp(key, "width") == 0 )
1519 width = atoi(val);
1521 else if( strcasecmp(key, "height") == 0 )
1523 height = atoi(val);
1525 else if( strcasecmp(key, "rotation") == 0 )
1527 rotation = atoi(val);
1529 else if( strcasecmp(key, "pixelshape") == 0 )
1531 pixelshape = val;
1533 item = strtok_r(NULL, "&,", &saveptr);
1535 free(path);
1537 if( h->reqflags & FLAG_XFERSTREAMING || h->reqflags & FLAG_RANGE )
1539 DPRINTF(E_WARN, L_HTTP, "Client tried to specify transferMode as Streaming with a resized image!\n");
1540 Send406(h);
1541 goto resized_error;
1544 DPRINTF(E_INFO, L_HTTP, "Serving resized image for ObjectId: %lld [%s]\n", id, file_path);
1546 /* Figure out the best destination resolution we can use */
1547 dstw = width;
1548 dsth = ((((width<<10)/srcw)*srch)>>10);
1549 if( dsth > height )
1551 dsth = height;
1552 dstw = (((height<<10)/srch) * srcw>>10);
1555 if( dstw <= 640 && dsth <= 480 )
1556 strcpy(dlna_pn, "SM");
1557 else if( dstw <= 1024 && dsth <= 768 )
1558 strcpy(dlna_pn, "MED");
1559 else
1560 strcpy(dlna_pn, "LRG");
1562 if( srcw>>3 >= dstw && srch>>3 >= dsth)
1563 scale = 8;
1564 else if( srcw>>2 >= dstw && srch>>2 >= dsth )
1565 scale = 4;
1566 else if( srcw>>1 >= dstw && srch>>1 >= dsth )
1567 scale = 2;
1569 strftime(date, 30,"%a, %d %b %Y %H:%M:%S GMT" , gmtime(&curtime));
1570 snprintf(header, sizeof(header)-100, "HTTP/1.1 200 OK\r\n"
1571 "Content-Type: image/jpeg\r\n"
1572 "Connection: close\r\n"
1573 "Date: %s\r\n"
1574 "EXT:\r\n"
1575 "realTimeInfo.dlna.org: DLNA.ORG_TLAG=*\r\n"
1576 "contentFeatures.dlna.org: DLNA.ORG_PN=JPEG_%s;DLNA.ORG_CI=1\r\n"
1577 "Server: " MINIDLNA_SERVER_STRING "\r\n",
1578 date, dlna_pn);
1579 if( h->reqflags & FLAG_XFERINTERACTIVE )
1581 strcat(header, "transferMode.dlna.org: Interactive\r\n");
1583 else if( h->reqflags & FLAG_XFERBACKGROUND )
1585 strcat(header, "transferMode.dlna.org: Background\r\n");
1588 /* Resizing from a thumbnail is much faster than from a large image */
1589 #ifdef __sparc__
1590 if( dstw <= 160 && dsth <= 120 && atoi(tn) )
1592 l = exif_loader_new();
1593 exif_loader_write_file(l, file_path);
1594 ed = exif_loader_get_data(l);
1595 exif_loader_unref(l);
1597 if( !ed || !ed->size )
1599 if( ed )
1600 exif_data_unref(ed);
1601 DPRINTF(E_WARN, L_HTTP, "Unable to access image thumbnail!\n");
1602 Send500(h);
1603 goto resized_error;
1605 imsrc = image_new_from_jpeg(NULL, 0, (char *)ed->data, ed->size, 1);
1606 exif_data_unref(ed);
1608 else
1609 #endif
1610 if( strcmp(h->HttpVer, "HTTP/1.0") == 0 )
1612 imsrc = image_new_from_jpeg(file_path, 1, NULL, 0, scale);
1614 else
1616 chunked = 1;
1617 strcat(header, "Transfer-Encoding: chunked\r\n\r\n");
1620 if( !chunked )
1622 if( !imsrc )
1624 DPRINTF(E_WARN, L_HTTP, "Unable to open image %s!\n", file_path);
1625 Send500(h);
1626 goto resized_error;
1629 imdst = image_resize(imsrc, dstw, dsth);
1630 data = image_save_to_jpeg_buf(imdst, &size);
1632 sprintf(str_buf, "Content-Length: %d\r\n\r\n", size);
1633 strcat(header, str_buf);
1636 if( (send_data(h, header, strlen(header), 0) == 0) && (h->req_command != EHead) )
1638 if( chunked )
1640 imsrc = image_new_from_jpeg(file_path, 1, NULL, 0, scale);
1641 if( !imsrc )
1643 DPRINTF(E_WARN, L_HTTP, "Unable to open image %s!\n", file_path);
1644 Send500(h);
1645 goto resized_error;
1647 imdst = image_resize(imsrc, dstw, dsth);
1648 data = image_save_to_jpeg_buf(imdst, &size);
1650 ret = sprintf(str_buf, "%x\r\n", size);
1651 send_data(h, str_buf, ret, MSG_MORE);
1652 send_data(h, (char *)data, size, MSG_MORE);
1653 send_data(h, "\r\n0\r\n\r\n", 7, 0);
1655 else
1657 send_data(h, (char *)data, size, 0);
1660 DPRINTF(E_INFO, L_HTTP, "Done serving %s\n", file_path);
1661 if( imsrc )
1662 image_free(imsrc);
1663 if( imdst )
1664 image_free(imdst);
1665 resized_error:
1666 sqlite3_free_table(result);
1667 #if USE_FORK
1668 if( !newpid )
1669 _exit(0);
1670 #endif
1673 void
1674 SendResp_dlnafile(struct upnphttp * h, char * object)
1676 char header[1500];
1677 char hdr_buf[512];
1678 char sql_buf[256];
1679 char **result;
1680 int rows, ret;
1681 char date[30];
1682 time_t curtime = time(NULL);
1683 off_t total, offset, size;
1684 sqlite_int64 id;
1685 int sendfh;
1686 static struct { sqlite_int64 id; char path[PATH_MAX]; char mime[32]; char dlna[64]; } last_file = { 0 };
1687 #if USE_FORK
1688 pid_t newpid = 0;
1689 #endif
1691 id = strtoll(object, NULL, 10);
1692 if( id != last_file.id )
1694 sprintf(sql_buf, "SELECT PATH, MIME, DLNA_PN from DETAILS where ID = '%lld'", id);
1695 ret = sql_get_table(db, sql_buf, &result, &rows, NULL);
1696 if( (ret != SQLITE_OK) )
1698 DPRINTF(E_ERROR, L_HTTP, "Didn't find valid file for %lld!\n", id);
1699 Send500(h);
1700 return;
1702 if( !rows )
1704 DPRINTF(E_WARN, L_HTTP, "%s not found, responding ERROR 404\n", object);
1705 sqlite3_free_table(result);
1706 Send404(h);
1707 return;
1709 /* Cache the result */
1710 last_file.id = id;
1711 strncpy(last_file.path, result[3], sizeof(last_file.path)-1);
1712 if( result[4] )
1714 strncpy(last_file.mime, result[4], sizeof(last_file.mime)-1);
1715 /* From what I read, Samsung TV's expect a [wrong] MIME type of x-mkv. */
1716 if( h->req_client == ESamsungTV )
1718 if( strcmp(last_file.mime+6, "x-matroska") == 0 )
1719 strcpy(last_file.mime+8, "mkv");
1721 /* ... and Sony BDP-S370 won't play MKV unless we pretend it's a DiVX file */
1722 else if( h->req_client == ESonyBDP )
1724 if( strcmp(last_file.mime+6, "x-matroska") == 0 ||
1725 strcmp(last_file.mime+6, "mpeg") == 0 )
1726 strcpy(last_file.mime+6, "divx");
1729 else
1731 last_file.mime[0] = '\0';
1733 if( result[5] )
1734 snprintf(last_file.dlna, sizeof(last_file.dlna), "DLNA.ORG_PN=%s", result[5]);
1735 else if( h->reqflags & FLAG_DLNA )
1736 strcpy(last_file.dlna, dlna_no_conv);
1737 else
1738 last_file.dlna[0] = '\0';
1739 sqlite3_free_table(result);
1741 #if USE_FORK
1742 newpid = fork();
1743 if( newpid )
1744 return;
1745 #endif
1747 DPRINTF(E_INFO, L_HTTP, "Serving DetailID: %lld [%s]\n", id, last_file.path);
1749 if( h->reqflags & FLAG_XFERSTREAMING )
1751 if( strncmp(last_file.mime, "image", 5) == 0 )
1753 DPRINTF(E_WARN, L_HTTP, "Client tried to specify transferMode as Streaming with an image!\n");
1754 Send406(h);
1755 goto error;
1758 else if( h->reqflags & FLAG_XFERINTERACTIVE )
1760 if( h->reqflags & FLAG_REALTIMEINFO )
1762 DPRINTF(E_WARN, L_HTTP, "Bad realTimeInfo flag with Interactive request!\n");
1763 Send400(h);
1764 goto error;
1766 if( strncmp(last_file.mime, "image", 5) != 0 )
1768 DPRINTF(E_WARN, L_HTTP, "Client tried to specify transferMode as Interactive without an image!\n");
1769 /* Samsung TVs (well, at least the A950) do this for some reason,
1770 * and I don't see them fixing this bug any time soon. */
1771 if( h->req_client != ESamsungTV || GETFLAG(DLNA_STRICT_MASK) )
1773 Send406(h);
1774 goto error;
1779 strftime(date, 30,"%a, %d %b %Y %H:%M:%S GMT" , gmtime(&curtime));
1780 offset = h->req_RangeStart;
1781 sendfh = open(last_file.path, O_RDONLY);
1782 if( sendfh < 0 ) {
1783 DPRINTF(E_ERROR, L_HTTP, "Error opening %s\n", last_file.path);
1784 goto error;
1786 size = lseek(sendfh, 0, SEEK_END);
1787 lseek(sendfh, 0, SEEK_SET);
1789 sprintf(header, "HTTP/1.1 20%c OK\r\n"
1790 "Content-Type: %s\r\n", (h->reqflags & FLAG_RANGE ? '6' : '0'), last_file.mime);
1791 if( h->reqflags & FLAG_RANGE )
1793 if( !h->req_RangeEnd )
1794 h->req_RangeEnd = size;
1795 if( (h->req_RangeStart > h->req_RangeEnd) || (h->req_RangeStart < 0) )
1797 DPRINTF(E_WARN, L_HTTP, "Specified range was invalid!\n");
1798 Send400(h);
1799 close(sendfh);
1800 goto error;
1802 if( h->req_RangeEnd > size )
1804 DPRINTF(E_WARN, L_HTTP, "Specified range was outside file boundaries!\n");
1805 Send416(h);
1806 close(sendfh);
1807 goto error;
1810 if( h->req_RangeEnd < size )
1812 total = h->req_RangeEnd - h->req_RangeStart + 1;
1813 sprintf(hdr_buf, "Content-Length: %jd\r\n"
1814 "Content-Range: bytes %jd-%jd/%jd\r\n",
1815 total, h->req_RangeStart, h->req_RangeEnd, size);
1817 else
1819 h->req_RangeEnd = size;
1820 total = size - h->req_RangeStart;
1821 sprintf(hdr_buf, "Content-Length: %jd\r\n"
1822 "Content-Range: bytes %jd-%jd/%jd\r\n",
1823 total, h->req_RangeStart, size-1, size);
1826 else
1828 h->req_RangeEnd = size;
1829 total = size;
1830 sprintf(hdr_buf, "Content-Length: %jd\r\n", total);
1832 strcat(header, hdr_buf);
1834 if( h->reqflags & FLAG_XFERSTREAMING )
1836 strcat(header, "transferMode.dlna.org: Streaming\r\n");
1838 else if( h->reqflags & FLAG_XFERBACKGROUND )
1840 if( strncmp(last_file.mime, "image", 5) == 0 )
1841 strcat(header, "transferMode.dlna.org: Background\r\n");
1843 else //if( h->reqflags & FLAG_XFERINTERACTIVE )
1845 if( (strncmp(last_file.mime, "video", 5) == 0) ||
1846 (strncmp(last_file.mime, "audio", 5) == 0) )
1848 strcat(header, "transferMode.dlna.org: Streaming\r\n");
1850 else
1852 strcat(header, "transferMode.dlna.org: Interactive\r\n");
1856 if( h->reqflags & FLAG_CAPTION )
1858 if( sql_get_int_field(db, "SELECT ID from CAPTIONS where ID = '%lld'", id) > 0 )
1860 sprintf(hdr_buf, "CaptionInfo.sec: http://%s:%d/Captions/%lld.srt\r\n",
1861 lan_addr[0].str, runtime_vars.port, id);
1862 strcat(header, hdr_buf);
1866 sprintf(hdr_buf, "Accept-Ranges: bytes\r\n"
1867 "Connection: close\r\n"
1868 "Date: %s\r\n"
1869 "EXT:\r\n"
1870 "realTimeInfo.dlna.org: DLNA.ORG_TLAG=*\r\n"
1871 "contentFeatures.dlna.org: %s\r\n"
1872 "Server: " MINIDLNA_SERVER_STRING "\r\n\r\n",
1873 date, last_file.dlna);
1874 strcat(header, hdr_buf);
1876 if( (send_data(h, header, strlen(header), MSG_MORE) == 0) && (h->req_command != EHead) && (sendfh > 0) )
1878 send_file(h, sendfh, offset, h->req_RangeEnd);
1880 close(sendfh);
1882 error:
1883 #if USE_FORK
1884 if( !newpid )
1885 _exit(0);
1886 #endif
1887 return;