forked from samcleaver/phpGSB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphpgsb.class.php
1401 lines (1376 loc) · 47 KB
/
phpgsb.class.php
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
<?php
/*
phpGSB - PHP Google Safe Browsing Implementation
Version 0.2.4
Released under New BSD License (see LICENSE)
Copyright (c) 2010-2012, Sam Cleaver (Beaver6813, Beaver6813.com)
All rights reserved.
*/
ob_start();
class phpGSB
{
var $apikey = "";
var $version = "0.2";
var $realversion= "0.2.4";
//DO NOT CHANGE API VERSION
var $apiversion = "2.2";
var $ob = "";
var $adminemail = "";
var $usinglists = array('googpub-phish-shavar','goog-malware-shavar');
var $mainlist = array();
var $verbose = true;
var $transtarted= false;
var $transenabled=true;
var $pingfilepath=""; //This is the path used to store the ping/last update files. (Must inc. trailing slash)
//GENERIC FUNCTIONS (USED BY BOTH LOOKUP AND UPDATER)
/*Automatically connect to database on calling class*/
function phpGSB($database=false,$username=false,$password=false,$host="localhost",$verbose=true)
{
if(!$verbose)
$this->silent();
$this->outputmsg("phpGSB Loaded");
if($database&&$username)
$this->dbConnect($database,$username,$password,$host);
}
function close()
{
mysql_close();
$this->outputmsg("Closing phpGSB. (Peak Memory: ".(round(memory_get_peak_usage()/1048576,3))."MB)");
}
function silent()
{
$this->verbose = false;
}
function trans_disable()
{
$this->transenabled = false;
}
function trans_enable()
{
$this->transenabled = true;
}
function trans_begin()
{
if($this->transenabled)
{
$this->transtarted = true;
$this->outputmsg("Begin MySQL Transaction");
mysql_query("BEGIN");
}
}
function trans_commit()
{
if($this->transtarted&&mysql_ping()&&$this->transenabled)
{
$this->transtarted = false;
$this->outputmsg("Comitting Transaction");
mysql_query("COMMIT");
}
}
function trans_rollback()
{
if($this->transtarted&&mysql_ping()&&$this->transenabled)
{
$this->transtarted = false;
$this->outputmsg("Rolling Back Transaction");
mysql_query("ROLLBACK");
}
}
/*Function to output messages, used instead of echo,
will make it easier to have a verbose switch in later
releases*/
function outputmsg($msg)
{
if($this->verbose)
{
echo $msg.'...<br/>';
$this->ob .= ob_get_contents();
ob_flush();
}
}
/*Function to output errors, used instead of echo,
will make it easier to have a verbose switch in later
releases*/
function fatalerror($msg)
{
if($this->verbose)
{
print_r($msg);
echo '...<br/>';
$this->ob .= ob_get_contents();
ob_end_flush();
}
$this->trans_rollback();
die();
}
/*Wrapper to connect to database. Simples.*/
function dbConnect($database,$username,$password,$host="localhost")
{
$link = mysql_connect($host, $username, $password);
if (!$link) {
$this->fatalerror('Could not connect: ' . mysql_error());
}
$this->outputmsg('Connected successfully to database server');
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
$this->fatalerror('Can\'t use $database : ' . mysql_error());
}
$this->outputmsg('Connected to database successfully');
}
/*Simple logic function to calculate timeout
based on the number of previous errors*/
function calc($errors)
{
//According to Developer Guide Formula
if($errors==1)
{
//According to Developer Guide (1st error, wait a minute)
return 60;
}
elseif($errors>5)
{
//According to Developer Guide (Above 5 errors check every 4 hours)
return 28800;
}
else
{
//According to Developer Guide we simply double up our timeout each time and use formula:
//(Adapted to be relative to errors) ( ((2^$errors) * 7.5) * (decimalrand(0,1) + 1)) to produce
// a result between: 120min-240min for example
return floor((pow(2,$errors) * 7.5) * ((rand(0,1000)/1000) + 1));
}
}
/*Writes backoff timeouts, uses calc() to
calculate timeouts and then writes to file
for next check*/
function Backoff($errdata=false,$type)
{
if($type=="data")
$file = 'nextcheck.dat';
else
$file = 'nextcheckl.dat';
$curstatus = explode('||',file_get_contents($this->pingfilepath.$file));
$curstatus[1] = $curstatus[1] + 1;
$seconds = $this->calc($curstatus[1]);
$until = time()+$seconds.'||'.$curstatus[1];
file_put_contents($this->pingfilepath.$file,$until);
$this->fatalerror(array("Invalid Response... Backing Off",$errdata));
}
/*Writes timeout from valid requests to nextcheck file*/
function setTimeout($seconds)
{
if (file_exists($this->pingfilepath.'nextcheck.dat')) {
$curstatus = explode('||',@file_get_contents($this->pingfilepath.'nextcheck.dat'));
$until = time()+$seconds.'||'.$curstatus[1];
} else {
$until = time()+$seconds.'||';
}
file_put_contents($this->pingfilepath.'nextcheck.dat',$until);
}
/*Checks timeout in timeout files (usually performed at the
start of script)*/
function checkTimeout($type)
{
if($type=="data")
$file = 'nextcheck.dat';
else
$file = 'nextcheckl.dat';
$curstatus = explode('||',file_get_contents($this->pingfilepath.$file));
if(time()<$curstatus[0])
{
$this->fatalerror("Must wait another ".($curstatus[0]-time()). " seconds before another request");
}
else
$this->outputmsg("Allowed to request");
}
/*Function downloads from URL's, POST data can be
passed via $options. $followbackoff indicates
whether to follow backoff procedures or not*/
function googleDownloader($url,$options,$followbackoff=false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(is_array($options))
curl_setopt_array($ch, $options);
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if($followbackoff&&$info['http_code']>299)
{
$this->Backoff($info,$followbackoff);
}
return array($info,$data);
}
//UPDATER FUNCTIONS
/*Resets lists database, only called if GSB issues r:resetdatabase*/
function resetDatabase()
{
//Lord knows why they would EVER issue this request!
if(!empty($this->adminemail))
mail($this->adminemail,'Reset Database Request Issued','For some crazy unknown reason GSB requested a database reset at '.time());
foreach($this->usinglists as $value)
{
mysql_query("TRUNCATE TABLE `$value-s-index`");
mysql_query("TRUNCATE TABLE `$value-s-hosts`");
mysql_query("TRUNCATE TABLE `$value-s-prefixes`");
mysql_query("TRUNCATE TABLE `$value-a-index`");
mysql_query("TRUNCATE TABLE `$value-a-hosts`");
mysql_query("TRUNCATE TABLE `$value-a-prefixes`");
}
}
/*Processes data recieved from a GSB data request into a managable array*/
function processChunks($fulldata,$listname)
{
$subarray = array();
$addarray = array();
$loaddata = trim($fulldata);
$clonedata = $loaddata;
while(strlen($clonedata)>0)
{
$splithead = explode("\n",$clonedata,2);
$chunkinfo = explode(':',$splithead[0]);
$type = $chunkinfo[0];
$chunknum = $chunkinfo[1];
$hashlen = $chunkinfo[2];
$chunklen = $chunkinfo[3];
if($chunklen>0)
{
$tmparray = array();
//Convert to hex for easy processing
//First get chunkdata according to length
$chunkdata = bin2hex(substr($splithead[1],0,$chunklen));
if($type=='a')
{
$maini = 0;
while(strlen($chunkdata)>0)
{
$tmparray[$maini]['HOSTKEY'] = substr($chunkdata, 0, 8);
$tmparray[$maini]['COUNT'] = substr($chunkdata, 8, 2);
$chunkdata = substr($chunkdata,10);
$realcount = hexdec($tmparray[$maini]['COUNT']);
if($realcount>0)
{
for ($i = 0; $i < $realcount; $i++) {
$tmparray[$maini]['PAIRS'][$i]['PREFIX'] = substr($chunkdata, 0, ($hashlen*2));
$chunkdata = substr($chunkdata,(($hashlen*2)));
}
}
elseif($realcount<0)
{
$this->fatalerror(array("Decoding Error, Somethings gone wrong!",$tmparray[$maini]));
}
$maini++;
}
$addarray['CHUNKNUM'] = $chunknum;
$addarray['HASHLEN'] = $hashlen;
$addarray['CHUNKLEN'] = $chunklen;
$addarray['REAL'] = $tmparray;
$this->saveChunkPart($addarray,"ADD",$listname);
unset($addarray);
}
elseif($type=='s')
{
$maini = 0;
while(strlen($chunkdata)>0)
{
$tmparray[$maini]['HOSTKEY'] = substr($chunkdata, 0, 8);
$tmparray[$maini]['COUNT'] = substr($chunkdata, 8, 2);
$chunkdata = substr($chunkdata,10);
$realcount = hexdec($tmparray[$maini]['COUNT']);
if($realcount>0)
{
for ($i = 0; $i < $realcount; $i++) {
$tmparray[$maini]['PAIRS'][$i]['ADDCHUNKNUM'] = substr($chunkdata, 0, 8);
$tmparray[$maini]['PAIRS'][$i]['PREFIX'] = substr($chunkdata, 8, ($hashlen*2));
$chunkdata = substr($chunkdata,(($hashlen*2)+8));
}
}
elseif($realcount==0)
{
$tmparray[$maini]['PAIRS'][0]['ADDCHUNKNUM'] = substr($chunkdata, 0, 8);
$chunkdata = substr($chunkdata, 8);
}
else
{
$this->fatalerror(array("Decoding Error, Somethings gone wrong!",$tmparray[$maini]));
}
$maini++;
}
$subarray['CHUNKNUM'] = $chunknum;
$subarray['HASHLEN'] = $hashlen;
$subarray['CHUNKLEN'] = $chunklen;
$subarray['REAL'] = $tmparray;
$this->saveChunkPart($subarray,"SUB",$listname);
unset($subarray);
}
else
{
$this->outputmsg("DISCARDED CHUNKNUM: $chunknum (Had no valid label)");
}
}
else
{
//No ChunkData, Still Insert
if($type=='a')
{
$addarray['CHUNKNUM'] = $chunknum;
$addarray['HASHLEN'] = $hashlen;
$addarray['CHUNKLEN'] = $chunklen;
$this->saveChunkPart($addarray,"ADD",$listname);
unset($addarray);
}
elseif($type=='s')
{
$subarray['CHUNKNUM'] = $chunknum;
$subarray['HASHLEN'] = $hashlen;
$subarray['CHUNKLEN'] = $chunklen;
$this->saveChunkPart($subarray,"SUB",$listname);
unset($subarray);
}
else
{
$this->outputmsg("DISCARDED CHUNKNUM: $chunknum (Empty)");
}
}
$clonedata = substr($splithead[1],$chunklen);
}
return true;
}
/*Saves processed data to the MySQL database*/
function saveChunkPart($data,$type,$listname)
{
$listname = trim($listname);
//Check what type of data it is...
$buildindex = array();
$buildhost = array();
$buildpairs = array();
if($type=="SUB")
{
$value = $data;
if(!isset($this->mainlist['s'][$listname][$value['CHUNKNUM']]))
{
$this->mainlist['s'][$listname][$value['CHUNKNUM']] = true;
$buildindex[] = "('{$value['CHUNKNUM']}','{$value['CHUNKLEN']}')";
if($value['CHUNKLEN']>0)
{
foreach($value['REAL'] as $newkey=>$newvalue)
{
$buildhost[] = "('{$newvalue['HOSTKEY']}','{$value['CHUNKNUM']}','{$newvalue['COUNT']}','')";
if(isset($newvalue['PAIRS'])&&count($newvalue['PAIRS'])>0)
{
foreach($newvalue['PAIRS'] as $innerkey=>$innervalue)
{
if( isset($innervalue['PREFIX']) ) {
$buildpairs[] = "('{$newvalue['HOSTKEY']}','{$innervalue['ADDCHUNKNUM']}','{$innervalue['PREFIX']}','')";
} else {
$buildpairs[] = "('{$newvalue['HOSTKEY']}','{$innervalue['ADDCHUNKNUM']}','','')";
}
}
}
}
}
}
}
else if($type=="ADD")
{
//Then lets insert add data
$value = $data;
if(!isset($this->mainlist['a'][$listname][$value['CHUNKNUM']]))
{
$this->mainlist['a'][$listname][$value['CHUNKNUM']] = true;
$buildindex[] = "('{$value['CHUNKNUM']}','{$value['CHUNKLEN']}')";
if($value['CHUNKLEN']>0)
{
foreach($value['REAL'] as $newkey=>$newvalue)
{
$buildhost[] = "('{$newvalue['HOSTKEY']}','{$value['CHUNKNUM']}','{$newvalue['COUNT']}','')";
if(isset($newvalue['PAIRS'])&&count($newvalue['PAIRS'])>0)
{
foreach($newvalue['PAIRS'] as $innerkey=>$innervalue)
{
if( isset($innervalue['PREFIX']) ) {
$buildpairs[] = "('{$newvalue['HOSTKEY']}','{$innervalue['PREFIX']}','')";
} else {
$buildpairs[] = "('{$newvalue['HOSTKEY']}','','')";
}
}
}
}
}
}
}
if(count($buildindex)>0)
{
if($type=="ADD")
$listtype = 'a';
elseif($type=="SUB")
$listtype = 's';
//Insert index value
$indexinsert = implode(', ',$buildindex);
$indexins = mysql_query("INSERT INTO `$listname-$listtype-index` (`ChunkNum`,`Chunklen`) VALUES $indexinsert;");
$error = mysql_error();
if($indexins)
{
if(count($buildhost)>0)
{
//Insert hostkeys index
$hostinsert = implode(', ',$buildhost);
mysql_query("INSERT INTO `$listname-$listtype-hosts` (`Hostkey`,`Chunknum`,`Count`,`FullHash`) VALUES $hostinsert;");
$error = mysql_error();
if(!empty($error))
$this->outputmsg("INSERTED $listname $type HOST KEYS ".mysql_error());
}
if(count($buildpairs)>0)
{
//Insert prefixes
$pairinsert = implode(', ',$buildpairs);
if($type=="ADD")
mysql_query("INSERT INTO `$listname-$listtype-prefixes` (`Hostkey`,`Prefix`,`FullHash`) VALUES $pairinsert;");
elseif($type=="SUB")
mysql_query("INSERT INTO `$listname-$listtype-prefixes` (`Hostkey`,`AddChunkNum`,`Prefix`,`FullHash`) VALUES $pairinsert;");
$error = mysql_error();
if(!empty($error))
$this->outputmsg("INSERTED $listname $type PREFIX HOST KEYS ".mysql_error());
}
}
elseif(!empty($error))
$this->outputmsg("COULD NOT SAVE $listname $type INDEXS ".mysql_error());
}
}
/*Get ranges of existing chunks from a requested list
and type (add [a] or sub [s] return them and set
mainlist to recieved for that chunk (prevent dupes)*/
function getRanges($listname,$mode)
{
$checktable = $listname.'-'.$mode.'-index';
$results = mysql_query("SELECT ChunkNum FROM `$checktable` ORDER BY `ChunkNum` ASC");
$ranges = array();
$i = 0;
$start = 0;
while ($row = mysql_fetch_array($results, MYSQL_BOTH))
{
$this->mainlist[$mode][$listname][$row['ChunkNum']] = true;
if($i==0)
{
$start = $row['ChunkNum'];
$previous = $row['ChunkNum'];
}
else
{
$expected = $previous + 1;
if($row['ChunkNum']!=$expected)
{
if($start==$previous)
$ranges[] = $start;
else
$ranges[] = $start.'-'.$previous;
$start = $row['ChunkNum'];
}
$previous = $row['ChunkNum'];
}
$i++;
}
if($start>0&&$previous>0)
{
if($start==$previous)
$ranges[] = $start;
else
$ranges[] = $start.'-'.$previous;
}
return $ranges;
}
/*Get both add and sub ranges for a requested list*/
function getFullRanges($listname)
{
$subranges = $this->getRanges($listname,'s');
$addranges = $this->getRanges($listname,'a');
return array("Subranges"=>$subranges,"Addranges"=>$addranges);
}
/*Format a full request body for a desired list including
name and full ranges for add and sub*/
function formattedRequest($listname)
{
$fullranges = $this->getFullRanges($listname);
$buildpart = '';
if(count($fullranges['Subranges'])>0)
$buildpart .= 's:'.implode(',',$fullranges['Subranges']);
if(count($fullranges['Subranges'])>0&&count($fullranges['Addranges'])>0)
$buildpart .= ':';
if(count($fullranges['Addranges'])>0)
$buildpart .= 'a:'.implode(',',$fullranges['Addranges']);
return $listname.';'.$buildpart."\n";
}
/*Called when GSB returns a SUB-DEL or ADD-DEL response*/
function deleteRange($range,$mode,$listname)
{
$buildtrunk = $listname.'-'.$mode;
if(substr_count($range,'-')>0)
{
$deleterange = explode('-',trim($range));
$clause = "`ChunkNum` >= '{$deleterange[0]}' AND `ChunkNum` <= '{$deleterange[1]}'";
}
else
$clause = "`ChunkNum` = '$range'";
//Delete from index
mysql_query("DELETE FROM `$buildtrunk-index` WHERE $clause");
//Select all host keys that match chunks (we'll delete them after but we need the hostkeys list!)
$result = mysql_query("SELECT `Hostkey` FROM `$buildtrunk-hosts` WHERE $clause");
$buildprefixdel = array();
if($result&&mysql_num_rows($result)>0)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if(!empty($row['Hostkey']))
$buildprefixdel[] = $row['Hostkey'];
}
$mergeprefixdel = implode("' OR `Hostkey` = '",$buildprefixdel);
//Delete all matching hostkey prefixes
mysql_query("DELETE FROM `$buildtrunk-prefixes` WHERE `Hostkey` = '$mergeprefixdel'");
//Delete all matching hostkeys
mysql_query("DELETE FROM `$buildtrunk-hosts` WHERE $clause");
}
}
/*Main part of updater function, will call all other functions, merely requires
the request body, it will then process and save all data as well as checking
for ADD-DEL and SUB-DEL, runs silently so won't return anything on success*/
function getData($body)
{
if(empty($body))
$this->fatalerror("Missing a body for data request");
$this->trans_begin();
$buildopts = array(CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$body."\n");
$result = $this->googleDownloader("http://safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=".$this->apikey."&appver=".$this->version."&pver=".$this->apiversion,$buildopts,"data");
preg_match('/^n:(.*)$/m', $result[1], $match);
$timeout = $match[1];
$this->setTimeout($timeout);
if(substr_count($result[1],'r:pleasereset')>0)
$this->resetDatabase();
else
{
$formattedlist = array();
if(substr_count($result[1],'i:')>0)
{
$splitlists = explode('i:',$result[1]);
unset($splitlists[0]);
foreach($splitlists as $key=>$value)
{
$listdata = explode("\n",trim($value));
$listname = $listdata[0];
unset($listdata[0]);
$formattedlist[$listname] = $listdata;
}
foreach($formattedlist as $key=>$value)
{
$listname = $key;
foreach($value as $keyinner=>$valueinner)
{
if(substr_count($valueinner,"u:")>0)
{
$chunkdata = $this->googleDownloader('http://'.trim(str_replace('u:','',$valueinner)),false,"data");
$processed = $this->processChunks($chunkdata[1],$listname);
$this->outputmsg("Saved a chunk file");
}
elseif(substr_count($valueinner,"ad:")>0)
{
if(substr_count($valueinner,',')>0)
{
$valueinner = explode(',',trim(str_replace("ad:","",$valueinner)));
foreach($valueinner as $keyadd=>$valueadd)
{
$this->deleteRange($valueadd,'a',$listname);
}
}
else
$this->deleteRange(trim(str_replace("ad:","",$valueinner)),'a',$listname);
}
elseif(substr_count($valueinner,"sd:")>0)
{
if(substr_count($valueinner,',')>0)
{
$valueinner = explode(',',trim(str_replace("sd:","",$valueinner)));
foreach($valueinner as $keyadd=>$valueadd)
{
$this->deleteRange($valueadd,'s',$listname);
}
}
else
$this->deleteRange(trim(str_replace("sd:","",$valueinner)),'s',$listname);
}
}
}
}
else
{
$this->outputmsg('No data available in list');
}
}
$this->trans_commit();
return true;
}
/*Shortcut to run updater*/
function runUpdate()
{
$this->checkTimeout('data');
$require = "";
foreach($this->usinglists as $value)
$require .= $this->formattedRequest($value);
$this->outputmsg("Using $require");
$this->getData($require);
}
//LOOKUP FUNCTIONS
/*Used to check the canonicalize function*/
function validateMethod()
{
//Input => Expected
$cases = array(
"http://host/%25%32%35" => "http://host/%25",
"http://host/%25%32%35%25%32%35" => "http://host/%25%25",
"http://host/%2525252525252525" => "http://host/%25",
"http://host/asdf%25%32%35asd" => "http://host/asdf%25asd",
"http://host/%%%25%32%35asd%%" => "http://host/%25%25%25asd%25%25",
"http://www.google.com/" => "http://www.google.com/",
"http://%31%36%38%2e%31%38%38%2e%39%39%2e%32%36/%2E%73%65%63%75%72%65/%77%77%77%2E%65%62%61%79%2E%63%6F%6D/" => "http://168.188.99.26/.secure/www.ebay.com/",
"http://195.127.0.11/uploads/%20%20%20%20/.verify/.eBaysecure=updateuserdataxplimnbqmn-xplmvalidateinfoswqpcmlx=hgplmcx/" => "http://195.127.0.11/uploads/%20%20%20%20/.verify/.eBaysecure=updateuserdataxplimnbqmn-xplmvalidateinfoswqpcmlx=hgplmcx/",
"http://host%23.com/%257Ea%2521b%2540c%2523d%2524e%25f%255E00%252611%252A22%252833%252944_55%252B" => 'http://host%23.com/~a!b@c%23d$e%25f^00&11*22(33)44_55+',
"http://3279880203/blah" => "http://195.127.0.11/blah",
"http://www.google.com/blah/.." => "http://www.google.com/",
"www.google.com/" => "http://www.google.com/",
"www.google.com" => "http://www.google.com/",
"http://www.evil.com/blah#frag" => "http://www.evil.com/blah",
"http://www.GOOgle.com/" => "http://www.google.com/",
"http://www.google.com.../" => "http://www.google.com/",
"http://www.google.com/foo\tbar\rbaz\n2" => "http://www.google.com/foobarbaz2",
"http://www.google.com/q?" => "http://www.google.com/q?",
"http://www.google.com/q?r?" => "http://www.google.com/q?r?",
"http://www.google.com/q?r?s" => "http://www.google.com/q?r?s",
"http://evil.com/foo#bar#baz" => "http://evil.com/foo",
"http://evil.com/foo;" => "http://evil.com/foo;",
"http://evil.com/foo?bar;" => "http://evil.com/foo?bar;",
"http://\x01\x80.com/" => "http://%01%80.com/",
"http://notrailingslash.com" => "http://notrailingslash.com/",
"http://www.gotaport.com:1234/" => "http://www.gotaport.com:1234/",
" http://www.google.com/ " => "http://www.google.com/",
"http:// leadingspace.com/" => "http://%20leadingspace.com/",
"http://%20leadingspace.com/" => "http://%20leadingspace.com/",
"%20leadingspace.com/" => "http://%20leadingspace.com/",
"https://www.securesite.com/" => "https://www.securesite.com/",
"http://host.com/ab%23cd" => "http://host.com/ab%23cd",
"http://host.com//twoslashes?more//slashes" => "http://host.com/twoslashes?more//slashes"
);
foreach($cases as $key=>$value)
{
$canit = $this->Canonicalize($key);
$canit = $canit['GSBURL'];
if($canit==$value)
outputmsg("<span style='color:green'>PASSED: $key</span>");
else
outputmsg("<span style='color:red'>INVALID: <br>ORIGINAL: $key<br>EXPECTED: $value<br>RECIEVED: $canit<br> </span>");
}
}
/*Special thanks Steven Levithan (stevenlevithan.com) for the ridiculously complicated regex
required to parse urls. This is used over parse_url as it robustly provides access to
port, userinfo etc and handles mangled urls very well.
Expertly integrated into phpGSB by Sam Cleaver ;)
Thanks to mikegillis677 for finding the seg. fault issue in the old function.
Passed validateMethod() check on 17/01/12*/
function j_parseUrl($url)
{
$strict = '/^(?:([^:\/?#]+):)?(?:\/\/\/?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?(((?:\/(\w:))?((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/';
$loose = '/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((?:\/(\w:))?(\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/';
preg_match($loose, $url, $match);
if(empty($match))
{
//As odd as its sounds, we'll fall back to strict (as technically its more correct and so may salvage completely mangled urls)
unset($match);
preg_match($strict, $url, $match);
}
$parts = array("source"=>'',"scheme"=>'',"authority"=>'',"userinfo"=>'',"user"=>'',"password"=>'',"host"=>'',"port"=>'',"relative"=>'',"path"=>'',"drive"=>'',"directory"=>'',"file"=>'',"query"=>'',"fragment"=>'');
switch (count ($match)) {
case 15: $parts['fragment'] = $match[14];
case 14: $parts['query'] = $match[13];
case 13: $parts['file'] = $match[12];
case 12: $parts['directory'] = $match[11];
case 11: $parts['drive'] = $match[10];
case 10: $parts['path'] = $match[9];
case 9: $parts['relative'] = $match[8];
case 8: $parts['port'] = $match[7];
case 7: $parts['host'] = $match[6];
case 6: $parts['password'] = $match[5];
case 5: $parts['user'] = $match[4];
case 4: $parts['userinfo'] = $match[3];
case 3: $parts['authority'] = $match[2];
case 2: $parts['scheme'] = $match[1];
case 1: $parts['source'] = $match[0];
}
return $parts;
}
/*Regex to check if its a numerical IP address*/
function is_ip($ip)
{
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .
"(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
/*Checks if input is in hex format*/
function is_hex($x)
{
//Relys on the fact that hex often includes letters meaning PHP will disregard the string
if(($x+3) == 3)
return dechex(hexdec($x)) == $x;
return false;
}
/*Checks if input is in octal format*/
function is_octal($x)
{
//Relys on the fact that in IP addressing octals must begin with a 0 to denote octal
return substr($x,0,1) == 0;
}
/*Converts hex or octal input into decimal */
function hexoct2dec($value)
{
//As this deals with parts in IP's we can be more exclusive
if(substr_count(substr($value,0,2),'0x')>0&&$this->is_hex($value))
{
return hexdec($value);
}
elseif($this->is_octal($value))
{
return octdec($value);
}
else
return false;
}
/*Converts IP address part in HEX to decimal*/
function iphexdec($hex)
{
//Removes any leading 0x (used to denote hex) and then and leading 0's)
$temp = str_replace('0x','',$hex);
$temp = ltrim($temp,"0");
return hexdec($temp);
}
/*Converts full IP address in HEX to decimal*/
function hexIPtoIP($hex)
{
//Remove hex identifier and leading 0's (not significant)
$tempip = str_replace('0x','',$hex);
$tempip = ltrim($tempip,"0");
//It might be hex
if($this->is_hex($tempip))
{
//There may be a load of junk before the part we need
if(strlen($tempip)>8)
{
$tempip = substr($tempip,-8);
}
$hexplode = preg_split('//', $tempip, -1, PREG_SPLIT_NO_EMPTY);
while(count($hexplode)<8)
array_unshift($hexplode,0);
//Normalise
$newip = hexdec($hexplode[0].$hexplode[1]).'.'.hexdec($hexplode[2].$hexplode[3]).'.'.hexdec($hexplode[4].$hexplode[5]).'.'.hexdec($hexplode[6].$hexplode[7]);
//Now check if its an IP
if($this->is_ip($newip))
return $newip;
else
return false;
}
else
return false;
}
/*Checks if an IP provided in either hex, octal or decimal is in fact
an IP address. Normalises to a four part IP address.*/
function isValid_IP($ip)
{
//First do a simple check, if it passes this no more needs to be done
if($this->is_ip($ip))
return $ip;
//Its a toughy... eerm perhaps its all in hex?
$checkhex = $this->hexIPtoIP($ip);
if($checkhex)
return $checkhex;
//If we're still here it wasn't hex... maybe a DWORD format?
$checkdword = $this->hexIPtoIP(dechex($ip));
if($checkdword)
return $checkdword;
//Nope... maybe in octal or a combination of standard, octal and hex?!
$ipcomponents = explode('.',$ip);
$ipcomponents[0] = $this->hexoct2dec($ipcomponents[0]);
if(count($ipcomponents)==2)
{
//The writers of the RFC docs certainly didn't think about the clients! This could be a DWORD mixed with an IP part
if($ipcomponents[0]<=255&&is_int($ipcomponents[0])&&is_int($ipcomponents[1]))
{
$threeparts = dechex($ipcomponents[1]);
$hexplode = preg_split('//', $threeparts, -1, PREG_SPLIT_NO_EMPTY);
if(count($hexplode)>4)
{
$newip = $ipcomponents[0].'.'.$this->iphexdec($hexplode[0].$hexplode[1]).'.'.$this->iphexdec($hexplode[2].$hexplode[3]).'.'.$this->iphexdec($hexplode[4].$hexplode[5]);
//Now check if its valid
if($this->is_ip($newip))
return $newip;
}
}
}
$ipcomponents[1] = $this->hexoct2dec($ipcomponents[1]);
if(count($ipcomponents)==3)
{
//Guess what... it could also be a DWORD mixed with two IP parts!
if(($ipcomponents[0]<=255&&is_int($ipcomponents[0]))&&($ipcomponents[1]<=255&&is_int($ipcomponents[1]))&&is_int($ipcomponents[2]))
{
$twoparts = dechex($ipcomponents[2]);
$hexplode = preg_split('//', $twoparts, -1, PREG_SPLIT_NO_EMPTY);
if(count($hexplode)>3)
{
$newip = $ipcomponents[0].'.'.$ipcomponents[1].'.'.$this->iphexdec($hexplode[0].$hexplode[1]).'.'.$this->iphexdec($hexplode[2].$hexplode[3]);
//Now check if its valid
if($this->is_ip($newip))
return $newip;
}
}
}
//If not it may be a combination of hex and octal
if(count($ipcomponents)>=4)
{
$tmpcomponents = array($ipcomponents[2],$ipcomponents[3]);
foreach($tmpcomponents as $key=>$value)
{
if(!$tmpcomponents[$key] = $this->hexoct2dec($value))
return false;
}
array_unshift($tmpcomponents,$ipcomponents[0],$ipcomponents[1]);
//Convert back to IP form
$newip = implode('.',$tmpcomponents);
//Now check if its valid
if($this->is_ip($newip))
return $newip;
}
//Well its not an IP that we can recognise... theres only so much we can do!
return false;
}
/*Had to write another layer as built in PHP urlencode() escapes all non
alpha-numeric Google states to only urlencode if its below 32 or above
or equal to 127 (some of those are non alpha-numeric and so urlencode
on its own won't work).*/
function flexURLEncode($url,$ignorehash=false)
{
//Had to write another layer as built in PHP urlencode() escapes all non alpha-numeric
//google states to only urlencode if its below 32 or above or equal to 127 (some of those
//are non alpha-numeric and so urlencode on its own won't work).
$urlchars = preg_split('//', $url, -1, PREG_SPLIT_NO_EMPTY);
if(count($urlchars)>0)
{
foreach($urlchars as $key=>$value)
{
$ascii = ord($value);
if($ascii<=32||$ascii>=127||($value=='#'&&!$ignorehash)||$value=='%')
$urlchars[$key] = rawurlencode($value);
}
return implode('',$urlchars);
}
else
return $url;
}
/*Canonicalize a full URL according to Google's definition.*/
function Canonicalize($url)
{
//Remove line feeds, return carriages, tabs, vertical tabs
$finalurl = trim(str_replace(array("\x09","\x0A","\x0D","\x0B"),'',$url));
//URL Encode for easy extraction
$finalurl = $this->flexURLEncode($finalurl,true);
//Now extract hostname & path
$parts = $this->j_parseUrl($finalurl);
$hostname = $parts['host'];
$path = $parts['path'];
$query = $parts['query'];
$lasthost = "";
$lastpath = "";
$lastquery = "";
//Remove all hex coding (loops max of 50 times to stop craziness but should never
//reach that)
for ($i = 0; $i < 50; $i++) {
$hostname = rawurldecode($hostname);
$path = rawurldecode($path);
$query = rawurldecode($query);
if($hostname==$lasthost&&$path==$lastpath&&$query==$lastquery)
break;
$lasthost = $hostname;
$lastpath = $path;
$lastquery = $query;
}
//Deal with hostname first
//Replace all leading and trailing dots
$hostname = trim($hostname,'.');
//Replace all consecutive dots with one dot
$hostname = preg_replace("/\.{2,}/",".",$hostname);
//Make it lowercase
$hostname = strtolower($hostname);
//See if its a valid IP
$hostnameip = $this->isValid_IP($hostname);
if($hostnameip)
{
$usingip = true;
$usehost = $hostnameip;
}
else
{
$usingip = false;
$usehost = $hostname;
}
//The developer guide has lowercasing and validating IP other way round but its more efficient to
//have it this way
//Now we move onto canonicalizing the path
$pathparts = explode('/',$path);
foreach($pathparts as $key=>$value)
{
if($value=="..")
{
if($key!=0)
{
unset($pathparts[$key-1]);
unset($pathparts[$key]);
}
else
unset($pathparts[$key]);
}
elseif($value=="."||empty($value))
unset($pathparts[$key]);
}
if(substr($path,-1,1)=="/")
$append = "/";
else
$append = false;
$path = "/".implode("/",$pathparts);
if($append&&substr($path,-1,1)!="/")
$path .= $append;
$usehost = $this->flexURLEncode($usehost);
$path = $this->flexURLEncode($path);
$query = $this->flexURLEncode($query);
if(empty($parts['scheme']))
$parts['scheme'] = 'http';
$canurl = $parts['scheme'].'://';
$realurl = $canurl;
if(!empty($parts['userinfo']))
$realurl .= $parts['userinfo'].'@';
$canurl .= $usehost;
$realurl .= $usehost;
if(!empty($parts['port']))
{
$canurl .= ':'.$parts['port'];
$realurl .= ':'.$parts['port'];
}
$canurl .= $path;
$realurl .= $path;
if(substr_count($finalurl,"?")>0)
{
$canurl .= '?'.$parts['query'];
$realurl .= '?'.$parts['query'];
}
if(!empty($parts['fragment']))
$realurl .= '#'.$parts['fragment'];
return array("GSBURL"=>$canurl,"CleanURL"=>$realurl,"Parts"=>array("Host"=>$usehost,"Path"=>$path,"Query"=>$query,"IP"=>$usingip));
}
/*SHA-256 input (short method).*/
function sha256($data)
{
return hash('sha256',$data);
}
/*Make Hostkeys for use in a lookup*/
function makeHostKey($host,$usingip)
{
if($usingip)
$hosts = array($host."/");
else
{
$hostparts = explode(".",$host);