-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathwebisogetlib.c
1682 lines (1409 loc) · 45.4 KB
/
webisogetlib.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
/* ========================================================================
* Copyright (c) 2004-2014 The University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================================
*/
#define VERIFICATION_THE_OLD_WAY
/* Library for the webisoget package */
/* Retrieve a web page, following redirections, and
responding to some forms.
This allows us to obtain pubcookies and thereby
retrieve pubcookie protected pages.
by Fox
*/
#include "webisoget.h"
#include "openssl/ssl.h"
#include "openssl/x509.h"
#include "openssl/x509v3.h"
#include "openssl/err.h"
#if OPENSSL_VERSION_NUMBER<0x10100000L
#define ASN1_STRING_get0_data ASN1_STRING_data
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <netdb.h>
#include <arpa/inet.h>
int verify_peer = 0;
int delete_op = 0;
long lone = 1;
long ltwo = 2;
long lzero = 0;
extern char *postdata;
extern FILE *postfile;
extern char *putdata;
extern FILE *putfile;
/* String functions */
/* not everyone has strndup */
#ifdef I_REALLY_NEED_STRNDUP
static char *strndup(char *str, int len)
{
char *dup = (char*) malloc(len+1);
strncpy(dup, str, len);
dup[len] = '\0';
return (dup);
}
#endif
static Str newStr()
{
Str s = (Str) malloc(sizeof(Str_));
int l = STRSIZE;
s->base = (void*) malloc(l);
*s->base = '\0';
s->l = l;
s->c = 0;
return (s);
}
static void chkStr(Str s, int len)
{
int l = STRSIZE;
if (l<len) l = len;
if ((s->l)>(s->c+len+1)) return;
s->base = (void*) realloc(s->base, s->l + l);
s->l += l;
}
static void catStr(Str s, char *str, int lstr)
{
chkStr(s, lstr);
memcpy(s->base+s->c, str, lstr);
s->c += lstr;
*(s->base+s->c) = '\0';
}
static void freeStr(Str s)
{
if (s->base) free(s->base);
free(s);
}
/* frames and anchors */
void add_frame(WebGet W, char *name)
{
if (W->frames) W->frames = (char**) realloc(W->frames, sizeof(char*)*(W->nframes+1));
else W->frames = (char**) malloc(sizeof(char*));
W->frames[W->nframes++] = strdup(name);
}
void add_anchor(WebGet W, char *name)
{
if (W->anchors) W->anchors = (char**) realloc(W->anchors, sizeof(char*)*(W->nanchors+1));
else W->anchors = (char**) malloc(sizeof(char*));
W->anchors[W->nanchors++] = strdup(name);
}
void add_header(WebGet W, char *text)
{
if (W->num_user_headers<MAX_USER_HEADERS) W->user_headers[W->num_user_headers++] = strdup(text);
}
/* Since 2.7.4 we use curl's verification. Cirl now allows use to
fake DNS lookup differently.
*/
#ifdef VERIFICATION_THE_OLD_WAY
/* Peer verification. We can't let curl do this
because we allow hostname mappings.
Curl doesn't give us any control after the connection
is established, thus denying us the capability of
checking the cert's name then. So we have to do
that in the verify callback. However, that means
we are not thread-safe while establishing the connection. */
/* Check cert name, pattern can be: '*.aaa.bbb' etc.
Return 1 if match OK */
static int check_name(char *pat, char *name)
{
char c;
while (1) {
c = *pat++;
if (!c) return ((*name)?0:1);
if (c=='*') {
if (!*pat) return (1);
while (*name) if(check_name(name++, pat)) return (1);
return (0);
}
if (toupper(c) != toupper(*(name++))) return (0);
}
}
/* SSL verify callback.
If verifying, check that the cert name matches the peer name.
Return 1 if OK. */
char *static_peer_name;
static int sslverify_callback(int ok, X509_STORE_CTX *ctx)
{
X509 *peercert;
char cn[256];
STACK_OF(GENERAL_NAME) *altnams;
int i, na, r;
int d = X509_STORE_CTX_get_error_depth(ctx);
peercert=X509_STORE_CTX_get_current_cert(ctx);
X509_NAME_get_text_by_NID (X509_get_subject_name(peercert), NID_commonName, cn, sizeof(cn));
if (!ok) {
int err = X509_STORE_CTX_get_error(ctx);
if (verify_peer) return (ok);
}
if (d) return (verify_peer?ok:1);
/* If there's no hostname, or we're not verifying, return OK now */
if ((!static_peer_name) || (!verify_peer)) return (1);
/* Else check altnames first */
altnams = X509_get_ext_d2i(peercert, NID_subject_alt_name, NULL, NULL);
na = sk_GENERAL_NAME_num(altnams);
for (i=0; i<na; i++) {
char *altn;
GENERAL_NAME *ck = sk_GENERAL_NAME_value(altnams, i);
if (ck->type != GEN_DNS) continue;
altn = (char *)ASN1_STRING_get0_data(ck->d.ia5);
if (check_name(altn, static_peer_name)) break;
}
GENERAL_NAMES_free(altnams);
if (i<na) return (1); /* name ok */
if (na<0) { /* RFC2459: altnames must be used if present */
if (check_name(cn,static_peer_name)) return (1);
}
/* make up an error */
SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, SSL_R_CERTIFICATE_VERIFY_FAILED);
return (0);
}
static CURLcode curl_ctx_callback(CURL *curl, void *ctx, void *parm)
{
static_peer_name = (char*) parm;
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, sslverify_callback);
return (0);
}
#endif /* VERIFICATION_THE_OLD_WAY */
/* hostname mappings: for 'name' use 'realname' instead */
// get ip for dns name
char *get_dottedip(char *host) {
struct hostent *he;
int ret;
struct in_addr **addr_list;
he = gethostbyname(host);
if (he==NULL) {
perror(host);
return (NULL);
}
addr_list = (struct in_addr **) he->h_addr_list;
int i;
char *ip = (char*)malloc(256);;
for(i = 0; addr_list[i] != NULL; i++) {
//Return the first one;
strcpy(ip , inet_ntoa(*addr_list[i]) );
return (ip);
}
return (NULL);
}
#ifdef HAVE_CURLOPT_RESOLVE
void add_host_map(WebGet W, char *str)
{
HostMap m;
char *n, *s;
if ((s=strchr(str,'='))!=NULL) {
*s = '\0';
for (m=W->host_maps; m; m=m->next) {
if (!strcasecmp(m->name, str)) break;
}
if (m==NULL) {
m = (HostMap) malloc(sizeof(HostMap_));
m->name = strdup(str);
m->next = W->host_maps;;
W->host_maps = m;
} else {
if (m->realname) free(m->realname);
}
char *realname = strdup(s+1);
*s = '=';
if ((s=strchr(realname,'\n'))!=NULL) *s = '\0';
m->realname = get_dottedip(realname); // the map realname is string of dotted address
free(realname);
}
}
#endif
/* parse URL */
static URL parse_url(WebGet W, char *txt) {
char *p, *q;
URL url = (URL) malloc(sizeof(URL_));
int hl;
/* extract protocol string */
if (strncmp(txt,"http://",7)==0) {
url->prot = PROT_HTTP;
url->port = 80;
url->use_ssl = 0;
} else if (strncmp(txt,"https://",8)==0) {
url->prot = PROT_HTTPS;
url->port = 443;
url->use_ssl = 1;
} else {
free (url);
return (NULL);
}
if ((p = strstr(txt, "://")) == NULL) {
free (url);
return (NULL);
}
txt = p + 3;
/* extract host name and path */
url->domain = strdup(txt);
if ((p=strchr(url->domain,'/'))!=NULL) *p = '\0';
if ((q=strchr(url->domain,':'))!=NULL) {
*q++ = '\0';
url->port = atoi(q);
}
if ((p=strchr(txt,'/'))!=NULL) url->path = strdup(p);
else url->path = strdup("/");
if ((p=strchr(url->path,'\n'))!=NULL) *p = '\0';
if ((p=strchr(url->path,'\r'))!=NULL) *p = '\0';
return (url);
}
/* make a url string from a URL */
static char *make_url(WebGet W, URL u)
{
char *url = (char*) malloc(strlen(u->domain)+strlen(u->path)+32);
char pnum[16];
char *domain = u->domain;
if (u->prot==PROT_BAD) return (strdup("no_url"));
/* check for non-standard port */
if ( (u->use_ssl && (u->port!=443)) ||
((!u->use_ssl) && (u->port!=80)) ) sprintf(pnum,":%d", u->port);
else pnum[0] = '\0';
sprintf(url, "%s://%s%s%s", u->use_ssl?"https":"http", domain, pnum, u->path);
return (url);
}
/* Page and page headers */
void free_page(WebPage p)
{
if (p->content) freeStr(p->content);
if (p->text) free(p->text);
if (p->lower_text) free(p->lower_text);
/* other stuff to free ? */
}
/* ------- Cookies ------------- */
/* convert the awkward gmt string (wday, dd-mmm-yyyy hh:mm:ss) to a time_t */
static char *mon[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
static char *wday[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static time_t gmt2time(char *gmt)
{
char *s = strchr(gmt, ',');
int n;
char mtxt[12];
struct tm t;
time_t res;
if (!s) return (0);
memset(&t, 0, sizeof(t));
n = sscanf(s+1,"%d %3s %4d %2d:%2d:%2d",
&t.tm_mday, mtxt, &t.tm_year,
&t.tm_hour, &t.tm_min, &t.tm_sec);
if (n!=6) return (0);
t.tm_year -= 1900;
for (n=0;n<12;n++) if (!strcmp(mtxt,mon[n])) break;
t.tm_mon = n;
res = mktime(&t) - timezone;
return (res);
}
/* convert a time_t to the awkward gmt string (static allocation) */
static char *time2gmt(time_t tim)
{
static char gmt[256];
struct tm *t;
gmt[0] = '\0';
t = gmtime(&tim);
if (!t) return (gmt);
sprintf(gmt, "%s, %2d-%s-%4d %02d:%02d:%02d GMT",
wday[t->tm_wday], t->tm_mday, mon[t->tm_mon-1], t->tm_year+1900,
t->tm_hour, t->tm_min, t->tm_sec);
return (gmt);
}
/* free cookie struct */
void free_cookie(Cookie c)
{
if (!c) return;
if (c->name) free(c->name);
if (c->text) free(c->text);
if (c->domain) free(c->domain);
if (c->path) free(c->path);
free(c);
}
/* Add a cookie to our list. Sort common name+domain by path specificity */
static void add_cookie(WebGet W, Cookie new)
{
Cookie lc = NULL;
Cookie c;
for (c=W->cookies;c;lc=c,c=c->next) {
if (strcasecmp(c->name,new->name)) continue;
if (strcasecmp(c->domain,new->domain)) continue;
// same name and domain
if (!strcasecmp(c->path,new->path)) {
// replace old cookie
if (lc) lc->next = new;
else W->cookies = new;
new->next = c->next;
free_cookie(c);
return;
}
if (!strncasecmp(c->path, new->path, strlen(c->path))) {
// new is more specific than c
if (lc) lc->next = new;
else W->cookies = new;
new->next = c;
return;
}
}
// else add at end
if (lc) lc->next = new;
else W->cookies = new;
return;
}
/* Parse a set-cookie string. This is made difficult
by the comma having two functions: it is part of
a date specification; AND it delimits multiple cookies. */
static void parse_cookie(WebGet W, char *txt, int new, WebPage page)
{
Cookie c;
char *n, *d, *e, *p;
int ck;
char *mcp;
if ((n = strchr(txt, '\n'))!=NULL) *n = '\0';
for (;;) { /* loop on all possible cookies */
mcp = NULL;
ck = 0;
while (txt) { /* loop on cookie parts. comma might be end of cookie */
while (*txt && *txt==' ') txt++;
e = strchr(txt, ';'); /* end of cookie part */
if (strncasecmp(txt,"expires",7)) mcp = strchr(txt,',');
else mcp = strchr(txt+20,',');
if (e && mcp && mcp<e) e = mcp;
else mcp = NULL;
if (!e) e = mcp;
if (e) *e = '\0';
d = strchr(txt,'='); /* start of data */
if (d) *d = '\0';
if (ck || d) { /* no '=' at start is bogus cookie */
if (!ck) { /* first item is cookie name and value */
c = (Cookie) malloc(sizeof(Cookie_));
memset(c, '\0', sizeof(Cookie_));
c->name = strdup(txt);
c->text = strdup(d?d+1:"");
c->new = new;
ck = 1;
} else { /* domain, path, expires, secure */
if (d && !strcasecmp(txt,"domain")) {
c->domain = strdup(d+1);
} else if (d && !strcasecmp(txt,"path")) {
c->path = strdup(d+1);
} else if (d && !strcasecmp(txt,"expires")) {
c->expire = gmt2time(d+1);
c->expires = 1;
} else if (!strcasecmp(txt,"secure")) {
c->secure = 1;
}
}
}
if (mcp) break;
if (e) txt = e+1;
else break;
}
if (ck) {
PRINTF1(" > got cookie: %s\n", c->name);
if (!c->domain) {
c->domain = strdup(page?page->url->domain:"");
PRINTF1(" > fix domain to %s\n", c->domain);
}
if (!c->text) c->text = strdup("");
if (!c->path) {
c->path = strdup(page?page->url->path:"");
if ((p=strchr(c->path,'?'))!=NULL) *p = '\0';
if ((p=strrchr(c->path,'/'))!=NULL) *(p+1) = '\0';
PRINTF1(" > fix path to %s\n", c->path);
}
PRINTF2(" data: %s=%s, for %s/%s\n", c->name,
c->text, c->domain, c->path);
if (c->expires) PRINTF2(" expires: %s\n", ctime(&c->expire));
if (!strcmp(c->name, "xJSESSIONID")) {
PRINTF1(" > ignoring JSESSION\n");
} else {
add_cookie(W, c);
}
}
/* may have more cookies */
if (mcp) txt = mcp+1;
else break;
}
}
/* Retrieve cached cookies */
int restore_cookies(WebGet W)
{
FILE *f;
int fl;
char *buf;
if (!W->cache_name) return(0);
if (!(f=fopen(W->cache_name,"r"))) return (0);
if (fseek(f, 0, SEEK_END)) return (0);
fl = ftell(f);
fseek(f, 0, SEEK_SET);
buf = (char*) malloc(fl+1);
while (fgets(buf, fl, f)>0) {
parse_cookie(W, buf, 0, NULL);
}
fclose(f);
free(buf);
return (1);
}
/* Save cookies to cache */
int save_cookies(WebGet W)
{
int fd;
FILE *f;
Cookie c;
char exp[256];
time_t now = time(NULL);
if (!W->cache_name) return(0);
unlink(W->cache_name);
fd = open(W->cache_name, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) return (0);
f = fdopen(fd,"w");
if (!f) return (0);
for (c=W->cookies;c;c=c->next) {
exp[0] = '\0';
if (c->expires) {
if (c->expire<=now) continue;
sprintf(exp,"; expires=%s", time2gmt(c->expire));
}
fprintf(f, "%s=%s; domain=%s; path=%s%s\n",
c->name, c->text, c->domain, c->path, exp);
}
fclose(f);
return (1);
}
/* Get the cookies to send to this page */
static Str select_cookies(WebGet W, URL url)
{
Str ck = newStr();
Cookie c;
int n;
time_t now = time(NULL);
char *domain = url->domain;
HostMap M;
for (c=W->cookies;c;c=c->next) {
/* check domain (from right) and path (from left) */
if (c->domain && strcasecmp(c->domain,
domain+strlen(domain)-strlen(c->domain))) continue;
if (c->path && strncmp(c->path,
url->path, strlen(c->path))) continue;
if (c->expires && (c->expire<=now)) continue;
catStr(ck, c->name, strlen(c->name));
catStr(ck, "=", 1);
catStr(ck, c->text, strlen(c->text));
catStr(ck, ";", 1);
PRINTF1(" > sending cookie: %s\n", c->name);
PRINTF2(" > data: %s, for %s%s\n",
c->text, c->domain, c->path);
}
return (ck);
}
void print_cookies(WebGet W)
{
Cookie c;
for (c=W->cookies;c;c=c->next) {
if (c->new) printf("Cookie: %s=%s; domain=%s; path=%s\n",
c->name, c->text, c->domain, c->path);
}
}
/* Find the character ch outside of a quoted string.
Return a pointer to the character if found.
Return NULL if character not found. */
static char *find_unquoted(char *str, char ch)
{
char *s = str;
while(*s) {
if (*s == ch)
return s;
if (*s == '"') {
s++;
s = strchr(s,'"');
if (s == NULL)
return s;
}
s++;
}
return NULL;
}
/* Find the value for key 'name' in the string.
Return empty string if keyword only.
Return NULL if keyword not found.
"pos" get the pointer to the original value. */
static char *find_key(char *str, char *name, char **pos)
{
char *v, *e;
char *s = str;
int nl = strlen(name);
while (*s) {
while (isspace(*s) || (*s==';')) s++;
if (!strncmp(s, name, nl) && !isalnum(*(s+nl))) break;
while (*s && (!isspace(*s)) && (*s!=';')) s++;
}
if (!*s) return(NULL);
s += nl;
while (*s==' ') s++;
if (*s++!='=') return(strdup("")); /* keyword only */
/* look for value */
if (*s=='"') {
s++;
e = strchr(s,'"');
} else if (*s=='\'') {
s++;
e = strchr(s,'\'');
} else {
for (e=s;(*e)&&(*e!=';')&&(*e!=' ')&&(*e!='>'); e++);
}
if (!e) return (NULL); /* invalid */
v = strndup(s, e-s);
if (pos) *pos = s;
return (v);
}
/* Load a known form from a string */
int load_known_form(WebGet W, char *str)
{
KnownForm f = (KnownForm) malloc(sizeof(KnownForm_));
KnownFormInput fi;
char *s, *v, *z;
int ok = 0;
f->domain = NULL;
f->name = NULL;
f->inputs = NULL;
f->submit_name = NULL;
f->submit_value = NULL;
/* parse "name=value;" strings. semicolons can be escaped.
This leaves the '\\', which will be stripped in encode_form_text */
PRINTF3("..kf define\n");
if ((s=strchr(str,'\n'))!=NULL) *s = '\0';
for (s=str;*s;) {
int ctl = 1;
while (*s && *s==' ') s++;
if ((v=strchr(s,'='))!=NULL) {
for (z=v; *z; z++) if ((*z==';')&&(*(z-1)!='\\')) break;
ok++;
*v++ = '\0';
if (*z) *z++ = '\0';
if (!strncmp(s, "input:", 6)) {
s += 6;
ctl = 0;
}
if (ctl && !strcasecmp(s,"domain")) {
f->domain = strdup(v);
PRINTF3("..kf domain = %s\n", v);
} else if (ctl && !strcasecmp(s,"name")) {
f->name = strdup(v);
PRINTF3("..kf name = %s\n", v);
} else if (ctl && !strcasecmp(s,"submit_name")) {
f->submit_name = strdup(v);
PRINTF3("..kf submit_name = %s\n", v);
} else if (ctl && !strcasecmp(s,"submit_value")) {
f->submit_value = strdup(v);
PRINTF3("..kf submit_value = %s\n", v);
} else {
fi = (KnownFormInput) malloc(sizeof(KnownFormInput_));
fi->next = f->inputs;
f->inputs = fi;
fi->name = strdup(s);
fi->data = strdup(v);
PRINTF3("..kf (%s=%s)\n", s, v);
}
s = z;
} else break;
}
if (ok) {
f->next = W->known_forms;
W->known_forms = f;
PRINTF3("..kf done: %s\n", f->name?f->name:"--");
} else free (f);
return(1);
}
/* Load a known form from a file */
int load_known_form_from_file(WebGet W, char *file)
{
FILE *f;
int fl;
char *buf;
if (!file) return(0);
if (!(f=fopen(file,"r"))) return (0);
if (fseek(f, 0, SEEK_END)) return (0);
fl = ftell(f);
fseek(f, 0, SEEK_SET);
buf = (char*) malloc(fl+1);
while (fgets(buf, fl, f)>0) {
if (*buf=='#') continue;
load_known_form(W, buf);
}
fclose(f);
free(buf);
return (1);
}
/* Encode the form text. Single escapes are ignored.
"\;" -> semicolon, "\n" -> newline */
static char *encode_form_text(char *t)
{
char *enc = (char*) malloc(3*strlen(t)+12);
char *e = enc;
for (; *t; t++) {
if (isalnum(*t) || (*t=='.') || (*t=='_') || (*t=='-')) *e++ = *t;
else if (*t=='\n') *e++ = '%', *e++ = '0', *e++ = 'D', *e++ = '%', *e++ = '0', *e++ = 'A';
else if (*t=='\r') *e++ = '%', *e++ = '0', *e++ = 'D';
else if (*t==' ') *e++ = '+';
else if (*t=='%') *e++ = '%', *e++ = '2', *e++ = '5';
else if (*t=='/') *e++ = '%', *e++ = '2', *e++ = 'F';
else if (*t=='(') *e++ = '%', *e++ = '2', *e++ = '8';
else if (*t==')') *e++ = '%', *e++ = '2', *e++ = '9';
else if (*t=='\'') *e++ = '%', *e++ = '2', *e++ = '7';
else if (*t==':') *e++ = '%', *e++ = '3', *e++ = 'A';
else if (*t==';') *e++ = '%', *e++ = '3', *e++ = 'B';
else if (*t=='<') *e++ = '%', *e++ = '3', *e++ = 'C';
else if (*t=='>') *e++ = '%', *e++ = '3', *e++ = 'E';
else if (*t=='=') *e++ = '%', *e++ = '3', *e++ = 'D';
else if (*t=='?') *e++ = '%', *e++ = '3', *e++ = 'F';
else if (*t=='+') *e++ = '%', *e++ = '2', *e++ = 'B';
else if (*t=='&') *e++ = '%', *e++ = '2', *e++ = '6';
else if (*t=='#') *e++ = '%', *e++ = '2', *e++ = '3';
else if (*t=='!') *e++ = '%', *e++ = '2', *e++ = '1';
else if (*t==',') *e++ = '%', *e++ = '2', *e++ = 'C';
else if (*t=='"') *e++ = '%', *e++ = '2', *e++ = '2';
else if (*t=='^') *e++ = '%', *e++ = '5', *e++ = 'E';
else if (*t=='$') *e++ = '%', *e++ = '2', *e++ = '4';
else if (*t=='@') *e++ = '%', *e++ = '4', *e++ = '0';
else if (*t=='\\') {
if (*(t+1)=='\\') *e++ = '%', *e++ = '5', *e++ = 'C', t++;
if (*(t+1)=='n') *e++ = '%', *e++ = '0', *e++ = 'A', t++;
} else {
*e++ = *t;
}
}
*e = '\0';
return(enc);
}
/* Sometimes incoming form data is pre-encoded. That has to be undone. */
// thanks to Sam Attridge.
static char *decode_text(char *t) {
char *dec = (char*) malloc(3*strlen(t)+12);
char *ret = dec;
for (; *t; t++) {
if (!strncasecmp(t, "<", 4)) *dec++='<', t=t+3;
else if (!strncasecmp(t, ">", 4)) *dec++='>', t=t+3;
else if (!strncasecmp(t, "&", 5)) *dec++='&', t=t+4;
else if (!strncasecmp(t, """, 6)) *dec++='"', t=t+5;
else if (!strncasecmp(t, "'", 6)) *dec++='\'', t=t+5;
else *dec++ = *t;
}
*dec = '\0';
return(ret);
}
/* Add a name=value to our form response */
static void append_form_text(Str text, char *n, char *v)
{
char *enc;
if (text->c != 0) catStr(text, "&", 1);
enc = encode_form_text(n);
catStr(text, enc, strlen(enc));
// free(n);
free(enc);
catStr(text, "=", 1);
char *vv = decode_text(v);
enc = encode_form_text(vv);
catStr(text, enc, strlen(enc));
// free(v);
free(vv);
free(enc);
}
/* find the next input: '<input', '<button', ... */
static char *next_input(char *s)
{
char *i = strstr(s, "<input");
char *b = strstr(s, "<button");
if (i && b) {
if (i<b) return i;
return b;
}
if (i) return i;
return b;
}
/* See if this page has a form we should fill out.
If so, return that form */
static Form isaform(WebPage page)
{
WebGet W = page->W;
Form form;
KnownForm kf;
KnownFormInput kfi;
Str text;
char *fs, *fe;
char *action;
char *method;
char *name;
char *s, *e;
char *n, *v, *w, *wn;
char *enc_n, *enc_v;
URL url = page->url;
int l;
char *ap;
char *proto;
char port[7];
char *sub_n, *sub_v;
int need_sub;
char *fs_sav;
char *fe_sav;
/* Find a form that we should respond to */
fe = NULL;
for (fs=page->lower_text; (fs=strstr(fs,"<form")); fs=fe+1) {
fe = strchr(fs,'>');
if (!fe) return (NULL);
*fe = '\0'; /* to limit searches */
action = find_key(fs, "action", &ap);
/* get un-lowered action text */
if (action) {
l = strlen(action);
n = (char *) malloc(l+1);
strncpy(n, page->text+(ap-page->lower_text), l);
n[l] = '\0';
action = decode_text(n);
free(n);
} else action = strdup("");
method = find_key(fs, "method", NULL);
name = find_key(fs, "name", NULL);
if (!name) name = find_key(fs, "id", NULL);
if (!name) name = strdup("");
if (action && method) {
/* add protocol if missing */
if (strncmp(action,"http",4)) {
char portspec[24] = "";
if (url->prot==PROT_HTTP && url->port!=80) snprintf(portspec, 24, ":%d", url->port);
if (url->prot==PROT_HTTPS && url->port!=443) snprintf(portspec, 24, ":%d", url->port);
s = (char*)malloc(strlen(action)+strlen(url->domain)+21+strlen(url->path));
proto=(url->prot==PROT_HTTP? "http":"https");
if (*action) {
if (*action=='/') {
sprintf(s,"%s://%s%s%s", proto, url->domain, portspec, action);
} else {
sprintf(s,"%s://%s%s%s", proto, url->domain, portspec, url->path);
if (*action=='?') strcat(s, action);
else strcpy(strrchr(s,'/')+1, action);
}
} else {
sprintf(s,"%s://%s%s%s", proto, url->domain, portspec, url->path);
/* strip parameters if method is GET */
if (!strcasecmp(method,"get")) if ((ap=strrchr(s,'?'))!=NULL) *ap = '\0';
}
action = s;
PRINTF1(" > form action fixed to %s\n", action);
}
for (s=method;*s;s++) if (islower(*s)) *s = toupper(*s);
*fe = '>'; /* put back */
fs_sav = fs;
fe_sav = strstr(fs,"</form");
if (!fe_sav) return (NULL); /* invalid form */
*fe_sav = '\0'; /* to limit searches */
/* do we act on this form */
for (kf=W->known_forms;kf;kf=kf->next) {
int have_correct_submit = 0;
fs = fs_sav;
fe = fe_sav;
if (kf->domain && strcasecmp(kf->domain, url->domain)) continue;
if (kf->name && strcasecmp(kf->name, name)) continue;
/* Found a form - fill out and submit */
if ((!kf->submit_name)&&(!kf->submit_value)) have_correct_submit = 1;
PRINTF1(" > responding to form %s\n",
kf->name?kf->name:"-null-");
/* Start the response with all the user's supplied values */
text = newStr();
if (kf) {
for (kfi=kf->inputs;kfi;kfi=kfi->next) {
append_form_text(text, kfi->name, kfi->data);
}
}
#ifdef NOSCRIPT
s = fs;
while (s = strstr(s, "<script>")) { /* omit anything in scripts */
char *e = strstr(s, "</script>");
while (s<(e+9)) *s++ = ' ';
}
#endif
/* Process the inputs: <input ...>
If user supplied a "submit" we do only that one - else do the first one we find.
*/
s = fs;
e = NULL;
sub_n = NULL;
sub_v = NULL;
need_sub = 1;
while ((s = next_input(s))!=NULL) {
char *wp;
int userv = 0;