diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d159169d1050894d3ea3b98e1c965c4058208fe1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/ebpfcat/arraymap.py b/ebpfcat/arraymap.py index 9552eb35d5c2995297f2b02d7354e3c233e64e11..c687d46d8ae0fde3945df563ad275448a637be65 100644 --- a/ebpfcat/arraymap.py +++ b/ebpfcat/arraymap.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from itertools import chain from struct import pack_into, unpack_from, calcsize @@ -45,6 +62,7 @@ class ArrayGlobalVarDesc(MemoryDesc): class ArrayMapAccess: + """This is the array map proper""" def __init__(self, fd, write_size, size): self.fd = fd self.write_size = write_size @@ -52,12 +70,31 @@ class ArrayMapAccess: self.data = bytearray(size) def read(self): + """read all variables in the map from EBPF to user space""" self.data = lookup_elem(self.fd, b"\0\0\0\0", self.size) def write(self): + """write all variables in the map from user space to EBPF + + *all* variables are written, even those not marked ``write=True`` + """ update_elem(self.fd, b"\0\0\0\0", self.data, 0) def readwrite(self): + """read variables from EBPF and write them out immediately + + This reads all variables, swaps in the user-modified values for + the ``write=True`` variables, and writes the out again + immediately. + + This means that even the read-only variables will be overwritten + with the values we have just read. If the EBPF program changed + the value in the meantime, that may be a problem. + + Note that after this method returns, all *write* variables + will have the value from the EBPF program in user space, and + vice-versa. + """ write = self.data[:self.write_size] data = lookup_elem(self.fd, b"\0\0\0\0", self.size) self.data[:] = data @@ -66,6 +103,7 @@ class ArrayMapAccess: class ArrayMap(Map): + """A descriptor for an array map""" def globalVar(self, fmt="I", write=False): return ArrayGlobalVarDesc(self, fmt, write) diff --git a/ebpfcat/bpf.py b/ebpfcat/bpf.py index c1208a0872153eebb3a984d2b99b5d56ae29f520..bea41006debee46a4d3c1bc4a60e168b55c1dfd4 100644 --- a/ebpfcat/bpf.py +++ b/ebpfcat/bpf.py @@ -1,3 +1,23 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +"""\ +A module that wraps the `bpf` system call in Python, using `ctypes`. +""" from ctypes import CDLL, c_int, get_errno, cast, c_void_p, create_string_buffer, c_char_p, addressof, c_char from enum import Enum from struct import pack, unpack diff --git a/ebpfcat/chem.py b/ebpfcat/chem.py index da9d7a50617a7bddb5bcc3d75ad81b9fa388b8d9..4ac4f3e4261087bf1e5a0051f2a65fc4ba1373c6 100644 --- a/ebpfcat/chem.py +++ b/ebpfcat/chem.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from asyncio import gather, sleep, ensure_future from struct import unpack, pack from .terminals import EL7041, EL5042, Skip diff --git a/ebpfcat/devices.py b/ebpfcat/devices.py index 55e4288355c1f6f8897babb4783f7ff7b6bf0317..c61fcb2b0d78ae4931dfcf62f37317a71ae01c39 100644 --- a/ebpfcat/devices.py +++ b/ebpfcat/devices.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + """\ A collection of devices ======================= diff --git a/ebpfcat/ebpf.py b/ebpfcat/ebpf.py index 090dc42e3c0fc92de8be0c55907ec9f4f3b15f58..6fd6e5959064ccf639f23a3ac81c18e2e4df1fe3 100644 --- a/ebpfcat/ebpf.py +++ b/ebpfcat/ebpf.py @@ -1,3 +1,21 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from abc import ABC, abstractmethod from collections import namedtuple from contextlib import contextmanager, ExitStack from struct import pack, unpack, calcsize @@ -258,7 +276,9 @@ def comparison(uposop, unegop, sposop=None, snegop=None): return ret -class Comparison: +class Comparison(ABC): + """Base class for all logical operations""" + def __init__(self, ebpf): self.ebpf = ebpf self.else_origin = None @@ -279,9 +299,25 @@ class Comparison: self.ebpf.owners, self.owners = \ self.ebpf.owners & self.owners, self.ebpf.owners - def retarget_one(self): - op, dst, src, off, imm = self.ebpf.opcodes[self.origin] - self.ebpf.opcodes[self.origin] = Instruction(op, dst, src, off+1, imm) + @abstractmethod + def compare(self, negative): + """issue the actual comparison code + + the issued code should either jump to a position later + determined by the `target` method, or just fall through. + If `negative` is true, the code should jump away if the + condition in question is false, and vice versa. + """ + raise NotImplementedError + + @abstractmethod + def target(self, retarget=False): + """modify the already issued jumps to jump here + + you may re-set the target a second time, but then `retarget` needs + to be true. + """ + raise NotImplementedError def Else(self): self.else_origin = len(self.ebpf.opcodes) @@ -303,6 +339,8 @@ class Comparison: class SimpleComparison(Comparison): + """A simple numerical comparison, results in a jump instruction""" + def __init__(self, ebpf, left, right, opcode): super().__init__(ebpf) self.left = left @@ -385,6 +423,7 @@ def rbinary(opcode): class Expression: + """the base class for all numerical expressions""" __radd__ = __add__ = binary(Opcode.ADD) __sub__ = binary(Opcode.SUB) __rsub__ = rbinary(Opcode.SUB) @@ -428,6 +467,32 @@ class Expression: @contextmanager def calculate(self, dst, long, signed, force=False): + """issue the code that calculates the value of this expression + + this method returns three values: + + - the number of the register with the result + - a boolean indicating whether this is a 64 bit value + - and a booleand indicating whether the result is to be + considered signed. + + this method is a contextmanager to be used in a `with` + statement. At the end of the `with` block the result is + freed again, i.e. the register will not be reserved for the + result anymore. + + the default implementation calls `get_address` for values + which actually are in memory and moves that into a register. + + :param dst: the number of the register to put the result in, + or `None` if that does not matter. + :param long: True if the result is supposed to be 64 bit. None + if it does not matter. + :param signed: True if the result should be considered signed. + None if it does not matter. + :param force: if true, `dst` must be respected, otherwise this + is optional. + """ with self.ebpf.get_free_register(dst) as dst: with self.get_address(dst, long, signed) as (src, fmt): self.ebpf.append(Opcode.LD + Memory.fmt_to_opcode[fmt], @@ -436,16 +501,29 @@ class Expression: @contextmanager def get_address(self, dst, long, signed, force=False): + """get the address of the value of this expression + + this method returns the address of the result of this expression, + and its format letter. The default implementation uses + `calculate` to evaluate the expression and pushes the result onto + the stack. + """ with self.ebpf.get_stack(4 + 4 * long) as stack: with self.calculate(dst, long, signed) as (src, _, _): self.ebpf.append(Opcode.STX + Opcode.DW * long, 10, src, stack, 0) - self.ebpf.append(Opcode.MOV + Opcode.LONG + Opcode.REG, dst, 10, 0, 0) + self.ebpf.append(Opcode.MOV + Opcode.LONG + Opcode.REG, + dst, 10, 0, 0) self.ebpf.append(Opcode.ADD + Opcode.LONG, dst, 0, 0, stack) - yield + yield dst, "Q" if long else "I" + + def contains(self, no): + """return whether this expression contains the register `no`""" + return False class Binary(Expression): + """represent all binary expressions""" def __init__(self, ebpf, left, right, operator): self.ebpf = ebpf self.left = left @@ -532,6 +610,10 @@ class Negate(Expression): class Sum(Binary): + """represent the sum of one register and a constant value + + this is used to optimize memory addressing code. + """ def __init__(self, ebpf, left, right): super().__init__(ebpf, left, right, Opcode.ADD) @@ -551,6 +633,7 @@ class Sum(Binary): class AndExpression(SimpleComparison, Binary): + """The & operator may also be used as a comparison""" def __init__(self, ebpf, left, right): Binary.__init__(self, ebpf, left, right, Opcode.AND) SimpleComparison.__init__(self, ebpf, left, right, Opcode.JSET) @@ -580,15 +663,18 @@ class AndExpression(SimpleComparison, Binary): len(self.ebpf.opcodes) - self.else_origin + 1, imm) def Else(self): - if self.ebpf.opcodes[self.origin][0] == Opcode.JMP: + op, dst, src, off, imm = self.ebpf.opcodes[self.origin] + if op is Opcode.JMP: self.invert = self.origin else: - self.retarget_one() + self.ebpf.opcodes[self.origin] = \ + Instruction(op, dst, src, off+1, imm) self.else_origin = len(self.ebpf.opcodes) self.ebpf.opcodes.append(None) return self class Register(Expression): + """represent one EBPF register""" offset = 0 def __init__(self, no, ebpf, long, signed): @@ -613,8 +699,6 @@ class Register(Expression): @contextmanager def calculate(self, dst, long, signed, force=False): - #if signed is not None and signed != self.signed: - # raise AssembleError("cannot compile") if self.no not in self.ebpf.owners: raise AssembleError("register has no value") if dst != self.no and force: @@ -629,6 +713,7 @@ class Register(Expression): class IAdd: + """represent an in-place addition""" def __init__(self, value): self.value = value @@ -678,6 +763,12 @@ class Memory(Expression): class MemoryDesc: + """A base class used by descriptors for memory + + All memory access is relative to a base register. This is + defined by the member variable `base_register` in deriving + classes. + """ def __get__(self, instance, owner): if instance is None: return self @@ -710,6 +801,7 @@ class MemoryDesc: class LocalVar(MemoryDesc): + """variables on the stack""" base_register = 10 def __init__(self, fmt='I'): @@ -771,15 +863,18 @@ class MemoryMap: return Memory(self.ebpf, self.fmt, addr, self.signed, self.long) -class Map: +class Map(ABC): + """The base class for all maps""" + @abstractmethod def init(self, ebpf): - pass + """create the map and initialize its values""" def load(self, ebpf): - pass + """called after the program has been loaded""" class PseudoFd(Expression): + """represent a file descriptor to a map""" def __init__(self, ebpf, fd): self.ebpf = ebpf self.fd = fd @@ -793,6 +888,7 @@ class PseudoFd(Expression): class ktime(Expression): + """a function that returns the current ktime in ns""" def __init__(self, ebpf): self.ebpf = ebpf @@ -880,6 +976,11 @@ class TemporaryDesc(RegisterDesc): class EBPF: + """The base class for all EBPF programs + + This class may even be instantiated directly, in which case you + can just issue the program before the it is loaded. + """ stack = 0 name = None license = None @@ -920,12 +1021,13 @@ class EBPF: v.init(self) def program(self): - pass + """overwrite this method with your program while subclassing""" def append(self, opcode, dst, src, off, imm): self.opcodes.append(Instruction(opcode, dst, src, off, imm)) def assemble(self): + """return the assembled program""" self.program() return b"".join( pack("<BBHI", i.opcode.value, i.dst | i.src << 4, @@ -933,6 +1035,7 @@ class EBPF: for i in self.opcodes) def load(self, log_level=0, log_size=10 * 4096): + """load the program into the kernel""" ret = bpf.prog_load(self.prog_type, self.assemble(), self.license, log_level, log_size, self.kern_version, name=self.name) @@ -945,10 +1048,12 @@ class EBPF: return ret def jumpIf(self, comp): + """jump if `comp` is true to a later defined `target`""" comp.compare(False) return comp def jump(self): + """unconditionally jump to a later defined `target`""" comp = SimpleComparison(self, None, 0, Opcode.JMP) comp.origin = len(self.opcodes) comp.dst = 0 @@ -958,15 +1063,18 @@ class EBPF: return comp def get_fd(self, fd): + """return the file descriptor `fd` of a map""" return PseudoFd(self, fd) def call(self, no): + """call the kernel function `no` from enum `FuncId`""" assert isinstance(no, FuncId) self.append(Opcode.CALL, 0, 0, 0, no.value) self.owners.add(0) self.owners -= set(range(1, 6)) def exit(self, no=None): + """Exit the program with return value `no`""" if no is not None: self.r0 = no.value self.append(Opcode.EXIT, 0, 0, 0, 0) diff --git a/ebpfcat/ebpf.rst b/ebpfcat/ebpf.rst index d1dab1cc2985633d5fd4f9945ddc963dabe401a0..0548159875f5521a9e02ff881a81c5dd2dbdfad5 100644 --- a/ebpfcat/ebpf.rst +++ b/ebpfcat/ebpf.rst @@ -98,9 +98,9 @@ generate code that the static code checker understands, like so:: self.some_variable = p.pH[22] # read word at position 22 in this code, the variable ``p`` returned by the ``with`` statement also -allows to access the content of the packet. There are eight access modes +allows to access the content of the packet. There are six access modes to access different sizes in the packet, whose naming follows the Python -``struct`` module, indicated by the letters "BHIQbhiq". +``struct`` module, indicated by the letters "BHIQiq". Knowing this, we can modify the above example code to only count IP packets:: @@ -112,3 +112,48 @@ packets:: with p.pH[12] == 8: self.count += 1 self.exit(XDPExitCode.PASS) + +Maps +---- + +Maps are used to communicate to the outside world. They look like instance +variables. They may be used from within the EBPF program, and once it is +loaded also from everywhere else. There are two flavors: `hashmap.HashMap` +and `arraymap.ArrayMap`. They have different use cases: + +Hash Maps +~~~~~~~~~ + +all hash map variables have a fixed size of 8 bytes. Accessing them is +rather slow, but is done with proper locking: concurrent access is possible. +When accessing them from user space, they are read from the kernel each time +anew. They are declared as follows:: + + class MyProgram(EBPF): + hash_map = HashMap() + a_variable = hash_map.globalVar() + +They are used as normal variables, like in `self.a_variable = 5`, both +in EBPF and from user space once loaded. + +Array Maps +~~~~~~~~~~ + +from an EBPF program's perspective, all EPBF programs are accessing the same +variables at the same time. So concurrent access may lead to problems. An +exception is the in-place addition operator `+=`, which works under a lock, +but only if the variable is of 4 or 8 bytes size. + +Otherwise variables may be declared in all sizes. Additionally, one can mark +which variables are supposed to be written from user space to the EBPF, +as opposed to just being read. The declaration is like so:: + + class MyProgram(EBPF): + array_map = ArrayMap() + a_read_variable = array_map("B") # one byte read-only variable + a_write_variable = array_map("i", write=True) # a read-write integer + +the array map has methods to access the variables: + +.. autoclass:: ebpfcat.arraymap.ArrayMapAccess + :members: diff --git a/ebpfcat/ebpf_test.py b/ebpfcat/ebpf_test.py index 1ad296066f5985521a40bb1e528fe43941b2d421..a15f8d0c37f9694912b0447bc5d2fd3073e45c46 100644 --- a/ebpfcat/ebpf_test.py +++ b/ebpfcat/ebpf_test.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from unittest import TestCase, main from . import ebpf diff --git a/ebpfcat/ebpfcat.py b/ebpfcat/ebpfcat.py index bebc790f147f5b41985c64946758c79690d448f0..488fe2bee0ec9ef745dd429621feb2fd1d7c0019 100644 --- a/ebpfcat/ebpfcat.py +++ b/ebpfcat/ebpfcat.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + """The high-level API for EtherCAT loops""" from asyncio import ensure_future, gather, sleep from struct import pack, unpack, calcsize, pack_into, unpack_from diff --git a/ebpfcat/ethercat.py b/ebpfcat/ethercat.py index c9d2956c397c6a701d083eda10d67800eb4da8cb..6677da0ec405e4951b62cbbeca2295778b90c273 100644 --- a/ebpfcat/ethercat.py +++ b/ebpfcat/ethercat.py @@ -1,4 +1,28 @@ -"""Low-level access to EtherCAT +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# +# This program may contain technology patented by Beckhoff GmbH. +# The author is not affiliated with this company, nor does he own a +# license. As a private enthusiast he also does not need one, other +# users may want to consult a lawyer before using this program. + +"""\ +Low-level access to EtherCAT +============================ this modules contains the code to actually talk to EtherCAT terminals. """ diff --git a/ebpfcat/ethercat.rst b/ebpfcat/ethercat.rst index 1b041195facf3386d7142b58343f1ad24244515f..004991e698bad161825e9f0884228c35b4efef7f 100644 --- a/ebpfcat/ethercat.rst +++ b/ebpfcat/ethercat.rst @@ -94,6 +94,9 @@ The communication with the terminals can happen in three different ways: frequency exceeds 10 kHz. +Reference Documentation +----------------------- + .. automodule:: ebpfcat.devices :members: diff --git a/ebpfcat/ethercat_test.py b/ebpfcat/ethercat_test.py index 43b2e802715e2ae128c09daf09a2c5cc408eaecc..9921fd565ad7749e668f7b8ec64d400c16f7bbdd 100644 --- a/ebpfcat/ethercat_test.py +++ b/ebpfcat/ethercat_test.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from asyncio import CancelledError, Future, get_event_loop, sleep, gather from unittest import TestCase, main diff --git a/ebpfcat/hashmap.py b/ebpfcat/hashmap.py index 963afdc149eb265a09f46fc0c81142fdc8a0220f..63c9d545291735b02af8c620785b9ac76f123cfa 100644 --- a/ebpfcat/hashmap.py +++ b/ebpfcat/hashmap.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from contextlib import contextmanager from struct import pack, unpack, unpack diff --git a/ebpfcat/serial.py b/ebpfcat/serial.py index 98b9ef573909af2e2f0d62b0566cea37a5399c57..408c7567f07907427bdcee16ecc3128f9887ff6f 100644 --- a/ebpfcat/serial.py +++ b/ebpfcat/serial.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from asyncio import ensure_future, Event, Queue, StreamReader, gather from .ebpfcat import Device, TerminalVar diff --git a/ebpfcat/terminals.py b/ebpfcat/terminals.py index c46f4d4e1d6e6ad7f7fa63166e8b293fe2c5323e..bb709a32a4f41c22f0a35d263f895a92cbd6ca12 100644 --- a/ebpfcat/terminals.py +++ b/ebpfcat/terminals.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from .ebpfcat import EBPFTerminal, PacketDesc, Struct diff --git a/ebpfcat/testsystem.py b/ebpfcat/testsystem.py index 2af2a77346fc2789dfad1139cb93054ec18e018b..be7aab353c242c9490ca4e78112f6bf93f633da4 100644 --- a/ebpfcat/testsystem.py +++ b/ebpfcat/testsystem.py @@ -1,3 +1,20 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from asyncio import gather, sleep, ensure_future from .terminals import EL3164, EL4104, EK1814 from .devices import AnalogInput, AnalogOutput, DigitalInput, DigitalOutput diff --git a/ebpfcat/xdp.py b/ebpfcat/xdp.py index 522b376330bd237ef9ce4457b8944dfe6d798b1a..4a1526febb69a670a9e95a994283819889410cba 100644 --- a/ebpfcat/xdp.py +++ b/ebpfcat/xdp.py @@ -1,3 +1,21 @@ +# ebpfcat, A Python-based EBPF generator and EtherCAT master +# Copyright (C) 2021 Martin Teichmann <martin.teichmann@gmail.com> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +"""support for XDP programs""" from asyncio import DatagramProtocol, Future, get_event_loop from enum import Enum from contextlib import contextmanager @@ -18,6 +36,8 @@ class XDPExitCode(Enum): class XDRFD(DatagramProtocol): + """just implement enough of the NETLINK protocol to attach programs""" + def __init__(self, ifindex, fd, future): self.ifindex = ifindex self.fd = fd @@ -70,6 +90,7 @@ class XDRFD(DatagramProtocol): class PacketArray: + """access a packet like a Python array""" def __init__(self, ebpf, no, memory): self.ebpf = ebpf self.no = no @@ -123,12 +144,14 @@ class PacketSize: class XDP(EBPF): + """the base class for XDP programs""" def __init__(self, **kwargs): super().__init__(prog_type=ProgType.XDP, **kwargs) self.packetSize = PacketSize(self) async def attach(self, network): + """attach this program to a `network`""" ifindex = if_nametoindex(network) fd, _ = self.load(log_level=1) future = Future()