Oolite
Loading...
Searching...
No Matches
OOLegacyScriptWhitelist.m
Go to the documentation of this file.
1/*
2
3OOLegacyScriptWhitelist.m
4
5
6Oolite
7Copyright (C) 2004-2013 Giles C Williams and contributors
8
9This program is free software; you can redistribute it and/or
10modify it under the terms of the GNU General Public License
11as published by the Free Software Foundation; either version 2
12of the License, or (at your option) any later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with this program; if not, write to the Free Software
21Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22MA 02110-1301, USA.
23
24*/
25
29#import "OODeepCopy.h"
30#import "OOFoundation.h"
31#import "OOStringParsing.h"
33#import "ResourceManager.h"
34
35#define INCLUDE_RAW_STRING OOLITE_DEBUG // If nonzero, raw condition strings are included; if zero, a placeholder is used.
36
40 NSString* key; // Dictionary key; nil for arrays.
41 NSUInteger index; // Array index if key is nil.
42};
43
44static NSArray* OOSanitizeLegacyScriptInternal(NSArray* script, SanStackElement* stack, BOOL allowAIMethods);
45static NSArray* OOSanitizeLegacyScriptConditionsInternal(NSArray* conditions, SanStackElement* stack);
46
47static NSArray* SanitizeCondition(NSString* condition, SanStackElement* stack);
48static NSArray* SanitizeConditionalStatement(NSDictionary* statement, SanStackElement* stack, BOOL allowAIMethods);
49static NSArray* SanitizeActionStatement(NSString* statement, SanStackElement* stack, BOOL allowAIMethods);
50static OOOperationType ClassifyLHSConditionSelector(NSString* selectorString, NSString** outSanitizedMethod, SanStackElement* stack);
51static NSString* SanitizeQueryMethod(NSString* selectorString); // Checks aliases and whitelist, returns nil if whitelist fails.
52static NSString* SanitizeActionMethod(NSString* selectorString, BOOL allowAIMethods); // Checks aliases and whitelist, returns nil if whitelist fails.
53static NSArray* AlwaysFalseConditions(void);
54static BOOL IsAlwaysFalseConditions(NSArray* conditions);
55
56static NSString* StringFromStack(SanStackElement* topOfStack);
57
58NSArray* OOSanitizeLegacyScript(NSArray* script, NSString* context, BOOL allowAIMethods)
59{
60 SanStackElement stackRoot = { NULL, context, 0 };
61 NSArray* result = OOSanitizeLegacyScriptInternal(script, &stackRoot, allowAIMethods);
62 return [OODeepCopy(result) autorelease];
63}
64
65static NSArray* OOSanitizeLegacyScriptInternal(NSArray* script, SanStackElement* stack, BOOL allowAIMethods)
66{
67 NSAutoreleasePool* pool = nil;
68 NSMutableArray* result = nil;
69 id statement = nil;
70 NSUInteger index = 0;
71
72 pool = [[NSAutoreleasePool alloc] init];
73
74 result = [NSMutableArray arrayWithCapacity:[script count]];
75
76 foreach (statement, script) {
77 SanStackElement subStack = {
78 stack, nil, index++
79 };
80
81 if ([statement isKindOfClass:[NSDictionary class]]) {
82 statement = SanitizeConditionalStatement(statement, &subStack, allowAIMethods);
83 } else if ([statement isKindOfClass:[NSString class]]) {
84 statement = SanitizeActionStatement(statement, &subStack, allowAIMethods);
85 } else {
86 OOLog(@"script.syntax.statement.invalidType", @"***** SCRIPT ERROR: in %@, statement is of invalid type - expected string or dictionary, got %@.", StringFromStack(stack), [statement class]);
87 statement = nil;
88 }
89
90 if (statement != nil) {
91 [result addObject:statement];
92 }
93 }
94
95 [result retain];
96 [pool release];
97
98 return [result autorelease];
99}
100
101NSArray* OOSanitizeLegacyScriptConditions(NSArray* conditions, NSString* context)
102{
103 if (context == nil)
104 context = @"<anonymous conditions>";
105 SanStackElement stackRoot = { NULL, context, 0 };
106 NSArray* result = OOSanitizeLegacyScriptConditionsInternal(conditions, &stackRoot);
107 return [OODeepCopy(result) autorelease];
108}
109
110static NSArray* OOSanitizeLegacyScriptConditionsInternal(NSArray* conditions, SanStackElement* stack)
111{
112 NSString* condition = nil;
113 NSMutableArray* result = nil;
114 NSArray* tokens = nil;
115 BOOL OK = YES;
116 NSUInteger index = 0;
117
118 if (OOLegacyConditionsAreSanitized(conditions) || conditions == nil)
119 return conditions;
120
121 result = [NSMutableArray arrayWithCapacity:[conditions count]];
122
123 foreach (condition, conditions) {
124 SanStackElement subStack = {
125 stack, nil, index++
126 };
127
128 if (![condition isKindOfClass:[NSString class]]) {
129 OOLog(@"script.syntax.condition.notString", @"***** SCRIPT ERROR: in %@, bad condition - expected string, got %@; ignoring.", StringFromStack(stack), [condition class]);
130 OK = NO;
131 break;
132 }
133
134 tokens = SanitizeCondition(condition, &subStack);
135 if (tokens != nil) {
136 [result addObject:tokens];
137 } else {
138 OK = NO;
139 break;
140 }
141 }
142
143 if (OK)
144 return result;
145 else
146 return AlwaysFalseConditions();
147}
148
149BOOL OOLegacyConditionsAreSanitized(NSArray* conditions)
150{
151 if ([conditions count] == 0)
152 return YES; // Empty array is safe.
153 return [[conditions objectAtIndex:0] isKindOfClass:[NSArray class]];
154}
155
156static NSArray* SanitizeCondition(NSString* condition, SanStackElement* stack)
157{
158 NSArray* tokens = nil;
159 NSUInteger i, tokenCount;
160 OOOperationType opType;
161 NSString* selectorString = nil;
162 NSString* sanitizedSelectorString = nil;
163 NSString* comparatorString = nil;
164 OOComparisonType comparatorValue;
165 NSMutableArray* rhs = nil;
166 NSString* rhsItem = nil;
167 NSString* rhsSelector = nil;
168 NSArray* sanitizedRHSItem = nil;
169 NSString* stringSegment = nil;
170
171 tokens = ScanTokensFromString(condition);
172 tokenCount = [tokens count];
173
174 if (tokenCount < 1) {
175 OOLog(@"script.debug.syntax.scriptCondition.noneSpecified", @"***** SCRIPT ERROR: in %@, empty script condition.", StringFromStack(stack));
176 return nil;
177 }
178
179 // Parse left-hand side.
180 selectorString = [tokens oo_stringAtIndex:0];
181 opType = ClassifyLHSConditionSelector(selectorString, &sanitizedSelectorString, stack);
182 if (opType >= OP_INVALID) {
183 OOLog(@"script.unpermittedMethod", @"***** SCRIPT ERROR: in %@ (\"%@\"), method \"%@\" not allowed.", StringFromStack(stack), condition, selectorString);
184 return nil;
185 }
186
187 // Parse operator.
188 if (tokenCount > 1) {
189 comparatorString = [tokens oo_stringAtIndex:1];
190 if ([comparatorString isEqualToString:@"equal"])
191 comparatorValue = COMPARISON_EQUAL;
192 else if ([comparatorString isEqualToString:@"notequal"])
193 comparatorValue = COMPARISON_NOTEQUAL;
194 else if ([comparatorString isEqualToString:@"lessthan"])
195 comparatorValue = COMPARISON_LESSTHAN;
196 else if ([comparatorString isEqualToString:@"greaterthan"])
197 comparatorValue = COMPARISON_GREATERTHAN;
198 else if ([comparatorString isEqualToString:@"morethan"])
199 comparatorValue = COMPARISON_GREATERTHAN;
200 else if ([comparatorString isEqualToString:@"oneof"])
201 comparatorValue = COMPARISON_ONEOF;
202 else if ([comparatorString isEqualToString:@"undefined"])
203 comparatorValue = COMPARISON_UNDEFINED;
204 else {
205 OOLog(@"script.debug.syntax.badComparison", @"***** SCRIPT ERROR: in %@ (\"%@\"), unknown comparison operator \"%@\", will return NO.", StringFromStack(stack), condition, comparatorString);
206 return nil;
207 }
208 } else {
209 /* In the direct interpreter, having no operator resulted in an
210 implicit COMPARISON_NO operator, which always evaluated to false.
211 Returning NO here causes AlwaysFalseConditions() to be used, which
212 has the same effect.
213 */
214 OOLog(@"script.debug.syntax.noOperator", @"----- WARNING: SCRIPT in %@ -- No operator in expression \"%@\", will always evaluate as false.", StringFromStack(stack), condition);
215 return nil;
216 }
217
218 // Check for invalid opType/comparator combinations.
219 if (opType == OP_NUMBER && comparatorValue == COMPARISON_UNDEFINED) {
220 OOLog(@"script.debug.syntax.invalidOperator", @"***** SCRIPT ERROR: in %@ (\"%@\"), comparison operator \"%@\" is not valid for %@.", StringFromStack(stack), condition, @"undefined", @"numbers");
221 return nil;
222 } else if (opType == OP_BOOL) {
223 switch (comparatorValue) {
224 // Valid comparators
225 case COMPARISON_EQUAL:
227 break;
228
229 default:
230 OOLog(@"script.debug.syntax.invalidOperator", @"***** SCRIPT ERROR: in %@ (\"%@\"), comparison operator \"%@\" is not valid for %@.", StringFromStack(stack), condition, OOComparisonTypeToString(comparatorValue), @"booleans");
231 return nil;
232 }
233 }
234
235 /* Parse right-hand side. Each token is converted to an array of the
236 token and a boolean indicating whether it's a selector.
237
238 This also coalesces non-selector tokens, i.e. whitespace-separated
239 string segments.
240 */
241 if (tokenCount > 2) {
242 rhs = [NSMutableArray arrayWithCapacity:tokenCount - 2];
243 for (i = 2; i < tokenCount; i++) {
244 rhsItem = [tokens oo_stringAtIndex:i];
245 rhsSelector = SanitizeQueryMethod(rhsItem);
246 if (rhsSelector != nil) {
247 // Method
248 if (stringSegment != nil) {
249 // Add stringSegment as a literal token.
250 sanitizedRHSItem = [NSArray arrayWithObjects:[NSNumber numberWithBool:NO], stringSegment, nil];
251 [rhs addObject:sanitizedRHSItem];
252 stringSegment = nil;
253 }
254
255 sanitizedRHSItem = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], rhsSelector, nil];
256 [rhs addObject:sanitizedRHSItem];
257 } else {
258 // String; append to stringSegment
259 if (stringSegment == nil)
260 stringSegment = rhsItem;
261 else
262 stringSegment = [NSString stringWithFormat:@"%@ %@", stringSegment, rhsItem];
263 }
264 }
265
266 if (stringSegment != nil) {
267 sanitizedRHSItem = [NSArray arrayWithObjects:[NSNumber numberWithBool:NO], stringSegment, nil];
268 [rhs addObject:sanitizedRHSItem];
269 }
270 } else {
271 rhs = [NSMutableArray array];
272 }
273
274 NSString* rawString = nil;
275#if INCLUDE_RAW_STRING
276 rawString = condition;
277#else
278 rawString = @"<condition>";
279#endif
280
281 return [NSArray arrayWithObjects:
282 [NSNumber numberWithUnsignedInt:opType],
283 rawString,
284 sanitizedSelectorString,
285 [NSNumber numberWithUnsignedInt:comparatorValue],
286 rhs,
287 nil];
288}
289
290static NSArray* SanitizeConditionalStatement(NSDictionary* statement, SanStackElement* stack, BOOL allowAIMethods)
291{
292 NSArray* conditions = nil;
293 NSArray* doActions = nil;
294 NSArray* elseActions = nil;
295
296 conditions = [statement oo_arrayForKey:@"conditions"];
297 if (conditions == nil) {
298 OOLog(@"script.syntax.noConditions", @"***** SCRIPT ERROR: in %@, conditions array contains no \"conditions\" entry, ignoring.", StringFromStack(stack));
299 return nil;
300 }
301
302 // Sanitize conditions.
303 SanStackElement subStack = { stack, @"conditions", 0 };
304 conditions = OOSanitizeLegacyScriptConditionsInternal(conditions, &subStack);
305 if (conditions == nil) {
306 return nil;
307 }
308
309 // Sanitize do and else.
310 if (!IsAlwaysFalseConditions(conditions))
311 doActions = [statement oo_arrayForKey:@"do"];
312 if (doActions != nil) {
313 subStack.key = @"do";
314 doActions = OOSanitizeLegacyScriptInternal(doActions, &subStack, allowAIMethods);
315 }
316
317 elseActions = [statement oo_arrayForKey:@"else"];
318 if (elseActions != nil) {
319 subStack.key = @"else";
320 elseActions = OOSanitizeLegacyScriptInternal(elseActions, &subStack, allowAIMethods);
321 }
322
323 // If neither does anything, the statment has no effect.
324 if ([doActions count] == 0 && [elseActions count] == 0) {
325 return nil;
326 }
327
328 if (doActions == nil)
329 doActions = [NSArray array];
330 if (elseActions == nil)
331 elseActions = [NSArray array];
332
333 return [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], conditions, doActions, elseActions, nil];
334}
335
336static NSArray* SanitizeActionStatement(NSString* statement, SanStackElement* stack, BOOL allowAIMethods)
337{
338 NSMutableArray* tokens = nil;
339 NSUInteger tokenCount;
340 NSString* rawSelectorString = nil;
341 NSString* selectorString = nil;
342 NSString* argument = nil;
343
344 tokens = ScanTokensFromString(statement);
345 tokenCount = [tokens count];
346 if (tokenCount == 0)
347 return nil;
348
349 rawSelectorString = [tokens objectAtIndex:0];
350 selectorString = SanitizeActionMethod(rawSelectorString, allowAIMethods);
351 if (selectorString == nil) {
352 OOLog(@"script.unpermittedMethod", @"***** SCRIPT ERROR: in %@ (\"%@\"), method \"%@\" not allowed.", StringFromStack(stack), statement, rawSelectorString);
353 return nil;
354 }
355
356 if ([selectorString isEqualToString:@"doNothing"]) {
357 return nil;
358 }
359
360 if ([selectorString hasSuffix:@":"]) {
361 // Expects an argument
362 if (tokenCount == 2) {
363 argument = [tokens objectAtIndex:1];
364 } else {
365 [tokens removeObjectAtIndex:0];
366 argument = [tokens componentsJoinedByString:@" "];
367 }
368
369 argument = [argument stringByReplacingOccurrencesOfString:@"[credits_number]" withString:@"[_oo_legacy_credits_number]"];
370 }
371
372 return [NSArray arrayWithObjects:[NSNumber numberWithBool:NO], selectorString, argument, nil];
373}
374
375static OOOperationType ClassifyLHSConditionSelector(NSString* selectorString, NSString** outSanitizedSelector, SanStackElement* stack)
376{
377 assert(outSanitizedSelector != NULL);
378
379 *outSanitizedSelector = selectorString;
380
381 // Allow arbitrary mission_foo or local_foo pseudo-selectors.
382 if ([selectorString hasPrefix:@"mission_"])
383 return OP_MISSION_VAR;
384 if ([selectorString hasPrefix:@"local_"])
385 return OP_LOCAL_VAR;
386
387 // If it's a real method, check against whitelist.
388 *outSanitizedSelector = SanitizeQueryMethod(selectorString);
389 if (*outSanitizedSelector == nil) {
390 return OP_INVALID;
391 }
392
393 // If it's a real method, and in the whitelist, classify by suffix.
394 if ([selectorString hasSuffix:@"_string"])
395 return OP_STRING;
396 if ([selectorString hasSuffix:@"_number"])
397 return OP_NUMBER;
398 if ([selectorString hasSuffix:@"_bool"])
399 return OP_BOOL;
400
401 // If we got here, something's wrong.
402 OOLog(@"script.sanitize.unclassifiedSelector", @"***** ERROR: Whitelisted query method \"%@\" has no type suffix, treating as invalid.", selectorString);
403 return OP_INVALID;
404}
405
406static NSString* SanitizeQueryMethod(NSString* selectorString)
407{
408 static NSSet* whitelist = nil;
409 static NSDictionary* aliases = nil;
410 NSString* aliasedSelector = nil;
411
412 if (whitelist == nil) {
413 whitelist = [[NSSet alloc] initWithArray:[[ResourceManager whitelistDictionary] oo_arrayForKey:@"query_methods"]];
414 aliases = [[[ResourceManager whitelistDictionary] oo_dictionaryForKey:@"query_method_aliases"] retain];
415 }
416
417 aliasedSelector = [aliases oo_stringForKey:selectorString];
418 if (aliasedSelector != nil)
419 selectorString = aliasedSelector;
420
421 if (![whitelist containsObject:selectorString])
422 selectorString = nil;
423
424 return selectorString;
425}
426
427static NSString* SanitizeActionMethod(NSString* selectorString, BOOL allowAIMethods)
428{
429 static NSSet* whitelist = nil;
430 static NSSet* whitelistWithAI = nil;
431 static NSDictionary* aliases = nil;
432 static NSDictionary* aliasesWithAI = nil;
433 NSString* aliasedSelector = nil;
434
435 if (whitelist == nil) {
436 NSArray* actionMethods = nil;
437 NSArray* aiMethods = nil;
438 NSArray* aiAndActionMethods = nil;
439
440 actionMethods = [[ResourceManager whitelistDictionary] oo_arrayForKey:@"action_methods"];
441 aiMethods = [[ResourceManager whitelistDictionary] oo_arrayForKey:@"ai_methods"];
442 aiAndActionMethods = [[ResourceManager whitelistDictionary] oo_arrayForKey:@"ai_and_action_methods"];
443
444 if (actionMethods == nil)
445 actionMethods = [NSArray array];
446 if (aiMethods == nil)
447 aiMethods = [NSArray array];
448
449 if (aiAndActionMethods != nil)
450 actionMethods = [actionMethods arrayByAddingObjectsFromArray:aiAndActionMethods];
451
452 whitelist = [[NSSet alloc] initWithArray:actionMethods];
453 whitelistWithAI = [[NSSet alloc] initWithArray:[aiMethods arrayByAddingObjectsFromArray:actionMethods]];
454
455 aliases = [[[ResourceManager whitelistDictionary] oo_dictionaryForKey:@"action_method_aliases"] retain];
456
457 aliasesWithAI = [[ResourceManager whitelistDictionary] oo_dictionaryForKey:@"ai_method_aliases"];
458 if (aliasesWithAI != nil) {
459 aliasesWithAI = [[aliasesWithAI dictionaryByAddingEntriesFromDictionary:aliases] copy];
460 } else {
461 aliasesWithAI = [aliases copy];
462 }
463 }
464
465 aliasedSelector = [(allowAIMethods ? aliasesWithAI : aliases) oo_stringForKey:selectorString];
466 if (aliasedSelector != nil)
467 selectorString = aliasedSelector;
468
469 if (![(allowAIMethods ? whitelistWithAI : whitelist) containsObject:selectorString])
470 selectorString = nil;
471
472 return selectorString;
473}
474
475// Return a conditions array that always evaluates as false.
476static NSArray* AlwaysFalseConditions(void)
477{
478 static NSArray* alwaysFalse = nil;
479 if (alwaysFalse != nil) {
480 alwaysFalse = [NSArray arrayWithObject:[NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:OP_FALSE]]];
481 [alwaysFalse retain];
482 }
483
484 return alwaysFalse;
485}
486
487static BOOL IsAlwaysFalseConditions(NSArray* conditions)
488{
489 return [[conditions oo_arrayAtIndex:0] oo_unsignedIntAtIndex:0] == OP_FALSE;
490}
491
492static NSMutableString* StringFromStackInternal(SanStackElement* topOfStack)
493{
494 if (topOfStack == NULL)
495 return nil;
496
497 NSMutableString* base = StringFromStackInternal(topOfStack->back);
498 if (base == nil)
499 base = [NSMutableString string];
500
501 NSString* string = topOfStack->key;
502 if (string == nil)
503 string = [NSString stringWithFormat:@"%zu", topOfStack->index];
504 if ([base length] > 0)
505 [base appendString:@"."];
506
507 [base appendString:string];
508
509 return base;
510}
511
512static NSString* StringFromStack(SanStackElement* topOfStack)
513{
514 return StringFromStackInternal(topOfStack);
515}
static NSString * SanitizeActionMethod(NSString *selectorString, BOOL allowAIMethods)
static NSString * SanitizeQueryMethod(NSString *selectorString)
static NSString * StringFromStack(SanStackElement *topOfStack)
static NSArray * SanitizeConditionalStatement(NSDictionary *statement, SanStackElement *stack, BOOL allowAIMethods)
static OOOperationType ClassifyLHSConditionSelector(NSString *selectorString, NSString **outSanitizedMethod, SanStackElement *stack)
static NSMutableString * StringFromStackInternal(SanStackElement *topOfStack)
static NSArray * OOSanitizeLegacyScriptInternal(NSArray *script, SanStackElement *stack, BOOL allowAIMethods)
NSArray * OOSanitizeLegacyScriptConditions(NSArray *conditions, NSString *context)
static NSArray * OOSanitizeLegacyScriptConditionsInternal(NSArray *conditions, SanStackElement *stack)
static NSArray * SanitizeCondition(NSString *condition, SanStackElement *stack)
static NSArray * SanitizeActionStatement(NSString *statement, SanStackElement *stack, BOOL allowAIMethods)
static BOOL IsAlwaysFalseConditions(NSArray *conditions)
NSArray * OOSanitizeLegacyScript(NSArray *script, NSString *context, BOOL allowAIMethods)
BOOL OOLegacyConditionsAreSanitized(NSArray *conditions)
static NSArray * AlwaysFalseConditions(void)
#define OOLog(class, format,...)
Definition OOLogging.h:84
unsigned count
return nil
NSMutableArray * ScanTokensFromString(NSString *values)
NSString * OOComparisonTypeToString(OOComparisonType type) CONST_FUNC
NSDictionary * whitelistDictionary()
SanStackElement * back