Project

General

Profile

1 555 bojilova
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that loads eml-access.xml file containing ACL
4
 *             for a metadata document into relational DB
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Jivka Bojilova
8
 *    Release: @release@
9
 *
10
 *   '$Author$'
11
 *     '$Date$'
12
 * '$Revision$'
13 669 jones
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27 555 bojilova
 */
28
29
package edu.ucsb.nceas.metacat;
30
31
import java.io.*;
32
import java.sql.*;
33
import java.util.Stack;
34
import java.util.Vector;
35 652 bojilova
import java.util.Hashtable;
36
import java.net.URL;
37
import java.net.MalformedURLException;
38 555 bojilova
39
import org.xml.sax.Attributes;
40
import org.xml.sax.InputSource;
41 598 bojilova
import org.xml.sax.ContentHandler;
42
import org.xml.sax.EntityResolver;
43
import org.xml.sax.ErrorHandler;
44 555 bojilova
import org.xml.sax.SAXException;
45
import org.xml.sax.SAXParseException;
46
import org.xml.sax.XMLReader;
47
import org.xml.sax.helpers.XMLReaderFactory;
48
import org.xml.sax.helpers.DefaultHandler;
49
50
/**
51
 * A Class that loads eml-access.xml file containing ACL for a metadata
52
 * document into relational DB. It extends DefaultHandler class to handle
53
 * SAX parsing events when processing the XML stream.
54
 */
55
public class AccessControlList extends DefaultHandler {
56
57 862 berkley
  private static final int CHMOD = 1;
58 774 bojilova
  private static final int WRITE = 2;
59
  private static final int READ = 4;
60 862 berkley
  private static final int ALL = 7;
61 774 bojilova
  private static String sysdate = MetaCatUtil.dbAdapter.getDateTimeFunction();
62
  private static String isnull = MetaCatUtil.dbAdapter.getIsNULLFunction();
63 555 bojilova
64 570 bojilova
  private Connection conn;
65 555 bojilova
  private String parserName;
66
  private Stack elementStack;
67 645 bojilova
  private String server;
68 802 bojilova
  private String sep;
69 555 bojilova
70 598 bojilova
  private boolean	processingDTD;
71 645 bojilova
  private String  user;
72 802 bojilova
  private String[] groups;
73 638 bojilova
  private String  aclid;
74 802 bojilova
  private int     rev;
75 598 bojilova
  private String 	docname;
76
  private String 	doctype;
77
  private String 	systemid;
78
79 665 bojilova
  private String docurl;
80
  private Vector resourceURL;
81
  private Vector resourceID;
82 660 bojilova
  private Vector principal;
83 570 bojilova
  private int    permission;
84
  private String permType;
85
  private String permOrder;
86 802 bojilova
//  private String publicAcc;
87 570 bojilova
  private String beginTime;
88
  private String endTime;
89
  private int    ticketCount;
90 684 bojilova
  private int    serverCode = 1;
91 802 bojilova
92
  private Vector aclObjects = new Vector();
93 859 berkley
  private boolean instarttag = true;
94
  private String tagName = "";
95 555 bojilova
  /**
96
   * Construct an instance of the AccessControlList class.
97 688 bojilova
   * It is used by the permission check up from DBQuery or DocumentImpl
98
   * and from "getaccesscontrol" action
99 570 bojilova
   *
100 684 bojilova
   * @param conn the JDBC connection where acl info is get
101 570 bojilova
   */
102 684 bojilova
  public AccessControlList(Connection conn) throws SQLException
103 570 bojilova
  {
104 613 bojilova
    this.conn = conn;
105 570 bojilova
  }
106
107
  /**
108
   * Construct an instance of the AccessControlList class.
109 555 bojilova
   * It parse acl file and loads acl data into db connection.
110
   *
111
   * @param conn the JDBC connection where acl data are loaded
112 684 bojilova
   * @param aclid the Accession# of the document with the acl data
113 570 bojilova
   * @param acl the acl file containing acl data
114 684 bojilova
   * @param user the user connected to MetaCat servlet and owns the document
115 802 bojilova
   * @param groups the groups to which user belongs
116 684 bojilova
   * @param serverCode the serverid from xml_replication on which this document
117
   *        resides.
118 555 bojilova
   */
119 819 bojilova
  public AccessControlList(Connection conn, String aclid, //Reader acl,
120 802 bojilova
                           String user, String[] groups, int serverCode)
121 819 bojilova
                  throws SAXException, IOException, McdbException
122 555 bojilova
  {
123 802 bojilova
    String parserName = MetaCatUtil.getOption("saxparser");
124
    this.server = MetaCatUtil.getOption("server");
125
    this.sep = MetaCatUtil.getOption("accNumSeparator");
126 555 bojilova
127
    this.conn = conn;
128
    this.parserName = parserName;
129 598 bojilova
    this.processingDTD = false;
130 570 bojilova
    this.elementStack = new Stack();
131
132 645 bojilova
    this.user = user;
133 802 bojilova
    this.groups = groups;
134 638 bojilova
    this.aclid = aclid;
135 665 bojilova
    this.resourceURL = new Vector();
136
    this.resourceID = new Vector();
137 660 bojilova
    this.principal = new Vector();
138 570 bojilova
    this.permission = 0;
139
    this.ticketCount = 0;
140 802 bojilova
  //  this.publicAcc = null;
141 684 bojilova
    this.serverCode = serverCode;
142 638 bojilova
143 819 bojilova
    // read the access file from db connection
144
    DocumentImpl acldoc = new DocumentImpl(conn, aclid);
145
    String acl = acldoc.toString();
146
    this.rev = acldoc.getRev();
147
148
    // Initialize the parse
149 555 bojilova
    XMLReader parser = initializeParser();
150 819 bojilova
    // parse the access file and write the info to xml_access
151
    parser.parse(new InputSource(new StringReader(acl)));
152
153 555 bojilova
  }
154
155 819 bojilova
// NOT USED
156
//  /**
157
//   * Construct an instance of the AccessControlList class.
158
//   * It parses eml-access file and loads acl data into db connection.
159
//   * It is used from command line execution.
160
//   *
161
//   * @param conn the JDBC connection where acl data are loaded
162
//   * @param docid the Accession# of the document with the acl data
163
//   * @param aclfilename the name of acl file containing acl data
164
//   * @param user the user connected to MetaCat servlet and owns the document
165
//   * @param groups the groups to which user belongs
166
//   */
167
//  public AccessControlList( Connection conn, String aclid, String aclfilename,
168
//                           String user, String[] groups )
169
//                  throws SAXException, IOException, McdbException
170
//  {
171
//    this(conn, aclid, new FileReader(new File(aclfilename).toString()),
172
//         user, groups, 1);
173
//  }
174 638 bojilova
175 660 bojilova
  /* Set up the SAX parser for reading the XML serialized ACL */
176 555 bojilova
  private XMLReader initializeParser() throws SAXException
177
  {
178
    XMLReader parser = null;
179
180
    // Get an instance of the parser
181
    parser = XMLReaderFactory.createXMLReader(parserName);
182
183 598 bojilova
    // Turn off validation
184 638 bojilova
    parser.setFeature("http://xml.org/sax/features/validation", true);
185 598 bojilova
186
    // Set Handlers in the parser
187 555 bojilova
    // Set the ContentHandler to this instance
188 598 bojilova
    parser.setContentHandler((ContentHandler)this);
189 555 bojilova
190 598 bojilova
    // make a DBEntityResolver instance
191
    // Set the EntityReslover to DBEntityResolver instance
192
    EntityResolver eresolver = new DBEntityResolver(conn,this,null);
193
    parser.setEntityResolver((EntityResolver)eresolver);
194
195 555 bojilova
    // Set the ErrorHandler to this instance
196 598 bojilova
    parser.setErrorHandler((ErrorHandler)this);
197 555 bojilova
198 862 berkley
    return parser;
199 555 bojilova
  }
200
201
  /**
202 688 bojilova
   * Callback method used by the SAX Parser when beginning of the document
203 645 bojilova
   */
204
  public void startDocument() throws SAXException
205
  {
206
    //delete all previously submitted permissions @ relations
207
    //this happens only on UPDATE of the access file
208
    try {
209 819 bojilova
      this.aclObjects = getACLObjects(aclid);
210 802 bojilova
211 819 bojilova
      //delete all permissions for resources related to @aclid if any
212 645 bojilova
      if ( aclid != null ) {
213
        deletePermissionsForRelatedResources(aclid);
214
      }
215
    } catch (SQLException sqle) {
216
      throw new SAXException(sqle);
217
    }
218
  }
219
220
  /**
221 688 bojilova
   * Callback method used by the SAX Parser when the start tag of an
222 555 bojilova
   * element is detected. Used in this context to parse and store
223
   * the acl information in class variables.
224
   */
225
  public void startElement (String uri, String localName,
226
                            String qName, Attributes atts)
227
         throws SAXException
228
  {
229 859 berkley
    instarttag = true;
230
    if(localName.equals("allow"))
231
    {
232
      tagName = "allow";
233
    }
234
    else if(localName.equals("deny"))
235
    {
236
      tagName = "deny";
237
    }
238 555 bojilova
    BasicNode currentNode = new BasicNode(localName);
239
    if (atts != null) {
240
      int len = atts.getLength();
241
      for (int i = 0; i < len; i++) {
242
        currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i));
243
      }
244
    }
245 802 bojilova
    if ( currentNode.getTagName().equals("acl") ) {
246 570 bojilova
      permOrder = currentNode.getAttribute("order");
247 802 bojilova
    //  publicAcc = currentNode.getAttribute("public");
248 570 bojilova
    }
249 555 bojilova
    elementStack.push(currentNode);
250
  }
251
252
  /**
253 688 bojilova
   * Callback method used by the SAX Parser when the text sequences of an
254 555 bojilova
   * xml stream are detected. Used in this context to parse and store
255
   * the acl information in class variables.
256 859 berkley
   */
257 555 bojilova
  public void characters(char ch[], int start, int length)
258
         throws SAXException
259
  {
260 859 berkley
    if(!instarttag)
261
    {
262
      return;
263
    }
264 555 bojilova
    String inputString = new String(ch, start, length);
265 859 berkley
    inputString = inputString.trim();
266 862 berkley
    //System.out.println("==============inputString: " + inputString);
267 555 bojilova
    BasicNode currentNode = (BasicNode)elementStack.peek();
268
    String currentTag = currentNode.getTagName();
269
270 802 bojilova
      if (currentTag.equals("principal")) {
271 645 bojilova
272 802 bojilova
        principal.addElement(inputString);
273 645 bojilova
274 802 bojilova
      } else if (currentTag.equals("permission")) {
275 645 bojilova
276 802 bojilova
        if ( inputString.trim().toUpperCase().equals("READ") ) {
277
          permission = permission | READ;
278
        } else if ( inputString.trim().toUpperCase().equals("WRITE") ) {
279
          permission = permission | WRITE;
280 862 berkley
        } else if ( inputString.trim().toUpperCase().equals("CHANGEPERMISSION") ) {
281
          permission = permission | CHMOD;
282 802 bojilova
        } else if ( inputString.trim().toUpperCase().equals("ALL") ) {
283
          permission = permission | ALL;
284 862 berkley
        }/*else{
285 802 bojilova
          throw new SAXException("Unknown permission type: " + inputString);
286 859 berkley
        }*/
287 645 bojilova
288 802 bojilova
      } else if ( currentTag.equals("startDate") && beginTime == null ) {
289
        beginTime = inputString.trim();
290 645 bojilova
291 802 bojilova
      } else if ( currentTag.equals("stopDate") && endTime == null) {
292
        endTime = inputString.trim();
293 645 bojilova
294 802 bojilova
      } else if (currentTag.equals("ticketCount") && ticketCount == 0 ) {
295
        try {
296
          ticketCount = (new Integer(inputString.trim())).intValue();
297
        } catch (NumberFormatException nfe) {
298
          throw new SAXException("Wrong integer format for:" + inputString);
299
        }
300 555 bojilova
      }
301
  }
302
303
  /**
304 688 bojilova
   * Callback method used by the SAX Parser when the end tag of an
305 555 bojilova
   * element is detected. Used in this context to parse and store
306
   * the acl information in class variables.
307
   */
308
  public void endElement (String uri, String localName, String qName)
309
         throws SAXException
310
  {
311 859 berkley
    instarttag = false;
312 688 bojilova
    BasicNode leaving = (BasicNode)elementStack.pop();
313
    String leavingTagName = leaving.getTagName();
314
315 802 bojilova
    if ( leavingTagName.equals("allow") ||
316
         leavingTagName.equals("deny")    ) {
317 570 bojilova
318
      if ( permission > 0 ) {
319 555 bojilova
320 570 bojilova
        // insert into db calculated permission for the list of principals
321
        try {
322 802 bojilova
// System.out.println("before insertPermission " +leavingTagName);
323
          // go through the objects in xml_relation about this acl doc
324
          for (int i=0; i < aclObjects.size(); i++) {
325
            // docid of the current object
326
            String docid = (String)aclObjects.elementAt(i);
327
            DocumentIdentifier docID = new DocumentIdentifier(docid);
328
            docid = docID.getIdentifier();
329
// System.out.println(docid);
330
            insertPermissions(docid,leavingTagName);
331
          }
332
333 570 bojilova
        } catch (SQLException sqle) {
334
          throw new SAXException(sqle);
335 802 bojilova
        } catch (Exception e) {
336
          throw new SAXException(e);
337 570 bojilova
        }
338
      }
339
340 688 bojilova
      // reset the allow/deny permission
341 660 bojilova
      principal = new Vector();
342 555 bojilova
      permission = 0;
343 570 bojilova
      beginTime = null;
344
      endTime = null;
345
      ticketCount = 0;
346 555 bojilova
347 570 bojilova
    }
348 555 bojilova
349
  }
350 598 bojilova
351 688 bojilova
  /**
352
    * SAX Handler that receives notification of DOCTYPE. Sets the DTD.
353
    * @param name name of the DTD
354
    * @param publicId Public Identifier of the DTD
355
    * @param systemId System Identifier of the DTD
356
    */
357 598 bojilova
  public void startDTD(String name, String publicId, String systemId)
358
              throws SAXException {
359
    docname = name;
360
    doctype = publicId;
361
    systemid = systemId;
362
  }
363
364
  /**
365 688 bojilova
   * SAX Handler that receives notification of the start of entities.
366
   * @param name name of the entity
367 598 bojilova
   */
368
  public void startEntity(String name) throws SAXException {
369
    if (name.equals("[dtd]")) {
370
      processingDTD = true;
371
    }
372
  }
373
374
  /**
375 688 bojilova
   * SAX Handler that receives notification of the end of entities.
376
   * @param name name of the entity
377 598 bojilova
   */
378
  public void endEntity(String name) throws SAXException {
379
    if (name.equals("[dtd]")) {
380
      processingDTD = false;
381
    }
382
  }
383
384
  /**
385 688 bojilova
   * Get the document name.
386 598 bojilova
   */
387
  public String getDocname() {
388
    return docname;
389
  }
390
391
  /**
392 688 bojilova
   * Get the document processing state.
393 598 bojilova
   */
394
  public boolean processingDTD() {
395
    return processingDTD;
396
  }
397
398 802 bojilova
  /* Get all objects associated with @aclid from db.*/
399
  private Vector getACLObjects(String aclid)
400 638 bojilova
          throws SQLException
401
  {
402 802 bojilova
    Vector aclObjects = new Vector();
403 645 bojilova
    // delete all acl records for resources related to @aclid if any
404 802 bojilova
    PreparedStatement pstmt = conn.prepareStatement(
405
                             "SELECT object FROM xml_relation " +
406 830 jones
                             "WHERE subject = ? ");
407 802 bojilova
    pstmt.setString(1,aclid);
408
    pstmt.execute();
409
    ResultSet rs = pstmt.getResultSet();
410
    boolean hasRows = rs.next();
411
    while (hasRows) {
412
      aclObjects.addElement(rs.getString(1));
413
      hasRows = rs.next();
414
    }
415
416
    pstmt.close();
417
418
    return aclObjects;
419 638 bojilova
  }
420
421 802 bojilova
  /* Delete from db all permission for resources related to @aclid if any.*/
422
  private void deletePermissionsForRelatedResources(String aclid)
423 638 bojilova
          throws SQLException
424
  {
425 802 bojilova
    // delete all acl records for resources related to @aclid if any
426 645 bojilova
    Statement stmt = conn.createStatement();
427 802 bojilova
    stmt.execute("DELETE FROM xml_access WHERE accessfileid = '" + aclid + "'");
428 645 bojilova
    stmt.close();
429
  }
430
431 688 bojilova
  /* Insert into db calculated permission for the list of principals */
432 802 bojilova
  private void insertPermissions(String docid, String permType )
433 555 bojilova
          throws SQLException
434
  {
435 672 bojilova
    PreparedStatement pstmt;
436 638 bojilova
437 555 bojilova
    try {
438
      pstmt = conn.prepareStatement(
439
              "INSERT INTO xml_access " +
440 645 bojilova
              "(docid, principal_name, permission, perm_type, perm_order," +
441
              "begin_time,end_time,ticket_count, accessfileid) VALUES " +
442
              "(?,?,?,?,?,to_date(?,'mm/dd/yy'),to_date(?,'mm/dd/yy'),?,?)");
443 555 bojilova
      // Bind the values to the query
444 802 bojilova
      pstmt.setString(1, docid);
445 570 bojilova
      pstmt.setInt(3, permission);
446
      pstmt.setString(4, permType);
447
      pstmt.setString(5, permOrder);
448
      pstmt.setString(6, beginTime);
449
      pstmt.setString(7, endTime);
450 645 bojilova
      pstmt.setString(9, aclid);
451 570 bojilova
      if ( ticketCount > 0 ) {
452
        pstmt.setString(8, "" + ticketCount);
453
      } else {
454 555 bojilova
        pstmt.setString(8, "");
455 570 bojilova
      }
456 802 bojilova
457 688 bojilova
      String prName;
458 802 bojilova
      for ( int j = 0; j < principal.size(); j++ ) {
459
        prName = (String)principal.elementAt(j);
460
        pstmt.setString(2, prName);
461
        pstmt.execute();
462
      /*
463
        // check if there are conflict with permission's order
464
        String permOrderOpos = permOrder;
465
        int perm = getPermissions(permission, prName, docid, permOrder);
466
        if (  perm != 0 ) {
467
          if ( permOrder.equals("allowFirst") ) {
468
            permOrderOpos = "denyFirst";
469
          } else if ( permOrder.equals("denyFirst") ) {
470
            permOrderOpos = "allowFirst";
471 688 bojilova
          }
472 802 bojilova
          throw new SQLException("Permission(s) " + txtValue(perm) +
473
                    " for \"" + prName + "\" on document #" + docid +
474
                    " has/have been used with \"" + permOrderOpos + "\"");
475 665 bojilova
        }
476 802 bojilova
      */
477 570 bojilova
      }
478 672 bojilova
      pstmt.close();
479 555 bojilova
480 570 bojilova
    } catch (SQLException e) {
481
      throw new
482
      SQLException("AccessControlList.insertPermissions(): " + e.getMessage());
483 672 bojilova
    }
484
  }
485
486 688 bojilova
  /* Get permissions with permission order different than @permOrder. */
487
  private int getPermissions(int permission, String principal,
488
                             String docid, String permOrder)
489
          throws SQLException
490
  {
491
    PreparedStatement pstmt;
492
    pstmt = conn.prepareStatement(
493
            "SELECT permission FROM xml_access " +
494 765 bojilova
            "WHERE docid = ? " +
495
            "AND principal_name = ? " +
496
            "AND perm_order NOT = ?");
497 688 bojilova
    pstmt.setString(1, docid);
498
    pstmt.setString(2, principal);
499
    pstmt.setString(3, permOrder);
500
    pstmt.execute();
501
    ResultSet rs = pstmt.getResultSet();
502
    boolean hasRow = rs.next();
503
    int perm = 0;
504
    while ( hasRow ) {
505
      perm = rs.getInt(1);
506
      perm = permission & perm;
507
      if ( perm != 0 ) {
508
        pstmt.close();
509
        return perm;
510
      }
511
      hasRow = rs.next();
512
    }
513
    pstmt.close();
514
    return 0;
515
  }
516
517
  /* Get the int value of READ, WRITE or ALL. */
518
  private int intValue ( String permission )
519
  {
520
    if ( permission.equals("READ") ) {
521
      return READ;
522
    } else if ( permission.equals("WRITE") ) {
523
      return WRITE;
524
    } else if ( permission.equals("ALL") ) {
525
      return ALL;
526
    }
527
528
    return -1;
529
  }
530
531
  /* Get the text value of READ, WRITE or ALL. */
532
  private String txtValue ( int permission )
533
  {
534
    StringBuffer txtPerm = new StringBuffer("\"");
535
    if ( (permission & READ) != 0 ) {
536
      txtPerm.append("read");
537
    }
538
    if ( (permission & WRITE) != 0 ) {
539
      if ( txtPerm.length() > 0 ) txtPerm.append(",");
540
      txtPerm.append("write");
541
    }
542
    if ( (permission & ALL) != 0 ) {
543
      if ( txtPerm.length() > 0 ) txtPerm.append(",");
544
      txtPerm.append("all");
545
    }
546
547
    return txtPerm.append("\"").toString();
548
  }
549
550 802 bojilova
  /**
551
    * Check from db connection if at least one of the list of @principals
552
    * has @permission on @docid.
553
    * @param permission permission type to check for
554
    * @param principals list of names of principals to check for @permission
555
    * @param docid document identifier to check on
556
    */
557
  public boolean hasPermission(String permission, String user,
558
                               String[] groups, String docid )
559
                 throws SQLException
560 688 bojilova
  {
561 802 bojilova
    // b' of the command line invocation
562
    if ( (user == null) && (groups == null || groups.length == 0) ) {
563
      return true;
564
    }
565
566
    // Check for @permission on @docid for @user and/or @groups
567
    boolean hasPermission = hasPermission(permission,user,docid);
568
    int i = 0;
569
    if ( groups != null ) {
570
      while ( !hasPermission && i<groups.length ) {
571
        hasPermission = hasPermission(permission,groups[i++],docid);
572 688 bojilova
      }
573
    }
574 802 bojilova
    // Check for @permission for "public" user
575
    if ( !hasPermission ) {
576
      hasPermission = hasPermission(permission,"public",docid);
577
    }
578
579
    return hasPermission;
580
  }
581 688 bojilova
582
  /**
583 802 bojilova
    * Check from db connection if @principal has @permission on @docid.
584 688 bojilova
    * @param permission permission type to check for
585
    * @param principal name of principal to check for @permission
586 802 bojilova
    * @param docid document identifier to check on
587 688 bojilova
    */
588 802 bojilova
  private boolean hasPermission(String permission,
589
                                String principal, String docid)
590 570 bojilova
                 throws SQLException
591
  {
592 870 berkley
    //System.out.println("Does " + principal + " have " + permission + " on " + docid);
593 570 bojilova
    PreparedStatement pstmt;
594 802 bojilova
    // check public access to @docid from xml_documents table
595 570 bojilova
    if ( permission.equals("READ") ) {
596
      try {
597 607 bojilova
        pstmt = conn.prepareStatement(
598 570 bojilova
                "SELECT 'x' FROM xml_documents " +
599 765 bojilova
                "WHERE docid = ? AND public_access = 1");
600 570 bojilova
        // Bind the values to the query
601 802 bojilova
        pstmt.setString(1, docid);
602 570 bojilova
603 555 bojilova
        pstmt.execute();
604 570 bojilova
        ResultSet rs = pstmt.getResultSet();
605
        boolean hasRow = rs.next();
606
        pstmt.close();
607
        if (hasRow) {
608
          return true;
609
        }
610
611 869 berkley
612 570 bojilova
      } catch (SQLException e) {
613
        throw new
614 688 bojilova
        SQLException("AccessControlList.hasPermission(). " +
615 802 bojilova
                     "Error checking public access for document #"+docid+
616 688 bojilova
                     ". " + e.getMessage());
617 555 bojilova
      }
618 570 bojilova
    }
619
620
    // since owner of resource has all permission on it,
621 802 bojilova
    // check if @principal is owner of @docid in xml_documents table
622 570 bojilova
    if ( principal != null ) {
623
      try {
624 607 bojilova
        pstmt = conn.prepareStatement(
625 570 bojilova
                "SELECT 'x' FROM xml_documents " +
626 765 bojilova
                "WHERE docid = ? AND user_owner = ?");
627 570 bojilova
        // Bind the values to the query
628 802 bojilova
        pstmt.setString(1, docid);
629 570 bojilova
        pstmt.setString(2, principal);
630 555 bojilova
631 570 bojilova
        pstmt.execute();
632
        ResultSet rs = pstmt.getResultSet();
633
        boolean hasRow = rs.next();
634
        pstmt.close();
635
        if (hasRow) {
636
          return true;
637 869 berkley
        }
638 570 bojilova
639
      } catch (SQLException e) {
640
        throw new
641 688 bojilova
        SQLException("AccessControlList.hasPermission(). " +
642
                     "Error checking ownership for " + principal +
643 802 bojilova
                     " on document #" + docid + ". " + e.getMessage());
644 570 bojilova
      }
645 869 berkley
646
      //check to see if the file we are checking is an access file and if the
647
      //user that is trying to update it has ALL permissions
648
      try
649
      {
650
        pstmt = conn.prepareStatement("select 'x' from xml_access where " +
651
                                      "accessfileid like '" + docid +
652
                                      "' and principal_name like '" + principal +
653
                                      "' and perm_type like 'allow' and " +
654
                                      "permission = 7");
655
        pstmt.execute();
656
        ResultSet rs = pstmt.getResultSet();
657
        boolean hasRow = rs.next();
658
        pstmt.close();
659
        if(hasRow)
660
        {
661
          return true;
662
        }
663
      }
664
      catch(SQLException e)
665
      {
666
        throw new SQLException("AccessControlList.hasPermission():2 " +
667
                     "Error checking ownership for " + principal +
668
                     " on document #" + docid + ". " + e.getMessage());
669
      }
670 570 bojilova
671 802 bojilova
      // check @principal's @permission on @docid from xml_access table
672 570 bojilova
      int accessValue = 0;
673
      int ticketCount = 0;
674
      String permOrder = "";
675
      try {
676 607 bojilova
        pstmt = conn.prepareStatement(
677 570 bojilova
                "SELECT permission, perm_order, ticket_count " +
678
                "FROM xml_access " +
679 765 bojilova
                "WHERE docid = ? " +
680
                "AND principal_name = ? " +
681
                "AND perm_type = ? " +
682 774 bojilova
                "AND " + sysdate +
683
                " BETWEEN " + isnull + "(begin_time," + sysdate + ") " +
684
                     "AND " + isnull + "(end_time," + sysdate + ")");
685 688 bojilova
        // check if it is "deny" with "allowFirst" first
686 570 bojilova
        // Bind the values to the query
687 802 bojilova
        pstmt.setString(1, docid);
688 570 bojilova
        pstmt.setString(2, principal);
689 688 bojilova
        pstmt.setString(3, "deny");
690 570 bojilova
691
        pstmt.execute();
692
        ResultSet rs = pstmt.getResultSet();
693
        boolean hasRows = rs.next();
694
        while ( hasRows ) {
695
          accessValue = rs.getInt(1);
696
          permOrder = rs.getString(2);
697
          ticketCount = rs.getInt(3);
698
          if ( ( accessValue & intValue(permission) ) == intValue(permission) &&
699 638 bojilova
               ( permOrder.equals("allowFirst") ) &&
700 570 bojilova
               ( rs.wasNull() || ticketCount > 0 ) ) {
701
            if ( !rs.wasNull() && ticketCount > 0 ) {
702 802 bojilova
              decreaseNumberOfAccess(accessValue,principal,docid,"deny","allowFirst");
703 570 bojilova
            }
704
            pstmt.close();
705
            return false;
706
          }
707
          hasRows = rs.next();
708 555 bojilova
        }
709 688 bojilova
//System.out.println("Passed the check for \"deny\" access with \"allowFirst\"");
710 555 bojilova
711 688 bojilova
        // it is not denied then check if it is "allow"
712 570 bojilova
        // Bind the values to the query
713 802 bojilova
        pstmt.setString(1, docid);
714 570 bojilova
        pstmt.setString(2, principal);
715 688 bojilova
        pstmt.setString(3, "allow");
716 570 bojilova
717 555 bojilova
        pstmt.execute();
718 570 bojilova
        rs = pstmt.getResultSet();
719
        hasRows = rs.next();
720
        while ( hasRows ) {
721
          accessValue = rs.getInt(1);
722 688 bojilova
          permOrder = rs.getString(2);
723 570 bojilova
          ticketCount = rs.getInt(3);
724
          if ( ( accessValue & intValue(permission) )==intValue(permission) &&
725
               ( rs.wasNull() || ticketCount > 0 ) ) {
726
            if ( !rs.wasNull() && ticketCount > 0 ) {
727 802 bojilova
              decreaseNumberOfAccess(accessValue,principal,docid,"allow",permOrder);
728 570 bojilova
            }
729
            pstmt.close();
730
            return true;
731
          }
732
          hasRows = rs.next();
733
        }
734 688 bojilova
//System.out.println("Passed the check for \"allow\" access");
735 570 bojilova
736 688 bojilova
        // it is not allowed then check if it is "deny" with "denyFirst"
737
        // Bind the values to the query
738 802 bojilova
        pstmt.setString(1, docid);
739 688 bojilova
        pstmt.setString(2, principal);
740
        pstmt.setString(3, "deny");
741
742
        pstmt.execute();
743
        rs = pstmt.getResultSet();
744
        hasRows = rs.next();
745
        while ( hasRows ) {
746
          accessValue = rs.getInt(1);
747
          permOrder = rs.getString(2);
748
          ticketCount = rs.getInt(3);
749
          if ( ( accessValue & intValue(permission) ) == intValue(permission) &&
750
               ( permOrder.equals("denyFirst") ) &&
751
               ( rs.wasNull() || ticketCount > 0 ) ) {
752
            if ( !rs.wasNull() && ticketCount > 0 ) {
753 802 bojilova
              decreaseNumberOfAccess(accessValue,principal,docid,"deny","denyFirst");
754 688 bojilova
            }
755
            pstmt.close();
756
            return false;
757
          }
758
          hasRows = rs.next();
759
        }
760
//System.out.println("Passed the check for \"deny\" access wirh \"denyFirst\"");
761 570 bojilova
762
        pstmt.close();
763
        return false;
764
765
      } catch (SQLException e) {
766
        throw new
767 688 bojilova
        SQLException("AccessControlList.hasPermission(). " +
768
                     "Error checking " + permission + " permission for " +
769 802 bojilova
                     principal + " on document #" + docid + ". " +
770 688 bojilova
                     e.getMessage());
771 555 bojilova
      }
772 570 bojilova
    }
773
774
    return false;
775
  }
776 555 bojilova
777 802 bojilova
  /* Decrease the number of access to @docid for @principal in db. */
778 570 bojilova
  private void decreaseNumberOfAccess(int permission, String principal,
779 802 bojilova
                                      String docid, String permType,
780 688 bojilova
                                      String permOrder)
781 570 bojilova
               throws SQLException
782
  {
783
    PreparedStatement pstmt;
784
    pstmt = conn.prepareStatement(
785
            "UPDATE xml_access SET ticket_count = ticket_count - 1 " +
786 765 bojilova
            "WHERE docid = ? " +
787
            "AND principal_name = ? " +
788
            "AND permission = ? " +
789
            "AND perm_type = ? " +
790
            "AND perm_order = ? " +
791 774 bojilova
            "AND " + sysdate +
792
            " BETWEEN " + isnull + "(begin_time," + sysdate + ") " +
793
                 "AND " + isnull + "(end_time," + sysdate + ")");
794 570 bojilova
    // Bind the values to the query
795 802 bojilova
    pstmt.setString(1, docid);
796 570 bojilova
    pstmt.setString(2, principal);
797
    pstmt.setInt(3, permission);
798
    pstmt.setString(4, permType);
799 688 bojilova
    pstmt.setString(5, permOrder);
800 570 bojilova
801
    pstmt.execute();
802
    pstmt.close();
803
  }
804
805 688 bojilova
806
  /**
807
    * Get Access Control List information for document from db connetion.
808
    * User or Group should have permissions for reading
809
    * access control information for a document specified by @docid.
810
    * @param docid document identifier which acl info to get
811
    * @param user name of user connected to Metacat system
812 802 bojilova
    * @param groups names of user's groups to which user belongs
813 688 bojilova
    */
814 802 bojilova
  public String getACL(String docid, String user, String[] groups)
815 688 bojilova
          throws SQLException
816 570 bojilova
  {
817 688 bojilova
    StringBuffer output = new StringBuffer();
818
    StringBuffer outTemp = new StringBuffer();
819
    MetaCatUtil util = new MetaCatUtil();
820
    String accDoctype = util.getOption("accessdoctype");
821
    String server = util.getOption("server");
822
    String docurl = "metacat://" + server + "/?docid=" + docid;
823
    String systemID;
824
    boolean isOwned = false;
825
    boolean hasPermission = false;
826
    String publicAcc;
827 570 bojilova
828 688 bojilova
    String acfid = "";
829
    String acfid_prev = "";
830
    String principal;
831
    Vector principalArr = new Vector();
832
    int permission;
833
    int perm_prev = -1;
834
    String permType;
835
    String permOrder = "";
836
    String permOrder_prev = "";
837
    String beginTime = "";
838
    String begin_prev = "";
839
    String endTime = "";
840
    String end_prev = "";
841
    int ticketCount = -1;
842
    int ticket_prev = -1;
843
844 638 bojilova
    try {
845 688 bojilova
846
      isOwned = isOwned(docid, user);
847
      systemID = getSystemID(accDoctype);
848
      publicAcc = getPublicAccess(docid);
849
850
      output.append("<?xml version=\"1.0\"?>\n");
851
      output.append("<!DOCTYPE acl PUBLIC \"" + accDoctype + "\" \"" +
852
                    systemID + "\">\n");
853
      output.append("<acl authSystem=\"\">\n");
854
855
      PreparedStatement pstmt;
856
      pstmt = conn.prepareStatement(
857
              "SELECT distinct accessfileid, principal_name, permission, " +
858
              "perm_type, perm_order, to_char(begin_time,'mm/dd/yyyy'), " +
859
              "to_char(end_time,'mm/dd/yyyy'), ticket_count " +
860 765 bojilova
              "FROM xml_access WHERE docid = ? " +
861 688 bojilova
              "ORDER BY accessfileid, perm_order, perm_type, permission");
862
      // Bind the values to the query
863
      pstmt.setString(1, docid);
864
      pstmt.execute();
865
      ResultSet rs = pstmt.getResultSet();
866
      boolean hasRows = rs.next();
867
      while (hasRows) {
868
869
        acfid = rs.getString(1);
870
        principal = rs.getString(2);
871
        permission = rs.getInt(3);
872
        permType = rs.getString(4);
873
        permOrder = rs.getString(5);
874
        beginTime = rs.getString(6);
875
        endTime = rs.getString(7);
876
        ticketCount = rs.getInt(8);
877
878
        // if @docid is not owned by @user, only ACL info from that
879 802 bojilova
        // access files to which @user/@groups has "read" permission
880 688 bojilova
        // is extracted
881
        if ( !isOwned ) {
882
          if ( !acfid.equals(acfid_prev) ) {
883
            acfid_prev = acfid;
884 802 bojilova
            hasPermission = this.hasPermission("READ",user,groups,acfid);
885 688 bojilova
          }
886
          if ( !hasPermission ) {
887
            rs.next();
888
            continue;
889
          }
890
        }
891
892
        // open <resource> tag
893
        if ( !permOrder.equals(permOrder_prev) ) {
894
          // close </resource> tag if any was opened
895
          output.append(outTemp.toString());
896
          outTemp = new StringBuffer();
897
          if ( !permOrder_prev.equals("") ) {
898
            output.append("  </resource>\n");
899
          }
900
          output.append("  <resource order=\"" + permOrder + "\" public=\"" +
901
                        publicAcc + "\">\n");
902
          output.append("    <resourceIdentifier>" + docurl +
903
                        "</resourceIdentifier>\n");
904
          permOrder_prev = permOrder;
905
        }
906
907
        // close </allow> or </deny> tag then open new one
908
        if ( permission != perm_prev ||
909
             (endTime == null) && (end_prev != null) ||
910
             (beginTime == null) && (begin_prev != null) ||
911
             endTime != null && !endTime.equals(end_prev)  ||
912
             beginTime != null && !beginTime.equals(begin_prev) ||
913
             ticketCount != ticket_prev )  {
914
          output.append(outTemp.toString());
915
          outTemp = new StringBuffer();
916
          principalArr.removeAllElements();
917
          output.append("    <" + permType + ">\n");
918
        }
919
920
        // put all principals here for the same
921
        // permission, duration and ticket_count
922
        if ( !principalArr.contains(principal) ) {
923
          principalArr.addElement(principal);
924
          output.append("      <principal>" + principal + "</principal>\n");
925
        }
926
927
        // prepare <permission> tags, <duration> and <ticketCount>
928
        // if any to put within <allow> (<deny>) by next cicle
929
        if ( permission != perm_prev ||
930
             (endTime == null) && (end_prev != null) ||
931
             (beginTime == null) && (begin_prev != null) ||
932
             endTime != null && !endTime.equals(end_prev)  ||
933
             beginTime != null && !beginTime.equals(begin_prev) ||
934
             ticketCount != ticket_prev )  {
935
          if ( (permission & READ) != 0 ) {
936
            outTemp.append("      <permission>read</permission>\n");
937
          }
938
          if ( (permission & WRITE) != 0 ) {
939
            outTemp.append("      <permission>write</permission>\n");
940
          }
941
          if ( (permission & ALL) != 0 ) {
942
            outTemp.append("      <permission>all</permission>\n");
943
          }
944
          if ( (beginTime != null) || (endTime != null) ) {
945
            outTemp.append("      <duration>" + beginTime + " " + endTime +
946
                          "</duration>\n");
947
          }
948
          if ( ticketCount > 0 ) {
949
            outTemp.append("      <ticketCount>" + ticketCount +
950
                          "</ticketCount>\n");
951
          }
952
          outTemp.append("    </" + permType + ">\n");
953
          perm_prev = permission;
954
          ticket_prev = ticketCount;
955
          begin_prev = beginTime;
956
          end_prev = endTime;
957
        }
958
959
        hasRows = rs.next();
960 652 bojilova
      }
961 688 bojilova
962
      // close <allow> or <deny> if anything left in outTemp var
963
      output.append(outTemp.toString());
964
965
      // If there are no any acl info for @docid accessible by @user/@group,
966
      // extract only the following information
967
      if ( permOrder.equals("") ) {
968
        output.append("  <resource public=\"" + publicAcc + "\">\n");
969
        output.append("    <resourceIdentifier>" + docurl +
970
                      "</resourceIdentifier>\n");
971
      }
972
973
      // always close them
974
      output.append("  </resource>\n");
975
      output.append("</acl>\n");
976
977
      pstmt.close();
978
979
      return output.toString();
980
981
    } catch (SQLException e) {
982
      throw new
983
      SQLException("AccessControlList.getACL(). " + e.getMessage());
984 638 bojilova
    }
985 688 bojilova
  }
986
987
  /* Check if @user is owner of @docid from db conn. */
988
  private boolean isOwned(String docid, String user) throws SQLException {
989
990
    PreparedStatement pstmt;
991
    pstmt = conn.prepareStatement("SELECT 'x' FROM xml_documents " +
992 765 bojilova
                                  "WHERE docid = ? " +
993
                                  "AND user_owner = ?");
994 688 bojilova
    pstmt.setString(1, docid);
995
    pstmt.setString(2, user);
996
    pstmt.execute();
997
    ResultSet rs = pstmt.getResultSet();
998
    boolean hasRow = rs.next();
999
1000
    return hasRow;
1001
  }
1002 652 bojilova
1003 688 bojilova
  /* Get the flag for public "read" access for @docid from db conn. */
1004
  private String getPublicAccess(String docid) throws SQLException {
1005
1006
    int publicAcc = 0;
1007
    PreparedStatement pstmt;
1008
    pstmt = conn.prepareStatement("SELECT public_access FROM xml_documents " +
1009 765 bojilova
                                  "WHERE docid = ?");
1010 688 bojilova
    pstmt.setString(1, docid);
1011
    pstmt.execute();
1012
    ResultSet rs = pstmt.getResultSet();
1013
    boolean hasRow = rs.next();
1014
    if ( hasRow ) {
1015
      publicAcc = rs.getInt(1);
1016
    }
1017
1018
    return (publicAcc == 1) ? "yes" : "no";
1019
  }
1020
1021
  /* Get SystemID for @publicID from Metacat DB Catalog. */
1022
  private String getSystemID(String publicID) throws SQLException {
1023
1024
    String systemID = "";
1025
    PreparedStatement pstmt;
1026
    pstmt = conn.prepareStatement("SELECT system_id FROM xml_catalog " +
1027
                                  "WHERE entry_type = 'DTD' " +
1028 765 bojilova
                                  "AND public_id = ?");
1029 688 bojilova
    pstmt.setString(1, publicID);
1030
    pstmt.execute();
1031
    ResultSet rs = pstmt.getResultSet();
1032
    boolean hasRow = rs.next();
1033
    if ( hasRow ) {
1034
      systemID = rs.getString(1);
1035
    }
1036
1037
    return systemID;
1038
  }
1039
1040 555 bojilova
}