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
|
// -*- mode: cpp; mode: fold -*-
// Description /*{{{*/
// $Id: strutl.cc,v 1.9 1998/10/30 07:53:45 jgg Exp $
/* ######################################################################
String Util - Some usefull string functions.
These have been collected from here and there to do all sorts of usefull
things to strings. They are usefull in file parsers, URI handlers and
especially in APT methods.
This source is placed in the Public Domain, do with it what you will
It was originally written by Jason Gunthorpe <jgg@gpu.srv.ualberta.ca>
##################################################################### */
/*}}}*/
// Includes /*{{{*/
#include <strutl.h>
#include <apt-pkg/fileutl.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
/*}}}*/
// strstrip - Remove white space from the front and back of a string /*{{{*/
// ---------------------------------------------------------------------
/* This is handy to use when parsing a file. It also removes \n's left
over from fgets and company */
char *_strstrip(char *String)
{
for (;*String != 0 && (*String == ' ' || *String == '\t'); String++);
if (*String == 0)
return String;
char *End = String + strlen(String) - 1;
for (;End != String - 1 && (*End == ' ' || *End == '\t' || *End == '\n' ||
*End == '\r'); End--);
End++;
*End = 0;
return String;
};
/*}}}*/
// strtabexpand - Converts tabs into 8 spaces /*{{{*/
// ---------------------------------------------------------------------
/* */
char *_strtabexpand(char *String,size_t Len)
{
for (char *I = String; I != I + Len && *I != 0; I++)
{
if (*I != '\t')
continue;
if (I + 8 > String + Len)
{
*I = 0;
return String;
}
/* Assume the start of the string is 0 and find the next 8 char
division */
int Len;
if (String == I)
Len = 1;
else
Len = 8 - ((String - I) % 8);
Len -= 2;
if (Len <= 0)
{
*I = ' ';
continue;
}
memmove(I + Len,I + 1,strlen(I) + 1);
for (char *J = I; J + Len != I; *I = ' ', I++);
}
return String;
}
/*}}}*/
// ParseQuoteWord - Parse a single word out of a string /*{{{*/
// ---------------------------------------------------------------------
/* This grabs a single word, converts any % escaped characters to their
proper values and advances the pointer. Double quotes are understood
and striped out as well. This is for URI/URL parsing. */
bool ParseQuoteWord(const char *&String,string &Res)
{
// Skip leading whitespace
const char *C = String;
for (;*C != 0 && *C == ' '; C++);
if (*C == 0)
return false;
// Jump to the next word
for (;*C != 0 && *C != ' '; C++)
{
if (*C == '"')
{
for (C++;*C != 0 && *C != '"'; C++);
if (*C == 0)
return false;
}
}
// Now de-quote characters
char Buffer[1024];
char Tmp[3];
const char *Start = String;
char *I;
for (I = Buffer; I < Buffer + sizeof(Buffer) && Start != C; I++)
{
if (*Start == '%' && Start + 2 < C)
{
Tmp[0] = Start[1];
Tmp[1] = Start[2];
Tmp[3] = 0;
*I = (char)strtol(Tmp,0,16);
Start += 3;
continue;
}
if (*Start != '"')
*I = *Start;
else
I--;
Start++;
}
*I = 0;
Res = Buffer;
// Skip ending white space
for (;*C != 0 && *C == ' '; C++);
String = C;
return true;
}
/*}}}*/
// ParseCWord - Parses a string like a C "" expression /*{{{*/
// ---------------------------------------------------------------------
/* This expects a series of space seperated strings enclosed in ""'s.
It concatenates the ""'s into a single string. */
bool ParseCWord(const char *String,string &Res)
{
// Skip leading whitespace
const char *C = String;
for (;*C != 0 && *C == ' '; C++);
if (*C == 0)
return false;
char Buffer[1024];
char *Buf = Buffer;
if (strlen(String) >= sizeof(Buffer))
return false;
for (; *C != 0; C++)
{
if (*C == '"')
{
for (C++; *C != 0 && *C != '"'; C++)
*Buf++ = *C;
if (*C == 0)
return false;
continue;
}
if (C != String && isspace(*C) != 0 && isspace(C[-1]) != 0)
continue;
if (isspace(*C) == 0)
return false;
*Buf++ = ' ';
}
*Buf = 0;
Res = Buffer;
return true;
}
/*}}}*/
// QuoteString - Convert a string into quoted from /*{{{*/
// ---------------------------------------------------------------------
/* */
string QuoteString(string Str,const char *Bad)
{
string Res;
for (string::iterator I = Str.begin(); I != Str.end(); I++)
{
if (strchr(Bad,*I) != 0 || isprint(*I) == 0 ||
*I <= 0x20 || *I >= 0x7F)
{
char Buf[10];
sprintf(Buf,"%%%02x",(int)*I);
Res += Buf;
}
else
Res += *I;
}
return Res;
}
/*}}}*/
// SizeToStr - Convert a long into a human readable size /*{{{*/
// ---------------------------------------------------------------------
/* A max of 4 digits are shown before conversion to the next highest unit.
The max length of the string will be 5 chars unless the size is > 10
YottaBytes (E24) */
string SizeToStr(double Size)
{
char S[300];
double ASize;
if (Size >= 0)
ASize = Size;
else
ASize = -1*Size;
/* bytes, KiloBytes, MegaBytes, GigaBytes, TeraBytes, PetaBytes,
ExaBytes, ZettaBytes, YottaBytes */
char Ext[] = {'b','k','M','G','T','P','E','Z','Y'};
int I = 0;
while (I <= 8)
{
if (ASize < 100 && I != 0)
{
sprintf(S,"%.1f%c",ASize,Ext[I]);
break;
}
if (ASize < 10000)
{
sprintf(S,"%.0f%c",ASize,Ext[I]);
break;
}
ASize /= 1000.0;
I++;
}
return S;
}
/*}}}*/
// TimeToStr - Convert the time into a string /*{{{*/
// ---------------------------------------------------------------------
/* Converts a number of seconds to a hms format */
string TimeToStr(unsigned long Sec)
{
char S[300];
while (1)
{
if (Sec > 60*60*24)
{
sprintf(S,"%lid %lih%lim%lis",Sec/60/60/24,(Sec/60/60) % 24,(Sec/60) % 60,Sec % 60);
break;
}
if (Sec > 60*60)
{
sprintf(S,"%lih%lim%lis",Sec/60/60,(Sec/60) % 60,Sec % 60);
break;
}
if (Sec > 60)
{
sprintf(S,"%lim%lis",Sec/60,Sec % 60);
break;
}
sprintf(S,"%lis",Sec);
break;
}
return S;
}
/*}}}*/
// SubstVar - Substitute a string for another string /*{{{*/
// ---------------------------------------------------------------------
/* This replaces all occurances of Subst with Contents in Str. */
string SubstVar(string Str,string Subst,string Contents)
{
string::size_type Pos = 0;
string::size_type OldPos = 0;
string Temp;
while (OldPos < Str.length() &&
(Pos = Str.find(Subst,OldPos)) != string::npos)
{
Temp += string(Str,OldPos,Pos) + Contents;
OldPos = Pos + Subst.length();
}
if (OldPos == 0)
return Str;
return Temp + string(Str,OldPos);
}
/*}}}*/
// URItoFileName - Convert the uri into a unique file name /*{{{*/
// ---------------------------------------------------------------------
/* This converts a URI into a safe filename. It quotes all unsafe characters
and converts / to _ and removes the scheme identifier. The resulting
file name should be unique and never occur again for a different file */
string URItoFileName(string URI)
{
string::const_iterator I = URI.begin() + URI.find(':') + 1;
for (; I < URI.end() && *I == '/'; I++);
// "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
URI = QuoteString(string(I,URI.end() - I),"\\|{}[]<>\"^~_=!@#$%^&*");
string::iterator J = URI.begin();
for (; J != URI.end(); J++)
if (*J == '/')
*J = '_';
return URI;
}
/*}}}*/
// Base64Encode - Base64 Encoding routine for short strings /*{{{*/
// ---------------------------------------------------------------------
/* This routine performs a base64 transformation on a string. It was ripped
from wget and then patched and bug fixed.
This spec can be found in rfc2045 */
string Base64Encode(string S)
{
// Conversion table.
static char tbl[64] = {'A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X',
'Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3',
'4','5','6','7','8','9','+','/'};
// Pre-allocate some space
string Final;
Final.reserve((4*S.length() + 2)/3 + 2);
/* Transform the 3x8 bits to 4x6 bits, as required by
base64. */
for (string::const_iterator I = S.begin(); I < S.end(); I += 3)
{
char Bits[3] = {0,0,0};
Bits[0] = I[0];
if (I + 1 < S.end())
Bits[1] = I[1];
if (I + 2 < S.end())
Bits[2] = I[2];
Final += tbl[Bits[0] >> 2];
Final += tbl[((Bits[0] & 3) << 4) + (Bits[1] >> 4)];
if (I + 1 >= S.end())
break;
Final += tbl[((Bits[1] & 0xf) << 2) + (Bits[2] >> 6)];
if (I + 2 >= S.end())
break;
Final += tbl[Bits[2] & 0x3f];
}
/* Apply the padding elements, this tells how many bytes the remote
end should discard */
if (S.length() % 3 == 2)
Final += '=';
if (S.length() % 3 == 1)
Final += "==";
return Final;
}
/*}}}*/
// stringcmp - Arbitary string compare /*{{{*/
// ---------------------------------------------------------------------
/* This safely compares two non-null terminated strings of arbitary
length */
int stringcmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
{
for (; A != AEnd && B != BEnd; A++, B++)
if (*A != *B)
break;
if (A == AEnd && B == BEnd)
return 0;
if (A == AEnd)
return 1;
if (B == BEnd)
return -1;
if (*A < *B)
return -1;
return 1;
}
/*}}}*/
// stringcasecmp - Arbitary case insensitive string compare /*{{{*/
// ---------------------------------------------------------------------
/* */
int stringcasecmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
{
for (; A != AEnd && B != BEnd; A++, B++)
if (toupper(*A) != toupper(*B))
break;
if (A == AEnd && B == BEnd)
return 0;
if (A == AEnd)
return 1;
if (B == BEnd)
return -1;
if (toupper(*A) < toupper(*B))
return -1;
return 1;
}
/*}}}*/
// LookupTag - Lookup the value of a tag in a taged string /*{{{*/
// ---------------------------------------------------------------------
/* The format is like those used in package files and the method
communication system */
string LookupTag(string Message,const char *Tag,const char *Default)
{
// Look for a matching tag.
int Length = strlen(Tag);
for (string::iterator I = Message.begin(); I + Length < Message.end(); I++)
{
// Found the tag
if (I[Length] == ':' && stringcasecmp(I,I+Length,Tag) == 0)
{
// Find the end of line and strip the leading/trailing spaces
string::iterator J;
I += Length + 1;
for (; isspace(*I) != 0 && I < Message.end(); I++);
for (J = I; *J != '\n' && J < Message.end(); J++);
for (; J > I && isspace(J[-1]) != 0; J--);
return string(I,J-I);
}
for (; *I != '\n' && I < Message.end(); I++);
}
// Failed to find a match
if (Default == 0)
return string();
return Default;
}
/*}}}*/
// StringToBool - Converts a string into a boolean /*{{{*/
// ---------------------------------------------------------------------
/* This inspects the string to see if it is true or if it is false and
then returns the result. Several varients on true/false are checked. */
int StringToBool(string Text,int Default = -1)
{
char *End;
int Res = strtol(Text.c_str(),&End,0);
if (End != Text.c_str() && Res >= 0 && Res <= 1)
return Res;
// Check for positives
if (strcasecmp(Text.c_str(),"no") == 0 ||
strcasecmp(Text.c_str(),"false") == 0 ||
strcasecmp(Text.c_str(),"without") == 0 ||
strcasecmp(Text.c_str(),"disable") == 0)
return 0;
// Check for negatives
if (strcasecmp(Text.c_str(),"yes") == 0 ||
strcasecmp(Text.c_str(),"true") == 0 ||
strcasecmp(Text.c_str(),"with") == 0 ||
strcasecmp(Text.c_str(),"enable") == 0)
return 1;
return Default;
}
/*}}}*/
// TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
// ---------------------------------------------------------------------
/* This converts a time_t into a string time representation that is
year 2000 complient and timezone neutral */
string TimeRFC1123(time_t Date)
{
struct tm Conv = *gmtime(&Date);
char Buf[300];
const char *Day[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
const char *Month[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
"Aug","Sep","Oct","Nov","Dec"};
sprintf(Buf,"%s, %02i %s %i %02i:%02i:%02i GMT",Day[Conv.tm_wday],
Conv.tm_mday,Month[Conv.tm_mon],Conv.tm_year+1900,Conv.tm_hour,
Conv.tm_min,Conv.tm_sec);
return Buf;
}
/*}}}*/
// ReadMessages - Read messages from the FD /*{{{*/
// ---------------------------------------------------------------------
/* This pulls full messages from the input FD into the message buffer.
It assumes that messages will not pause during transit so no
fancy buffering is used. */
bool ReadMessages(int Fd, vector<string> &List)
{
char Buffer[4000];
char *End = Buffer;
while (1)
{
int Res = read(Fd,End,sizeof(Buffer) - (End-Buffer));
// Process is dead, this is kind of bad..
if (Res == 0)
return false;
// No data
if (Res <= 0)
return true;
End += Res;
// Look for the end of the message
for (char *I = Buffer; I + 1 < End; I++)
{
if (I[0] != '\n' || I[1] != '\n')
continue;
// Pull the message out
string Message(Buffer,0,I-Buffer);
// Fix up the buffer
for (; I < End && *I == '\n'; I++);
End -= I-Buffer;
memmove(Buffer,I,End-Buffer);
I = Buffer;
List.push_back(Message);
}
if (End == Buffer)
return true;
if (WaitFd(Fd) == false)
return false;
}
}
/*}}}*/
// MonthConv - Converts a month string into a number /*{{{*/
// ---------------------------------------------------------------------
/* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
Made it a bit more robust with a few touppers though. */
static int MonthConv(char *Month)
{
switch (toupper(*Month))
{
case 'A':
return toupper(Month[1]) == 'P'?3:7;
case 'D':
return 11;
case 'F':
return 1;
case 'J':
if (toupper(Month[1]) == 'A')
return 0;
return toupper(Month[2]) == 'N'?5:6;
case 'M':
return toupper(Month[2]) == 'R'?2:4;
case 'N':
return 10;
case 'O':
return 9;
case 'S':
return 8;
// Pretend it is January..
default:
return 0;
}
}
/*}}}*/
// StrToTime - Converts a string into a time_t /*{{{*/
// ---------------------------------------------------------------------
/* This handles all 3 populare time formats including RFC 1123, RFC 1036
and the C library asctime format. It requires the GNU library function
'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
reason the C library does not provide any such function :<*/
bool StrToTime(string Val,time_t &Result)
{
struct tm Tm;
char Month[10];
const char *I = Val.c_str();
// Skip the day of the week
for (;*I != 0 && *I != ' '; I++);
// Handle RFC 1123 time
if (sscanf(I," %d %3s %d %d:%d:%d GMT",&Tm.tm_mday,Month,&Tm.tm_year,
&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
{
// Handle RFC 1036 time
if (sscanf(I," %d-%3s-%d %d:%d:%d GMT",&Tm.tm_mday,Month,
&Tm.tm_year,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) == 6)
Tm.tm_year += 1900;
else
{
// asctime format
if (sscanf(I," %3s %d %d:%d:%d %d",Month,&Tm.tm_mday,
&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec,&Tm.tm_year) != 6)
return false;
}
}
Tm.tm_isdst = 0;
Tm.tm_mon = MonthConv(Month);
Tm.tm_year -= 1900;
// Convert to local time and then to GMT
Result = timegm(&Tm);
return true;
}
/*}}}*/
// URI::URI - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* This parses the URI into all of its components */
URI::URI(string U)
{
string::const_iterator I = U.begin();
// Locate the first colon, this seperates the scheme
for (; I < U.end() && *I != ':' ; I++);
string::const_iterator FirstColon = I;
// Determine if this is a host type URI with a leading double //
string::const_iterator SingleSlash = I;
if (I + 3 < U.end() && I[1] == '/' && I[2] == '/')
{
// Locate the single / that starts the path
for (; I < U.end(); I++)
{
if (*I == '/' && I[1] == '/')
I += 2;
else
if (*I == '/')
break;
}
if (I > U.end())
I = U.end();
SingleSlash = I;
}
// We can now write the access and path specifiers
Access = string(U,0,FirstColon - U.begin());
if (SingleSlash != U.end())
Path = string(U,SingleSlash - U.begin() + 1);
// Now we attempt to locate a user:pass@host fragment
FirstColon += 3;
if (FirstColon >= U.end())
return;
if (FirstColon > SingleSlash)
FirstColon = SingleSlash;
// Search for the @
I = FirstColon;
for (; I < SingleSlash && *I != '@'; I++);
string::const_iterator At = I;
// Colon in the @ section
I = FirstColon + 1;
for (; I < At && *I != ':'; I++);
string::const_iterator SecondColon = I;
// Now write the host and user/pass
if (At == SingleSlash)
{
if (FirstColon < SingleSlash)
Host = string(U,FirstColon - U.begin(),SingleSlash - FirstColon);
}
else
{
Host = string(U,At - U.begin() + 1,SingleSlash - At - 1);
User = string(U,FirstColon - U.begin(),SecondColon - FirstColon);
if (SecondColon < At)
Password = string(U,SecondColon - U.begin() + 1,At - SecondColon - 1);
}
// Now we parse off a pot number from the hostname
Port = 0;
string::size_type Pos = Host.rfind(':');
if (Pos == string::npos)
return;
Port = atoi(string(Host,Pos+1).c_str());
Host = string(Host,0,Pos);
}
/*}}}*/
// URI::operator string - Convert the URI to a string /*{{{*/
// ---------------------------------------------------------------------
/* */
URI::operator string()
{
string Res = Access + ':';
if (Host.empty() == false)
{
if (User.empty() == false)
{
Res += "//" + User;
if (Password.empty() == false)
Res += ":" + Password;
Res += "@";
}
Res += Host;
}
if (Path.empty() == false)
Res += "/" + Path;
return Res;
}
/*}}}*/
|