-
Notifications
You must be signed in to change notification settings - Fork 2
/
driver.c
3426 lines (3354 loc) · 165 KB
/
driver.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) 2002-2009, John Forkosh Associates, Inc. All rights reserved.
* http://www.forkosh.com mailto: [email protected]
* --------------------------------------------------------------------------
* This file is part of mimeTeX, which is free software. You may redistribute
* and/or modify it under the terms of the GNU General Public License,
* version 3 or later, as published by the Free Software Foundation.
* MimeTeX is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY, not even the implied warranty of MERCHANTABILITY.
* See the GNU General Public License for specific details.
* By using mimeTeX, you warrant that you have read, understood and
* agreed to these terms and conditions, and that you possess the legal
* right and ability to enter into this agreement and to use mimeTeX
* in accordance with it.
* Your mimetex.zip distribution file should contain the file COPYING,
* an ascii text copy of the GNU General Public License, version 3.
* If not, point your browser to http://www.gnu.org/licenses/
* or write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
****************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "mimetex.h"
#include "gifsave.h"
#include "md5.h"
/* --- check whether or not to perform http_referer check --- */
#ifdef REFERER /* only specified referers allowed */
#undef NOREFMAXLEN
#define NOREFMAXLEN NOREFSAFELEN
#else
/* all http_referer's allowed */
#define REFERER NULL
#endif
#ifdef INPUTREFERER /*http_referer's permitted to \input*/
#ifndef INPUTSECURITY /* so we need to permit \input{} */
#define INPUTSECURITY (99999) /* make sure SECURITY<INPUTSECURITY */
#endif
#else
/* no INPUTREFERER list supplied */
#define INPUTREFERER NULL /* so init it as NULL pointer */
#endif
/* --- check top levels of http_referer against server_name --- */
#ifdef REFLEVELS /* #topmost levels to check */
#undef NOREFMAXLEN
#define NOREFMAXLEN NOREFSAFELEN
#else
#ifdef NOREFCHECK
#define REFLEVELS 0 /* don't match host and referer */
#else
#define REFLEVELS 3 /* default matches abc.def.com */
#endif
#endif
/* --- max query_string length if no http_referer supplied --- */
#ifndef NOREFMAXLEN
#define NOREFMAXLEN 9999 /* default to any length query */
#endif
#ifndef NOREFSAFELEN
#define NOREFSAFELEN 24 /* too small for hack exploit */
#endif
#ifndef LOGFILE
#define LOGFILE "mimetex.log" /* default log file */
#endif
#ifndef CACHELOG
#define CACHELOG "mimetex.log" /* default caching log file */
#endif
/* --- image caching (cache images if given -DCACHEPATH=\"path\") --- */
#ifndef CACHEPATH
#define ISCACHING 0 /* no caching */
#define CACHEPATH "\000" /* same directory as mimetex.cgi */
#else
#define ISCACHING 1 /* caching if -DCACHEPATH="path" */
#endif
/* --- \input paths (prepend prefix if given -DPATHPREFIX=\"prefix\") --- */
#define PATHPREFIX "\000" /* paths relative mimetex.cgi */
/* --- treat +'s in query string as blanks? --- */
#ifdef PLUSBLANK /* + always interpreted as blank */
#define ISPLUSBLANK 1
#else
#ifdef PLUSNOTBLANK /* + never interpreted as blank */
#define ISPLUSBLANK 0
#else
/* program tries to determine */
#define ISPLUSBLANK (-1)
#endif
#endif
/* --- skip argv[]'s preceding ARGSIGNAL when parsing command-line args --- */
#ifdef NOARGSIGNAL
#define ARGSIGNAL NULL
#endif
#ifndef ARGSIGNAL
#define ARGSIGNAL "++"
#endif
/* --- security and logging (inhibit message logging, etc) --- */
#ifndef SECURITY
#define SECURITY 999 /* default highest security level */
#endif
#if !defined(NODUMPENVP) && !defined(DUMPENVP)
#define DUMPENVP /* assume char *envp[] available */
#endif
/* --- check whether or not \input, \counter, \environment permitted --- */
#ifdef DEFAULTSECURITY /* default security specified */
#define EXPLICITDEFSECURITY /* don't override explicit default */
#else
/* defualt security not specified */
#define DEFAULTSECURITY (8) /* so set default security level */
#endif
#ifndef INPUTPATH /* \input{} paths permitted for... */
#define INPUTPATH NULL /* ...any referer */
#endif
#ifndef INPUTSECURITY /* \input{} security not specified */
#ifdef INPUTOK /* but INPUTOK flag specified */
#define INPUTSECURITY (99999) /* so enable \input{} */
#ifndef EXPLICITDEFSECURITY /* don't override explicit default */
#undef DEFAULTSECURITY /* but we'll override our default */
#define DEFAULTSECURITY (99999) /*let -DINPUTOK enable \counter,etc*/
#endif
#else
/* else no \input{} specified */
#define INPUTSECURITY DEFAULTSECURITY /* set default \input security */
#endif
#endif
#ifndef COUNTERSECURITY /*\counter{} security not specified*/
#ifdef COUNTEROK /* but COUNTEROK flag specified */
#define COUNTERSECURITY (99999) /* so enable \counter{} */
#else
/* else no \counter{} specified */
#define COUNTERSECURITY DEFAULTSECURITY /*set default \counter security*/
#endif
#endif
#ifndef ENVIRONSECURITY /* \environ security not specified */
#ifdef ENVIRONOK /* but ENVIRONOK flag specified */
#define ENVIRONSECURITY (99999) /* so enable \environ */
#else
/* else no \environ specified */
#define ENVIRONSECURITY DEFAULTSECURITY /*set default \environ security*/
#endif
#endif
#ifndef ERRORSTATUS /* exit(ERRORSTATUS) for any error */
#define ERRORSTATUS 0 /* default doesn't signal errors */
#endif
#ifndef FORMLEVEL
#define FORMLEVEL LOGLEVEL /*mctx.msglevel if called from html form*/
#endif
/* --- anti-aliasing flags (needed by GetPixel() as well as main()) --- */
#ifdef AA /* if anti-aliasing requested */
#define ISAAVALUE 1 /* turn flag on */
#else
#define ISAAVALUE 0 /* else turn flag off */
#endif
extern char **environ; /* for \environment directive */
/* ------------------------------------------------------------
messages (used mostly by main() and also by rastmessage())
------------------------------------------------------------ */
static char *copyright1 = /* copyright, gnu/gpl notice */
"+-----------------------------------------------------------------------+\n"
"|mimeTeX vers " VERSION
", Copyright(c) 2002-2009, John Forkosh Associates, Inc|\n"
"+-----------------------------------------------------------------------+\n"
"| mimeTeX is free software, licensed to you under terms of the GNU/GPL, |\n"
"| and comes with absolutely no warranty whatsoever. |";
static char *copyright2 =
"| See http://www.forkosh.com/mimetex.html for details. |\n"
"+-----------------------------------------------------------------------+";
static int maxmsgnum = 3, /* maximum msgtable[] index */
invmsgnum = 0, /* general invalid message */
refmsgnum = 3; /* urlncmp() failed to validate */
static char *msgtable[] = { /* messages referenced by [index] */
"\\red\\small\\rm\\fbox{\\array{"
/* [0] is invalid_referer_msg */
"Please~read~www.forkosh.com/mimetex.html\\\\and~install~mimetex.cgi~"
"on~your~own~server.\\\\Thank~you,~John~Forkosh}}",
"\\red\\small\\rm\\fbox{\\array{"
/* [1] */
"Please~provide~your~{\\tiny~HTTP-REFERER}~to~access~the~public\\\\"
"mimetex~server.~~Or~please~read~~www.forkosh.com/mimetex.html\\\\"
"and~install~mimetex.cgi~on~your~own~server.~~Thank~you,~John~Forkosh}}",
"\\red\\small\\rm\\fbox{\\array{"
/* [2] */
"The~public~mimetex~server~is~for~testing.~~For~production,\\\\"
"please~read~~www.forkosh.com/mimetex.html~~and~install\\\\"
"mimetex.cgi~on~your~own~server.~~Thank~you,~John~Forkosh}}",
"\\red\\small\\rm\\fbox{\\array{"
/* [3] */
"Only~SERVER_NAME~may~use~mimetex~on~this~server.\\\\"
"Please~read~~www.forkosh.com/mimetex.html~~and~install\\\\"
"mimetex.cgi~on~your~own~server.~~Thank~you,~John~Forkosh}}",
NULL
} ; /* trailer */
static int iscaching = ISCACHING; /* true if caching images */
static char cachepath[256] = CACHEPATH; /* relative path to cached files */
static int isemitcontenttype = 1; /* true to emit mime content-type */
static int isnomath = 0; /* true to inhibit math mode */
static int seclevel = SECURITY; /* security level */
static int inputseclevel = INPUTSECURITY; /* \input{} security level */
static int counterseclevel = COUNTERSECURITY; /* \counter{} security level */
static int environseclevel = ENVIRONSECURITY; /* \environ{} security level */
static char pathprefix[256] = { '\000' }; /*prefix for \input,\counter paths*/
static int exitstatus = 0;
static char exprprefix[256] = "\000"; /* prefix prepended to expressions */
static int ninputcmds = 0; /* # of \input commands processed */
static int errorstatus = ERRORSTATUS; /* exit status if error encountered*/
static int isplusblank = -1; /*interpret +'s in query as blanks?*/
static int tzdelta = 0;
static char *md5str(char *instr)
{
static char outstr[64];
unsigned char md5sum[16];
md5_context ctx;
int j;
md5_starts(&ctx);
md5_update(&ctx, (uint8_t *)instr, strlen(instr));
md5_finish(&ctx, md5sum);
for (j = 0; j < 16; j++)
sprintf(outstr + j*2, "%02x", md5sum[j]);
outstr[32] = '\000';
return (outstr);
}
/* ==========================================================================
* Function: urlprune ( url, n )
* Purpose: Prune http://abc.def.ghi.com/etc into abc.def.ghi.com
* (if n=2 only ghi.com is returned, or if n=-1 only "ghi")
* --------------------------------------------------------------------------
* Arguments: url (I) char * to null-terminated string
* containing url to be pruned
* n (i) int containing number of levels retained
* in pruned url. If n<0 its abs() is used,
* but the topmost level (usually .com, .org,
* etc) is omitted. That is, if n=2 would
* return "ghi.com" then n=-1 returns "ghi".
* n=0 retains all levels.
* --------------------------------------------------------------------------
* Returns: ( char * ) pointer to (static) null-terminated string
* containing pruned url with the first n
* top-level domain, e.g., for n=2,
* http://abc.def.ghi.com/etc returns ghi.com,
* or an empty string "\000" for any error
* --------------------------------------------------------------------------
* Notes: o
* ======================================================================= */
/* --- entry point --- */
static char *urlprune(char *url, int n)
{
/* ------------------------------------------------------------
Allocations and Declarations
------------------------------------------------------------ */
/* pruned url returned to caller */
static char pruned[1024];
char *purl = /*NULL*/pruned; /* ptr to pruned, init for error */
/* delimiter separating components */
char *delim = NULL;
/* lowercase a string */
char *strnlower();
/*true to truncate .com from pruned*/
int istruncate = (n < 0 ? 1 : 0);
/* number of dots found in url */
int ndots = 0;
/* ------------------------------------------------------------
prune the url
------------------------------------------------------------ */
/* --- first check input --- */
/* init for error */
*pruned = '\000';
/* missing input, so return NULL */
if (isempty(url)) goto end_of_job;
/* flip n positive */
if (n < 0) n = (-n);
/* retain all levels of url */
if (n == 0) n = 999;
/* --- preprocess url --- */
/* copy url to our static buffer */
strninit(pruned, url, 999);
/* lowercase it and... */
strlower(pruned);
trimwhite(pruned);
/*remove leading/trailing whitespace*/
/* --- first remove leading http:// --- */
if ((delim = strstr(pruned, "://")) != NULL) /* found http:// or ftp:// etc */
if (((int)(delim - pruned)) <= 8) { /* make sure it's a prefix */
strcpy(pruned, delim + 3); /* squeeze out leading http:// */
trimwhite(pruned);
} /*remove leading/trailing whitespace*/
/* --- next remove leading www. --- */
if ((delim = strstr(pruned, "www.")) != NULL) /* found www. */
if (((int)(delim - pruned)) == 0) { /* make sure it's the leading chars*/
/* squeeze out leading www. */
strcpy(pruned, delim + 4);
trimwhite(pruned);
} /*remove leading/trailing whitespace*/
/* --- finally remove leading / and everything following it --- */
if ((delim = strchr(pruned, '/')) != NULL) /* found first / */
*delim = '\000'; /* null-terminate url at first / */
/* nothing left in url */
if (isempty(pruned)) goto end_of_job;
/* --- count dots from back of url --- */
/*ptr to '\000' terminating pruned*/
delim = pruned + strlen(pruned);
while (((int)(delim - pruned)) > 0) { /* don't back up before first char */
/* ptr to preceding character */
delim--;
/* not a dot, so keep looking */
if (*delim != '.') continue;
/* count another dot found */
ndots++;
if (istruncate) { /* remove trailing .com */
/* don't truncate any more dots */
istruncate = 0;
/* truncate pruned url */
*delim = '\000';
ndots = 0;
} /* and reset dot count */
if (ndots >= n) { /* have all requested levels */
/* squeeze out any leading levels */
strcpy(pruned, delim + 1);
break;
} /* and we're done */
} /* --- end-of-while() --- */
/*completed okay, return pruned url*/
purl = pruned;
end_of_job:
/* back with pruned url */
return (purl);
} /* --- end-of-function urlprune() --- */
/* ==========================================================================
* Function: urlncmp ( url1, url2, n )
* Purpose: Compares the n topmost levels of two urls
* --------------------------------------------------------------------------
* Arguments: url1 (I) char * to null-terminated string
* containing url to be compared with url2
* url2 (I) char * to null-terminated string
* containing url to be compared with url1
* n (I) int containing number of top levels
* to compare, or 0 to compare them all.
* n<0 compares that many top levels excluding
* the last, i.e., for n=-1, xxx.com and xxx.org
* would be considered a match
* --------------------------------------------------------------------------
* Returns: ( int ) 1 if url's match, or
* 0 if not.
* --------------------------------------------------------------------------
* Notes: o
* ======================================================================= */
/* --- entry point --- */
static int urlncmp(char *url1, char *url2, int n)
{
/* ------------------------------------------------------------
Allocations and Declarations
------------------------------------------------------------ */
char *prune = NULL, /* prune url's */
prune1[1024], prune2[1024]; /* pruned copies of url1,url2 */
/* true if url's match */
int ismatch = 0;
/* ------------------------------------------------------------
prune url's and compare the pruned results
------------------------------------------------------------ */
/* --- check input --- */
if (isempty(url1) /*make sure both url1,url2 supplied*/
/* missing input, so return 0 */
|| isempty(url2)) goto end_of_job;
/* --- prune url's --- */
/* ptr to pruned version of url1 */
prune = urlprune(url1, n);
/* some problem with url1 */
if (isempty(prune)) goto end_of_job;
/* local copy of pruned url1 */
strninit(prune1, prune, 999);
/* ptr to pruned version of url2 */
prune = urlprune(url2, n);
/* some problem with url2 */
if (isempty(prune)) goto end_of_job;
/* local copy of pruned url2 */
strninit(prune2, prune, 999);
/* --- compare pruned url's --- */
if (strcmp(prune1, prune2) == 0) /* pruned url's are identical */
/* signal match to caller */
ismatch = 1;
end_of_job:
/*back with #matching url components*/
return (ismatch);
} /* --- end-of-function urlncmp() --- */
/* ==========================================================================
* Functions: int unescape_url ( char *url, int isescape )
* char x2c ( char *what )
* Purpose: unescape_url replaces 3-character sequences %xx in url
* with the single character represented by hex xx.
* x2c returns the single character represented by hex xx
* passed as a 2-character sequence in what.
* --------------------------------------------------------------------------
* Arguments: url (I) char * containing null-terminated
* string with embedded %xx sequences
* to be converted.
* isescape (I) int containing 1 to _not_ unescape
* \% sequences (0 would be NCSA default)
* what (I) char * whose first 2 characters are
* interpreted as ascii representations
* of hex digits.
* --------------------------------------------------------------------------
* Returns: ( int ) unescape_url always returns 0.
* ( char ) x2c returns the single char
* corresponding to hex xx passed in what.
* --------------------------------------------------------------------------
* Notes: o These two functions were taken verbatim from util.c in
* ftp://ftp.ncsa.uiuc.edu/Web/httpd/Unix/ncsa_httpd/cgi/ncsa-default.tar.Z
* o Not quite "verbatim" -- I added the "isescape logic" 4-Dec-03
* so unescape_url() can be safely applied to input which may or
* may not have been url-encoded. (Note: currently, all calls
* to unescape_url() pass iescape=0, so it's not used.)
* o Added +++'s to blank xlation on 24-Sep-06
* o Added ^M,^F,etc to blank xlation 0n 01-Oct-06
* ======================================================================= */
/* --- entry point --- */
static int unescape_url(char *url, int isescape)
{
int x = 0, y = 0, prevescape = 0, gotescape = 0;
/* true to xlate plus to blank */
int xlateplus = (isplusblank == 1 ? 1 : 0);
/* replace + with blank, if needed */
int strreplace();
char x2c();
static char *hex = "0123456789ABCDEFabcdef";
/* ---
* xlate ctrl chars to blanks
* ------------------------------------------------------------ */
if (1) { /* xlate ctrl chars to blanks */
char *ctrlchars = "\n\t\v\b\r\f\a\015";
/*initial segment with ctrlchars*/
int seglen = strspn(url, ctrlchars);
/* total length of url string */
int urllen = strlen(url);
/* --- first, entirely remove ctrlchars from beginning and end --- */
if (seglen > 0) { /*have ctrlchars at start of string*/
/* squeeze out initial ctrlchars */
strcpy(url, url + seglen);
urllen -= seglen;
} /* string is now shorter */
while (--urllen >= 0) /* now remove ctrlchars from end */
if (isthischar(url[urllen], ctrlchars)) /* ctrlchar at end */
/* re-terminate string before it */
url[urllen] = '\000';
/* or we're done */
else break;
/* length of url string */
urllen++;
/* --- now, replace interior ctrlchars with ~ blanks --- */
while ((seglen = strcspn(url, ctrlchars)) < urllen) /*found a ctrlchar*/
/* replace ctrlchar with ~ */
url[seglen] = '~';
} /* --- end-of-if(1) --- */
/* ---
* xlate +'s to blanks if requested or if deemed necessary
* ------------------------------------------------------------ */
if (isplusblank == (-1)) { /*determine whether or not to xlate*/
char *searchfor[] = { " ", "%20", "%2B", "%2b", "+++", "++",
"+=+", "+-+", NULL
};
int isearch = 0, /* searchfor[] index */
/*#occurrences*/
nfound[11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
/* --- locate occurrences of searchfor[] strings in url --- */
for (isearch = 0; searchfor[isearch] != NULL; isearch++) {
/* start search at beginning */
char *psearch = url;
/* init #occurrences count */
nfound[isearch] = 0;
while ((psearch = strstr(psearch, searchfor[isearch])) != NULL) {
/* count another occurrence */
nfound[isearch] += 1;
psearch += strlen(searchfor[isearch]);
} /*resume search after it*/
} /* --- end-of-for(isearch) --- */
/* --- apply some common-sense logic --- */
if (nfound[0] + nfound[1] > 0) /* we have actual " "s or "%20"s */
/* so +++'s aren't blanks */
isplusblank = xlateplus = 0;
if (nfound[2] + nfound[3] > 0) { /* we have "%2B" for +++'s */
if (isplusblank != 0) /* and haven't disabled xlation */
/* so +++'s are blanks */
isplusblank = xlateplus = 1;
else
/* we have _both_ "%20" and "%2b" */
xlateplus = 0;
} /* tough call */
if (nfound[4] + nfound[5] > 0 /* we have multiple ++'s */
|| nfound[6] + nfound[7] > 0) /* or we have a +=+ or +-+ */
if (isplusblank != 0) /* and haven't disabled xlation */
/* so xlate +++'s to blanks */
xlateplus = 1;
} /* --- end-of-if(isplusblank==-1) --- */
if (xlateplus > 0) { /* want +'s xlated to blanks */
char *xlateto[] = { "", " ", " ", " + ", " ", " ", " ", " ", " " };
while (xlateplus > 0) { /* still have +++'s to xlate */
/* longest +++ string */
char plusses[99] = "++++++++++++++++++++";
/* null-terminate +++'s */
plusses[xlateplus] = '\000';
/* xlate +++'s */
strreplace(url, plusses, xlateto[xlateplus], 0);
/* next shorter +++ string */
xlateplus--;
} /* --- end-of-while(xlateplus>0) --- */
} /* --- end-of-if(xlateplus) --- */
/* don't iterate this xlation */
isplusblank = 0;
/* ---
* xlate %nn to corresponding char
* ------------------------------------------------------------ */
for (; url[y]; ++x, ++y) {
gotescape = prevescape;
prevescape = (url[x] == '\\');
if ((url[x] = url[y]) == '%')
if (!isescape || !gotescape)
if (isthischar(url[y+1], hex)
&& isthischar(url[y+2], hex)) {
url[x] = x2c(&url[y+1]);
y += 2;
}
}
url[x] = '\0';
return 0;
} /* --- end-of-function unescape_url() --- */
/* ==========================================================================
* Function: rasteditfilename ( filename )
* Purpose: edits filename to remove security problems,
* e.g., removes all ../'s and ..\'s.
* --------------------------------------------------------------------------
* Arguments: filename (I) char * to null-terminated string containing
* name of file to be edited
* --------------------------------------------------------------------------
* Returns: ( char * ) pointer to edited filename,
* or empty string "\000" if any problem
* --------------------------------------------------------------------------
* Notes: o
* ======================================================================= */
/* --- entry point --- */
static char *rasteditfilename(char *filename)
{
/* ------------------------------------------------------------
Allocations and Declarations
------------------------------------------------------------ */
static char editname[2050]; /*edited filename returned to caller*/
int isprefix = (*pathprefix=='\000'?0:1); /* true if paths have prefix */
/* ------------------------------------------------------------
edit filename
------------------------------------------------------------ */
/* --- first check filename arg --- */
*editname = '\000'; /* init edited name as empty string*/
if (filename == (char *)NULL)
/* no filename arg */
goto end_of_job;
if (*filename == '\000')
/* filename is an empty string */
goto end_of_job;
/* --- init edited filename --- */
strcpy(editname, filename); /* init edited name as input name */
compress(editname, ' '); /* remove embedded blanks */
/* --- remove leading or embedded ....'s --- */
while (strreplace(editname,"....",NULL,0) > 0); /* squeeze out ....'s */
/* --- remove leading / and \ and dots (and blanks) --- */
if (*editname != '\000') {
/* still have chars in filename */
while (isthischar(*editname, " ./\\"))
/* absolute paths invalid so flush leading / or \ (or ' ')*/
strcpy(editname, editname + 1);
}
if (*editname == '\000')
/* no chars left in filename */
goto end_of_job;
/* --- remove leading or embedded ../'s and ..\'s --- */
while (strreplace(editname, "../", NULL, 0) > 0); /* squeeze out ../'s */
while (strreplace(editname, "..\\", NULL, 0) > 0); /* and ..\'s */
while (strreplace(editname, "../", NULL, 0) > 0); /* and ../'s again */
/* --- prepend path prefix (if compiled with -DPATHPREFIX) --- */
if (isprefix && *editname!='\000') /* filename is preceded by prefix */
strchange(0, editname, pathprefix); /* so prepend prefix */
end_of_job:
/* back with edited filename */
return ( editname );
}
/* --- end-of-function rasteditfilename() --- */
/* ========================================================================== * Function: sanitize_pathname ( filename )
* Purpose: edits filename to remove security problems,
* e.g., removes all ../'s and ..\'s.
* --------------------------------------------------------------------------
* Arguments: filename (I) char * to null-terminated string containing
* name of file to be edited
* --------------------------------------------------------------------------
* Returns: ( char * ) pointer to edited filename,
* or empty string "\000" if any problem
* --------------------------------------------------------------------------
* Notes: o
* ======================================================================= */
/* --- entry point --- */
char *sanitize_pathname(char *filename)
{
/* ------------------------------------------------------------
Allocations and Declarations
------------------------------------------------------------ */
int strreplace();
/*edited filename returned to caller*/
static char editname[2050];
/* prepend pathprefix if necessary */
/* true if paths have prefix */
int isprefix = (*pathprefix == '\000' ? 0 : 1);
/* ------------------------------------------------------------
edit filename
------------------------------------------------------------ */
/* --- first check filename arg --- */
/* init edited name as empty string*/
*editname = '\000';
/* no filename arg */
if (filename == (char *)NULL) goto end_of_job;
/* filename is an empty string */
if (*filename == '\000') goto end_of_job;
/* --- init edited filename --- */
/* init edited name as input name */
strcpy(editname, filename);
/* remove embedded blanks */
compress(editname, ' ');
/* --- remove leading or embedded ....'s --- */
/* squeeze out ....'s */
while (strreplace(editname, "....", NULL, 0) > 0) ;
/* --- remove leading / and \ and dots (and blanks) --- */
if (*editname != '\000') /* still have chars in filename */
while (isthischar(*editname, " ./\\")) /* absolute paths invalid */
strcpy(editname, editname + 1); /* so flush leading / or \ (or ' ')*/
/* no chars left in filename */
if (*editname == '\000') goto end_of_job;
/* --- remove leading or embedded ../'s and ..\'s --- */
while (strreplace(editname, "../", NULL, 0) > 0) ; /* squeeze out ../'s */
/* and ..\'s */
while (strreplace(editname, "..\\", NULL, 0) > 0) ;
while (strreplace(editname, "../", NULL, 0) > 0) ; /* and ../'s again */
/* --- prepend path prefix (if compiled with -DPATHPREFIX) --- */
if (isprefix && *editname != '\000') /* filename is preceded by prefix */
/* so prepend prefix */
strchange(0, editname, pathprefix);
end_of_job:
/* back with edited filename */
return (editname);
} /* --- end-of-function sanitize_pathname() --- */
/* ==========================================================================
* Function: rastopenfile ( filename, mode )
* Purpose: Opens filename[.tex] in mode, returning FILE *
* --------------------------------------------------------------------------
* Arguments: filename (I/O) char * to null-terminated string containing
* name of file to open (preceded by path
* relative to mimetex executable)
* If fopen() fails, .tex appeneded,
* and returned if that fopen() succeeds
* mode (I) char * to null-terminated string containing
* fopen() mode
* --------------------------------------------------------------------------
* Returns: ( FILE * ) pointer to opened file, or NULL if error
* --------------------------------------------------------------------------
* Notes: o
* ======================================================================= */
/* --- entry point --- */
FILE *rastopenfile(mimetex_ctx *mctx, char *filename, char *mode)
{
/* ------------------------------------------------------------
Allocations and Declarations
------------------------------------------------------------ */
char *sanitize_pathname();
FILE *fp = (FILE *)NULL; /*file pointer to opened filename*/
char texfile[2050] = "\000", /* local, edited copy of filename */
amode[512] = "r"; /* test open mode if arg mode=NULL */
/* true of mode!=NULL */
int ismode = 0;
/* ------------------------------------------------------------
Check mode and open file
------------------------------------------------------------ */
/* --- edit filename --- */
/*edited copy of filename*/
strncpy(texfile, sanitize_pathname(filename), 2047);
/* make sure it's null terminated */
texfile[2047] = '\000';
/* --- check mode --- */
if (mode != (char *)NULL) /* caller passed mode arg */
if (*mode != '\000') { /* and it's not an empty string */
/* so flip mode flag true */
ismode = 1;
/* and replace "r" with caller's */
strncpy(amode, mode, 254);
/* make sure it's null terminated */
amode[254] = '\000';
compress(amode, ' ');
} /* remove embedded blanks */
/* --- open filename or filename.tex --- */
if (strlen(texfile) > 1) /* make sure we got actual filename*/
if ((fp = fopen(texfile, amode)) /* try opening given filename */
== NULL) { /* failed to open given filename */
/* signal possible filename error */
strcpy(filename, texfile);
/* but first try adding .tex */
strcat(texfile, ".tex");
if ((fp = fopen(texfile, amode)) /* now try opening filename.tex */
!= NULL) /* filename.tex succeeded */
strcpy(filename, texfile);
} /* replace caller's filename */
/* --- close file if only opened to check name --- */
if (!ismode && fp != NULL) /* no mode, so just checking */
/* close file, fp signals success */
fclose(fp);
/* --- return fp or NULL to caller --- */
/*end_of_job:*/
if (mctx->msglevel >= 9 && mctx->msgfp != NULL) { /* debuging */
fprintf(mctx->msgfp, "rastopenfile> returning fopen(%s,%s) = %s\n",
filename, amode, (fp == NULL ? "NULL" : "Okay"));
fflush(mctx->msgfp);
}
/* return fp or NULL to caller */
return (fp);
} /* --- end-of-function rastopenfile() --- */
/* ==========================================================================
* Function: rastreadfile ( filename, islock, tag, value )
* Purpose: Read filename, returning value as string
* between <tag>...</tag> or entire file if tag=NULL passed.
* --------------------------------------------------------------------------
* Arguments: filename (I) char * to null-terminated string containing
* name of file to read (preceded by path
* relative to mimetex executable)
* islock (I) int containing 1 to lock file while reading
* (hopefully done by opening in "r+" mode)
* tag (I) char * to null-terminated string containing
* html-like tagname. File contents between
* <tag> and </tag> will be returned, or
* entire file if tag=NULL passed.
* value (O) char * returning value between <tag>...</tag>
* or entire file if tag=NULL.
* --------------------------------------------------------------------------
* Returns: ( int ) 1=okay, 0=some error
* --------------------------------------------------------------------------
* Notes: o
* ======================================================================= */
/* --- entry point --- */
int rastreadfile(mimetex_ctx *mctx, char *filename, int islock, char *tag, char *value)
{
/* ------------------------------------------------------------
Allocations and Declarations
------------------------------------------------------------ */
/* pointer to opened filename */
FILE *fp = (FILE *)NULL;
char texfile[1024] = "\000", /* local copy of input filename */
text[MAXLINESZ+1]; /* line from input file */
char *tagp, tag1[1024], tag2[1024]; /* left <tag> and right <tag/> */
/* #chars in value, max allowed */
int vallen = 0, maxvallen = MAXFILESZ;
/* status returned, 1=okay */
int status = (-1);
/* tag we're looking for */
int tagnum = 0;
/*int islock = 1;*/ /* true to lock file */
/* ------------------------------------------------------------
Open file
------------------------------------------------------------ */
/* --- first check output arg --- */
/* no output buffer supplied */
if (value == (char *)NULL) goto end_of_job;
/* init buffer with empty string */
*value = '\000';
/* --- open filename or filename.tex --- */
if (filename != (char *)NULL) { /* make sure we got filename arg */
/* local copy of filename */
strncpy(texfile, filename, 1023);
/* make sure it's null terminated */
texfile[1023] = '\000';
fp = rastopenfile(mctx, texfile, (islock ? "r+" : "r"));
} /* try opening it */
/* --- check that file opened --- */
if (fp == (FILE *)NULL) { /* failed to open file */
sprintf(value, "{\\normalsize\\rm[file %s?]}", texfile);
goto end_of_job;
} /* return error message to caller */
/* file opened successfully */
status = 0;
/* start at beginning of file */
if (islock) rewind(fp);
/* ------------------------------------------------------------
construct <tag>'s
------------------------------------------------------------ */
if (tag != (char *)NULL) /* caller passed tag arg */
if (*tag != '\000') { /* and it's not an empty string */
strcpy(tag1, "<");
strcpy(tag2, "</"); /* begin with < and </ */
strcat(tag1, tag);
/* followed by caller's tag */
strcat(tag2, tag);
strcat(tag1, ">");
/* ending both tags with > */
strcat(tag2, ">");
compress(tag1, ' ');
/* remove embedded blanks */
compress(tag2, ' ');
tagnum = 1;
} /* signal that we have tag */
/* ------------------------------------------------------------
Read file, concatnate lines
------------------------------------------------------------ */
while (fgets(text, MAXLINESZ - 1, fp) != (char *)NULL) { /*read input till eof*/
switch (tagnum) { /* look for left- or right-tag */
case 0:
status = 1;
/* no tag to look for */
break;
case 1: /* looking for opening left <tag> */
/*haven't found it yet*/
if ((tagp = strstr(text, tag1)) == NULL) break;
/* shift out preceding text */
strcpy(text, tagp + strlen(tag1));
/*now looking for closing right tag*/
tagnum = 2;
case 2: /* looking for closing right </tag> */
/*haven't found it yet*/
if ((tagp = strstr(text, tag2)) == NULL) break;
/* terminate line at tag */
*tagp = '\000';
/* done after this line */
tagnum = 3;
/* successfully read tag */
status = 1;
break;
} /* ---end-of-switch(tagnum) --- */
if (tagnum != 1) { /* no tag or left tag already found*/
/* #chars in current line */
int textlen = strlen(text);
/* quit before overflow */
if (vallen + textlen > maxvallen) break;
/* concat line to end of value */
strcat(value, text);
/* bump length */
vallen += textlen;
if (tagnum > 2) break;
} /* found right tag, so we're done */
} /* --- end-of-while(fgets()!=NULL) --- */
/* okay if no tag or we found tag */
if (tagnum < 1 || tagnum > 2) status = 1;
/* close input file after reading */
fclose(fp);
/* --- return value and status to caller --- */
end_of_job:
/* return status to caller */
return (status);
} /* --- end-of-function rastreadfile() --- */
/* ==========================================================================
* Function: rastwritefile ( filename, tag, value, isstrict )
* Purpose: Re/writes filename, replacing string between <tag>...</tag>
* with value, or writing entire file as value if tag=NULL.
* --------------------------------------------------------------------------
* Arguments: filename (I) char * to null-terminated string containing
* name of file to write (preceded by path
* relative to mimetex executable)
* tag (I) char * to null-terminated string containing
* html-like tagname. File contents between
* <tag> and </tag> will be replaced, or
* entire file written if tag=NULL passed.
* value (I) char * containing string replacing value
* between <tag>...</tag> or replacing entire
* file if tag=NULL.
* isstrict (I) int containing 1 to only rewrite existing
* files, or 0 to create new file if necessary.
* --------------------------------------------------------------------------
* Returns: ( int ) 1=okay, 0=some error
* --------------------------------------------------------------------------
* Notes: o
* ======================================================================= */
/* --- entry point --- */
int rastwritefile(mimetex_ctx *mctx, char *filename, char *tag, char *value, int isstrict)
{
/* ------------------------------------------------------------
Allocations and Declarations
------------------------------------------------------------ */
char *timestamp();
FILE *rastopenfile();
int rastreadfile();
/* pointer to opened filename */
FILE *fp = (FILE *)NULL;
char texfile[1024] = "\000"; /* local copy of input filename */
char filebuff[MAXFILESZ+1] = "\000"; /* entire contents of file */
char tag1[1024], tag2[1024]; /* left <tag> and right <tag/> */
int istag = 0,
isnewfile = 0, /* true if writing new file */
status = 0; /* status returned, 1=okay */
/* true to update <timestamp> tag */
int istimestamp = 0;
/* ------------------------------------------------------------
check args
------------------------------------------------------------ */
/* --- check filename and value --- */
if (filename == (char *)NULL /* quit if no filename arg supplied*/
/* or no value arg supplied */
|| value == (char *)NULL) goto end_of_job;
if (strlen(filename) < 2 /* quit if unreasonable filename */
/* or empty value string supplied */
|| *value == '\000') goto end_of_job;
/* --- establish filename[.tex] --- */
/* local copy of input filename */
strncpy(texfile, filename, 1023);
/* make sure it's null terminated */
texfile[1023] = '\000';
if (rastopenfile(mctx, texfile, NULL) /* unchanged or .tex appended */
== (FILE *)NULL) { /* can't open, so write new file */
/* fail if new files not permitted */
if (isstrict) goto end_of_job;
isnewfile = 1;
} /* signal we're writing new file */
/* --- check whether tag supplied by caller --- */
if (tag != (char *)NULL) /* caller passed tag argument */
if (*tag != '\000') { /* and it's not an empty string */
/* so flip tag flag true */
istag = 1;
strcpy(tag1, "<");
strcpy(tag2, "</"); /* begin tags with < and </ */
strcat(tag1, tag);
/* followed by caller's tag */
strcat(tag2, tag);
strcat(tag1, ">");
/* ending both tags with > */
strcat(tag2, ">");
compress(tag1, ' ');
compress(tag2, ' ');
} /* remove embedded blanks */
/* ------------------------------------------------------------
read existing file if just rewriting a single tag
------------------------------------------------------------ */
/* --- read original file if only replacing a tag within it --- */
/* init as empty file */
*filebuff = '\000';
if (!isnewfile) /* if file already exists */
if (istag) /* and just rewriting one tag */
if (rastreadfile(mctx, texfile, 1, NULL, filebuff) /* read entire existing file */
/* signal error if failed to read */
<= 0) goto end_of_job;
/* ------------------------------------------------------------
construct new file data if needed (entire file replaced by value if no tag)
------------------------------------------------------------ */
if (istag) { /* only replacing tag in file */
/* --- find <tag> and </tag> in file --- */
/*tag,buff lengths*/
int tlen1 = strlen(tag1), tlen2 = strlen(tag2), flen;
char *tagp1 = (isnewfile ? NULL : strstr(filebuff, tag1)), /* <tag> in file*/
*tagp2 = (isnewfile ? NULL : strstr(filebuff, tag2)); /*</tag> in file*/
/* --- if adding new <tag> just concatanate at end of file --- */
if (tagp1 == (char *)NULL) { /* add new tag to file */
/* --- preprocess filebuff --- */
if (tagp2 != (char *)NULL) /* apparently have ...</tag> */
strcpy(filebuff, tagp2 + tlen2); /* so get rid of leading ...</tag> */
if ((flen = strlen(filebuff)) /* #chars currently in buffer */
> 0) /* we have non-empty buffer */
if (!isthischar(*(filebuff + flen - 1), "\n\r")) /*no newline at end of file*/
/* so add one before new tag */
if (0)strcat(filebuff, "\n");
/* --- add new tag --- */
/* add opening <tag> */
strcat(filebuff, tag1);
/* then value */
strcat(filebuff, value);
strcat(filebuff, tag2); /* finally closing </tag> */
/* newline at end of file */
strcat(filebuff, "\n");
} /* --- end-of-if(tagp1==NULL) --- */
else { /* found existing opening <tag> */
if (tagp2 == NULL) { /* apparently have <tag>... */
/* so get rid of trailing ... */
*(tagp1 + tlen1) = '\000';
/* then concatanate value */