-
-
Save hugsy/c2dbc3e3c11836dcebf53a2189f35976 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- original.c 2017-01-17 17:17:43.805314775 -0800 | |
+++ websrv.c 2017-01-17 16:50:16.189912144 -0800 | |
@@ -103,6 +103,40 @@ | |
return 200; | |
} | |
+static void* get_range_header(char* req, size_t reqlen) | |
+{ | |
+ const char *s = "\r\nRange: bytes="; | |
+ return memmem(req, reqlen, s, strlen(s)); | |
+} | |
+ | |
+static int get_ranges_from_header(char *request, unsigned long *start , unsigned long *end) | |
+{ | |
+ char *req = request+strlen("\r\nRange: bytes="); | |
+ char *c, _c; | |
+ char *tmp; | |
+ | |
+ for(c=req; *c!='\r' && *c!='\n' && *c!='-' && *c!=' ' && *c!='\0'; c++); | |
+ if (*c!='-') | |
+ return -1; | |
+ | |
+ // get beginning of range | |
+ _c = *c; | |
+ *c = '\0'; | |
+ tmp = strdupa(req); | |
+ *start = strtoul(tmp, NULL, 10); | |
+ *c = _c; | |
+ | |
+ // get end of range | |
+ req = ++c; | |
+ for(c=req; *c!='\r' && *c!='\n' && *c!=' ' && *c!='\0'; c++); | |
+ _c = *c; | |
+ *c = '\0'; | |
+ tmp = strdupa(req); | |
+ *end = strtoul(tmp, NULL, 10); | |
+ *c = _c; | |
+ return 0; | |
+} | |
+ | |
int handle_req(int socket, char* request, size_t len) | |
{ | |
FILE* f; | |
@@ -142,7 +176,33 @@ | |
return send_error(socket, 404, "Not Found"); | |
fseek(f, 0, SEEK_END); | |
fsize = ftell(f); | |
- fseek(f, 0, 0); | |
+ fseek(f, 0, SEEK_SET); | |
+ | |
+ /* | |
+ * Follow HTTP Range header directive if provided | |
+ */ | |
+ unsigned long start, end; | |
+ char *ptr; | |
+ int r; | |
+ | |
+ start = end = 0; | |
+ ptr = get_range_header(request, len); | |
+ if (ptr){ | |
+ if(get_ranges_from_header(ptr, &start, &end)==0){ | |
+ if (start && end){ | |
+ printf("%s:%d reading range of file '%s' from %u-%u\n", inet_ntoa(client.sin_addr), htons(client.sin_port), file, start, end); | |
+ if (lseek(fileno(f), start, SEEK_SET)==-1){ | |
+ perror("lseek() failed:"); | |
+ } else { | |
+ fsize = end - start; | |
+ } | |
+ } | |
+ } | |
+ } | |
+ | |
+ if (fsize==0){ | |
+ fsize=0x8000; | |
+ } | |
/* | |
* Send header | |
@@ -156,6 +216,8 @@ | |
*/ | |
while ((len = fread(buf, 1, sizeof(buf), f)) > 0) { | |
send(socket, buf, len, 0); | |
+ if(--fsize <= 0) | |
+ break; | |
} | |
fclose(f); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment