blob: 27026ae19b80938205ae0a961514facb806e4ac3 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.osgi;
2
3import java.io.*;
4import java.util.*;
5import java.util.Map.Entry;
6import java.util.jar.*;
7import java.util.regex.*;
8
9import aQute.lib.base64.*;
10import aQute.lib.io.*;
11import aQute.lib.osgi.Descriptors.PackageRef;
12import aQute.lib.osgi.Descriptors.TypeRef;
13import aQute.libg.cryptography.*;
14import aQute.libg.header.*;
15import aQute.libg.qtokens.*;
16
17public class Verifier extends Processor {
18
19 private final Jar dot;
20 private final Manifest manifest;
21 private final Domain main;
22
23 private boolean r3;
24 private boolean usesRequire;
25
Stuart McCulloch2286f232012-06-15 13:27:53 +000026 final static Pattern EENAME = Pattern.compile("CDC-1\\.0/Foundation-1\\.0" + "|CDC-1\\.1/Foundation-1\\.1"
27 + "|OSGi/Minimum-1\\.[1-9]" + "|JRE-1\\.1" + "|J2SE-1\\.2" + "|J2SE-1\\.3"
28 + "|J2SE-1\\.4" + "|J2SE-1\\.5" + "|JavaSE-1\\.6" + "|JavaSE-1\\.7"
Stuart McCullochbb014372012-06-07 21:57:32 +000029 + "|PersonalJava-1\\.1" + "|PersonalJava-1\\.2"
Stuart McCulloch2286f232012-06-15 13:27:53 +000030 + "|CDC-1\\.0/PersonalBasis-1\\.0" + "|CDC-1\\.0/PersonalJava-1\\.0");
Stuart McCullochbb014372012-06-07 21:57:32 +000031
32 final static int V1_1 = 45;
33 final static int V1_2 = 46;
34 final static int V1_3 = 47;
35 final static int V1_4 = 48;
36 final static int V1_5 = 49;
37 final static int V1_6 = 50;
38 final static int V1_7 = 51;
39 final static int V1_8 = 52;
40
41 static class EE {
42 String name;
43 int target;
44
45 EE(String name, int source, int target) {
46 this.name = name;
47 this.target = target;
48 }
49
50 public String toString() {
51 return name + "(" + target + ")";
52 }
53 }
54
55 final static EE[] ees = {
56 new EE("CDC-1.0/Foundation-1.0", V1_3, V1_1),
57 new EE("CDC-1.1/Foundation-1.1", V1_3, V1_2),
58 new EE("OSGi/Minimum-1.0", V1_3, V1_1),
59 new EE("OSGi/Minimum-1.1", V1_3, V1_2),
60 new EE("JRE-1.1", V1_1, V1_1), //
61 new EE("J2SE-1.2", V1_2, V1_1), //
62 new EE("J2SE-1.3", V1_3, V1_1), //
63 new EE("J2SE-1.4", V1_3, V1_2), //
64 new EE("J2SE-1.5", V1_5, V1_5), //
65 new EE("JavaSE-1.6", V1_6, V1_6), //
66 new EE("PersonalJava-1.1", V1_1, V1_1), //
67 new EE("JavaSE-1.7", V1_7, V1_7), //
68 new EE("PersonalJava-1.1", V1_1, V1_1), //
Stuart McCulloch2286f232012-06-15 13:27:53 +000069 new EE("PersonalJava-1.2", V1_1, V1_1), new EE("CDC-1.0/PersonalBasis-1.0", V1_3, V1_1),
70 new EE("CDC-1.0/PersonalJava-1.0", V1_3, V1_1), new EE("CDC-1.1/PersonalBasis-1.1", V1_3, V1_2),
71 new EE("CDC-1.1/PersonalJava-1.1", V1_3, V1_2)
72 };
Stuart McCullochbb014372012-06-07 21:57:32 +000073
Stuart McCulloch2286f232012-06-15 13:27:53 +000074 final static Pattern CARDINALITY_PATTERN = Pattern.compile("single|multiple");
75 final static Pattern RESOLUTION_PATTERN = Pattern.compile("optional|mandatory");
Stuart McCullochbb014372012-06-07 21:57:32 +000076 final static Pattern BUNDLEMANIFESTVERSION = Pattern.compile("2");
77 public final static String SYMBOLICNAME_STRING = "[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)*";
Stuart McCulloch2286f232012-06-15 13:27:53 +000078 public final static Pattern SYMBOLICNAME = Pattern.compile(SYMBOLICNAME_STRING);
Stuart McCullochbb014372012-06-07 21:57:32 +000079
80 public final static String VERSION_STRING = "[0-9]+(\\.[0-9]+(\\.[0-9]+(\\.[0-9A-Za-z_-]+)?)?)?";
81 public final static Pattern VERSION = Pattern.compile(VERSION_STRING);
82 final static Pattern FILTEROP = Pattern.compile("=|<=|>=|~=");
83 public final static Pattern VERSIONRANGE = Pattern.compile("((\\(|\\[)"
84
Stuart McCulloch2286f232012-06-15 13:27:53 +000085 + VERSION_STRING + "," + VERSION_STRING + "(\\]|\\)))|"
Stuart McCullochbb014372012-06-07 21:57:32 +000086 + VERSION_STRING);
87 final static Pattern FILE = Pattern
88 .compile("/?[^/\"\n\r\u0000]+(/[^/\"\n\r\u0000]+)*");
89 final static Pattern WILDCARDPACKAGE = Pattern
90 .compile("((\\p{Alnum}|_)+(\\.(\\p{Alnum}|_)+)*(\\.\\*)?)|\\*");
91 public final static Pattern ISO639 = Pattern.compile("[A-Z][A-Z]");
Stuart McCulloch2286f232012-06-15 13:27:53 +000092 public final static Pattern HEADER_PATTERN = Pattern.compile("[A-Za-z0-9][-a-zA-Z0-9_]+");
Stuart McCullochbb014372012-06-07 21:57:32 +000093 public final static Pattern TOKEN = Pattern.compile("[-a-zA-Z0-9_]+");
94
95 public final static Pattern NUMBERPATTERN = Pattern.compile("\\d+");
96 public final static Pattern PACKAGEPATTERN = Pattern
97 .compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*(\\.\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)*");
98 public final static Pattern PATHPATTERN = Pattern.compile(".*");
99 public final static Pattern FQNPATTERN = Pattern.compile(".*");
100 public final static Pattern URLPATTERN = Pattern.compile(".*");
101 public final static Pattern ANYPATTERN = Pattern.compile(".*");
102 public final static Pattern FILTERPATTERN = Pattern.compile(".*");
Stuart McCulloch2286f232012-06-15 13:27:53 +0000103 public final static Pattern TRUEORFALSEPATTERN = Pattern.compile("true|false|TRUE|FALSE");
Stuart McCullochbb014372012-06-07 21:57:32 +0000104 public static final Pattern WILDCARDNAMEPATTERN = Pattern.compile(".*");
105 public static final Pattern BUNDLE_ACTIVATIONPOLICYPATTERN = Pattern.compile("lazy");
106
Stuart McCulloch2286f232012-06-15 13:27:53 +0000107 public final static String EES[] = {
108 "CDC-1.0/Foundation-1.0", "CDC-1.1/Foundation-1.1", "OSGi/Minimum-1.0", "OSGi/Minimum-1.1",
109 "OSGi/Minimum-1.2", "JRE-1.1", "J2SE-1.2", "J2SE-1.3", "J2SE-1.4", "J2SE-1.5", "JavaSE-1.6", "JavaSE-1.7",
110 "PersonalJava-1.1", "PersonalJava-1.2", "CDC-1.0/PersonalBasis-1.0", "CDC-1.0/PersonalJava-1.0"
111 };
Stuart McCullochbb014372012-06-07 21:57:32 +0000112
Stuart McCulloch2286f232012-06-15 13:27:53 +0000113 public final static String OSNAMES[] = {
114 "AIX", // IBM
Stuart McCullochbb014372012-06-07 21:57:32 +0000115 "DigitalUnix", // Compaq
116 "Embos", // Segger Embedded Software Solutions
117 "Epoc32", // SymbianOS Symbian OS
118 "FreeBSD", // Free BSD
119 "HPUX", // hp-ux Hewlett Packard
120 "IRIX", // Silicon Graphics
121 "Linux", // Open source
122 "MacOS", // Apple
123 "NetBSD", // Open source
124 "Netware", // Novell
125 "OpenBSD", // Open source
126 "OS2", // OS/2 IBM
127 "QNX", // procnto QNX
128 "Solaris", // Sun (almost an alias of SunOS)
129 "SunOS", // Sun Microsystems
130 "VxWorks", // WindRiver Systems
131 "Windows95", "Win32", "Windows98", "WindowsNT", "WindowsCE", "Windows2000", // Win2000
132 "Windows2003", // Win2003
Stuart McCulloch2286f232012-06-15 13:27:53 +0000133 "WindowsXP", "WindowsVista",
134 };
Stuart McCullochbb014372012-06-07 21:57:32 +0000135
136 public final static String PROCESSORNAMES[] = { //
Stuart McCulloch2286f232012-06-15 13:27:53 +0000137 //
Stuart McCullochbb014372012-06-07 21:57:32 +0000138 "68k", // Motorola 68000
139 "ARM_LE", // Intel Strong ARM. Deprecated because it does not
140 // specify the endianness. See the following two rows.
141 "arm_le", // Intel Strong ARM Little Endian mode
142 "arm_be", // Intel String ARM Big Endian mode
143 "Alpha", //
144 "ia64n",// Hewlett Packard 32 bit
145 "ia64w",// Hewlett Packard 64 bit mode
146 "Ignite", // psc1k PTSC
147 "Mips", // SGI
148 "PArisc", // Hewlett Packard
149 "PowerPC", // power ppc Motorola/IBM Power PC
150 "Sh4", // Hitachi
151 "Sparc", // SUN
152 "Sparcv9", // SUN
153 "S390", // IBM Mainframe 31 bit
154 "S390x", // IBM Mainframe 64-bit
155 "V850E", // NEC V850E
156 "x86", // pentium i386
157 "i486", // i586 i686 Intel& AMD 32 bit
Stuart McCulloch2286f232012-06-15 13:27:53 +0000158 "x86-64",
159 };
Stuart McCullochbb014372012-06-07 21:57:32 +0000160
161 final Analyzer analyzer;
162 private Instructions dynamicImports;
163
164 public Verifier(Jar jar) throws Exception {
165 this.analyzer = new Analyzer(this);
166 this.analyzer.use(this);
167 addClose(analyzer);
168 this.analyzer.setJar(jar);
169 this.manifest = this.analyzer.calcManifest();
170 this.main = Domain.domain(manifest);
171 this.dot = jar;
172 getInfo(analyzer);
173 }
174
175 public Verifier(Analyzer analyzer) throws Exception {
176 this.analyzer = analyzer;
177 this.dot = analyzer.getJar();
178 this.manifest = dot.getManifest();
179 this.main = Domain.domain(manifest);
180 }
181
182 private void verifyHeaders() {
183 for (String h : main) {
184 if (!HEADER_PATTERN.matcher(h).matches())
185 error("Invalid Manifest header: " + h + ", pattern=" + HEADER_PATTERN);
186 }
187 }
188
189 /*
190 * Bundle-NativeCode ::= nativecode ( ',' nativecode )* ( ’,’ optional) ?
191 * nativecode ::= path ( ';' path )* // See 1.4.2 ( ';' parameter )+
192 * optional ::= ’*’
193 */
194 public void verifyNative() {
195 String nc = get("Bundle-NativeCode");
196 doNative(nc);
197 }
198
199 public void doNative(String nc) {
200 if (nc != null) {
201 QuotedTokenizer qt = new QuotedTokenizer(nc, ",;=", false);
202 char del;
203 do {
204 do {
205 String name = qt.nextToken();
206 if (name == null) {
207 error("Can not parse name from bundle native code header: " + nc);
208 return;
209 }
210 del = qt.getSeparator();
211 if (del == ';') {
212 if (dot != null && !dot.exists(name)) {
213 error("Native library not found in JAR: " + name);
214 }
215 } else {
216 String value = null;
217 if (del == '=')
218 value = qt.nextToken();
219
220 String key = name.toLowerCase();
221 if (key.equals("osname")) {
222 // ...
223 } else if (key.equals("osversion")) {
224 // verify version range
225 verify(value, VERSIONRANGE);
226 } else if (key.equals("language")) {
227 verify(value, ISO639);
228 } else if (key.equals("processor")) {
229 // verify(value, PROCESSORS);
230 } else if (key.equals("selection-filter")) {
231 // verify syntax filter
232 verifyFilter(value);
233 } else if (name.equals("*") && value == null) {
234 // Wildcard must be at end.
235 if (qt.nextToken() != null)
236 error("Bundle-Native code header may only END in wildcard: nc");
237 } else {
238 warning("Unknown attribute in native code: " + name + "=" + value);
239 }
240 del = qt.getSeparator();
241 }
242 } while (del == ';');
243 } while (del == ',');
244 }
245 }
246
247 public boolean verifyFilter(String value) {
248 String s = validateFilter(value);
249 if (s == null)
250 return true;
251
252 error(s);
253 return false;
254 }
255
256 public static String validateFilter(String value) {
257 try {
258 verifyFilter(value, 0);
259 return null;
Stuart McCulloch2286f232012-06-15 13:27:53 +0000260 }
261 catch (Exception e) {
Stuart McCullochbb014372012-06-07 21:57:32 +0000262 return "Not a valid filter: " + value + e.getMessage();
263 }
264 }
265
266 private void verifyActivator() throws Exception {
267 String bactivator = main.get("Bundle-Activator");
268 if (bactivator != null) {
269 TypeRef ref = analyzer.getTypeRefFromFQN(bactivator);
270 if (analyzer.getClassspace().containsKey(ref))
271 return;
272
273 PackageRef packageRef = ref.getPackageRef();
274 if (packageRef.isDefaultPackage())
275 error("The Bundle Activator is not in the bundle and it is in the default package ");
276 else if (!analyzer.isImported(packageRef)) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000277 error("Bundle-Activator not found on the bundle class path nor in imports: " + bactivator);
Stuart McCullochbb014372012-06-07 21:57:32 +0000278 }
279 }
280 }
281
282 private void verifyComponent() {
283 String serviceComponent = main.get("Service-Component");
284 if (serviceComponent != null) {
285 Parameters map = parseHeader(serviceComponent);
286 for (String component : map.keySet()) {
287 if (component.indexOf("*") < 0 && !dot.exists(component)) {
288 error("Service-Component entry can not be located in JAR: " + component);
289 } else {
290 // validate component ...
291 }
292 }
293 }
294 }
295
296 /**
297 * Check for unresolved imports. These are referrals that are not imported
298 * by the manifest and that are not part of our bundle class path. The are
299 * calculated by removing all the imported packages and contained from the
300 * referred packages.
301 */
302 private void verifyUnresolvedReferences() {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000303 Set<PackageRef> unresolvedReferences = new TreeSet<PackageRef>(analyzer.getReferred().keySet());
Stuart McCullochbb014372012-06-07 21:57:32 +0000304 unresolvedReferences.removeAll(analyzer.getImports().keySet());
305 unresolvedReferences.removeAll(analyzer.getContained().keySet());
306
307 // Remove any java.** packages.
308 for (Iterator<PackageRef> p = unresolvedReferences.iterator(); p.hasNext();) {
309 PackageRef pack = p.next();
310 if (pack.isJava())
311 p.remove();
312 else {
313 // Remove any dynamic imports
314 if (isDynamicImport(pack))
315 p.remove();
316 }
317 }
318
319 if (!unresolvedReferences.isEmpty()) {
320 // Now we want to know the
321 // classes that are the culprits
322 Set<String> culprits = new HashSet<String>();
323 for (Clazz clazz : analyzer.getClassspace().values()) {
324 if (hasOverlap(unresolvedReferences, clazz.getReferred()))
325 culprits.add(clazz.getAbsolutePath());
326 }
327
Stuart McCulloch2286f232012-06-15 13:27:53 +0000328 error("Unresolved references to %s by class(es) %s on the Bundle-Classpath: %s", unresolvedReferences,
329 culprits, analyzer.getBundleClasspath().keySet());
Stuart McCullochbb014372012-06-07 21:57:32 +0000330 }
331 }
332
333 /**
334 * @param p
335 * @param pack
336 */
337 private boolean isDynamicImport(PackageRef pack) {
338 if (dynamicImports == null)
339 dynamicImports = new Instructions(main.getDynamicImportPackage());
340
341 return dynamicImports.matches(pack.getFQN());
342 }
343
Stuart McCulloch2286f232012-06-15 13:27:53 +0000344 private boolean hasOverlap(Set< ? > a, Set< ? > b) {
345 for (Iterator< ? > i = a.iterator(); i.hasNext();) {
Stuart McCullochbb014372012-06-07 21:57:32 +0000346 if (b.contains(i.next()))
347 return true;
348 }
349 return false;
350 }
351
352 public void verify() throws Exception {
353 verifyHeaders();
Stuart McCulloch2286f232012-06-15 13:27:53 +0000354 verifyDirectives("Export-Package", "uses:|mandatory:|include:|exclude:|" + IMPORT_DIRECTIVE, PACKAGEPATTERN,
355 "package");
Stuart McCullochbb014372012-06-07 21:57:32 +0000356 verifyDirectives("Import-Package", "resolution:", PACKAGEPATTERN, "package");
357 verifyDirectives("Require-Bundle", "visibility:|resolution:", SYMBOLICNAME, "bsn");
358 verifyDirectives("Fragment-Host", "extension:", SYMBOLICNAME, "bsn");
359 verifyDirectives("Provide-Capability", "effective:|uses:", null, null);
Stuart McCulloch2286f232012-06-15 13:27:53 +0000360 verifyDirectives("Require-Capability", "effective:|resolution:|filter:", null, null);
361 verifyDirectives("Bundle-SymbolicName", "singleton:|fragment-attachment:|mandatory:", SYMBOLICNAME, "bsn");
Stuart McCullochbb014372012-06-07 21:57:32 +0000362
363 verifyManifestFirst();
364 verifyActivator();
365 verifyActivationPolicy();
366 verifyComponent();
367 verifyNative();
368 verifyUnresolvedReferences();
369 verifySymbolicName();
370 verifyListHeader("Bundle-RequiredExecutionEnvironment", EENAME, false);
371 verifyHeader("Bundle-ManifestVersion", BUNDLEMANIFESTVERSION, false);
372 verifyHeader("Bundle-Version", VERSION, true);
373 verifyListHeader("Bundle-Classpath", FILE, false);
374 verifyDynamicImportPackage();
375 verifyBundleClasspath();
376 verifyUses();
377 if (usesRequire) {
378 if (!getErrors().isEmpty()) {
379 getWarnings()
380 .add(0,
381 "Bundle uses Require Bundle, this can generate false errors because then not enough information is available without the required bundles");
382 }
383 }
384
385 verifyRequirements();
386 verifyCapabilities();
387 }
388
389 private void verifyRequirements() {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000390 Parameters map = parseHeader(manifest.getMainAttributes().getValue(Constants.REQUIRE_CAPABILITY));
Stuart McCullochbb014372012-06-07 21:57:32 +0000391 for (String key : map.keySet()) {
392 Attrs attrs = map.get(key);
393 verify(attrs, "filter:", FILTERPATTERN, false, "Requirement %s filter not correct", key);
Stuart McCulloch2286f232012-06-15 13:27:53 +0000394 verify(attrs, "cardinality:", CARDINALITY_PATTERN, false, "Requirement %s cardinality not correct", key);
395 verify(attrs, "resolution:", RESOLUTION_PATTERN, false, "Requirement %s resolution not correct", key);
Stuart McCullochbb014372012-06-07 21:57:32 +0000396
397 if (key.equals("osgi.extender")) {
398 // No requirements on extender
399 } else if (key.equals("osgi.serviceloader")) {
400 verify(attrs, "register:", PACKAGEPATTERN, false,
401 "Service Loader extender register: directive not a fully qualified Java name");
402 } else if (key.equals("osgi.contract")) {
403
404 } else if (key.equals("osgi.service")) {
405
406 } else if (key.equals("osgi.ee")) {
407
408 } else if (key.startsWith("osgi.wiring.") || key.startsWith("osgi.identity")) {
409 error("osgi.wiring.* namespaces must not be specified with generic requirements/capabilities");
410 }
411
412 verifyAttrs(attrs);
413
414 if (attrs.containsKey("mandatory:"))
415 error("mandatory: directive is intended for Capabilities, not Requirement %s", key);
416
417 if (attrs.containsKey("uses:"))
418 error("uses: directive is intended for Capabilities, not Requirement %s", key);
419 }
420 }
421
422 /**
423 * @param attrs
424 */
425 void verifyAttrs(Attrs attrs) {
426 for (String a : attrs.keySet()) {
427 String v = attrs.get(a);
428
429 if (!a.endsWith(":")) {
430 Attrs.Type t = attrs.getType(a);
431 if ("version".equals(a)) {
432 if (t != Attrs.Type.VERSION)
433 error("Version attributes should always be of type version, it is %s", t);
434 } else
435 verifyType(t, v);
436 }
437 }
438 }
439
440 private void verifyCapabilities() {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000441 Parameters map = parseHeader(manifest.getMainAttributes().getValue(Constants.PROVIDE_CAPABILITY));
Stuart McCullochbb014372012-06-07 21:57:32 +0000442 for (String key : map.keySet()) {
443 Attrs attrs = map.get(key);
Stuart McCulloch2286f232012-06-15 13:27:53 +0000444 verify(attrs, "cardinality:", CARDINALITY_PATTERN, false, "Requirement %s cardinality not correct", key);
445 verify(attrs, "resolution:", RESOLUTION_PATTERN, false, "Requirement %s resolution not correct", key);
Stuart McCullochbb014372012-06-07 21:57:32 +0000446
447 if (key.equals("osgi.extender")) {
448 verify(attrs, "osgi.extender", SYMBOLICNAME, true,
449 "Extender %s must always have the osgi.extender attribute set", key);
Stuart McCulloch2286f232012-06-15 13:27:53 +0000450 verify(attrs, "version", VERSION, true, "Extender %s must always have a version", key);
Stuart McCullochbb014372012-06-07 21:57:32 +0000451 } else if (key.equals("osgi.serviceloader")) {
452 verify(attrs, "register:", PACKAGEPATTERN, false,
453 "Service Loader extender register: directive not a fully qualified Java name");
454 } else if (key.equals("osgi.contract")) {
455 verify(attrs, "osgi.contract", SYMBOLICNAME, true,
456 "Contracts %s must always have the osgi.contract attribute set", key);
457
458 } else if (key.equals("osgi.service")) {
459 verify(attrs, "objectClass", PACKAGEPATTERN, true,
460 "osgi.service %s must have the objectClass attribute set", key);
461
462 } else if (key.equals("osgi.ee")) {
463 // TODO
464 } else if (key.startsWith("osgi.wiring.") || key.startsWith("osgi.identity")) {
465 error("osgi.wiring.* namespaces must not be specified with generic requirements/capabilities");
466 }
467
468 verifyAttrs(attrs);
469
470 if (attrs.containsKey("filter:"))
471 error("filter: directive is intended for Requirements, not Capability %s", key);
472 if (attrs.containsKey("cardinality:"))
473 error("cardinality: directive is intended for Requirements, not Capability %s", key);
474 if (attrs.containsKey("resolution:"))
475 error("resolution: directive is intended for Requirements, not Capability %s", key);
476 }
477 }
478
Stuart McCulloch2286f232012-06-15 13:27:53 +0000479 private void verify(Attrs attrs, String ad, Pattern pattern, boolean mandatory, String msg, String... args) {
Stuart McCullochbb014372012-06-07 21:57:32 +0000480 String v = attrs.get(ad);
481 if (v == null) {
482 if (mandatory)
483 error("Missing required attribute/directive %s", ad);
484 } else {
485 Matcher m = pattern.matcher(v);
486 if (!m.matches())
487 error(msg, (Object[]) args);
488 }
489 }
490
491 private void verifyType(Attrs.Type type, String string) {
492
493 }
494
495 /**
496 * Verify if the header does not contain any other directives
497 *
498 * @param header
499 * @param directives
500 */
501 private void verifyDirectives(String header, String directives, Pattern namePattern, String type) {
502 Pattern pattern = Pattern.compile(directives);
503 Parameters map = parseHeader(manifest.getMainAttributes().getValue(header));
Stuart McCulloch2286f232012-06-15 13:27:53 +0000504 for (Entry<String,Attrs> entry : map.entrySet()) {
Stuart McCullochbb014372012-06-07 21:57:32 +0000505 String pname = removeDuplicateMarker(entry.getKey());
506
507 if (namePattern != null) {
508 if (!namePattern.matcher(pname).matches())
509 if (isPedantic())
510 error("Invalid %s name: '%s'", type, pname);
511 else
512 warning("Invalid %s name: '%s'", type, pname);
513 }
Stuart McCulloch2286f232012-06-15 13:27:53 +0000514
Stuart McCullochbb014372012-06-07 21:57:32 +0000515 for (String key : entry.getValue().keySet()) {
516 if (key.endsWith(":")) {
517 if (!key.startsWith("x-")) {
518 Matcher m = pattern.matcher(key);
519 if (m.matches())
520 continue;
521
Stuart McCulloch2286f232012-06-15 13:27:53 +0000522 warning("Unknown directive %s in %s, allowed directives are %s, and 'x-*'.", key, header,
523 directives.replace('|', ','));
Stuart McCullochbb014372012-06-07 21:57:32 +0000524 }
525 }
526 }
527 }
528 }
529
530 /**
531 * Verify the use clauses
532 */
533 private void verifyUses() {
534 // Set<String> uses = Create.set();
535 // for ( Map<String,String> attrs : analyzer.getExports().values()) {
536 // if ( attrs.containsKey(Constants.USES_DIRECTIVE)) {
537 // String s = attrs.get(Constants.USES_DIRECTIVE);
538 // uses.addAll( split(s));
539 // }
540 // }
541 // uses.removeAll(analyzer.getExports().keySet());
542 // uses.removeAll(analyzer.getImports().keySet());
543 // if ( !uses.isEmpty())
544 // warning("Export-Package uses: directive contains packages that are not imported nor exported: %s",
545 // uses);
546 }
547
548 public boolean verifyActivationPolicy() {
549 String policy = main.get(Constants.BUNDLE_ACTIVATIONPOLICY);
550 if (policy == null)
551 return true;
552
553 return verifyActivationPolicy(policy);
554 }
555
556 public boolean verifyActivationPolicy(String policy) {
557 Parameters map = parseHeader(policy);
558 if (map.size() == 0)
559 warning("Bundle-ActivationPolicy is set but has no argument %s", policy);
560 else if (map.size() > 1)
561 warning("Bundle-ActivationPolicy has too many arguments %s", policy);
562 else {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000563 Map<String,String> s = map.get("lazy");
Stuart McCullochbb014372012-06-07 21:57:32 +0000564 if (s == null)
565 warning("Bundle-ActivationPolicy set but is not set to lazy: %s", policy);
566 else
567 return true;
568 }
569
570 return false;
571 }
572
573 public void verifyBundleClasspath() {
574 Parameters bcp = main.getBundleClassPath();
575 if (bcp.isEmpty() || bcp.containsKey("."))
576 return;
577
578 for (String path : bcp.keySet()) {
579 if (path.endsWith("/"))
580 error("A Bundle-ClassPath entry must not end with '/': %s", path);
581
582 if (dot.getDirectories().containsKey(path))
583 // We assume that any classes are in a directory
584 // and therefore do not care when the bundle is included
585 return;
586 }
587
588 for (String path : dot.getResources().keySet()) {
589 if (path.endsWith(".class")) {
590 warning("The Bundle-Classpath does not contain the actual bundle JAR (as specified with '.' in the Bundle-Classpath) but the JAR does contain classes. Is this intentional?");
591 return;
592 }
593 }
594 }
595
596 /**
597 * <pre>
598 * DynamicImport-Package ::= dynamic-description
599 * ( ',' dynamic-description )*
600 *
601 * dynamic-description::= wildcard-names ( ';' parameter )*
602 * wildcard-names ::= wildcard-name ( ';' wildcard-name )*
603 * wildcard-name ::= package-name
604 * | ( package-name '.*' ) // See 1.4.2
605 * | '*'
606 * </pre>
607 */
608 private void verifyDynamicImportPackage() {
609 verifyListHeader("DynamicImport-Package", WILDCARDPACKAGE, true);
610 String dynamicImportPackage = get("DynamicImport-Package");
611 if (dynamicImportPackage == null)
612 return;
613
614 Parameters map = main.getDynamicImportPackage();
615 for (String name : map.keySet()) {
616 name = name.trim();
617 if (!verify(name, WILDCARDPACKAGE))
618 error("DynamicImport-Package header contains an invalid package name: " + name);
619
Stuart McCulloch2286f232012-06-15 13:27:53 +0000620 Map<String,String> sub = map.get(name);
Stuart McCullochbb014372012-06-07 21:57:32 +0000621 if (r3 && sub.size() != 0) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000622 error("DynamicPackage-Import has attributes on import: " + name
Stuart McCullochbb014372012-06-07 21:57:32 +0000623 + ". This is however, an <=R3 bundle and attributes on this header were introduced in R4. ");
624 }
625 }
626 }
627
628 private void verifyManifestFirst() {
629 if (!dot.isManifestFirst()) {
630 error("Invalid JAR stream: Manifest should come first to be compatible with JarInputStream, it was not");
631 }
632 }
633
634 private void verifySymbolicName() {
635 Parameters bsn = parseHeader(main.get(Analyzer.BUNDLE_SYMBOLICNAME));
636 if (!bsn.isEmpty()) {
637 if (bsn.size() > 1)
638 error("More than one BSN specified " + bsn);
639
640 String name = bsn.keySet().iterator().next();
641 if (!isBsn(name)) {
642 error("Symbolic Name has invalid format: " + name);
643 }
644 }
645 }
646
647 /**
648 * @param name
649 * @return
650 */
651 public static boolean isBsn(String name) {
652 return SYMBOLICNAME.matcher(name).matches();
653 }
654
655 /**
656 * <pre>
657 * filter ::= ’(’ filter-comp ’)’
658 * filter-comp ::= and | or | not | operation
659 * and ::= ’&amp;’ filter-list
660 * or ::= ’|’ filter-list
661 * not ::= ’!’ filter
662 * filter-list ::= filter | filter filter-list
663 * operation ::= simple | present | substring
664 * simple ::= attr filter-type value
665 * filter-type ::= equal | approx | greater | less
666 * equal ::= ’=’
667 * approx ::= ’&tilde;=’
668 * greater ::= ’&gt;=’
669 * less ::= ’&lt;=’
670 * present ::= attr ’=*’
671 * substring ::= attr ’=’ initial any final
672 * inital ::= () | value
673 * any ::= ’*’ star-value
674 * star-value ::= () | value ’*’ star-value
675 * final ::= () | value
676 * value ::= &lt;see text&gt;
677 * </pre>
678 *
679 * @param expr
680 * @param index
681 * @return
682 */
683
684 public static int verifyFilter(String expr, int index) {
685 try {
686 while (Character.isWhitespace(expr.charAt(index)))
687 index++;
688
689 if (expr.charAt(index) != '(')
Stuart McCulloch2286f232012-06-15 13:27:53 +0000690 throw new IllegalArgumentException("Filter mismatch: expected ( at position " + index + " : " + expr);
Stuart McCullochbb014372012-06-07 21:57:32 +0000691
692 index++; // skip (
693
694 while (Character.isWhitespace(expr.charAt(index)))
695 index++;
696
697 switch (expr.charAt(index)) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000698 case '!' :
699 index++; // skip !
700 while (Character.isWhitespace(expr.charAt(index)))
701 index++;
Stuart McCullochbb014372012-06-07 21:57:32 +0000702
Stuart McCulloch2286f232012-06-15 13:27:53 +0000703 if (expr.charAt(index) != '(')
704 throw new IllegalArgumentException("Filter mismatch: ! (not) must have one sub expression "
705 + index + " : " + expr);
706 while (Character.isWhitespace(expr.charAt(index)))
707 index++;
Stuart McCullochbb014372012-06-07 21:57:32 +0000708
Stuart McCullochbb014372012-06-07 21:57:32 +0000709 index = verifyFilter(expr, index);
710 while (Character.isWhitespace(expr.charAt(index)))
711 index++;
Stuart McCulloch2286f232012-06-15 13:27:53 +0000712 if (expr.charAt(index) != ')')
713 throw new IllegalArgumentException("Filter mismatch: expected ) at position " + index + " : "
714 + expr);
715 return index + 1;
Stuart McCullochbb014372012-06-07 21:57:32 +0000716
Stuart McCulloch2286f232012-06-15 13:27:53 +0000717 case '&' :
718 case '|' :
719 index++; // skip operator
720 while (Character.isWhitespace(expr.charAt(index)))
721 index++;
722 while (expr.charAt(index) == '(') {
723 index = verifyFilter(expr, index);
724 while (Character.isWhitespace(expr.charAt(index)))
725 index++;
726 }
Stuart McCullochbb014372012-06-07 21:57:32 +0000727
Stuart McCulloch2286f232012-06-15 13:27:53 +0000728 if (expr.charAt(index) != ')')
729 throw new IllegalArgumentException("Filter mismatch: expected ) at position " + index + " : "
730 + expr);
731 return index + 1; // skip )
732
733 default :
734 index = verifyFilterOperation(expr, index);
735 if (expr.charAt(index) != ')')
736 throw new IllegalArgumentException("Filter mismatch: expected ) at position " + index + " : "
737 + expr);
738 return index + 1;
Stuart McCullochbb014372012-06-07 21:57:32 +0000739 }
Stuart McCulloch2286f232012-06-15 13:27:53 +0000740 }
741 catch (IndexOutOfBoundsException e) {
Stuart McCullochbb014372012-06-07 21:57:32 +0000742 throw new IllegalArgumentException("Filter mismatch: early EOF from " + index);
743 }
744 }
745
746 static private int verifyFilterOperation(String expr, int index) {
747 StringBuilder sb = new StringBuilder();
748 while ("=><~()".indexOf(expr.charAt(index)) < 0) {
749 sb.append(expr.charAt(index++));
750 }
751 String attr = sb.toString().trim();
752 if (attr.length() == 0)
753 throw new IllegalArgumentException("Filter mismatch: attr at index " + index + " is 0");
754 sb = new StringBuilder();
755 while ("=><~".indexOf(expr.charAt(index)) >= 0) {
756 sb.append(expr.charAt(index++));
757 }
758 String operator = sb.toString();
759 if (!verify(operator, FILTEROP))
Stuart McCulloch2286f232012-06-15 13:27:53 +0000760 throw new IllegalArgumentException("Filter error, illegal operator " + operator + " at index " + index);
Stuart McCullochbb014372012-06-07 21:57:32 +0000761
762 sb = new StringBuilder();
763 while (")".indexOf(expr.charAt(index)) < 0) {
764 switch (expr.charAt(index)) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000765 case '\\' :
766 if ("\\)(*".indexOf(expr.charAt(index + 1)) >= 0)
767 index++;
768 else
769 throw new IllegalArgumentException("Filter error, illegal use of backslash at index " + index
770 + ". Backslash may only be used before * or () or \\");
Stuart McCullochbb014372012-06-07 21:57:32 +0000771 }
772 sb.append(expr.charAt(index++));
773 }
774 return index;
775 }
776
777 private boolean verifyHeader(String name, Pattern regex, boolean error) {
778 String value = manifest.getMainAttributes().getValue(name);
779 if (value == null)
780 return false;
781
782 QuotedTokenizer st = new QuotedTokenizer(value.trim(), ",");
783 for (Iterator<String> i = st.getTokenSet().iterator(); i.hasNext();) {
784 if (!verify(i.next(), regex)) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000785 String msg = "Invalid value for " + name + ", " + value + " does not match " + regex.pattern();
Stuart McCullochbb014372012-06-07 21:57:32 +0000786 if (error)
787 error(msg);
788 else
789 warning(msg);
790 }
791 }
792 return true;
793 }
794
795 static private boolean verify(String value, Pattern regex) {
796 return regex.matcher(value).matches();
797 }
798
799 private boolean verifyListHeader(String name, Pattern regex, boolean error) {
800 String value = manifest.getMainAttributes().getValue(name);
801 if (value == null)
802 return false;
803
804 Parameters map = parseHeader(value);
805 for (String header : map.keySet()) {
806 if (!regex.matcher(header).matches()) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000807 String msg = "Invalid value for " + name + ", " + value + " does not match " + regex.pattern();
Stuart McCullochbb014372012-06-07 21:57:32 +0000808 if (error)
809 error(msg);
810 else
811 warning(msg);
812 }
813 }
814 return true;
815 }
816
817 public String getProperty(String key, String deflt) {
818 if (properties == null)
819 return deflt;
820 return properties.getProperty(key, deflt);
821 }
822
823 public static boolean isVersion(String version) {
824 return VERSION.matcher(version).matches();
825 }
826
827 public static boolean isIdentifier(String value) {
828 if (value.length() < 1)
829 return false;
830
831 if (!Character.isJavaIdentifierStart(value.charAt(0)))
832 return false;
833
834 for (int i = 1; i < value.length(); i++) {
835 if (!Character.isJavaIdentifierPart(value.charAt(i)))
836 return false;
837 }
838 return true;
839 }
840
841 public static boolean isMember(String value, String[] matches) {
842 for (String match : matches) {
843 if (match.equals(value))
844 return true;
845 }
846 return false;
847 }
848
849 public static boolean isFQN(String name) {
850 if (name.length() == 0)
851 return false;
852 if (!Character.isJavaIdentifierStart(name.charAt(0)))
853 return false;
854
855 for (int i = 1; i < name.length(); i++) {
856 char c = name.charAt(i);
857 if (Character.isJavaIdentifierPart(c) || c == '$' || c == '.')
858 continue;
859
860 return false;
861 }
862
863 return true;
864 }
865
866 /**
867 * Verify checksums
868 */
869 /**
870 * Verify the checksums from the manifest against the real thing.
871 *
872 * @param all
873 * if each resources must be digested
874 * @return true if ok
875 * @throws Exception
876 */
877
878 public void verifyChecksums(boolean all) throws Exception {
879 Manifest m = dot.getManifest();
880 if (m == null || m.getEntries().isEmpty()) {
881 if (all)
882 error("Verify checksums with all but no digests");
883 return;
884 }
885
886 List<String> missingDigest = new ArrayList<String>();
887
888 for (String path : dot.getResources().keySet()) {
889 if (path.equals("META-INF/MANIFEST.MF"))
890 continue;
891
892 Attributes a = m.getAttributes(path);
893 String digest = a.getValue("SHA1-Digest");
894 if (digest == null) {
895 if (!path.matches(""))
896 missingDigest.add(path);
897 } else {
898 byte[] d = Base64.decodeBase64(digest);
899 SHA1 expected = new SHA1(d);
900 Digester<SHA1> digester = SHA1.getDigester();
901 InputStream in = dot.getResource(path).openInputStream();
902 IO.copy(in, digester);
903 digester.digest();
904 if (!expected.equals(digester.digest())) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000905 error("Checksum mismatch %s, expected %s, got %s", path, expected, digester.digest());
Stuart McCullochbb014372012-06-07 21:57:32 +0000906 }
907 }
908 }
909 if (missingDigest.size() > 0) {
910 error("Entries in the manifest are missing digests: %s", missingDigest);
911 }
912 }
913}