Debian Codegraph @

ssl-proxies/src/main/java/org/globus/gsi/gridmap/GridMap.java

raw
1 /*
2 * Copyright 1999-2010 University of Chicago
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 * express or implied.
12 *
13 * See the License for the specific language governing permissions and limitations under the License.
14 */
15 package org.globus.gsi.gridmap;
16
17 import java.util.Map;
18 import java.util.Vector;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.StringTokenizer;
22 import java.io.IOException;
23 import java.io.File;
24 import java.io.BufferedReader;
25 import java.io.InputStreamReader;
26 import java.io.FileInputStream;
27 import java.io.InputStream;
28 import java.io.Serializable;
29
30 import org.globus.util.I18n;
31
32 import org.globus.util.QuotedStringTokenizer;
33 import org.globus.util.ConfigUtil;
34
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37
38 public class GridMap implements Serializable {
39
40 private static I18n i18n =
41 I18n.getI18n("org.globus.gsi.gridmap.errors",
42 GridMap.class.getClassLoader());
43
44 private static Log logger =
45 LogFactory.getLog(GridMap.class.getName());
46
47 private static final String COMMENT_CHARS = "#";
48 // keywords that need to be replaced
49 private static final char[] EMAIL_KEYWORD_1 = { 'e', '=' };
50 private static final char[] EMAIL_KEYWORD_2 = { 'e', 'm', 'a', 'i', 'l',
51 '=' };
52 private static final char[] UID_KEYWORD = { 'u', 'i', 'd', '=' };
53 // Length of key words that need to be replaced
54 private static final int EMAIL_KEYWORD_1_L = 2;
55 private static final int EMAIL_KEYWORD_2_L = 6;
56 private static final int UID_KEYWORD_L = 4;
57 // Keywords to be replaced with.
58 private static final String EMAIL_KEYWORD = "emailaddress=";
59 private static final String USERID_KEYWORD = "userid=";
60
61 protected Map map;
62
63 // the file the grim map was loaded from
64 private File file;
65 // last time the file was modified
66 private long lastModified;
67 // log or throw exception on bad entries
68 private boolean ignoreErrors = false;
69
70 /**
71 * Sets whether errors in the gridmap file
72 * should be ignored. Errors are not ignored by default.
73 *
74 * @param ignoreErrors if true, errors in the gridmap file
75 * will be ignored (warnings will be logged). If false,
76 * an exception will be raised on errors.
77 */
78 public void setIgnoreErrors(boolean ignoreErrors) {
79 this.ignoreErrors = ignoreErrors;
80 }
81
82 /**
83 * Returns whether errors in the gridmap file are
84 * ignored.
85 *
86 * @return true if errors in the gridmap file are ignored.
87 * False, otherwise.
88 */
89 public boolean getIgnoreErrors() {
90 return this.ignoreErrors;
91 }
92
93 /**
94 * Returns the absolute path anme of file used to load gridmap
95 * either using the {@link #load(File) load} or {@link
96 * #load(String) load} functions. If no file was used, returns
97 * null.
98 *
99 * @return absolute file path, if gridmap was loaded from
100 * file. Null otherwise.
101 */
102 public String getFileName() {
103
104 if (this.file == null) {
105 return null;
106 }
107
108 return this.file.getAbsolutePath();
109 }
110
111 /**
112 * Loads grid map definition from a given file.
113 *
114 * @param file the grid map file
115 * @exception IOException in case of I/O error or
116 * when there are parsing errors in the file (only when errors
117 * are not ignored).
118 * @return <tt>true</tt> if the file was parsed and loaded successfully.
119 * <tt>False</tt> otherwise.
120 */
121 public boolean load(String file)
122 throws IOException {
123 return load(new File(file));
124 }
125
126 /**
127 * Loads grid map definition from a given file.
128 *
129 * @param file the grid map file
130 * @exception IOException in case of I/O error or
131 * when there are parsing errors in the file (only when errors
132 * are not ignored).
133 * @return <tt>true</tt> if the file was parsed and loaded successfully.
134 * <tt>False</tt> otherwise.
135 */
136 public boolean load(File file)
137 throws IOException {
138 InputStream in = null;
139 try {
140 in = new FileInputStream(file);
141 this.file = file;
142 this.lastModified = file.lastModified();
143 return load(in);
144 } finally {
145 if (in != null) {
146 try { in.close(); } catch(Exception e) {}
147 }
148 }
149 }
150
151 /**
152 * Reloads the gridmap from a file only if the gridmap
153 * was initially loaded using the {@link #load(File)
154 * load} or {@link #load(String) load} functions.
155 * The file will only be reloaded if it has changed
156 * since the last time.
157 *
158 * @exception IOException in case of I/O error or
159 * when there are parsing errors in the file (only when errors
160 * are not ignored).
161 * @return <tt>true</tt> if the file was parsed and refreshed successfully.
162 * <tt>False</tt> otherwise.
163 */
164 public boolean refresh()
165 throws IOException {
166 if (this.file != null &&
167 this.file.lastModified() != this.lastModified) {
168 return load(this.file);
169 } else {
170 return true;
171 }
172 }
173
174 /**
175 * Loads grid map file definition from a given input stream. The input
176 * stream is not closed in case of an error.
177 *
178 * @param input the input stream that contains the gridmap
179 * definitions.
180 * @exception IOException in case of I/O error or
181 * when there are parsing errors in the input (only when errors
182 * are not ignored).
183 * @return <tt>true</tt> if the input was parsed successfully.
184 * <tt>False</tt> otherwise.
185 */
186 public boolean load(InputStream input)
187 throws IOException {
188 boolean success = true;
189
190 BufferedReader reader =
191 new BufferedReader(new InputStreamReader(input));
192
193 Map localMap = new HashMap();
194 GridMapEntry entry;
195 QuotedStringTokenizer tokenizer;
196 StringTokenizer idTokenizer;
197 String line;
198 while( (line = reader.readLine()) != null) {
199 line = line.trim();
200 if ( (line.length() == 0) ||
201 ( COMMENT_CHARS.indexOf(line.charAt(0)) != -1) ) {
202 continue;
203 }
204
205 tokenizer = new QuotedStringTokenizer(line);
206
207 String globusID = null;
208
209 if (tokenizer.hasMoreTokens()) {
210 globusID = tokenizer.nextToken();
211 } else {
212 if (this.ignoreErrors) {
213 success = false;
214 logger.warn("Globus ID missing: " + line);
215 continue;
216 } else {
217 throw new IOException(i18n.getMessage("globusIdErr",
218 line));
219 }
220 }
221
222 String userIDs = null;
223
224 if (tokenizer.hasMoreTokens()) {
225 userIDs = tokenizer.nextToken();
226 } else {
227 if (this.ignoreErrors) {
228 success = false;
229 logger.warn("User ID mapping missing: " + line);
230 continue;
231 } else {
232 throw new IOException(i18n.getMessage("userIdErr", line));
233 }
234 }
235
236 idTokenizer = new StringTokenizer(userIDs, ",");
237 String [] ids = new String [ idTokenizer.countTokens() ];
238 int i = 0;
239 while(idTokenizer.hasMoreTokens()) {
240 ids[i++] = idTokenizer.nextToken();
241 }
242
243 String normalizedDN = normalizeDN(globusID);
244 entry = (GridMapEntry)localMap.get(normalizedDN);
245 if (entry == null) {
246 entry = new GridMapEntry();
247 entry.setGlobusID(globusID);
248 entry.setUserIDs(ids);
249 localMap.put(normalizedDN, entry);
250 } else {
251 entry.addUserIDs(ids);
252 }
253 }
254
255 this.map = localMap;
256
257 return success;
258 }
259
260 /**
261 * Returns first local user name mapped to the specified
262 * globusID.
263 *
264 * @param globusID globusID
265 * @return local user name for the specified globusID.
266 * Null if the globusID is not mapped
267 * to a local user name.
268 */
269 public String getUserID(String globusID) {
270 String [] ids = getUserIDs(globusID);
271 if (ids != null && ids.length > 0) {
272 return ids[0];
273 } else {
274 return null;
275 }
276 }
277
278 /**
279 * Returns local user names mapped to the specified
280 * globusID.
281 *
282 * @param globusID globusID
283 * @return array of local user names for the specified globusID.
284 * Null if the globusID is not mapped
285 * to any local user name.
286 */
287 public String[] getUserIDs(String globusID) {
288 if (globusID == null) {
289 throw new IllegalArgumentException(i18n
290 .getMessage("globusIdNull"));
291 }
292
293 if (this.map == null) {
294 return null;
295 }
296
297 GridMapEntry entry = (GridMapEntry)this.map.get(normalizeDN(globusID));
298 return (entry == null) ? null : entry.getUserIDs();
299 }
300
301 /**
302 * Checks if a given globus ID is associated with given
303 * local user account.
304 *
305 * @param globusID globus ID
306 * @param userID userID
307 * @return true if globus ID is associated with given local
308 * user account, false, otherwise.
309 */
310 public boolean checkUser(String globusID, String userID) {
311 if (globusID == null) {
312 throw new IllegalArgumentException(i18n.getMessage("glousIdNull"));
313 }
314 if (userID == null) {
315 throw new IllegalArgumentException(i18n.getMessage("userIdNull"));
316 }
317
318 if (this.map == null) {
319 return false;
320 }
321
322 GridMapEntry entry = (GridMapEntry)this.map.get(normalizeDN(globusID));
323 return (entry == null) ? false : entry.containsUserID(userID);
324 }
325
326 /**
327 * Returns globus ID associated with the
328 * specified local user name.
329 *
330 * @param userID local user name
331 * @return associated globus ID, null
332 * if there is not any.
333 */
334 public String getGlobusID(String userID) {
335 if (userID == null) {
336 throw new IllegalArgumentException(i18n.getMessage("userIdNull"));
337 }
338
339 if (this.map == null) {
340 return null;
341 }
342
343 Iterator iter = this.map.entrySet().iterator();
344 Map.Entry mapEntry;
345 GridMapEntry entry;
346 while(iter.hasNext()) {
347 mapEntry = (Map.Entry)iter.next();
348 entry = (GridMapEntry)mapEntry.getValue();
349 if (entry.containsUserID(userID)) {
350 return entry.getGlobusID();
351 }
352 }
353 return null;
354 }
355
356 /**
357 * Returns all globus IDs associated with the
358 * specified local user name.
359 *
360 * @param userID local user name
361 * @return associated globus ID, null
362 * if there is not any.
363 */
364 public String[] getAllGlobusID(String userID) {
365 if (userID == null) {
366 throw new IllegalArgumentException(i18n.getMessage("userIdNull"));
367 }
368
369 if (this.map == null) {
370 return null;
371 }
372
373 Vector v = new Vector();
374
375 Iterator iter = this.map.entrySet().iterator();
376 Map.Entry mapEntry;
377 GridMapEntry entry;
378 while(iter.hasNext()) {
379 mapEntry = (Map.Entry)iter.next();
380 entry = (GridMapEntry)mapEntry.getValue();
381 if (entry.containsUserID(userID)) {
382 v.add(entry.getGlobusID());
383 }
384 }
385
386 // create array of strings and add values back in
387 if(v.size() == 0) {
388 return null;
389 }
390
391 String idS[] = new String[v.size()];
392 for(int ctr = 0; ctr < v.size(); ctr++) {
393 idS[ctr] = (String) v.elementAt(ctr);
394 }
395
396 return idS;
397 }
398
399 public void map(String globusID, String userID) {
400 if (globusID == null) {
401 throw new IllegalArgumentException(i18n
402 .getMessage("globusIdNull"));
403 }
404 if (userID == null) {
405 throw new IllegalArgumentException(i18n.getMessage("userIdNull"));
406 }
407
408 if (this.map == null) {
409 this.map = new HashMap();
410 }
411
412 String normalizedDN = normalizeDN(globusID);
413
414 GridMapEntry entry = (GridMapEntry)this.map.get(normalizedDN);
415 if (entry == null) {
416 entry = new GridMapEntry();
417 entry.setGlobusID(globusID);
418 entry.setUserIDs(new String [] {userID});
419 this.map.put(normalizedDN, entry);
420 } else {
421 entry.addUserID(userID);
422 }
423 }
424
425 static class GridMapEntry implements Serializable {
426 String globusID;
427 String[] userIDs;
428
429 public String getFirstUserID() {
430 return userIDs[0];
431 }
432
433 public String[] getUserIDs() {
434 return userIDs;
435 }
436
437 public String getGlobusID() {
438 return globusID;
439 }
440
441 public void setGlobusID(String globusID) {
442 this.globusID = globusID;
443 }
444
445 public void setUserIDs(String [] userIDs) {
446 this.userIDs = userIDs;
447 }
448
449 public boolean containsUserID(String userID) {
450 if (userID == null) {
451 return false;
452 }
453 for (int i=0;i<userIDs.length;i++) {
454 if (userIDs[i].equalsIgnoreCase(userID)) {
455 return true;
456 }
457 }
458 return false;
459 }
460
461 public void addUserID(String userID) {
462 if (containsUserID(userID)) return;
463 String [] ids = new String[ userIDs.length + 1 ];
464 System.arraycopy(userIDs, 0, ids, 0, userIDs.length);
465 ids[userIDs.length] = userID;
466 userIDs = ids;
467 }
468
469 public void addUserIDs(String [] userIDs) {
470 for (int i=0;i<userIDs.length;i++) {
471 addUserID(userIDs[i]);
472 }
473 }
474
475 }
476
477 private static boolean keyWordPresent(char[] args, int startIndex,
478 char[] keyword, int length) {
479
480 if (startIndex + length > args.length) {
481 return false;
482 }
483
484 int j=startIndex;
485 for (int i=0; i<length; i++) {
486 if (args[j] != keyword[i]) {
487 return false;
488 }
489 j++;
490 }
491 return true;
492 }
493
494 public static String normalizeDN(String globusID) {
495
496 if (globusID == null) {
497 return null;
498 }
499
500 globusID = globusID.toLowerCase();
501 char[] globusIdChars = globusID.toCharArray();
502
503 StringBuffer normalizedDN = new StringBuffer();
504
505 int i=0;
506
507 while (i<globusIdChars.length) {
508
509 if (globusIdChars[i] == '/') {
510
511 normalizedDN.append("/");
512
513 if (keyWordPresent(globusIdChars, i+1, EMAIL_KEYWORD_1,
514 EMAIL_KEYWORD_1_L)) {
515 normalizedDN.append(EMAIL_KEYWORD);
516 i = i + EMAIL_KEYWORD_1_L;
517 } else if (keyWordPresent(globusIdChars, i+1, EMAIL_KEYWORD_2,
518 EMAIL_KEYWORD_2_L)) {
519 normalizedDN.append(EMAIL_KEYWORD);
520 i = i + EMAIL_KEYWORD_2_L;
521 } else if (keyWordPresent(globusIdChars, i+1, UID_KEYWORD,
522 UID_KEYWORD_L)) {
523 normalizedDN.append(USERID_KEYWORD);
524 i = i + UID_KEYWORD_L;
525 }
526 i++;
527 } else {
528 normalizedDN.append(globusIdChars[i]);
529 i++;
530 }
531 }
532
533 return normalizedDN.toString();
534 }
535
536 /*
537 * Determine the location of the gridmap file based on the standard
538 * Globus logic:
539 * 1. If the GRIDMAP system property is set, return it.
540 * 2. If the user is not root, return $HOME/.gridmap
541 * 3. Otherwise, return /etc/grid-security/grid-mapfile
542 */
543 public static String getDefaultGridMapLocation() {
544 String location = System.getProperty("GRIDMAP");
545 if (location == null || location.length() == 0) {
546 String uid = null;
547 try {
548 uid = ConfigUtil.getUID();
549 } catch (IOException e) {
550 // ignore it
551 }
552 if (uid != null && uid.equals("0")) {
553 location = "/etc/grid-security/grid-mapfile";
554 } else {
555 location = System.getProperty("user.home") + "/.gridmap";
556 }
557 }
558 return location;
559 }
560 }