_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q19300
Agenda._load_all
train
async def _load_all(self): ''' Load all the appointments from persistent storage ''' to_delete = [] for iden, val in self._hivedict.items(): try: appt = _Appt.unpack(val) if appt.iden != iden: raise s_exc.InconsistentStorage(mesg='iden inconsistency') self._addappt(iden, appt) self._next_indx = max(self._next_indx, appt.indx + 1) except (s_exc.InconsistentStorage, s_exc.BadStorageVersion, s_exc.BadTime, TypeError, KeyError, UnicodeDecodeError) as e: logger.warning('Invalid appointment %r found in storage: %r. Removing.', iden, e) to_delete.append(iden) continue for iden in to_delete: await self._hivedict.pop(iden) # Make sure we don't assign the same index to 2 appointments if self.appts: maxindx = max(appt.indx for appt in self.appts.values()) self._next_indx = maxindx + 1
python
{ "resource": "" }
q19301
Agenda._addappt
train
def _addappt(self, iden, appt): ''' Updates the data structures to add an appointment ''' if appt.nexttime: heapq.heappush(self.apptheap, appt) self.appts[iden] = appt if self.apptheap and self.apptheap[0] is appt: self._wake_event.set()
python
{ "resource": "" }
q19302
Agenda._storeAppt
train
async def _storeAppt(self, appt): ''' Store a single appointment ''' await self._hivedict.set(appt.iden, appt.pack())
python
{ "resource": "" }
q19303
Agenda.add
train
async def add(self, useriden, query: str, reqs, incunit=None, incvals=None): ''' Persistently adds an appointment Args: query (str): storm query to run reqs (Union[None, Dict[TimeUnit, Union[int, Tuple[int]], List[...]): one or more dicts of the fixed aspects of the appointment. dict value may be a single or multiple. May be an empty dict or None. incunit (Union[None, TimeUnit]): the unit that changes for recurring, or None for non-recurring. It is an error for this value to match a key in reqdict. incvals (Union[None, int, Iterable[int]): count of units of incunit or explicit day of week or day of month. Not allowed for incunit == None, required for others (1 would be a typical value) Notes: For values in reqs that are lists and incvals if a list, all combinations of all values (the product) are used Returns: iden of new appointment ''' iden = s_common.guid() recur = incunit is not None indx = self._next_indx self._next_indx += 1 if reqs is None: reqs = {} if not query: raise ValueError('empty query') if not reqs and incunit is None: raise ValueError('at least one of reqs and incunit must be non-empty') if incunit is not None and incvals is None: raise ValueError('incvals must be non-None if incunit is non-None') if isinstance(reqs, Mapping): reqs = [reqs] # Find all combinations of values in reqdict values and incvals values recs = [] for req in reqs: reqdicts = self._dictproduct(req) if not isinstance(incvals, Iterable): incvals = (incvals, ) recs.extend(ApptRec(rd, incunit, v) for (rd, v) in itertools.product(reqdicts, incvals)) appt = _Appt(iden, recur, indx, query, useriden, recs) self._addappt(iden, appt) await self._storeAppt(appt) return iden
python
{ "resource": "" }
q19304
Agenda.mod
train
async def mod(self, iden, query): ''' Change the query of an appointment ''' appt = self.appts.get(iden) if appt is None: raise s_exc.NoSuchIden() if not query: raise ValueError('empty query') if self.enabled: self.core.getStormQuery(query) appt.query = query appt.enabled = True # in case it was disabled for a bad query await self._storeAppt(appt)
python
{ "resource": "" }
q19305
Agenda.delete
train
async def delete(self, iden): ''' Delete an appointment ''' appt = self.appts.get(iden) if appt is None: raise s_exc.NoSuchIden() try: heappos = self.apptheap.index(appt) except ValueError: pass # this is OK, just a non-recurring appt that has no more records else: # If we're already the last item, just delete it if heappos == len(self.apptheap) - 1: del self.apptheap[heappos] else: # put the last item at the current position and reheap self.apptheap[heappos] = self.apptheap.pop() heapq.heapify(self.apptheap) del self.appts[iden] await self._hivedict.pop(iden)
python
{ "resource": "" }
q19306
Agenda._scheduleLoop
train
async def _scheduleLoop(self): ''' Task loop to issue query tasks at the right times. ''' while True: try: timeout = None if not self.apptheap else self.apptheap[0].nexttime - time.time() if timeout is None or timeout >= 0.0: await asyncio.wait_for(self._wake_event.wait(), timeout=timeout) except asyncio.TimeoutError: pass if self.isfini: return self._wake_event.clear() now = time.time() while self.apptheap and self.apptheap[0].nexttime <= now: appt = heapq.heappop(self.apptheap) appt.updateNexttime(now) if appt.nexttime: heapq.heappush(self.apptheap, appt) if not appt.enabled: continue if appt.isrunning: logger.warning( 'Appointment %s is still running from previous time when scheduled to run. Skipping.', appt.iden) else: await self._execute(appt)
python
{ "resource": "" }
q19307
Agenda._execute
train
async def _execute(self, appt): ''' Fire off the task to make the storm query ''' user = self.core.auth.user(appt.useriden) if user is None: logger.warning('Unknown user %s in stored appointment', appt.useriden) await self._markfailed(appt) return await self.core.boss.execute(self._runJob(user, appt), f'Agenda {appt.iden}', user)
python
{ "resource": "" }
q19308
Agenda._runJob
train
async def _runJob(self, user, appt): ''' Actually run the storm query, updating the appropriate statistics and results ''' count = 0 appt.isrunning = True appt.laststarttime = time.time() appt.startcount += 1 await self._storeAppt(appt) with s_provenance.claim('cron', iden=appt.iden): logger.info('Agenda executing for iden=%s, user=%s, query={%s}', appt.iden, user.name, appt.query) starttime = time.time() try: async for _ in self.core.eval(appt.query, user=user): # NOQA count += 1 except asyncio.CancelledError: result = 'cancelled' raise except Exception as e: result = f'raised exception {e}' logger.exception('Agenda job %s raised exception', appt.iden) else: result = f'finished successfully with {count} nodes' finally: finishtime = time.time() logger.info('Agenda completed query for iden=%s with result "%s" took %0.3fs', appt.iden, result, finishtime - starttime) appt.lastfinishtime = finishtime appt.isrunning = False appt.lastresult = result if not self.isfini: await self._storeAppt(appt)
python
{ "resource": "" }
q19309
get
train
def get(name, defval=None): ''' Return an object from the embedded synapse data folder. Example: for tld in syanpse.data.get('iana.tlds'): dostuff(tld) NOTE: Files are named synapse/data/<name>.mpk ''' with s_datfile.openDatFile('synapse.data/%s.mpk' % name) as fd: return s_msgpack.un(fd.read())
python
{ "resource": "" }
q19310
prop
train
def prop(pode, prop): ''' Return the valu of a given property on the node. Args: pode (tuple): A packed node. prop (str): Property to retrieve. Notes: The prop argument may be the full property name (foo:bar:baz), relative property name (:baz) , or the unadorned property name (baz). Returns: ''' form = pode[0][0] if prop.startswith(form): prop = prop[len(form):] if prop[0] == ':': prop = prop[1:] return pode[1]['props'].get(prop)
python
{ "resource": "" }
q19311
tags
train
def tags(pode, leaf=False): ''' Get all the tags for a given node. Args: pode (tuple): A packed node. leaf (bool): If True, only return the full tags. Returns: list: A list of tag strings. ''' fulltags = [tag for tag in pode[1]['tags']] if not leaf: return fulltags # longest first retn = [] # brute force rather than build a tree. faster in small sets. for size, tag in sorted([(len(t), t) for t in fulltags], reverse=True): look = tag + '.' if any([r.startswith(look) for r in retn]): continue retn.append(tag) return retn
python
{ "resource": "" }
q19312
tagged
train
def tagged(pode, tag): ''' Check if a packed node has a given tag. Args: pode (tuple): A packed node. tag (str): The tag to check. Examples: Check if a node is tagged with "woot" and dostuff if it is. if s_node.tagged(node,'woot'): dostuff() Notes: If the tag starts with `#`, this is removed prior to checking. Returns: bool: True if the tag is present. False otherwise. ''' if tag.startswith('#'): tag = tag[1:] return pode[1]['tags'].get(tag) is not None
python
{ "resource": "" }
q19313
Node.seen
train
async def seen(self, tick, source=None): ''' Update the .seen interval and optionally a source specific seen node. ''' await self.set('.seen', tick) if source is not None: seen = await self.snap.addNode('meta:seen', (source, self.ndef)) await seen.set('.seen', tick)
python
{ "resource": "" }
q19314
Node.set
train
async def set(self, name, valu, init=False): ''' Set a property on the node. Args: name (str): The name of the property. valu (obj): The value of the property. init (bool): Set to True to disable read-only enforcement Returns: (bool): True if the property was changed. ''' with s_editatom.EditAtom(self.snap.core.bldgbuids) as editatom: retn = await self._setops(name, valu, editatom, init) if not retn: return False await editatom.commit(self.snap) return True
python
{ "resource": "" }
q19315
Node._setops
train
async def _setops(self, name, valu, editatom, init=False): ''' Generate operations to set a property on a node. ''' prop = self.form.prop(name) if prop is None: if self.snap.strict: raise s_exc.NoSuchProp(name=name) await self.snap.warn(f'NoSuchProp: name={name}') return False if self.isrunt: if prop.info.get('ro'): raise s_exc.IsRuntForm(mesg='Cannot set read-only props on runt nodes', form=self.form.full, prop=name, valu=valu) return await self.snap.core.runRuntPropSet(self, prop, valu) curv = self.props.get(name) # normalize the property value... try: norm, info = prop.type.norm(valu) except Exception as e: mesg = f'Bad property value: {prop.full}={valu!r}' return await self.snap._raiseOnStrict(s_exc.BadPropValu, mesg, name=prop.name, valu=valu, emesg=str(e)) # do we already have the value? if curv == norm: return False if curv is not None and not init: if prop.info.get('ro'): if self.snap.strict: raise s_exc.ReadOnlyProp(name=prop.full) # not setting a set-once prop unless we are init... await self.snap.warn(f'ReadOnlyProp: name={prop.full}') return False # check for type specific merging... norm = prop.type.merge(curv, norm) if curv == norm: return False sops = prop.getSetOps(self.buid, norm) editatom.sops.extend(sops) # self.props[prop.name] = norm editatom.npvs.append((self, prop, curv, norm)) # do we have any auto nodes to add? auto = self.snap.model.form(prop.type.name) if auto is not None: buid = s_common.buid((auto.name, norm)) await self.snap._addNodeFnibOps((auto, norm, info, buid), editatom) # does the type think we have special auto nodes to add? # ( used only for adds which do not meet the above block ) for autoname, autovalu in info.get('adds', ()): auto = self.snap.model.form(autoname) autonorm, autoinfo = auto.type.norm(autovalu) buid = s_common.buid((auto.name, autonorm)) await self.snap._addNodeFnibOps((auto, autovalu, autoinfo, buid), editatom) # do we need to set any sub props? subs = info.get('subs') if subs is not None: for subname, subvalu in subs.items(): full = prop.name + ':' + subname subprop = self.form.prop(full) if subprop is None: continue await self._setops(full, subvalu, editatom, init=init) return True
python
{ "resource": "" }
q19316
Node.get
train
def get(self, name): ''' Return a secondary property value from the Node. Args: name (str): The name of a secondary property. Returns: (obj): The secondary property value or None. ''' if name.startswith('#'): return self.tags.get(name[1:]) return self.props.get(name)
python
{ "resource": "" }
q19317
Node.pop
train
async def pop(self, name, init=False): ''' Remove a property from a node and return the value ''' prop = self.form.prop(name) if prop is None: if self.snap.strict: raise s_exc.NoSuchProp(name=name) await self.snap.warn(f'No Such Property: {name}') return False if self.isrunt: if prop.info.get('ro'): raise s_exc.IsRuntForm(mesg='Cannot delete read-only props on runt nodes', form=self.form.full, prop=name) return await self.snap.core.runRuntPropDel(self, prop) if not init: if prop.info.get('ro'): if self.snap.strict: raise s_exc.ReadOnlyProp(name=name) await self.snap.warn(f'Property is read-only: {name}') return False curv = self.props.pop(name, s_common.novalu) if curv is s_common.novalu: return False sops = prop.getDelOps(self.buid) splice = self.snap.splice('prop:del', ndef=self.ndef, prop=prop.name, valu=curv) await self.snap.stor(sops, [splice]) await prop.wasDel(self, curv)
python
{ "resource": "" }
q19318
Node.delTag
train
async def delTag(self, tag, init=False): ''' Delete a tag from the node. ''' path = s_chop.tagpath(tag) name = '.'.join(path) if self.isrunt: raise s_exc.IsRuntForm(mesg='Cannot delete tags from runt nodes.', form=self.form.full, tag=tag) curv = self.tags.pop(name, s_common.novalu) if curv is s_common.novalu: return False pref = name + '.' subtags = [(len(t), t) for t in self.tags.keys() if t.startswith(pref)] subtags.sort(reverse=True) removed = [] for sublen, subtag in subtags: valu = self.tags.pop(subtag, None) removed.append((subtag, valu)) removed.append((name, curv)) info = {'univ': True} sops = [('prop:del', (self.buid, self.form.name, '#' + t, info)) for (t, v) in removed] # fire all the splices splices = [self.snap.splice('tag:del', ndef=self.ndef, tag=t, valu=v) for (t, v) in removed] await self.snap.stor(sops, splices) # fire all the handlers / triggers [await self.snap.core.runTagDel(self, t, v) for (t, v) in removed]
python
{ "resource": "" }
q19319
Node.delete
train
async def delete(self, force=False): ''' Delete a node from the cortex. The following tear-down operations occur in order: * validate that you have permissions to delete the node * validate that you have permissions to delete all tags * validate that there are no remaining references to the node. * delete all the tags (bottom up) * fire onDelTag() handlers * delete tag properties from storage * log tag:del splices * delete all secondary properties * fire onDelProp handler * delete secondary property from storage * log prop:del splices * delete the primary property * fire onDel handlers for the node * delete primary property from storage * log node:del splices ''' formname, formvalu = self.ndef if self.isrunt: raise s_exc.IsRuntForm(mesg='Cannot delete runt nodes', form=formname, valu=formvalu) tags = [(len(t), t) for t in self.tags.keys()] # check for tag permissions # TODO # check for any nodes which reference us... if not force: # refuse to delete tag nodes with existing tags if self.form.name == 'syn:tag': async for _ in self.snap._getNodesByTag(self.ndef[1]): # NOQA mesg = 'Nodes still have this tag.' return await self.snap._raiseOnStrict(s_exc.CantDelNode, mesg, form=formname) async for refr in self.snap._getNodesByType(formname, formvalu, addform=False): if refr.buid == self.buid: continue mesg = 'Other nodes still refer to this node.' return await self.snap._raiseOnStrict(s_exc.CantDelNode, mesg, form=formname) for size, tag in sorted(tags, reverse=True): await self.delTag(tag, init=True) for name in list(self.props.keys()): await self.pop(name, init=True) sops = self.form.getDelOps(self.buid) splice = self.snap.splice('node:del', ndef=self.ndef) await self.snap.stor(sops, [splice]) self.snap.livenodes.pop(self.buid) self.snap.core.pokeFormCount(formname, -1) await self.form.wasDeleted(self)
python
{ "resource": "" }
q19320
Type._getIndxChop
train
def _getIndxChop(self, indx): ''' A helper method for Type subclasses to use for a simple way to truncate indx bytes. ''' # cut down an index value to 256 bytes... if len(indx) <= 256: return indx base = indx[:248] sufx = xxhash.xxh64(indx).digest() return base + sufx
python
{ "resource": "" }
q19321
Type.cmpr
train
def cmpr(self, val1, name, val2): ''' Compare the two values using the given type specific comparator. ''' ctor = self.getCmprCtor(name) if ctor is None: raise s_exc.NoSuchCmpr(cmpr=name, name=self.name) norm1 = self.norm(val1)[0] norm2 = self.norm(val2)[0] return ctor(norm2)(norm1)
python
{ "resource": "" }
q19322
Type.norm
train
def norm(self, valu): ''' Normalize the value for a given type. Args: valu (obj): The value to normalize. Returns: ((obj,dict)): The normalized valu, info tuple. Notes: The info dictionary uses the following key conventions: subs (dict): The normalized sub-fields as name: valu entries. ''' func = self._type_norms.get(type(valu)) if func is None: raise s_exc.NoSuchFunc(name=self.name, mesg='no norm for type: %r' % (type(valu),)) return func(valu)
python
{ "resource": "" }
q19323
Type.extend
train
def extend(self, name, opts, info): ''' Extend this type to construct a sub-type. Args: name (str): The name of the new sub-type. opts (dict): The type options for the sub-type. info (dict): The type info for the sub-type. Returns: (synapse.types.Type): A new sub-type instance. ''' tifo = self.info.copy() tifo.update(info) topt = self.opts.copy() topt.update(opts) tobj = self.__class__(self.modl, name, tifo, topt) tobj.subof = self.name return tobj
python
{ "resource": "" }
q19324
Type.clone
train
def clone(self, opts): ''' Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance. ''' topt = self.opts.copy() topt.update(opts) return self.__class__(self.modl, self.name, self.info, topt)
python
{ "resource": "" }
q19325
Type.getIndxOps
train
def getIndxOps(self, valu, cmpr='='): ''' Return a list of index operation tuples to lift values in a table. Valid index operations include: ('eq', <indx>) ('pref', <indx>) ('range', (<minindx>, <maxindx>)) ''' func = self.indxcmpr.get(cmpr) if func is None: raise s_exc.NoSuchCmpr(name=self.name, cmpr=cmpr) return func(valu)
python
{ "resource": "" }
q19326
Time.getTickTock
train
def getTickTock(self, vals): ''' Get a tick, tock time pair. Args: vals (list): A pair of values to norm. Returns: (int, int): A ordered pair of integers. ''' val0, val1 = vals try: _tick = self._getLiftValu(val0) except ValueError as e: raise s_exc.BadTypeValu(name=self.name, valu=val0, mesg='Unable to process the value for val0 in getTickTock.') sortval = False if isinstance(val1, str): if val1.startswith(('+-', '-+')): sortval = True delt = s_time.delta(val1[2:]) # order matters _tock = _tick + delt _tick = _tick - delt elif val1.startswith('-'): sortval = True _tock = self._getLiftValu(val1, relto=_tick) else: _tock = self._getLiftValu(val1, relto=_tick) else: _tock = self._getLiftValu(val1, relto=_tick) if sortval and _tick >= _tock: tick = min(_tick, _tock) tock = max(_tick, _tock) return tick, tock return _tick, _tock
python
{ "resource": "" }
q19327
unixlisten
train
async def unixlisten(path, onlink): ''' Start an PF_UNIX server listening on the given path. ''' info = {'path': path, 'unix': True} async def onconn(reader, writer): link = await Link.anit(reader, writer, info=info) link.schedCoro(onlink(link)) return await asyncio.start_unix_server(onconn, path=path)
python
{ "resource": "" }
q19328
unixconnect
train
async def unixconnect(path): ''' Connect to a PF_UNIX server listening on the given path. ''' reader, writer = await asyncio.open_unix_connection(path=path) info = {'path': path, 'unix': True} return await Link.anit(reader, writer, info=info)
python
{ "resource": "" }
q19329
AstNode.sibling
train
def sibling(self, offs=1): ''' Return sibling node by relative offset from self. ''' indx = self.pindex + offs if indx < 0: return None if indx >= len(self.parent.kids): return None return self.parent.kids[indx]
python
{ "resource": "" }
q19330
AstNode.iterright
train
def iterright(self): ''' Yield "rightward" siblings until None. ''' offs = 1 while True: sibl = self.sibling(offs) if sibl is None: break yield sibl offs += 1
python
{ "resource": "" }
q19331
executor
train
def executor(func, *args, **kwargs): ''' Execute a non-coroutine function in the ioloop executor pool. Args: func: Function to execute. *args: Args for the function. **kwargs: Kwargs for the function. Examples: Execute a blocking API call in the executor pool:: import requests def block(url, params=None): return requests.get(url, params=params).json() fut = s_coro.executor(block, 'http://some.tld/thign') resp = await fut Returns: asyncio.Future: An asyncio future. ''' def real(): return func(*args, **kwargs) return asyncio.get_running_loop().run_in_executor(None, real)
python
{ "resource": "" }
q19332
event_wait
train
async def event_wait(event: asyncio.Event, timeout=None): ''' Wait on an an asyncio event with an optional timeout Returns: true if the event got set, None if timed out ''' if timeout is None: await event.wait() return True try: await asyncio.wait_for(event.wait(), timeout) except asyncio.TimeoutError: return False return True
python
{ "resource": "" }
q19333
ornot
train
async def ornot(func, *args, **kwargs): ''' Calls func and awaits it if a returns a coroutine. Note: This is useful for implementing a function that might take a telepath proxy object or a local object, and you must call a non-async method on that object. This is also useful when calling a callback that might either be a coroutine function or a regular function. Usage: ok = await s_coro.ornot(maybeproxy.allowed, 'path') ''' retn = func(*args, **kwargs) if iscoro(retn): return await retn return retn
python
{ "resource": "" }
q19334
hexstr
train
def hexstr(text): ''' Ensure a string is valid hex. Args: text (str): String to normalize. Examples: Norm a few strings: hexstr('0xff00') hexstr('ff00') Notes: Will accept strings prefixed by '0x' or '0X' and remove them. Returns: str: Normalized hex string. ''' text = text.strip().lower() if text.startswith(('0x', '0X')): text = text[2:] if not text: raise s_exc.BadTypeValu(valu=text, name='hexstr', mesg='No string left after stripping') try: # checks for valid hex width and does character # checking in C without using regex s_common.uhex(text) except (binascii.Error, ValueError) as e: raise s_exc.BadTypeValu(valu=text, name='hexstr', mesg=str(e)) return text
python
{ "resource": "" }
q19335
tags
train
def tags(norm): ''' Divide a normalized tag string into hierarchical layers. ''' # this is ugly for speed.... parts = norm.split('.') return ['.'.join(parts[:i]) for i in range(1, len(parts) + 1)]
python
{ "resource": "" }
q19336
getDynLocal
train
def getDynLocal(name): ''' Dynamically import a python module and return a local. Example: cls = getDynLocal('foopkg.barmod.BlahClass') blah = cls() ''' if name.find('.') == -1: return None modname, objname = name.rsplit('.', 1) mod = getDynMod(modname) if mod is None: return None return getattr(mod, objname, None)
python
{ "resource": "" }
q19337
getDynMeth
train
def getDynMeth(name): ''' Retrieve and return an unbound method by python path. ''' cname, fname = name.rsplit('.', 1) clas = getDynLocal(cname) if clas is None: return None return getattr(clas, fname, None)
python
{ "resource": "" }
q19338
tryDynMod
train
def tryDynMod(name): ''' Dynamically import a python module or exception. ''' try: return importlib.import_module(name) except ModuleNotFoundError: raise s_exc.NoSuchDyn(name=name)
python
{ "resource": "" }
q19339
tryDynLocal
train
def tryDynLocal(name): ''' Dynamically import a module and return a module local or raise an exception. ''' if name.find('.') == -1: raise s_exc.NoSuchDyn(name=name) modname, objname = name.rsplit('.', 1) mod = tryDynMod(modname) item = getattr(mod, objname, s_common.novalu) if item is s_common.novalu: raise s_exc.NoSuchDyn(name=name) return item
python
{ "resource": "" }
q19340
runDynTask
train
def runDynTask(task): ''' Run a dynamic task and return the result. Example: foo = runDynTask( ('baz.faz.Foo', (), {} ) ) ''' func = getDynLocal(task[0]) if func is None: raise s_exc.NoSuchFunc(name=task[0]) return func(*task[1], **task[2])
python
{ "resource": "" }
q19341
Migration.setFormName
train
async def setFormName(self, oldn, newn): ''' Rename a form within all the layers. ''' logger.info(f'Migrating [{oldn}] to [{newn}]') async with self.getTempSlab(): i = 0 async for buid, valu in self.getFormTodo(oldn): await self.editNodeNdef((oldn, valu), (newn, valu)) i = i + 1 if i and i % _progress == 0: logger.info(f'Migrated {i} buids.')
python
{ "resource": "" }
q19342
Migration.editNdefProps
train
async def editNdefProps(self, oldndef, newndef): ''' Change all props as a result of an ndef change. ''' oldbuid = s_common.buid(oldndef) oldname, oldvalu = oldndef newname, newvalu = newndef rename = newname != oldname # we only need to update secondary props if they have diff vals # ( vs for example a pure rename ) if oldvalu != newvalu: # get the indx bytes for the *value* of the ndef indx = self.slab.get(oldbuid, db=self.oldb2indx) if indx is not None: # the only way for indx to be None is if we dont have the node... for prop in self.core.model.getPropsByType(newname): coff = prop.getCompOffs() for layr in self.layers: async for buid, valu in layr.iterPropIndx(prop.form.name, prop.name, indx): await layr.storPropSet(buid, prop, newvalu) # for now, assume any comp sub is on the same layer as it's form prop if coff is not None: ndef = await layr.getNodeNdef(buid) edit = list(ndef[1]) edit[coff] = newvalu await self.editNodeNdef(ndef, (ndef[0], edit)) for prop in self.core.model.getPropsByType('ndef'): formsub = self.core.model.prop(prop.full + ':' + 'form') coff = prop.getCompOffs() for layr in self.layers: async for buid, valu in layr.iterPropIndx(prop.form.name, prop.name, oldbuid): await layr.storPropSet(buid, prop, newndef) if rename and formsub is not None: await layr.storPropSet(buid, formsub, newname) if coff is not None: # for now, assume form and prop on the same layer... ndef = await layr.getNodeNdef(buid) edit = list(ndef[1]) edit[coff] = newndef await self.editNodeNdef(ndef, (ndef[0], edit))
python
{ "resource": "" }
q19343
Snap.iterStormPodes
train
async def iterStormPodes(self, text, opts=None, user=None): ''' Yield packed node tuples for the given storm query text. ''' if user is None: user = self.user dorepr = False dopath = False self.core._logStormQuery(text, user) if opts is not None: dorepr = opts.get('repr', False) dopath = opts.get('path', False) async for node, path in self.storm(text, opts=opts, user=user): pode = node.pack(dorepr=dorepr) pode[1]['path'] = path.pack(path=dopath) yield pode
python
{ "resource": "" }
q19344
Snap.getNodeByBuid
train
async def getNodeByBuid(self, buid): ''' Retrieve a node tuple by binary id. Args: buid (bytes): The binary ID for the node. Returns: Optional[s_node.Node]: The node object or None. ''' node = self.livenodes.get(buid) if node is not None: return node props = {} proplayr = {} for layr in self.layers: layerprops = await layr.getBuidProps(buid) props.update(layerprops) proplayr.update({k: layr for k in layerprops}) node = s_node.Node(self, buid, props.items(), proplayr=proplayr) # Give other tasks a chance to run await asyncio.sleep(0) if node.ndef is None: return None # Add node to my buidcache self.buidcache.append(node) self.livenodes[buid] = node return node
python
{ "resource": "" }
q19345
Snap.getNodesBy
train
async def getNodesBy(self, full, valu=None, cmpr='='): ''' The main function for retrieving nodes by prop. Args: full (str): The property/tag name. valu (obj): A lift compatible value for the type. cmpr (str): An optional alternate comparator. Yields: (synapse.lib.node.Node): Node instances. ''' if self.debug: await self.printf(f'get nodes by: {full} {cmpr} {valu!r}') # special handling for by type (*type=) here... if cmpr == '*type=': async for node in self._getNodesByType(full, valu=valu): yield node return if full.startswith('#'): async for node in self._getNodesByTag(full, valu=valu, cmpr=cmpr): yield node return fields = full.split('#', 1) if len(fields) > 1: form, tag = fields async for node in self._getNodesByFormTag(form, tag, valu=valu, cmpr=cmpr): yield node return async for node in self._getNodesByProp(full, valu=valu, cmpr=cmpr): yield node
python
{ "resource": "" }
q19346
Snap.addNode
train
async def addNode(self, name, valu, props=None): ''' Add a node by form name and value with optional props. Args: name (str): The form of node to add. valu (obj): The value for the node. props (dict): Optional secondary properties for the node. ''' try: fnib = self._getNodeFnib(name, valu) retn = await self._addNodeFnib(fnib, props=props) return retn except asyncio.CancelledError: raise except Exception: mesg = f'Error adding node: {name} {valu!r} {props!r}' logger.exception(mesg) if self.strict: raise return None
python
{ "resource": "" }
q19347
Snap._getNodeFnib
train
def _getNodeFnib(self, name, valu): ''' return a form, norm, info, buid tuple ''' form = self.model.form(name) if form is None: raise s_exc.NoSuchForm(name=name) try: norm, info = form.type.norm(valu) except Exception as e: raise s_exc.BadPropValu(prop=form.name, valu=valu, mesg=str(e)) buid = s_common.buid((form.name, norm)) return form, norm, info, buid
python
{ "resource": "" }
q19348
Snap.getLiftRows
train
async def getLiftRows(self, lops): ''' Yield row tuples from a series of lift operations. Row tuples only requirement is that the first element be the binary id of a node. Args: lops (list): A list of lift operations. Yields: (tuple): (layer_indx, (buid, ...)) rows. ''' for layeridx, layr in enumerate(self.layers): async for x in layr.getLiftRows(lops): yield layeridx, x
python
{ "resource": "" }
q19349
CoreModule.getModName
train
def getModName(self): ''' Return the lowercased name of this module. Notes: This pulls the ``mod_name`` attribute on the class. This allows an implementer to set a arbitrary name for the module. If this attribute is not set, it defaults to ``self.__class__.__name__.lower()`` and sets ``mod_name`` to that value. Returns: (str): The module name. ''' ret = self.mod_name if ret is None: ret = self.__class__.__name__ return ret.lower()
python
{ "resource": "" }
q19350
CoreModule.getModPath
train
def getModPath(self, *paths): ''' Construct a path relative to this module's working directory. Args: *paths: A list of path strings Notes: This creates the module specific directory if it does not exist. Returns: (str): The full path (or None if no cortex dir is configured). ''' dirn = self.getModDir() return s_common.genpath(dirn, *paths)
python
{ "resource": "" }
q19351
ctor
train
def ctor(name, func, *args, **kwargs): ''' Add a ctor callback to the global scope. ''' return globscope.ctor(name, func, *args, **kwargs)
python
{ "resource": "" }
q19352
Scope.get
train
def get(self, name, defval=None): ''' Retrieve a value from the closest scope frame. ''' for frame in reversed(self.frames): valu = frame.get(name, s_common.novalu) if valu != s_common.novalu: return valu task = self.ctors.get(name) if task is not None: func, args, kwargs = task item = func(*args, **kwargs) self.frames[-1][name] = item return item return defval
python
{ "resource": "" }
q19353
Scope.ctor
train
def ctor(self, name, func, *args, **kwargs): ''' Add a constructor to be called when a specific property is not present. Example: scope.ctor('foo',FooThing) ... foo = scope.get('foo') ''' self.ctors[name] = (func, args, kwargs)
python
{ "resource": "" }
q19354
AQueue.put
train
def put(self, item): ''' Add an item to the queue. ''' if self.isfini: return False self.fifo.append(item) if len(self.fifo) == 1: self.event.set() return True
python
{ "resource": "" }
q19355
EditAtom.getNodeBeingMade
train
def getNodeBeingMade(self, buid): ''' Return a node if it is currently being made, mark as a dependency, else None if none found ''' nodeevnt = self.allbldgbuids.get(buid) if nodeevnt is None: return None if buid not in self.mybldgbuids: self.otherbldgbuids.add(buid) return nodeevnt[0]
python
{ "resource": "" }
q19356
EditAtom.addNode
train
def addNode(self, node): ''' Update the shared map with my in-construction node ''' self.mybldgbuids[node.buid] = node self.allbldgbuids[node.buid] = (node, self.doneevent)
python
{ "resource": "" }
q19357
EditAtom._notifyDone
train
def _notifyDone(self): ''' Allow any other editatoms waiting on me to complete to resume ''' if self.notified: return self.doneevent.set() for buid in self.mybldgbuids: del self.allbldgbuids[buid] self.notified = True
python
{ "resource": "" }
q19358
EditAtom._wait
train
async def _wait(self): ''' Wait on the other editatoms who are constructing nodes my new nodes refer to ''' for buid in self.otherbldgbuids: nodeevnt = self.allbldgbuids.get(buid) if nodeevnt is None: continue await nodeevnt[1].wait()
python
{ "resource": "" }
q19359
EditAtom.commit
train
async def commit(self, snap): ''' Push the recorded changes to disk, notify all the listeners ''' if not self.npvs: # nothing to do return for node, prop, _, valu in self.npvs: node.props[prop.name] = valu node.proplayr[prop.name] = snap.wlyr splices = [snap.splice('node:add', ndef=node.ndef) for node in self.mybldgbuids.values()] for node, prop, oldv, valu in self.npvs: info = {'ndef': node.ndef, 'prop': prop.name, 'valu': valu} if oldv is not None: info['oldv'] = oldv splices.append(snap.splice('prop:set', **info)) await snap.stor(self.sops, splices) for node in self.mybldgbuids.values(): snap.core.pokeFormCount(node.form.name, 1) snap.buidcache.append(node) snap.livenodes[node.buid] = node await self.rendevous() for node in self.mybldgbuids.values(): await node.form.wasAdded(node) # fire all his prop sets for node, prop, oldv, valu in self.npvs: await prop.wasSet(node, oldv) if prop.univ: univ = snap.model.prop(prop.univ) await univ.wasSet(node, oldv) # Finally, fire all the triggers for node, prop, oldv, _ in self.npvs: await snap.core.triggers.runPropSet(node, prop, oldv)
python
{ "resource": "" }
q19360
getItemCmdr
train
async def getItemCmdr(cell, outp=None, **opts): ''' Construct and return a cmdr for the given remote cell. Example: cmdr = await getItemCmdr(foo) ''' cmdr = await s_cli.Cli.anit(cell, outp=outp) typename = await cell.getCellType() for ctor in cmdsbycell.get(typename, ()): cmdr.addCmdClass(ctor) return cmdr
python
{ "resource": "" }
q19361
runItemCmdr
train
async def runItemCmdr(item, outp=None, **opts): ''' Create a cmdr for the given item and run the cmd loop. Example: runItemCmdr(foo) ''' cmdr = await getItemCmdr(item, outp=outp, **opts) await cmdr.runCmdLoop()
python
{ "resource": "" }
q19362
getDocPath
train
def getDocPath(fn, root=None): ''' Helper for getting a documentation data file paths. Args: fn (str): Name of the file to retrieve the full path for. root (str): Optional root path to look for a docdata in. Notes: Defaults to looking for the ``docdata`` directory in the current working directory. This behavior works fine for notebooks nested in the docs directory of synapse; but this root directory that is looked for may be overridden by providing an alternative root. Returns: str: A file path. Raises: ValueError if the file does not exist or directory traversal attempted.. ''' cwd = pathlib.Path(os.getcwd()) if root: cwd = pathlib.Path(root) # Walk up a directory until you find '...d./data' while True: dpath = cwd.joinpath('docdata') if dpath.is_dir(): break parent = cwd.parent if parent == cwd: raise ValueError(f'Unable to find data directory from {os.getcwd()}.') cwd = parent # Protect against traversal fpath = os.path.abspath(os.path.join(dpath.as_posix(), fn)) if not fpath.startswith(dpath.as_posix()): raise ValueError(f'Path escaping detected: {fn}') # Existence if not os.path.isfile(fpath): raise ValueError(f'File does not exist: {fn}') return fpath
python
{ "resource": "" }
q19363
genTempCoreProxy
train
async def genTempCoreProxy(mods=None): '''Get a temporary cortex proxy.''' with s_common.getTempDir() as dirn: async with await s_cortex.Cortex.anit(dirn) as core: if mods: for mod in mods: await core.loadCoreModule(mod) async with core.getLocalProxy() as prox: # Use object.__setattr__ to hulk smash and avoid proxy getattr magick object.__setattr__(prox, '_core', core) yield prox
python
{ "resource": "" }
q19364
getItemCmdr
train
async def getItemCmdr(prox, outp=None, locs=None): '''Get a Cmdr instance with prepopulated locs''' cmdr = await s_cmdr.getItemCmdr(prox, outp=outp) cmdr.echoline = True if locs: cmdr.locs.update(locs) return cmdr
python
{ "resource": "" }
q19365
getTempCoreProx
train
async def getTempCoreProx(mods=None): ''' Get a Telepath Proxt to a Cortex instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. Notes: The Proxy returned by this should be fini()'d to tear down the temporary Cortex. Returns: s_telepath.Proxy ''' acm = genTempCoreProxy(mods) prox = await acm.__aenter__() # Use object.__setattr__ to hulk smash and avoid proxy getattr magick object.__setattr__(prox, '_acm', acm) async def onfini(): await prox._acm.__aexit__(None, None, None) prox.onfini(onfini) return prox
python
{ "resource": "" }
q19366
getTempCoreCmdr
train
async def getTempCoreCmdr(mods=None, outp=None): ''' Get a CmdrCore instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. outp: A output helper. Will be used for the Cmdr instance. Notes: The CmdrCore returned by this should be fini()'d to tear down the temporary Cortex. Returns: CmdrCore: A CmdrCore instance. ''' acm = genTempCoreProxy(mods) prox = await acm.__aenter__() cmdrcore = await CmdrCore.anit(prox, outp=outp) cmdrcore.acm = acm return cmdrcore
python
{ "resource": "" }
q19367
CmdrCore.addFeedData
train
async def addFeedData(self, name, items, seqn=None): ''' Add feed data to the cortex. ''' return await self.core.addFeedData(name, items, seqn)
python
{ "resource": "" }
q19368
CmdrCore.storm
train
async def storm(self, text, opts=None, num=None, cmdr=False): ''' A helper for executing a storm command and getting a list of storm messages. Args: text (str): Storm command to execute. opts (dict): Opt to pass to the cortex during execution. num (int): Number of nodes to expect in the output query. Checks that with an assert statement. cmdr (bool): If True, executes the line via the Cmdr CLI and will send output to outp. Notes: The opts dictionary will not be used if cmdr=True. Returns: list: A list of storm messages. ''' mesgs = await self._runStorm(text, opts, cmdr) if num is not None: nodes = [m for m in mesgs if m[0] == 'node'] if len(nodes) != num: raise AssertionError(f'Expected {num} nodes, got {len(nodes)}') return mesgs
python
{ "resource": "" }
q19369
_inputrc_enables_vi_mode
train
def _inputrc_enables_vi_mode(): ''' Emulate a small bit of readline behavior. Returns: (bool) True if current user enabled vi mode ("set editing-mode vi") in .inputrc ''' for filepath in (os.path.expanduser('~/.inputrc'), '/etc/inputrc'): try: with open(filepath) as f: for line in f: if _setre.fullmatch(line): return True except IOError: continue return False
python
{ "resource": "" }
q19370
Cmd.runCmdLine
train
async def runCmdLine(self, line): ''' Run a line of command input for this command. Args: line (str): Line to execute Examples: Run the foo command with some arguments: await foo.runCmdLine('foo --opt baz woot.com') ''' opts = self.getCmdOpts(line) return await self.runCmdOpts(opts)
python
{ "resource": "" }
q19371
Cli.addSignalHandlers
train
async def addSignalHandlers(self): ''' Register SIGINT signal handler with the ioloop to cancel the currently running cmdloop task. ''' def sigint(): self.printf('<ctrl-c>') if self.cmdtask is not None: self.cmdtask.cancel() self.loop.add_signal_handler(signal.SIGINT, sigint)
python
{ "resource": "" }
q19372
Cli.prompt
train
async def prompt(self, text=None): ''' Prompt for user input from stdin. ''' if self.sess is None: hist = FileHistory(s_common.getSynPath('cmdr_history')) self.sess = PromptSession(history=hist) if text is None: text = self.cmdprompt with patch_stdout(): retn = await self.sess.prompt(text, async_=True, vi_mode=self.vi_mode, enable_open_in_editor=True) return retn
python
{ "resource": "" }
q19373
Cli.addCmdClass
train
def addCmdClass(self, ctor, **opts): ''' Add a Cmd subclass to this cli. ''' item = ctor(self, **opts) name = item.getCmdName() self.cmds[name] = item
python
{ "resource": "" }
q19374
Cli.runCmdLine
train
async def runCmdLine(self, line): ''' Run a single command line. Args: line (str): Line to execute. Examples: Execute the 'woot' command with the 'help' switch: await cli.runCmdLine('woot --help') Returns: object: Arbitrary data from the cmd class. ''' if self.echoline: self.outp.printf(f'{self.cmdprompt}{line}') ret = None name = line.split(None, 1)[0] cmdo = self.getCmdByName(name) if cmdo is None: self.printf('cmd not found: %s' % (name,)) return try: ret = await cmdo.runCmdLine(line) except s_exc.CliFini: await self.fini() except asyncio.CancelledError: self.printf('Cmd cancelled') except Exception as e: exctxt = traceback.format_exc() self.printf(exctxt) self.printf('error: %s' % e) return ret
python
{ "resource": "" }
q19375
CertDir.genCaCert
train
def genCaCert(self, name, signas=None, outp=None, save=True): ''' Generates a CA keypair. Args: name (str): The name of the CA keypair. signas (str): The CA keypair to sign the new CA with. outp (synapse.lib.output.Output): The output buffer. Examples: Make a CA named "myca": mycakey, mycacert = cdir.genCaCert('myca') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the private key and certificate objects. ''' pkey, cert = self._genBasePkeyCert(name) ext0 = crypto.X509Extension(b'basicConstraints', False, b'CA:TRUE') cert.add_extensions([ext0]) if signas is not None: self.signCertAs(cert, signas) else: self.selfSignCert(cert, pkey) if save: keypath = self._savePkeyTo(pkey, 'cas', '%s.key' % name) if outp is not None: outp.printf('key saved: %s' % (keypath,)) crtpath = self._saveCertTo(cert, 'cas', '%s.crt' % name) if outp is not None: outp.printf('cert saved: %s' % (crtpath,)) return pkey, cert
python
{ "resource": "" }
q19376
CertDir.genHostCert
train
def genHostCert(self, name, signas=None, outp=None, csr=None, sans=None): ''' Generates a host keypair. Args: name (str): The name of the host keypair. signas (str): The CA keypair to sign the new host keypair with. outp (synapse.lib.output.Output): The output buffer. csr (OpenSSL.crypto.PKey): The CSR public key when generating the keypair from a CSR. sans (list): List of subject alternative names. Examples: Make a host keypair named "myhost": myhostkey, myhostcert = cdir.genHostCert('myhost') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the private key and certificate objects. ''' pkey, cert = self._genBasePkeyCert(name, pkey=csr) ext_sans = {'DNS:' + name} if isinstance(sans, str): ext_sans = ext_sans.union(sans.split(',')) ext_sans = ','.join(sorted(ext_sans)) cert.add_extensions([ crypto.X509Extension(b'nsCertType', False, b'server'), crypto.X509Extension(b'keyUsage', False, b'digitalSignature,keyEncipherment'), crypto.X509Extension(b'extendedKeyUsage', False, b'serverAuth'), crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'), crypto.X509Extension(b'subjectAltName', False, ext_sans.encode('utf-8')), ]) if signas is not None: self.signCertAs(cert, signas) else: self.selfSignCert(cert, pkey) if not pkey._only_public: keypath = self._savePkeyTo(pkey, 'hosts', '%s.key' % name) if outp is not None: outp.printf('key saved: %s' % (keypath,)) crtpath = self._saveCertTo(cert, 'hosts', '%s.crt' % name) if outp is not None: outp.printf('cert saved: %s' % (crtpath,)) return pkey, cert
python
{ "resource": "" }
q19377
CertDir.genUserCert
train
def genUserCert(self, name, signas=None, outp=None, csr=None): ''' Generates a user keypair. Args: name (str): The name of the user keypair. signas (str): The CA keypair to sign the new user keypair with. outp (synapse.lib.output.Output): The output buffer. csr (OpenSSL.crypto.PKey): The CSR public key when generating the keypair from a CSR. Examples: Generate a user cert for the user "myuser": myuserkey, myusercert = cdir.genUserCert('myuser') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the key and certificate objects. ''' pkey, cert = self._genBasePkeyCert(name, pkey=csr) cert.add_extensions([ crypto.X509Extension(b'nsCertType', False, b'client'), crypto.X509Extension(b'keyUsage', False, b'digitalSignature'), crypto.X509Extension(b'extendedKeyUsage', False, b'clientAuth'), crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'), ]) if signas is not None: self.signCertAs(cert, signas) else: self.selfSignCert(cert, pkey) crtpath = self._saveCertTo(cert, 'users', '%s.crt' % name) if outp is not None: outp.printf('cert saved: %s' % (crtpath,)) if not pkey._only_public: keypath = self._savePkeyTo(pkey, 'users', '%s.key' % name) if outp is not None: outp.printf('key saved: %s' % (keypath,)) return pkey, cert
python
{ "resource": "" }
q19378
CertDir.valUserCert
train
def valUserCert(self, byts, cacerts=None): ''' Validate the PEM encoded x509 user certificate bytes and return it. Args: byts (bytes): The bytes for the User Certificate. cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates. Raises: OpenSSL.crypto.X509StoreContextError: If the certificate is not valid. Returns: OpenSSL.crypto.X509: The certificate, if it is valid. ''' cert = crypto.load_certificate(crypto.FILETYPE_PEM, byts) if cacerts is None: cacerts = self.getCaCerts() store = crypto.X509Store() [store.add_cert(cacert) for cacert in cacerts] ctx = crypto.X509StoreContext(store, cert) ctx.verify_certificate() # raises X509StoreContextError if unable to verify return cert
python
{ "resource": "" }
q19379
CertDir.getCaCerts
train
def getCaCerts(self): ''' Return a list of CA certs from the CertDir. Returns: [OpenSSL.crypto.X509]: List of CA certificates. ''' retn = [] path = s_common.genpath(self.certdir, 'cas') for name in os.listdir(path): if not name.endswith('.crt'): continue full = s_common.genpath(self.certdir, 'cas', name) retn.append(self._loadCertPath(full)) return retn
python
{ "resource": "" }
q19380
CertDir.getHostCaPath
train
def getHostCaPath(self, name): ''' Gets the path to the CA certificate that issued a given host keypair. Args: name (str): The name of the host keypair. Examples: Get the path to the CA cert which issue the cert for "myhost": mypath = cdir.getHostCaPath('myhost') Returns: str: The path if exists. ''' cert = self.getHostCert(name) if cert is None: return None return self._getCaPath(cert)
python
{ "resource": "" }
q19381
CertDir.getHostCertPath
train
def getHostCertPath(self, name): ''' Gets the path to a host certificate. Args: name (str): The name of the host keypair. Examples: Get the path to the host certificate for the host "myhost": mypath = cdir.getHostCertPath('myhost') Returns: str: The path if exists. ''' path = s_common.genpath(self.certdir, 'hosts', '%s.crt' % name) if not os.path.isfile(path): return None return path
python
{ "resource": "" }
q19382
CertDir.getUserCaPath
train
def getUserCaPath(self, name): ''' Gets the path to the CA certificate that issued a given user keypair. Args: name (str): The name of the user keypair. Examples: Get the path to the CA cert which issue the cert for "myuser": mypath = cdir.getUserCaPath('myuser') Returns: str: The path if exists. ''' cert = self.getUserCert(name) if cert is None: return None return self._getCaPath(cert)
python
{ "resource": "" }
q19383
CertDir.getUserForHost
train
def getUserForHost(self, user, host): ''' Gets the name of the first existing user cert for a given user and host. Args: user (str): The name of the user. host (str): The name of the host. Examples: Get the name for the "myuser" user cert at "cool.vertex.link": usercertname = cdir.getUserForHost('myuser', 'cool.vertex.link') Returns: str: The cert name, if exists. ''' for name in iterFqdnUp(host): usercert = '%s@%s' % (user, name) if self.isUserCert(usercert): return usercert
python
{ "resource": "" }
q19384
CertDir.importFile
train
def importFile(self, path, mode, outp=None): ''' Imports certs and keys into the Synapse cert directory Args: path (str): The path of the file to be imported. mode (str): The certdir subdirectory to import the file into. Examples: Import CA certifciate 'mycoolca.crt' to the 'cas' directory. certdir.importFile('mycoolca.crt', 'cas') Notes: importFile does not perform any validation on the files it imports. Returns: None ''' if not os.path.isfile(path): raise s_exc.NoSuchFile('File does not exist') fname = os.path.split(path)[1] parts = fname.rsplit('.', 1) ext = parts[1] if len(parts) is 2 else None if not ext or ext not in ('crt', 'key', 'p12'): mesg = 'importFile only supports .crt, .key, .p12 extensions' raise s_exc.BadFileExt(mesg=mesg, ext=ext) newpath = s_common.genpath(self.certdir, mode, fname) if os.path.isfile(newpath): raise s_exc.FileExists('File already exists') shutil.copy(path, newpath) if outp is not None: outp.printf('copied %s to %s' % (path, newpath))
python
{ "resource": "" }
q19385
CertDir.isCaCert
train
def isCaCert(self, name): ''' Checks if a CA certificate exists. Args: name (str): The name of the CA keypair. Examples: Check if the CA certificate for "myca" exists: exists = cdir.isCaCert('myca') Returns: bool: True if the certificate is present, False otherwise. ''' crtpath = self._getPathJoin('cas', '%s.crt' % name) return os.path.isfile(crtpath)
python
{ "resource": "" }
q19386
CertDir.isHostCert
train
def isHostCert(self, name): ''' Checks if a host certificate exists. Args: name (str): The name of the host keypair. Examples: Check if the host cert "myhost" exists: exists = cdir.isUserCert('myhost') Returns: bool: True if the certificate is present, False otherwise. ''' crtpath = self._getPathJoin('hosts', '%s.crt' % name) return os.path.isfile(crtpath)
python
{ "resource": "" }
q19387
CertDir.isUserCert
train
def isUserCert(self, name): ''' Checks if a user certificate exists. Args: name (str): The name of the user keypair. Examples: Check if the user cert "myuser" exists: exists = cdir.isUserCert('myuser') Returns: bool: True if the certificate is present, False otherwise. ''' crtpath = self._getPathJoin('users', '%s.crt' % name) return os.path.isfile(crtpath)
python
{ "resource": "" }
q19388
CertDir.signCertAs
train
def signCertAs(self, cert, signas): ''' Signs a certificate with a CA keypair. Args: cert (OpenSSL.crypto.X509): The certificate to sign. signas (str): The CA keypair name to sign the new keypair with. Examples: Sign a certificate with the CA "myca": cdir.signCertAs(mycert, 'myca') Returns: None ''' cakey = self.getCaKey(signas) if cakey is None: raise s_exc.NoCertKey('Missing .key for %s' % signas) cacert = self.getCaCert(signas) if cacert is None: raise s_exc.NoCertKey('Missing .crt for %s' % signas) cert.set_issuer(cacert.get_subject()) cert.sign(cakey, self.signing_digest)
python
{ "resource": "" }
q19389
CertDir.signHostCsr
train
def signHostCsr(self, xcsr, signas, outp=None, sans=None): ''' Signs a host CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output buffer. sans (list): List of subject alternative names. Examples: Sign a host key with the CA "myca": cdir.signHostCsr(mycsr, 'myca') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the public key and certificate objects. ''' pkey = xcsr.get_pubkey() name = xcsr.get_subject().CN return self.genHostCert(name, csr=pkey, signas=signas, outp=outp, sans=sans)
python
{ "resource": "" }
q19390
CertDir.selfSignCert
train
def selfSignCert(self, cert, pkey): ''' Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given private key: cdir.selfSignCert(mycert, myotherprivatekey) Returns: None ''' cert.set_issuer(cert.get_subject()) cert.sign(pkey, self.signing_digest)
python
{ "resource": "" }
q19391
CertDir.signUserCsr
train
def signUserCsr(self, xcsr, signas, outp=None): ''' Signs a user CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output buffer. Examples: cdir.signUserCsr(mycsr, 'myca') Returns: ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the public key and certificate objects. ''' pkey = xcsr.get_pubkey() name = xcsr.get_subject().CN return self.genUserCert(name, csr=pkey, signas=signas, outp=outp)
python
{ "resource": "" }
q19392
CertDir.getClientSSLContext
train
def getClientSSLContext(self): ''' Returns an ssl.SSLContext appropriate for initiating a TLS session ''' sslctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) self._loadCasIntoSSLContext(sslctx) return sslctx
python
{ "resource": "" }
q19393
CertDir.getServerSSLContext
train
def getServerSSLContext(self, hostname=None): ''' Returns an ssl.SSLContext appropriate to listen on a socket Args: hostname: if None, the value from socket.gethostname is used to find the key in the servers directory. This name should match the not-suffixed part of two files ending in .key and .crt in the hosts subdirectory ''' sslctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) if hostname is None: hostname = socket.gethostname() certfile = self.getHostCertPath(hostname) if certfile is None: raise s_exc.NoCertKey('Missing .crt for %s' % hostname) keyfile = self.getHostKeyPath(hostname) if keyfile is None: raise s_exc.NoCertKey('Missing .key for %s' % hostname) sslctx.load_cert_chain(certfile, keyfile) return sslctx
python
{ "resource": "" }
q19394
CertDir.saveCertPem
train
def saveCertPem(self, cert, path): ''' Save a certificate in PEM format to a file outside the certdir. ''' with s_common.genfile(path) as fd: fd.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
python
{ "resource": "" }
q19395
CertDir.savePkeyPem
train
def savePkeyPem(self, pkey, path): ''' Save a private key in PEM format to a file outside the certdir. ''' with s_common.genfile(path) as fd: fd.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
python
{ "resource": "" }
q19396
doECDHE
train
def doECDHE(statprv_u, statpub_v, ephmprv_u, ephmpub_v, length=64, salt=None, info=None): ''' Perform one side of an Ecliptic Curve Diffie Hellman Ephemeral key exchange. Args: statprv_u (PriKey): Static Private Key for U statpub_v (PubKey: Static Public Key for V ephmprv_u (PriKey): Ephemeral Private Key for U ephmpub_v (PubKey): Ephemeral Public Key for V length (int): Number of bytes to return salt (bytes): Salt to use when computing the key. info (bytes): Additional information to use when computing the key. Notes: This makes no assumption about the reuse of the Ephemeral keys passed to the function. It is the caller's responsibility to destroy the keys after they are used for doing key generation. This implementation is the dhHybrid1 scheme described in NIST 800-56A Revision 2. Returns: bytes: The derived key. ''' zs = statprv_u.exchange(statpub_v) ze = ephmprv_u.exchange(ephmpub_v) z = ze + zs kdf = c_hkdf.HKDF(c_hashes.SHA256(), length=length, salt=salt, info=info, backend=default_backend()) k = kdf.derive(z) return k
python
{ "resource": "" }
q19397
PriKey.sign
train
def sign(self, byts): ''' Compute the ECC signature for the given bytestream. Args: byts (bytes): The bytes to sign. Returns: bytes: The RSA Signature bytes. ''' chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() return self.priv.sign(digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash)) )
python
{ "resource": "" }
q19398
PriKey.exchange
train
def exchange(self, pubkey): ''' Perform a ECDH key exchange with a public key. Args: pubkey (PubKey): A PubKey to perform the ECDH with. Returns: bytes: The ECDH bytes. This is deterministic for a given pubkey and private key. ''' try: return self.priv.exchange(c_ec.ECDH(), pubkey.publ) except ValueError as e: raise s_exc.BadEccExchange(mesg=str(e))
python
{ "resource": "" }
q19399
PubKey.verify
train
def verify(self, byts, sign): ''' Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise. ''' try: chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() self.publ.verify(sign, digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash)) ) return True except InvalidSignature: logger.exception('Error in publ.verify') return False
python
{ "resource": "" }