Пример #1
0
 def _handle_get_row(self, res):
     result, ctxt, row = res
     if (result[0] == Storage.NO_MORE_ROWS
         or result[0] == Storage.SUCCESS and len(row) == 0):
         # TBD: Remove second clause above when storage API is fixed
         # TBD: so that it doesn't return an empty row to a get when
         # TBD: nothing matches the query.
         self._d = None
         if (self._numResults == 0
             and len(self._query) == 1
             and self._query.has_key("GUID")):
             notFound(self.request,
                     "Table %s does not have row with GUID: %s" 
                     %(self.table_name,
                     self._query["GUID"][1].encode("hex")))
         else:
             self._write_query_header()
             self.request.write("]}")
             self.request.finish()
     elif result[0] == Storage.SUCCESS:
         self._numResults += 1
         self._write_query_header()
         ui_guid = (row["GUID"][1]).encode("hex")
         row["GUID"] = ui_guid
         row["GUID.link"] = u"/ws.v1/storage/" + self.schema.dbname
         row["GUID.link"] += u"/table/" + self.table_name + u"/" + ui_guid
         self.request.write(simplejson.dumps(row))
         self.request.write(",")
         self._d = self.db.get_next(ctxt)
         self._d.addCallback(self._handle_get_row)
         self._d.addErrback(self._handle_err)
     else:
         lg.error("Unknown success result code from database ")
         webservice.internalError(self.request, "Unknown success result "\
                 "code from database")
Пример #2
0
 def _handle_get_row(self, res):
     result, ctxt, row = res
     if (result[0] == Storage.NO_MORE_ROWS
             or result[0] == Storage.SUCCESS and len(row) == 0):
         # TBD: Remove second clause above when storage API is fixed
         # TBD: so that it doesn't return an empty row to a get when
         # TBD: nothing matches the query.
         self._d = None
         if (self._numResults == 0 and len(self._query) == 1
                 and self._query.has_key("GUID")):
             notFound(
                 self.request, "Table %s does not have row with GUID: %s" %
                 (self.table_name, self._query["GUID"][1].encode("hex")))
         else:
             self._write_query_header()
             self.request.write("]}")
             self.request.finish()
     elif result[0] == Storage.SUCCESS:
         self._numResults += 1
         self._write_query_header()
         ui_guid = (row["GUID"][1]).encode("hex")
         row["GUID"] = ui_guid
         row["GUID.link"] = u"/ws.v1/storage/" + self.schema.dbname
         row["GUID.link"] += u"/table/" + self.table_name + u"/" + ui_guid
         self.request.write(simplejson.dumps(row))
         self.request.write(",")
         self._d = self.db.get_next(ctxt)
         self._d.addCallback(self._handle_get_row)
         self._d.addErrback(self._handle_err)
     else:
         lg.error("Unknown success result code from database ")
         webservice.internalError(self.request, "Unknown success result "\
                 "code from database")
Пример #3
0
 def _handle_err(self, failure):
     if isinstance(failure.value, StorageException):
         if failure.value.code == Storage.NONEXISTING_TABLE:
             notFound(self.request, "Table '%s' does not exist." 
                     %self.table_name)
             return
         else:
             webservice.internalError(self.request,
                     "Database %s operation failed: %s" %(self.op, 
                     str(failure.value)))
             return
     failure.raiseException()
Пример #4
0
 def _handle_err(self, failure):
     if isinstance(failure.value, StorageException):
         if failure.value.code == Storage.NONEXISTING_TABLE:
             notFound(self.request,
                      "Table '%s' does not exist." % self.table_name)
             return
         else:
             webservice.internalError(
                 self.request, "Database %s operation failed: %s" %
                 (self.op, str(failure.value)))
             return
     failure.raiseException()
Пример #5
0
 def _modify_cb(res):
     if res[0] == Storage.SUCCESS:
         # TBD: setting response code here is causing errors deep
         # TBD: in twisted.  Need to figure out why.
         #self.request.setResponseCode("204")
         self.request.finish() # No body for 204 response
         return
     else:
         msg = "Modify success callback called with unexpected "\
               "results"
         lg.error(msg)
         webservice.internalError(self.request, msg)
Пример #6
0
 def _get_guid_cb(rows):
     if len(rows) == 0:
         notFound(self.request,
                  "Table %s does not have row with GUID: %s"
                  % (self.table_name,
                     self._query["GUID"][1].encode("hex")))
     elif len(rows) > 1:
         msg = "Multiple rows returned (unexpectedly) by the "\
                 "database and possibly removed."
         lg.error(msg)
         webservice.internalError(request, msg)
     else:
         d = StorageTableUtil.get_connection_if_none(self.db)
         d.addCallback(_do_remove, rows[0])
         return d
Пример #7
0
    def _get_fingerprints(self, request, arg):
        try:
            name = arg['<principal name>']
            dirname = arg['<dir name>']
            mangled_name = mangle_name(dirname, name)

            def interfaces_cb(res):
                mac_ip_list = []
                for iface in res:
                    mac_ip_list.append((iface['dladdr'], iface['nwaddr']))
                return mac_ip_list

            def fp_lookup_cb(res):
                ret_map = {}
                for mac_str, ip_str in res:
                    if ip_str in ret_map:
                        continue  # host may be on multiple locations
                    rs = pf_results()
                    is_valid = self.pypf.get_fingerprints(\
                        create_eaddr(mac_str),create_ipaddr(ip_str),rs)
                    if is_valid and rs.bpf.os != "":
                        ret_map[ip_str] = rs.bpf.os
                request.write(simplejson.dumps({"fingerprints": ret_map}))
                request.finish()

            d = self.bindings_dir.get_interfaces_for_host(mangled_name)
            d.addCallback(interfaces_cb)
            d.addCallback(fp_lookup_cb)
        except Exception, e:
            traceback.print_exc()
            return webservice.internalError(request, str(e))
Пример #8
0
 def err(self, failure, request, fn_name, msg):
     lg.error('%s: %s' % (fn_name, str(failure)))
     if isinstance(failure.value, DirectoryException) \
             and (failure.value.code == DirectoryException.COMMUNICATION_ERROR \
             or failure.value.code == DirectoryException.REMOTE_ERROR):
         msg = failure.value.message
     return webservice.internalError(request, msg)
Пример #9
0
 def err(self, failure, request, fn_name, msg):
     lg.error('%s: %s' % (fn_name, str(failure)))
     if isinstance(failure.value, DirectoryException) \
             and (failure.value.code == DirectoryException.COMMUNICATION_ERROR \
             or failure.value.code == DirectoryException.REMOTE_ERROR):
         msg = failure.value.message
     return webservice.internalError(request, msg)
Пример #10
0
    def _get_fingerprints(self, request, arg):
        try :
          name = arg['<principal name>']
          dirname = arg['<dir name>']
          mangled_name = mangle_name(dirname,name)
          def interfaces_cb(res): 
            mac_ip_list = [] 
            for iface in res: 
              mac_ip_list.append((iface['dladdr'],iface['nwaddr'])) 
            return mac_ip_list
          def fp_lookup_cb(res):
            ret_map = {} 
            for mac_str,ip_str in res: 
              if ip_str in ret_map: 
                continue # host may be on multiple locations
              rs = pf_results()
              is_valid = self.pypf.get_fingerprints(\
                  create_eaddr(mac_str),create_ipaddr(ip_str),rs)
              if is_valid and rs.bpf.os != "": 
                  ret_map[ip_str] = rs.bpf.os
            request.write(simplejson.dumps({ "fingerprints" : ret_map}))
            request.finish()

          d = self.bindings_dir.get_interfaces_for_host(mangled_name) 
          d.addCallback(interfaces_cb)
          d.addCallback(fp_lookup_cb)
        except Exception , e : 
          traceback.print_exc()
          return webservice.internalError(request, str(e)) 
Пример #11
0
 def _handle_put(self, res):
     result, guid = res
     if (result[0] != Storage.SUCCESS):
         msg = "Unexpected return code (%d) from Storage API put call."\
                 % result[0]
         webservice.internalError(request, msg)
         return
     ui_guid = guid[1].encode("hex")
     self._row["GUID"] = ui_guid
     self._row["GUID.link"] = u"/ws.v1/storage/" + self.schema.dbname
     self._row["GUID.link"] += u"/table/" + self.table_name + u"/" + ui_guid
     self.request.setResponseCode(201, "Created")
     #self.request.setHeader("Location", self._row["GUID.link"])
     self._write_query_header()
     self.request.write(simplejson.dumps(self._row))
     self.request.write("]}")
     self.request.finish()
Пример #12
0
 def _handle_put(self, res):
     result, guid = res
     if (result[0] != Storage.SUCCESS):
         msg = "Unexpected return code (%d) from Storage API put call."\
                 % result[0]
         webservice.internalError(request, msg)
         return
     ui_guid = guid[1].encode("hex")
     self._row["GUID"] = ui_guid
     self._row["GUID.link"] = u"/ws.v1/storage/" + self.schema.dbname
     self._row["GUID.link"] += u"/table/" + self.table_name + u"/" + ui_guid
     self.request.setResponseCode(201, "Created")
     #self.request.setHeader("Location", self._row["GUID.link"])
     self._write_query_header()
     self.request.write(simplejson.dumps(self._row))
     self.request.write("]}")
     self.request.finish()
Пример #13
0
    def post_config_base64(self,request, arg): 
        try:
            section_id = arg['<section>']
            content = {}
      
            boundary = None
            content_type = request.getHeader("Content-Type")
            for field in content_type.split("; "):
                arr = field.split("=")
                if arr[0] == "boundary": 
                    boundary = arr[1] 
                    break

            if not boundary: 
                lg.error("Could not find boundary in multipart request") 
                return webservice.badRequest(request, \
                                                 "Could not find boundary to parse multipart/form-data")
        
            if str(type(request.content)) == "<type 'cStringIO.StringO'>": 
                multipart_str = str(request.content.getvalue()).lower()
            elif isinstance(request.content,file): 
                multipart_str = request.content.read()
            else:
                lg.error("request.content has unknown type '%s'" % \
                             str(type(request.content)))
                return webservice.internalError(request,"Cannot handle request.content type.")

            multipart_arr = multipart_str.split(boundary)

            for key,value in request.args.iteritems():
                if key == "section_id":
                    continue  # TODO: figure out how to stop this in javascript
                content[key] = [ base64.b64encode(value[0])] 
                found = False
                for chunk in multipart_arr:
                    if chunk.find("name=\""+key+"\"") >= 0: 
                        start_index = chunk.find("content-type:")
                        end_index = chunk.find("\n",start_index)
                        content [key + "_content_type"] = \
                            chunk[start_index:end_index].split(" ")[1].strip()
                        start_index = chunk.find("filename=")
                        q1_index = chunk.find("\"", start_index)
                        q2_index = chunk.find("\"", q1_index + 1) 
                        content [key + "_filename"] =  chunk[(q1_index + 1):q2_index]
                        found = True
                        break
                if not found:
                    msg = "Could not find Content-Type in multipart/form-data for item %s" % key
                    lg.error("post_config_base64: %s" % msg)
                    return webservice.badRequest(request, msg)

            request.setHeader("Content-Type", "text/plain") 
            return self.set_config_common(request,section_id,content)
        
        except Exception, e:
            return self.err(Failure(), request, "post_config_base64", "Could not set key.")
Пример #14
0
 def _get_last_seen_str(self, request, arg):
     try:
         name = arg['<principal name>']
         dirname = arg['<dir name>']
         mangled_name = mangle_name(dirname, name)
         if mangled_name in self.data:
             text = self.data[mangled_name]
         else:
             text = ""
         return simplejson.dumps({"lastSeen": text})
     except Exception, e:
         traceback.print_exc()
         return webservice.internalError(request, str(e))
Пример #15
0
 def _get_last_seen_str(self, request, arg):
     try :
       name = arg['<principal name>']
       dirname = arg['<dir name>']
       mangled_name = mangle_name(dirname,name)
       if mangled_name in self.data:
         text = self.data[mangled_name]
       else: 
         text = ""
       return simplejson.dumps({ "lastSeen" : text }) 
     except Exception , e : 
       traceback.print_exc()
       return webservice.internalError(request, str(e)) 
Пример #16
0
    def get_interface(self, request, arg):
        try:
            name = arg["<interface>"]

            iflist = self.cfg.get_interfaces()
            ifnames = []
            for item in iflist:
                if item.name == name:
                    request.write(simplejson.dumps(item.get_dict()))
                    request.finish()
                    return NOT_DONE_YET

            return webservice.internalError(request, "Could not look up interface %s." % name)
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "get_interface",
                            "Could not retrieve interface information.")
Пример #17
0
    def get_interface(self, request, arg):
        try:
            name = arg["<interface>"]

            iflist = self.cfg.get_interfaces()
            ifnames = []
            for item in iflist:
                if item.name == name:
                    request.write(simplejson.dumps(item.get_dict()))
                    request.finish()
                    return NOT_DONE_YET

            return webservice.internalError(
                request, "Could not look up interface %s." % name)
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "get_interface",
                            "Could not retrieve interface information.")
Пример #18
0
 def _handle_remove_get_row(self, res):
     result, context, row = res
     if (result[0] == Storage.NO_MORE_ROWS
         or result[0] == Storage.SUCCESS and len(row) == 0):
         # TBD: Remove second clause above when storage API is fixed
         # TBD: so that it doesn't return an empty row to a get when
         # TBD: nothing matches the query.
         self._d = None
         if self._numResults == 0:
             notFound(self.request,
                      "Table %s does not have row with GUID: %s"
                      % (self.table_name,
                         self._query["GUID"][1].encode("hex")))
         elif self._numResults == 1:
             if self._remove_failed:
                 msg = "Remove success callback called with unexpected "\
                         "results"
                 lg.error(msg)
                 webservice.internalError(request, msg)
             else:
                 # TBD: setting response code here is causing errors deep
                 # TBD: in twisted.  Need to figure out why.
                 #self.request.setResponseCode("204")
                 self.request.finish() # No body for 204 response
         else:
             msg = "Multiple rows returned (unexpectedly) by the "\
                     "database and possibly removed."
             lg.error(msg)
             webservice.internalError(request, msg)
     elif result[0] == Storage.SUCCESS:
         if self._numResults < 1:
             # TBD: remove this check after db fix for issue with
             # TBD: removing all rows when only one is selected.
             self._numResults += 1
             d = self.db.remove(context)
             d.addCallback(self._handle_remove)
             self._d = self.db.get_next(context)
             self._d.addCallback(self._handle_remove_get_row)
             self._d.addErrback(self._handle_err)
         else:
             result = ((Storage.NO_MORE_ROWS, "Force DONE"), None, {})
             self._handle_remove_get_row(result)
     else:
         lg.errror("Unknown success result code in code from database")
         webservice.internalError(self.request, "Unknown success result "\
                 "code from database")
Пример #19
0
 def _handle_remove_get_row(self, res):
     result, context, row = res
     if (result[0] == Storage.NO_MORE_ROWS
             or result[0] == Storage.SUCCESS and len(row) == 0):
         # TBD: Remove second clause above when storage API is fixed
         # TBD: so that it doesn't return an empty row to a get when
         # TBD: nothing matches the query.
         self._d = None
         if self._numResults == 0:
             notFound(
                 self.request, "Table %s does not have row with GUID: %s" %
                 (self.table_name, self._query["GUID"][1].encode("hex")))
         elif self._numResults == 1:
             if self._remove_failed:
                 msg = "Remove success callback called with unexpected "\
                         "results"
                 lg.error(msg)
                 webservice.internalError(request, msg)
             else:
                 # TBD: setting response code here is causing errors deep
                 # TBD: in twisted.  Need to figure out why.
                 #self.request.setResponseCode("204")
                 self.request.finish()  # No body for 204 response
         else:
             msg = "Multiple rows returned (unexpectedly) by the "\
                     "database and possibly removed."
             lg.error(msg)
             webservice.internalError(request, msg)
     elif result[0] == Storage.SUCCESS:
         if self._numResults < 1:
             # TBD: remove this check after db fix for issue with
             # TBD: removing all rows when only one is selected.
             self._numResults += 1
             d = self.db.remove(context)
             d.addCallback(self._handle_remove)
             self._d = self.db.get_next(context)
             self._d.addCallback(self._handle_remove_get_row)
             self._d.addErrback(self._handle_err)
         else:
             result = ((Storage.NO_MORE_ROWS, "Force DONE"), None, {})
             self._handle_remove_get_row(result)
     else:
         lg.errror("Unknown success result code in code from database")
         webservice.internalError(self.request, "Unknown success result "\
                 "code from database")
Пример #20
0
 def _handle_modify_get_row(self, res):
     result, self.context, old_row = res
     if (result[0] == Storage.NO_MORE_ROWS
         or result[0] == Storage.SUCCESS and len(old_row) == 0):
         # TBD: Remove second clause above when storage API is fixed
         # TBD: so that it doesn't return an empty row to a get when
         # TBD: nothing matches the query.
         self._d = None
         if self._numResults == 0:
             notFound(self.request,
                      "Table %s does not have row with GUID: %s"
                      % (self.table_name,
                         self._query["GUID"][1].encode("hex")))
         elif self._numResults == 1:
             if self._modify_failed:
                 msg = "Modify success callback called with unexpected "\
                       "results"
                 lg.error(msg)
                 webservice.internalError(self.request, msg)
             else:
                 # TBD: setting response code here is causing errors deep
                 # TBD: in twisted.  Need to figure out why.
                 #self.request.setResponseCode("204")
                 self.request.finish() # No body for 204 response
         else:
             msg = "Multiple rows returned (unexpectedly) by the database "\
                   "and possibly modified."
             lg.error(msg)
             webservice.internalError(self.request, msg)
     elif result[0] == Storage.SUCCESS:
         self._numResults += 1
         d = self.db.modify(self.context, self._row)
         d.addCallback(self._handle_modify)
         self._d = self.db.get_next(self.context)
         self._d.addCallback(self._handle_modify_get_row)
         self._d.addErrback(self._handle_err)
     else:
         lg.error("Unknown success result code in ")
         webservice.internalError(self.request, "Unknown success result "\
                 "code from database")
Пример #21
0
 def _handle_modify_get_row(self, res):
     result, self.context, old_row = res
     if (result[0] == Storage.NO_MORE_ROWS
             or result[0] == Storage.SUCCESS and len(old_row) == 0):
         # TBD: Remove second clause above when storage API is fixed
         # TBD: so that it doesn't return an empty row to a get when
         # TBD: nothing matches the query.
         self._d = None
         if self._numResults == 0:
             notFound(
                 self.request, "Table %s does not have row with GUID: %s" %
                 (self.table_name, self._query["GUID"][1].encode("hex")))
         elif self._numResults == 1:
             if self._modify_failed:
                 msg = "Modify success callback called with unexpected "\
                       "results"
                 lg.error(msg)
                 webservice.internalError(self.request, msg)
             else:
                 # TBD: setting response code here is causing errors deep
                 # TBD: in twisted.  Need to figure out why.
                 #self.request.setResponseCode("204")
                 self.request.finish()  # No body for 204 response
         else:
             msg = "Multiple rows returned (unexpectedly) by the database "\
                   "and possibly modified."
             lg.error(msg)
             webservice.internalError(self.request, msg)
     elif result[0] == Storage.SUCCESS:
         self._numResults += 1
         d = self.db.modify(self.context, self._row)
         d.addCallback(self._handle_modify)
         self._d = self.db.get_next(self.context)
         self._d.addCallback(self._handle_modify_get_row)
         self._d.addErrback(self._handle_err)
     else:
         lg.error("Unknown success result code in ")
         webservice.internalError(self.request, "Unknown success result "\
                 "code from database")
Пример #22
0
 def _remove_cb(res):
     if res[0] != Storage.SUCCESS:
         msg = "Remove failed: %s (%s)" %(res[0], res[1])
         lg.error(msg)
         webservice.internalError(msg)
Пример #23
0
 def err(res):
     lg.error("Error looking for signed cert: %s" % str(res))
     webservice.internalError(request, "server error: %s" % str(res))
Пример #24
0
 def _search_table(self, request, arg):
     e = "The handler for this request has not been implemented yet."
     return webservice.internalError(request, e)
Пример #25
0
 def _get_schema(self, request, arg):
     schema = arg[self.dbschema.dbname]
     if not schema.isLoaded():
         return webservice.internalError(request, "Schema has not been "\
                 "loaded yet.")
     return schema.jsonRepr()
Пример #26
0
 def _get_schema(self, request, arg):
     schema = arg[self.dbschema.dbname]
     if not schema.isLoaded():
         return webservice.internalError(request, "Schema has not been "\
                 "loaded yet.")
     return schema.jsonRepr()
Пример #27
0
 def err(self, failure, request, fn_name, msg):
     lg.error('%s: %s' % (fn_name, str(failure)))
     return webservice.internalError(request, msg)
Пример #28
0
 def _search_table(self, request, arg):
     e = "The handler for this request has not been implemented yet."
     return webservice.internalError(request, e)
Пример #29
0
 def err(res): 
   lg.error("Error looking for signed cert: %s" % str(res))
   webservice.internalError(request, "server error: %s" % str(res))
Пример #30
0
 def err(res):
     lg.error("error submitting pki sign req: %s" % str(res))
     webservice.internalError(request,
                              "server error: %s" % str(res))
Пример #31
0
 def err(self, failure, request, fn_name, msg):
     lg.error('%s: %s' % (fn_name, str(failure)))
     return webservice.internalError(request, msg)
Пример #32
0
 def err(res): 
   lg.error("error submitting pki sign req: %s" % str(res))
   webservice.internalError(request, "server error: %s" % str(res))