This repository has been archived by the owner on Dec 14, 2020. It is now read-only.
/
httpd.c
2287 lines (2011 loc) · 54.8 KB
/
httpd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/* milli_httpd - pretty small HTTP server
** A combination of
** micro_httpd - really small HTTP server
** and
** mini_httpd - small HTTP server
**
** Copyright ?1999,2000 by Jef Poskanzer <jef@acme.com>.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
** SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
//#include <sys/stat.h>
#include <assert.h>
#include <sys/ioctl.h>
#include <ctype.h>
typedef unsigned int __u32; // 1225 ham
#include <httpd.h>
//2008.08 magic{
#include <bcmnvram.h> //2008.08 magic
#include <arpa/inet.h> //2008.08 magic
#include <error.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <shared.h>
#include <shutils.h>
#define ETCPHYRD 14
#define SIOCGETCPHYRD 0x89FE
//#include "etioctl.h"
#ifdef RTCONFIG_HTTPS
#include <syslog.h>
#include <mssl.h>
#include <shutils.h>
#define SERVER_PORT_SSL 443
#endif
#include "bcmnvram_f.h"
/* A multi-family sockaddr. */
typedef union {
struct sockaddr sa;
struct sockaddr_in sa_in;
} usockaddr;
#include "queue.h"
#define MAX_CONN_ACCEPT 64
#define MAX_CONN_TIMEOUT 60
#ifdef RTCONFIG_IFTTT
#define IFTTTUSERAGENT "asusrouter-Windows-IFTTT-1.0"
#define GETIFTTTCGI "get_IFTTTPincode.cgi"
#endif
typedef struct conn_item {
TAILQ_ENTRY(conn_item) entry;
int fd;
usockaddr usa;
} conn_item_t;
typedef struct conn_list {
TAILQ_HEAD(, conn_item) head;
int count;
} conn_list_t;
/* Globals. */
static FILE *conn_fp;
static char auth_userid[AUTH_MAX];
static char auth_passwd[AUTH_MAX];
static char auth_realm[AUTH_MAX];
char host_name[64];
char referer_host[64];
char user_agent[1024];
char gen_token[32]={0};
#ifdef TRANSLATE_ON_FLY
char Accept_Language[16];
struct language_table language_tables[] = {
{"br", "BR"},
{"pt-BR", "BR"},
{"zh-cn", "CN"},
{"zh-Hans-CN", "CN"},
{"cs", "CZ"},
{"cs-cz", "CZ"},
{"da", "DA"},
{"da-DK", "DA"},
{"de", "DE"},
{"de-at", "DE"},
{"de-ch", "DE"},
{"de-de", "DE"},
{"de-li", "DE"},
{"de-lu", "DE"},
{"en", "EN"},
{"en-us", "EN"},
{"es", "ES"},
{"es-ec", "ES"},
{"es-py", "ES"},
{"es-pa", "ES"},
{"es-ni", "ES"},
{"es-gt", "ES"},
{"es-do", "ES"},
{"es-es", "ES"},
{"es-hn", "ES"},
{"es-ve", "ES"},
{"es-pr", "ES"},
{"es-ar", "ES"},
{"es-bo", "ES"},
{"es-us", "ES"},
{"es-co", "ES"},
{"es-cr", "ES"},
{"es-uy", "ES"},
{"es-pe", "ES"},
{"es-cl", "ES"},
{"es-mx", "ES"},
{"es-sv", "ES"},
{"fi", "FI"},
{"fi-FI", "FI"},
{"fr", "FR"},
{"fr-fr", "FR"},
{"fr-BE", "FR"},
{"fr-CA", "FR"},
{"fr-CH", "FR"},
{"fr-MC", "FR"},
{"fr-LU", "FR"},
{"hu-hu", "HU"},
{"hu", "HU"},
{"it", "IT"},
{"it-it", "IT"},
{"it-ch", "IT"},
{"ja", "JP"},
{"ja-JP", "JP"},
{"ko", "KR"},
{"ko-kr", "KR"},
{"ms", "MS"},
{"ms-MY", "MS"},
{"ms-BN", "MS"},
{"no", "NO"},
{"nb", "NO"},
{"nn", "NO"},
{"nb-NO", "NO"},
{"nn-NO", "NO"},
{"pl-pl", "PL"},
{"pl", "PL"},
{"ru", "RU"},
{"ru-ru", "RU"},
{"ro", "RO"},
{"ro-ro", "RO"},
{"sv", "SV"},
{"sv-FI", "SV"},
{"sv-SE", "SV"},
{"th", "TH"},
{"th-TH", "TH"},
{"th-TH-TH", "TH"},
{"tr", "TR"},
{"tr-TR", "TR"},
{"zh", "TW"},
{"zh-tw", "TW"},
{"zh-Hant-TW", "TW"},
{"zh-hk", "TW"},
{"uk", "UK"},
{NULL, NULL}
};
#endif //TRANSLATE_ON_FLY
/* Forwards. */
static int initialize_listen_socket(usockaddr* usa, const char *ifname);
static int auth_check( char* dirname, char* authorization, char* url, char* cookies, int fromapp_flag);
static int referer_check(char* referer, int fromapp_flag);
char *generate_token(void);
static void send_error( int status, char* title, char* extra_header, char* text );
//#ifdef RTCONFIG_CLOUDSYNC
static void send_page( int status, char* title, char* extra_header, char* text , int fromapp);
//#endif
static void send_headers( int status, char* title, char* extra_header, char* mime_type, int fromapp);
static void send_token_headers( int status, char* title, char* extra_header, char* mime_type, int fromapp);
static int match( const char* pattern, const char* string );
static int match_one( const char* pattern, int patternlen, const char* string );
static void handle_request(void);
void send_login_page(int fromapp_flag, int error_status, char* url, int lock_time);
void __send_login_page(int fromapp_flag, int error_status, char* url, int lock_time);
int check_user_agent(char* user_agent);
#ifdef RTCONFIG_IFTTT
void add_ifttt_flag(void);
#endif
/* added by Joey */
//2008.08 magic{
//int redirect = 1;
int redirect = 0;
int change_passwd = 0;
int reget_passwd = 0;
int x_Setting = 0;
int skip_auth = 0;
char url[128];
int http_port = SERVER_PORT;
char *http_ifname = NULL;
/* Added by Joey for handle one people at the same time */
unsigned int login_ip=0; // the logined ip
time_t login_timestamp=0; // the timestamp of the logined ip
time_t login_timestamp_tmp=0; // the timestamp of the current session.
time_t last_login_timestamp=0; // the timestamp of the current session.
unsigned int login_ip_tmp=0; // the ip of the current session.
unsigned int login_try=0;
unsigned int last_login_ip = 0; // the last logined ip 2008.08 magic
/* limit login IP addr; 2012.03 Yau */
struct {
struct in_addr ip;
struct in_addr netmask;
} access_ip[4];
unsigned int MAX_login;
int lock_flag = 0;
// 2008.08 magic {
time_t request_timestamp = 0;
time_t turn_off_auth_timestamp = 0;
int temp_turn_off_auth = 0; // for QISxxx.htm pages
/* Const vars */
const int int_1 = 1;
void http_login(unsigned int ip, char *url);
void http_login_timeout(unsigned int ip, char *cookies, int fromapp_flag);
void http_logout(unsigned int ip, char *cookies, int fromapp_flag);
int http_login_check(void);
asus_token_t* search_token_in_list(char* token, asus_token_t **prev);
#if 0
static int check_if_inviteCode(const char *dirpath){
return 1;
}
#endif
void sethost(char *host)
{
char *cp;
if(!host) return;
memset(host_name, 0, sizeof(host_name));
strncpy(host_name, host, sizeof(host_name)-1);
cp = host_name;
for ( cp = cp + 7; *cp && *cp != '\r' && *cp != '\n'; cp++ );
*cp = '\0';
}
char *gethost(void)
{
if(strlen(host_name)) {
return host_name;
}
else return(nvram_safe_get("lan_ipaddr"));
}
#include <sys/sysinfo.h>
long uptime(void)
{
struct sysinfo info;
sysinfo(&info);
return info.uptime;
}
static int
initialize_listen_socket(usockaddr* usa, const char *ifname)
{
struct ifreq ifr;
int fd;
memset(usa, 0, sizeof(usockaddr));
usa->sa.sa_family = AF_INET;
usa->sa_in.sin_addr.s_addr = htonl(INADDR_ANY);
usa->sa_in.sin_port = htons(http_port);
fd = socket(usa->sa.sa_family, SOCK_STREAM, 0);
if (fd < 0) {
perror("socket");
return -1;
}
if (ifname) {
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) {
perror("ioctl");
goto error;
}
usa->sa_in.sin_addr.s_addr = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr.s_addr;
}
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &int_1, sizeof(int_1)) < 0) {
perror("setsockopt");
goto error;
}
if (bind(fd, &usa->sa, sizeof(struct sockaddr_in)) < 0) {
perror("bind");
goto error;
}
if (listen(fd, 1024) < 0) {
perror( "listen" );
goto error;
}
return fd;
error:
close(fd);
return -1;
}
void
send_login_page(int fromapp_flag, int error_status, char* url, int lock_time)
{
char inviteCode[256]={0};
char url_tmp[64]={0};
if(url == NULL)
strncpy(url_tmp, "index.asp", sizeof(url_tmp));
else
strncpy(url_tmp, url, sizeof(url_tmp));
if(fromapp_flag == 0){
snprintf(inviteCode, sizeof(inviteCode), "<script>top.location.href='/Main_Login.asp?error_status=%d&page=%s&lock_time=%d';</script>",error_status, url_tmp, lock_time);
}else{
snprintf(inviteCode, sizeof(inviteCode), "\"error_status\":\"%d\"", error_status);
}
send_page( 200, "OK", (char*) 0, inviteCode, fromapp_flag);
}
void
__send_login_page(int fromapp_flag, int error_status, char* url, int lock_time)
{
login_try++;
last_login_timestamp = login_timestamp_tmp;
send_login_page(fromapp_flag, error_status, url, lock_time);
}
static int
referer_check(char* referer, int fromapp_flag)
{
char *auth_referer=NULL;
char *cp1=NULL, *cp2=NULL, *location_cp1=NULL;
if(fromapp_flag != 0)
return 0;
if(!referer){
send_login_page(fromapp_flag, NOREFERER, NULL, 0);
return NOREFERER;
}else{
location_cp1 = strstr(referer,"//");
if(location_cp1 != (char*) 0){
cp1 = &location_cp1[2];
if(strstr(cp1,"/") != (char*) 0){
cp2 = strtok(cp1, "/");
auth_referer = cp2;
}else
auth_referer = cp1;
}else
auth_referer = referer;
}
if(referer_host[0] == 0){
send_login_page(fromapp_flag, WEB_NOREFERER, NULL, 0);
return WEB_NOREFERER;
}
if(strncmp(DUT_DOMAIN_NAME, auth_referer, strlen(DUT_DOMAIN_NAME))==0){
strcpy(auth_referer, nvram_safe_get("lan_ipaddr"));
}
/* form based referer info? */
if(strncmp( auth_referer, referer_host, strlen(referer_host) ) == 0){
//_dprintf("asus token referer_check: the right user and password\n");
return 0;
}else{
//_dprintf("asus token referer_check: the wrong user and password\n");
send_login_page(fromapp_flag, REFERERFAIL, NULL, 0);
return REFERERFAIL;
}
send_login_page(fromapp_flag, REFERERFAIL, NULL, 0);
return REFERERFAIL;
}
#define HEAD_HTTP_LOGIN "HTTP login" // copy from push_log/push_log.h
static int
auth_check( char* dirname, char* authorization ,char* url, char* cookies, int fromapp_flag)
{
struct in_addr temp_ip_addr;
char *temp_ip_str;
time_t dt;
char asustoken[32];
char *cp=NULL, *location_cp;
memset(asustoken,0,sizeof(asustoken));
login_timestamp_tmp = uptime();
dt = login_timestamp_tmp - last_login_timestamp;
if(last_login_timestamp != 0 && dt > 60){
login_try = 0;
last_login_timestamp = 0;
lock_flag = 0;
}
if (MAX_login <= DEFAULT_LOGIN_MAX_NUM)
MAX_login = DEFAULT_LOGIN_MAX_NUM;
if(login_try >= MAX_login){
lock_flag = 1;
temp_ip_addr.s_addr = login_ip_tmp;
temp_ip_str = inet_ntoa(temp_ip_addr);
if(login_try%MAX_login == 0)
logmessage(HEAD_HTTP_LOGIN, "Detect abnormal logins at %d times. The newest one was from %s.", login_try, temp_ip_str);
//#ifdef LOGIN_LOCK
send_login_page(fromapp_flag, LOGINLOCK, url, dt);
return LOGINLOCK;
//#endif
}
/* Is this directory unprotected? */
if ( !strlen(auth_passwd) ){
/* Yes, let the request go through. */
return 0;
}
if(!cookies){
send_login_page(fromapp_flag, NOTOKEN, url, 0);
return NOTOKEN;
}else{
location_cp = strstr(cookies,"asus_token");
if(location_cp != NULL){
cp = &location_cp[11];
cp += strspn( cp, " \t" );
snprintf(asustoken, sizeof(asustoken), "%s", cp);
}else{
send_login_page(fromapp_flag, NOTOKEN, url, 0);
return NOTOKEN;
}
}
/* form based authorization info? */
if(search_token_in_list(asustoken, NULL) != NULL){
//_dprintf("asus token auth_check: the right user and password\n");
#ifdef RTCONFIG_IFTTT
if(strncmp(url, GETIFTTTCGI, strlen(GETIFTTTCGI))==0) add_ifttt_flag();
#endif
login_try = 0;
last_login_timestamp = 0;
lock_flag = 0;
return 0;
}else{
//_dprintf("asus token auth_check: the wrong user and password\n");
send_login_page(fromapp_flag, AUTHFAIL, url, 0);
return AUTHFAIL;
}
send_login_page(fromapp_flag, AUTHFAIL, url, 0);
return AUTHFAIL;
}
char *generate_token(void){
int a=0, b=0, c=0, d=0;
//char create_token[32]={0};
memset(gen_token,0,sizeof(gen_token));
srand (time(NULL));
a=rand();
b=rand();
c=rand();
d=rand();
snprintf(gen_token, sizeof(gen_token),"%d%d%d%d", a, b, c, d);
return gen_token;
}
static void
send_error( int status, char* title, char* extra_header, char* text )
{
send_headers( status, title, extra_header, "text/html", 0);
(void) fprintf( conn_fp, "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n<BODY BGCOLOR=\"#cc9999\"><H4>%d %s</H4>\n", status, title, status, title );
(void) fprintf( conn_fp, "%s\n", text );
(void) fprintf( conn_fp, "</BODY></HTML>\n" );
(void) fflush( conn_fp );
}
//#ifdef RTCONFIG_CLOUDSYNC
static void
send_page( int status, char* title, char* extra_header, char* text , int fromapp){
if(fromapp == 0){
send_headers( status, title, extra_header, "text/html", fromapp);
(void) fprintf( conn_fp, "<HTML><HEAD>");
(void) fprintf( conn_fp, "%s\n", text );
(void) fprintf( conn_fp, "</HEAD></HTML>\n" );
}else{
send_headers( status, title, extra_header, "application/json;charset=UTF-8", fromapp );
(void) fprintf( conn_fp, "{\n");
(void) fprintf( conn_fp, "%s\n", text );
(void) fprintf( conn_fp, "}\n" );
}
(void) fflush( conn_fp );
}
//#endif
static void
send_headers( int status, char* title, char* extra_header, char* mime_type, int fromapp)
{
time_t now;
char timebuf[100];
(void) fprintf( conn_fp, "%s %d %s\r\n", PROTOCOL, status, title );
(void) fprintf( conn_fp, "Server: %s\r\n", SERVER_NAME );
if (fromapp != 0){
(void) fprintf( conn_fp, "Cache-Control: no-store\r\n");
(void) fprintf( conn_fp, "Pragma: no-cache\r\n");
if(fromapp == FROM_DUTUtil){
(void) fprintf( conn_fp, "AiHOMEAPILevel: %d\r\n", EXTEND_AIHOME_API_LEVEL );
(void) fprintf( conn_fp, "Httpd_AiHome_Ver: %d\r\n", EXTEND_HTTPD_AIHOME_VER );
(void) fprintf( conn_fp, "Model_Name: %s\r\n", get_productid() );
}else if(fromapp == FROM_ASSIA){
(void) fprintf( conn_fp, "ASSIA_API_Level: %d\r\n", EXTEND_ASSIA_API_LEVEL );
}
}
now = time( (time_t*) 0 );
(void) strftime( timebuf, sizeof(timebuf), RFC1123FMT, gmtime( &now ) );
(void) fprintf( conn_fp, "Date: %s\r\n", timebuf );
if ( extra_header != (char*) 0 )
(void) fprintf( conn_fp, "%s\r\n", extra_header );
if ( mime_type != (char*) 0 ){
if(fromapp != 0)
(void) fprintf( conn_fp, "Content-Type: %s\r\n", "application/json;charset=UTF-8" );
else
(void) fprintf( conn_fp, "Content-Type: %s\r\n", mime_type );
}
(void) fprintf( conn_fp, "Connection: close\r\n" );
(void) fprintf( conn_fp, "\r\n" );
}
static void
send_token_headers( int status, char* title, char* extra_header, char* mime_type, int fromapp)
{
time_t now;
char timebuf[100];
char asus_token[32]={0};
memset(asus_token,0,sizeof(asus_token));
if(nvram_match("x_Setting", "0") && strcmp( gen_token, "") != 0){
strncpy(asus_token, gen_token, sizeof(asus_token));
}else{
strncpy(asus_token, generate_token(), sizeof(asus_token));
add_asus_token(asus_token);
}
(void) fprintf( conn_fp, "%s %d %s\r\n", PROTOCOL, status, title );
(void) fprintf( conn_fp, "Server: %s\r\n", SERVER_NAME );
if(fromapp == FROM_DUTUtil){
(void) fprintf( conn_fp, "AiHOMEAPILevel: %d\r\n", EXTEND_AIHOME_API_LEVEL );
(void) fprintf( conn_fp, "Httpd_AiHome_Ver: %d\r\n", EXTEND_HTTPD_AIHOME_VER );
(void) fprintf( conn_fp, "Model_Name: %s\r\n", get_productid() );
}else if(fromapp == FROM_ASSIA){
(void) fprintf( conn_fp, "ASSIA_API_Level: %d\r\n", EXTEND_ASSIA_API_LEVEL );
}
now = time( (time_t*) 0 );
(void) strftime( timebuf, sizeof(timebuf), RFC1123FMT, gmtime( &now ) );
(void) fprintf( conn_fp, "Date: %s\r\n", timebuf );
if ( extra_header != (char*) 0 )
(void) fprintf( conn_fp, "%s\r\n", extra_header );
if ( mime_type != (char*) 0 )
(void) fprintf( conn_fp, "Content-Type: %s\r\n", mime_type );
(void) fprintf( conn_fp, "Set-Cookie: asus_token=%s; HttpOnly;\r\n",asus_token );
(void) fprintf( conn_fp, "Connection: close\r\n" );
(void) fprintf( conn_fp, "\r\n" );
}
/* Simple shell-style filename matcher. Only does ? * and **, and multiple
** patterns separated by |. Returns 1 or 0.
*/
int
match( const char* pattern, const char* string )
{
const char* or;
for (;;)
{
or = strchr( pattern, '|' );
if ( or == (char*) 0 )
return match_one( pattern, strlen( pattern ), string );
if ( match_one( pattern, or - pattern, string ) )
return 1;
pattern = or + 1;
}
}
static int
match_one( const char* pattern, int patternlen, const char* string )
{
const char* p;
for ( p = pattern; p - pattern < patternlen; ++p, ++string )
{
if ( *p == '?' && *string != '\0' )
continue;
if ( *p == '*' )
{
int i, pl;
++p;
if ( *p == '*' )
{
/* Double-wildcard matches anything. */
++p;
i = strlen( string );
}
else
/* Single-wildcard matches anything but slash. */
i = strcspn( string, "/" );
pl = patternlen - ( p - pattern );
for ( ; i >= 0; --i )
if ( match_one( p, pl, &(string[i]) ) )
return 1;
return 0;
}
if ( *p != *string )
return 0;
}
if ( *string == '\0' )
return 1;
return 0;
}
int web_write(const char *buffer, int len, FILE *stream)
{
int n = len;
int r = 0;
while (n > 0) {
r = fwrite(buffer, 1, n, stream);
if (( r == 0) && (errno != EINTR)) return -1;
buffer += r;
n -= r;
}
return r;
}
int check_user_agent(char* user_agent){
int fromapp = 0;
if(user_agent != NULL){
char *cp1=NULL, *app_router=NULL, *app_platform=NULL, *app_framework=NULL, *app_verison=NULL;
cp1 = strdup(user_agent);
vstrsep(cp1, "-", &app_router, &app_platform, &app_framework, &app_verison);
if(app_router != NULL && app_framework != NULL && strcmp( app_router, "asusrouter") == 0){
fromapp=FROM_ASUSROUTER;
if(strcmp( app_framework, "DUTUtil") == 0)
fromapp=FROM_DUTUtil;
else if(strcmp( app_framework, "ASSIA") == 0)
fromapp=FROM_ASSIA;
else if(strcmp( app_framework, "IFTTT") == 0)
fromapp=FROM_IFTTT;
}
if(cp1) free(cp1);
}
return fromapp;
}
#ifdef RTCONFIG_IFTTT
void add_ifttt_flag(void){
memset(user_agent, 0, sizeof(user_agent));
sprintf(user_agent, "%s",IFTTTUSERAGENT);
return;
}
#endif
#if 0
void
do_file(char *path, FILE *stream)
{
FILE *fp;
char buf[1024];
int nr;
if (!(fp = fopen(path, "r")))
return;
while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) {
web_write(buf, nr, stream);
}
fclose(fp);
}
#else
int do_fwrite(const char *buffer, int len, FILE *stream)
{
int n = len;
int r = 0;
while (n > 0) {
r = fwrite(buffer, 1, n, stream);
if ((r == 0) && (errno != EINTR)) return -1;
buffer += r;
n -= r;
}
return r;
}
void do_file(char *path, FILE *stream)
{
FILE *fp;
char buf[1024];
int nr;
if ((fp = fopen(path, "r")) != NULL) {
while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0)
do_fwrite(buf, nr, stream);
fclose(fp);
}
}
#endif
int is_firsttime(void);
time_t detect_timestamp, detect_timestamp_old, signal_timestamp;
char detect_timestampstr[32];
#define APPLYAPPSTR "applyapp.cgi"
#define GETAPPSTR "getapp"
#define APPGETCGI "appGet.cgi"
#ifdef RTCONFIG_ROG
#define APPLYROGSTR "api.asp"
#endif
static void
handle_request(void)
{
char line[10000], *cur;
char *method, *path, *protocol, *authorization, *boundary, *alang, *cookies, *referer, *useragent;
char *cp;
char *file;
int len;
struct mime_handler *handler;
struct except_mime_handler *exhandler;
struct mime_referer *doreferer;
int mime_exception, do_referer, login_state = -1;
int fromapp=0;
int cl = 0, flags;
int auth_result = 1;
int referer_result = 1;
#ifdef RTCONFIG_FINDASUS
int i, isDeviceDiscovery=0;
char id_local[32],prouduct_id[32];
#endif
/* Initialize the request variables. */
authorization = boundary = cookies = referer = useragent = NULL;
host_name[0] = 0;
bzero( line, sizeof line );
/* Parse the first line of the request. */
if ( fgets( line, sizeof(line), conn_fp ) == (char*) 0 ) {
send_error( 400, "Bad Request", (char*) 0, "No request found." );
return;
}
method = path = line;
strsep(&path, " ");
//while (*path == ' ') path++;
while (path && *path == ' ') path++; // oleg patch
protocol = path;
strsep(&protocol, " ");
//while (*protocol == ' ') protocol++;
while (protocol && *protocol == ' ') protocol++; // oleg pat
cp = protocol;
strsep(&cp, " ");
if ( !method || !path || !protocol ) {
send_error( 400, "Bad Request", (char*) 0, "Can't parse request." );
return;
}
cur = protocol + strlen(protocol) + 1;
#ifdef TRANSLATE_ON_FLY
memset(Accept_Language, 0, sizeof(Accept_Language));
#endif
/* Parse the rest of the request headers. */
while ( fgets( cur, line + sizeof(line) - cur, conn_fp ) != (char*) 0 )
{
//_dprintf("handle_request:cur = %s\n",cur);
if ( strcmp( cur, "\n" ) == 0 || strcmp( cur, "\r\n" ) == 0 ) {
break;
}
#ifdef TRANSLATE_ON_FLY
else if ( strncasecmp( cur, "Accept-Language:",16) ==0) {
char *p;
struct language_table *pLang;
char lang_buf[256];
memset(lang_buf, 0, sizeof(lang_buf));
alang = &cur[16];
strncpy(lang_buf, alang, sizeof(lang_buf)-1);
p = lang_buf;
while (p != NULL)
{
p = strtok (p, "\r\n ,;");
if (p == NULL) break;
//2008.11 magic{
int i, len=strlen(p);
for (i=0;i<len;++i)
if (isupper(p[i])) {
p[i]=tolower(p[i]);
}
//2008.11 magic}
for (pLang = language_tables; pLang->Lang != NULL; ++pLang)
{
if (strcasecmp(p, pLang->Lang)==0)
{
char dictname[32];
if (!check_lang_support(pLang->Target_Lang))
continue;
snprintf(dictname,sizeof(dictname),"%s.dict", pLang->Target_Lang);
if(!check_if_file_exist(dictname))
{
//_dprintf("language(%s) is not supported!!\n", pLang->Target_Lang);
continue;
}
snprintf(Accept_Language,sizeof(Accept_Language),"%s",pLang->Target_Lang);
if (is_firsttime() && nvram_match("ui_Setting", "0")) {
_dprintf("%s", Accept_Language);
nvram_set("ui_Setting", "1");
nvram_set("preferred_lang", Accept_Language);
#ifdef RTCONFIG_DSL_TCLINUX
if(!strcmp(Accept_Language, "CZ") || !strcmp(Accept_Language, "DE")) {
int do_restart = 0;
if( nvram_match("dslx_annex", "4")
&& nvram_match("dsltmp_adslsyncsts", "down")
){
_dprintf("DSL: auto switch to annex b/j\n");
nvram_set("dslx_annex", "6");
do_restart = 1;
}
if(!strcmp(Accept_Language, "DE")
&& nvram_match("dslx_vdsl_profile", "0")) {
_dprintf("DSL: auto switch to 17a multi mode\n");
nvram_set("dslx_vdsl_profile", "1");
do_restart = 1;
}
if (do_restart)
notify_rc("restart_dsl_setting");
}
#endif
}
break;
}
}
if (Accept_Language[0] != 0) {
break;
}
p+=strlen(p)+1;
}
if (Accept_Language[0] == 0) {
// If all language setting of user's browser are not supported, use English.
//printf ("Auto detect language failed. Use English.\n");
strcpy (Accept_Language, "EN");
// 2008.10 magic {
if (is_firsttime())
nvram_set("preferred_lang", "EN");
// 2008.10 magic }
}
}
#endif
else if ( strncasecmp( cur, "Authorization:", 14 ) == 0 )
{
cp = &cur[14];
cp += strspn( cp, " \t" );
authorization = cp;
cur = cp + strlen(cp) + 1;
}
else if ( strncasecmp( cur, "User-Agent:", 11 ) == 0 )
{
cp = &cur[11];
cp += strspn( cp, " \t" );
useragent = cp;
cur = cp + strlen(cp) + 1;
}
else if ( strncasecmp( cur, "Cookie:", 7 ) == 0 )
{
cp = &cur[7];
cp += strspn( cp, " \t" );
cookies = cp;
cur = cp + strlen(cp) + 1;
}
else if ( strncasecmp( cur, "Referer:", 8 ) == 0 )
{
cp = &cur[8];
cp += strspn( cp, " \t" );
referer = cp;
cur = cp + strlen(cp) + 1;
//_dprintf("httpd referer = %s\n", referer);
}
else if ( strncasecmp( cur, "Host:", 5 ) == 0 )
{
cp = &cur[5];
cp += strspn( cp, " \t" );
sethost(cp);
cur = cp + strlen(cp) + 1;
#ifdef RTCONFIG_FINDASUS
sprintf(prouduct_id, "%s",get_productid());
for(i = 0 ; i < strlen(prouduct_id) ; i++ ){
prouduct_id[i] = tolower(prouduct_id[i]) ;
}
sprintf(id_local, "%s.local",prouduct_id);
if(!strncmp(cp, "findasus", 8) || !strncmp(cp, id_local,strlen(id_local)))
isDeviceDiscovery = 1;
else
isDeviceDiscovery = 0;
#endif
}
else if (strncasecmp( cur, "Content-Length:", 15 ) == 0) {
cp = &cur[15];
cp += strspn( cp, " \t" );
cl = strtoul( cp, NULL, 0 );
}
else if ((cp = strstr( cur, "boundary=" ))) {
boundary = &cp[9];
for ( cp = cp + 9; *cp && *cp != '\r' && *cp != '\n'; cp++ );
*cp = '\0';
cur = ++cp;
}
}
if ( strcasecmp( method, "get" ) != 0 && strcasecmp(method, "post") != 0 && strcasecmp(method, "head") != 0 ) {
send_error( 501, "Not Implemented", (char*) 0, "That method is not implemented." );
return;
}