pax_global_header00006660000000000000000000000064122316354520014515gustar00rootroot0000000000000052 comment=a8e813848a7b1ef23e3664d3fcc7519259b605e9 gns3-legacy-GNS3-0.8.6/000077500000000000000000000000001223163545200143545ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/.gitignore000066400000000000000000000004721223163545200163470ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject .settings gns3-legacy-GNS3-0.8.6/.hgignore000077500000000000000000000001711223163545200161610ustar00rootroot00000000000000syntax: glob *~ .settings/* *.pyc *.swp .DS_Store gns3.conf build/* dist/* *.orig *.log syntax: regexp (.*/)?\#[^/]*\#$ gns3-legacy-GNS3-0.8.6/AUTHORS000077500000000000000000000002461223163545200154310ustar00rootroot00000000000000Jeremy Grossmann Xavier Alt Aurelien Levesque David Ruiz Romain Lamaison Alexey Eromenko "Technologov" Benjamin Marsili Claire Goudjil Philippe Baum Jeremy Menetrier gns3-legacy-GNS3-0.8.6/CHANGELOG000077500000000000000000000701731223163545200156010ustar00rootroot00000000000000#################### # GNS3 - CHANGELOG # #################### === v0.8.6 22.10.2013 === * Windows version now supports VirtualBox 4.3 and still works with 4.2.x * Fixed the broken snapshot feature. * Host devices don't automatically add tap interfaces in the generic Ethernet NIO list anymore. * Auto open for instructions files when opening the topology via the command line, a file explorer or a drag & drop on the workspace. * Modified the default Etherswitch configuration (renamed some macros + added vtp file nvram:vlan.dat) * Fixed small bugs with "idlepc get" command and Ethernet switch auto port allocation. * Added wpcap.dll to the Windows standalone versions. * Dynamips 0.2.10 is now the default on OSX. * New Dutch translation & Italian translation updated. === v0.8.5 09.09.2013 === * Dynamips 0.2.10 is included in our Windows all-in-one package and OSX DMG, this version allows Crypto keys to be saved and it fixes a bug that prevented startup-configs to be loaded by c3745 IOS. Hooray! * New symbols for ASA, Qemu guest and Vbox guest. * Fixed a major issue that prevented to use the auto idle-pc calculation feature. * Implemented the Restore snapshot feature following Rednectar's suggestions (http://forum.gns3.net/post20664.html#p20664) * Snapshots are now stored in a separate directory inside project directory. * Increased lowest and max zoom values. * Updated Italian translation. * Added Xshell 4 command lines in terminal settings. * Fixed issue with contextual device menu. * Fixed bug when launching VPCS and there was a space in the project path. * Option 'Use hypervisor manager' changed to 'Bind to external hypervisor(s)' (logic is inverted) in IOS images and hypervisors dialog. * Checks: if VPCS is installed and if Dynamips is marked as executable. * Added instructions entry to Help menu. * Automatic opening of instructions file when loading a project. * Fixed Teraterm, SecureCRT and Konsole terminal command lines. * Added "-vga none" option to ASA Pre-configuration * Updated the SecureCRT script to automatically reconnect if disconnected. * Fixed a bug with load-balancing on multiple external hypervisors. * Fixed issue when binding Qemuwrapper to a PC's real IP address. * Various other small bug fixes. === v0.8.4 05.07.2013 === * Many GUI improvements. * New hub device. * New Idlemax and Idlesleep settings (advanced manipulation of IDLE PC). * IOS image and settings test button. * New Tool menu to start external scripts/tools. * Drag & drop of multiple devices when pressing SHIFT. * Temporary projects are created by default. * VirtualBox interface numbering starts at 0 (e.g. e0 = VirtualBox interface 1 = eth0 on Linux). * Support for 36 network cards in VirtualBox (using ICH9 chipset) * New option to save traffic capture in project directories. * Experimental auto IDLE PC calculation feature (requires Dynamips > 0.2.8-RC5, included in Windows all-in-one and OSX DMG). * Added entries to have Dynamips/Qemu/VirtualBox hypervisors bind/listen to all available IP/host addresses (optional). * AW+ router support by Allied Telesis from New Zealand (educational version of their OS to be released). * QinQ fixed in Dynamips 0.2.8 RC6. * Removed the "Save IOS configs option". Always save IOS configs. * Qemu FLASH files are automatically saved in a directory named 'qemu-flash-drives' (in the project directory). * VPCS is included in DMG package on Mac OS X. * New tips/ads dialog to promote GNS3 products/videos/tutorials (totally optional and can be deactivated). * Winpcap 4.1.3 included in Windows all-on-one package (compatible with Windows 8). * Dynamips 0.2.8-community is now default on Windows. * Qemu 0.11.0 integrated to the DMG for Mac OS X (used by default). * Qemu 0.14.1 integrated to the DMG for Mac OS X. * Qemu monitor (to pause/resume) and user backend options (experimental and only with recent versions of Qemu). * Support for multiple flavors of Qemu: sparc, arm, i386, x86_64 * SuperPutty command line support. * SuperPutty in all-in-one on Windows (optional). * Dash is now accepted for hostnames. * Fixed issues with ports reported as already in use. * Gray out VLAN box when selecting dot1q port type in Ethernet Switch. * Default delay for console adjusted from 0.5 to 1 second. * Default base console is now 2101 instead of 2001 * Changed Dynamips default base UDP from 10000 to 10001 * Mouse wheel scrolls the scene by default + options to deactivate the wheel or use it for zooming * Patching for Dynagen (see http://forum.gns3.net/topic5659.html for details) * Wrappers improvements all over the place. * New baseconfig.txt * ASA pre-configurations. * Introduced human readable byte sizes for stats in tooltips (what you see when hovering a device). * Fixed the 'unbase' feature (but the whole idea behind is flawed). * Reversed steps 1 & 2 of the Setup Wizard. * The EtherSwitch router is grayed out in the node dock if no c3700 IOS image is configured. * Set the 'Reserve first NIC for VirtualBox NAT to host OS' by default in VirtualBox preferences. * Added 'virtio-net-pci' to the list of available NICs for Qemu based devices. * Changed capture filenames to include the source and destination interfaces. * The 'layouts' directory is now created in GNS3 install directory (used by SuperPutty). * Fix: Allow '-' character to be used in VirtualBox hostnames. * File securecrt.vbs has been modified to include tranzitwww changes -> post18869.html#p18869 * Clean VirtualBox VMs from UDP tunnels when stopping them. * Instructions entry for tools menu. * Fixed bug with VirtualBox/Qemu devices while importing a topology: duplicated UDP tunnels. * Use Qemu guest identifier names to set Qemu guest device hostnames. * Fixed bug when modifying an Ethernet switch configuration after loading a topology. * Possibility to press shift to force the display of link types when adding a link with option 'always use manual mode when adding links' activated. * Better default directory when using file browsers (ellipse buttons in preferences). * Fixed bug when a device was named 'LAN'. * Option to activate/deactivate the inclusion of a screenshot when saving a project. The screenshot is named the same as the project file (e.g. topology.net = topology.png). * Possibility to open a project by opening its corresponding screenshot. * Added a warning message when an c7200p image is added in the IOS images and hypervisors window. * Check for unsaved image settings in Qemu Preferences. * 512 MB is the default RAM for JunOS * Added default VPCS NIO UDPs for "Host" device. * Fixed major bug with UDP port allocations. === v0.8.3.1 20.10.2012 === * Vboxwrapper recompilation to run with VirtualBox 4.2 * Support for access to the GNS3 VirtualBox VM name from inside a VM: VBoxControl guestproperty get NameInGNS3 * Minor fixes === v0.8.3 12.12.2012 === New features: * Option to freely use the first VBox interface inside VMs (i.e. eth0 on Linux). * New base configuration (startup-config) for devices with NM-16ESW (named baseconfig_sw.txt). * Console and headless mode support for VirtualBox devices. * Embedded console/terminal server to access VirtualBox VM consoles using Telnet. * Support for drag & drop of topology files inside GNS3. * Double quote support for Qemu options and ASA kernel/initrd command lines. * Import & export for GNS3 configuration file (gns3.ini). * Global TCP port tracker to allocate ports and avoid conflicts (console + AUX ports for IOS routers and console ports for Qemu-like/VirtualBox devices are tracked) * Scripts for using consoles with VBox VMs (Windows only). * Backup nvram export when Dynamips has crashed. * New command line option for patched Putty on Windows (for details: http://forum.gns3.net/topic4859-20.html). * Experimental live pipe capture (Windows only). * Option (activated by default) to use the VirtualBox VM names to name VirtualBox devices in GNS3. * Complete IPv6 support (with correct functions). * Support for binding on specific addresses when loading a topology * Option to track opened node consoles in order to close them when the node gets deleted. * New Dynamips 0.2.8-RC4 community (full IPv6 support), only included in Windows all-in-one package for now. Fixes and other improvements: * Fixed issue when saving as a project. * Workaround: sparse memory feature is not activated on c2600 and c1700 platforms because Dynamips can freeze after IOS restarts (Windows only). * Added Idle PC help button to gives some hints how to get good idle pc values. * Prevent tail processes staying in memory after stopping captures. * Fixed/improved some console command lines (SecureCRT, TeraTerm, Putty) * Fixed issue when connecting recent Qemu (new -net syntax) to other non-Qemu devices. * Fixed vboxwrapper loading issue for DMG version on OSX. * Fixed rpcap interface name parsing on Windows. * Improved securecrt.vbs to "press" a enter into the device console to show the prompt. * Modified default IOS startup-config (baseconfig.txt). * Handle connection lost during Idle pc calculation. * Warn users if their working directories are not accessible and/or writable. * Allow dash and brackets for device hostnames. * Option to clear stopped captures from the captures dock. * Italian and Chinese translations updated. * Fixed bug that prevented loading topologies with non-existing IOS paths. * Some minor fixes for recent files menu (add saved file paths, order, non existing path entries are removed etc.) * New key shortcuts for object rotation (notes, ellipses, rectangles). ALT and + (or P) / ALT and - (or M). * Removed default shell execution for console programs. * Default delay between each device start when starting all devices is now 1 second. * Auto-increment base AUX port for external hypervisors. * MessageBox "Object moved to a background layer ..." is now displayed only once by execution. * Fixed issue when starting a capture on a node without any links (!) * Fixed problem with version comparison in "Check for Update" feature. * Fixed multi-window opening issue with snapshot dialog. * Added recent files button for the project window. * Press escape to stop adding a link. * Detect old GNS3 configuration and ask user to clear it. * Fixed minor issues with the Ethernet Switch. * Prevent capture for Pemu and decorative nodes. * Show VirtualBox version in ver command. * Support for more characters (e.g. #) in annotations. * New wrappers installation directory on Linux. * Prevent to use the same VBox VM multiple times. * Fixed minor issue with path normalization on Windows. * Time reference for debugs, auto saving messages and logged exceptions. * Log file dynagen_exception.log has been renamed import_exception.log (date + GNS3 version is added into the file). * Command 'show ports' to display all port allocations. * NVRAM configuration extractor utility for Windows. * Smarter handling of errors when starting/stopping/suspending all nodes. * Do not show special cursors when a rectangle or ellipse is on the background layer. * Qemuwrapper base UDP has been changed from 20000 to 40000. * Qemuwrapper base console has been changed from 3000 to 3001. * VBoxwrapper base console has been changed from 3900 to 3501. === v0.8.2 13.03.2012 === * The issue with Qemu VMs that were stuck on “Booting from Hard Disk” message when using Qemu Manager on Linux has been fixed. * Vboxwrapper can be started on a remote host and VirtualBox VMs locally controlled in GNS3. * Loopback Manager included in Windows all-in-one now work on Win7/Vista. * Start/pause/stop icons are colored as before BETA2. * Checks for the correct version of Qemuwrapper and VBoxwrapper. * New SecureCRT command line for OSX in terminal settings preferences. * New option to set a delay between console when consoling to all devices. * Qemu <-> VBox linking has been fixed. * FlexiNetwork VirtualBox feature has been patched. * Italian translation has been updated. * Give a chance to hypervisor/wrapper processes to stop before they get killed. * An issue when trying to choose the file in the Startup-Config dialog has been fixed. * Additional check to avoid false positives when detecting compressed IOS. * Symbol import/export issue for 'Cloud' nodes has been fixed. * Windows interface names with non-ascii characters are now supported. * Unicode support improvements. === v0.8.2 BETA2 31.01.2012 === * IOS images can be directly uncompressed by GNS3. * Open recent files menu. * “Start all captures” and “stop all captures” options for Captures Dock. * New icons with fancy hover effects (start, stop, pause, ellipse and rectangle). * Farsi, Czech, Japanese and Italian translations updated. * GNS3 settings file (gns3.ini) can be put in the same folder as gns3.exe (Windows only). This allows GNS3 to be standalone on USB stick for instance. * New host device: a cloud with the ‘computer’ symbol and configured with all host interfaces. * Qemu mac address generator has been fixed. * Access to VirtualBox Manager from the GUI. * Soft link gns3 -> gns3.pyw has been added (Unix/Linux only). * Changed default paths for wrappers on OSX and UNIX/Linux. * Wrappers are now GPL licensed. * PEMU binary has been removed from our sources (it is still available on our download page). * Capture option is now available from the “Device” contextual menu. * Link actions are available from the summary topology window pane. * Show rpcap interface names in a tooltip when hovering an entry in the interface menu (Windows only). * Qemuwrapper support for the new Qemu networking syntax. * Option to send Qemu and Qemu-img paths to an external Qemuwrapper. * Possibility to use stylesheets from the view menu, for now only the ‘Energy saving’ theme is available. * Tooltip for clouds. * User guidance: status bar messages. * Splash screen at startup. * Small improvements and bug fixes all over the place. === v0.8.2 BETA 12.12.2011 === * Official integration of VirtualBox Edition features. * Auto-update checker / notifier (by default disabled on Linux, BSD, enabled on Mac and Windows). * Qemu got a predictable MAC address pseudo-random number generator (brezular’s case). * VirtualBox interface numbering match VBox VM vNics numbering – VBox ethernet adapter now starts counting with “e2″, instead of “e0″ to remove confusion with VBox GUI. (this change may break existing topologies, so people will need to manually edit them. Making automatic converter is too problematic.) * Windows version is now pre-compiled. (like in v0.7.x), 64-bit version is introduced. * Windows all-in-one package includes Wireshark. * Windows all-in-one package allows you to choose between 32-bit and 64-bit versions. * Live Capture is now enabled by default on all platforms. * Fixed screenshots (enabled Qt 4.7.x library in GNS3 + shipped Qt 4.7.4 on Windows) * Dynagen: Fixed standalone text-mode / CLI operation. * Fixed QemuManager, which failed to start qemuwrapper.py (Windows XP hosts only). * Main: should start from relative paths now. * GUI: Hide display window errors fixed. * GUI: got new ‘Device’ menu mirroring contextual menu (right-click on a device). * GNS3 version is saved in topology files. * Many small GUI improvements all over the place. (RedNectar’s wishes). * Improvements for setup Wizard and first time users. * Reverted GUI limit to hide Linux options (VDE, NIO_Linux, KVM) due to use case: Windows GUI + Linux server. * Experimental: layers < 0 are now considered background layers. Only annotations, pictures and shaped items can be on a background layer. Once on a background layer, an item cannot be selected and moved anymore. However they still can be individually selected why right-click. === v0.8.0 VirtualBox Edition === Major Improvements: * VirtualBox support (v4.1 required) * Wireshark Live Traffic Capture * Basic IPv6 enablement * Basic Netbook enablement * Architecture: On Windows, GNS3 now runs from source code * Architecture: PEMU is now moved from GNS3 core to a separate component. (PEMU will be part of Windows "All-in-One" installer) * Architecture: Resolved conflict with Debian's built-in GNS3 package. On Linux, setup is no longer needed. * Dynagen Console got a massive rewrite / cleanup * Russian translation got a major update Other Changes and Fixes: * Windows Setup was rewritten from scratch * Changed Default Qemu Ethernet Controller from "e1000" to "Realtek 8139" for Windows XP compatibility. * GUI: Swapped AUX & Console icons - more convenient to have "console" button near "start" button. * Disallowed to hot-add new links to running Qemu. * Fixed VM states coherency between Dynagen's Console and GNS3. * Several fixes for using GNS3 with external qemu/vboxwrappers (multi-host distributed topologies) * GUI: Disabled Linux features on Windows hosts. (KVM, NIO_VDE, NIO_UNIX and NIO Linux Ethernet) * GUI: Disallowed connecting devices with incorrect link types, such as Frame-Relay switches with Ethernet cable. * Fixed the problem of filled WIC slots in Routers (0.7.4 Regression; UldisD's case) * Fixed SecureCRT (SARS' case, minor bug; Windows hosts only) * Terminal Emulator Settings: sorted & hide non-platform-related options * Fixed AUX port error messages * Fixed translation file generator * Dynagen Console: 'hypervisors', 'ver' and 'versions' commands are now merged into just 'ver'. * Dynagen Console: 'exit' and 'disconnect' commands are now merged into 'clear topology'. * Dynagen Console: Removed non-working commands: 'shell', 'cpuinfo', 'py', 'conf', 'confreg', 'hypervisor', 'end', 'send' * For full list of changes, see "modified.txt" VirtualBox / vboxwrapper backend features: * FlexiNetwork: Link hot-add/hot-remove * Traffic Capture * Suspend/Resume VMs * Instant reboot * "automatic" NIC type (just mirrors existing NIC type) * Network statistics (Bytes Transmitted / Bytes Received) * View of Guest OS IP addresses, by retrieving data from Virtual machine (if GuestAdditions installed) * GuestControl execution; send commands from Dynagen console * Double-click on VBOX VM brings it's display window to front. * Modular design === v0.7.4 11.04.2011 === * AUX ports integrated in the GUI * Greek translation * Hypervisor allocation per IOS type * Improvements on Ethernet Switch (dynamic remapping of VLAN or type) * Adaptations to support Dynamips 0.2.8 RC3 community * Integration of a loopback manager for Windows === v0.7.3 12.12.2010 === * Easily change the symbol of one or several nodes (Select a node, then right click -> Change symbol). * A docked window to see on what device interface captures are running (View -> Docks -> Captures). You can stop capturing or start Wireshark using this view. * Only the necessary files (nvram, flash, disks etc.) are copied or kept when creating projects and snapshots. * Preventing unsaved interface labels to show up after loading a topology. This can be reset using the "show interface labels" button. * Improvements for ATM and Frame Relay switches: proper naming, dynamic mapping support and it is not needed to remove a link to change its DLCI/VC mapping. * PCAP capture support for Qemu based devices (Qemu host, JunOS ASA, PIX, IDS). This option cannot be used after the selected device is started. * Fixed many issues with the snapshot feature. Now it should work as expected. * New node type: EtherSwitch router. This is a c3700 router with a Etherswitch NM-16ESW loaded. * Better consistency between buttons and menus. Many items have been renamed, toolbar buttons accessible from the menu etc. * Possibility to configure the AUX port. Only works for c7200 routers (Preferences -> Dynamips -> Base AUX port). * Changed standard naming convention for project and snapshots. Topology file is named topology.net, working directory: working and configurations directory: configs. * Duplicate option for annotations, ellipses and rectangles (Select an item, right click -> Duplicate). * Horizontal + vertical alignment options (Select nodes, right click -> Align horizontally/vertically). * Possibility to have multiple images for Qemu hosts, JunOS, PIX, ASA and IDS and to configure the number of interfaces on each devices. * Autosave feature to save your topology every x secondes (Preferences -> General). * A default base config (with hostname, exec-timeout commands etc.) is automatically loaded when creating a new IOS based router. The path to this default config can be changed in "IOS images and hypervisors" dialog. * A more understandable MAC address table for Ethernet switches (right click on a switch -> Show MAC address table). * Qemuwrapper improvements like cleaning old FLASH/SWAP files when creating a new device with a same hostname. * Multi Qemu based devices topologies now work using base images on Windows. Patched in Qemu 0.11.0 binary included in the all-in-one package (thanks tranzitwww!!!). * Support for unbasing Qemu images when creating or saving as a project. This means no dependencies with your base images thus you can easily distribute your project. * Option to replace unknown references (GUID: \device\npf_{802b5272-cd1b-431c-8cb5-f57ba76145c6}) to network interfaces on Windows when loading a NET file. * Option to replace unknown IOS image when loading a NET file. * Scroll the scene with the mouse middle click or right and left clicks a the same time. This behavior is to be changed in a future release. * Possibility to specify a directory where GNS3 settings file (gns3.ini) is located with the parameter --config-dir on the command line. * Romanian translation (thanks to tranzitwww). * Double click on a running node opens a console. * Reload all devices option. * French and Italian translation updates. === v0.7.2 16.06.2010 === * Lot of small fixes (relative paths, link removal, .net loading, Ethernet switch connection to a Cloud etc.) * Qemuwrapper: random MAC address for devices * NPE-G2 option for c7200 routers (need a specific and uncompressed IOS image and C7200-IO-2FE, C7200-IO-GE-E, PA-2FE-TX and PA-GE are unlikely to work) * Simulated switch daisy chaining support * Improved directory selection for new projects * New translations: Bulgarian, Italian and Ukrainian * Frame Relay capture option for all serial links * Dialog to display the MAC address table of a simulated Ethernet switch The following features will work only with Dynamips version > 0.2.8 RC2: * OIR (Online Insertion and Removal) for c3660 and c3745 (only NM-4T). * JIT sharing support (saves memory). * C7200-JC-PA Jacket Card support. Allow the use of a slot 7 for c7200 routers with NPE-G2. * QinQ support for simulated Ethernet switches. * Interfaces statistics (Packets in, Packets out, Bytes in, Bytes out). Displayed in node tooltips. === v0.7.1 29.04.2010 === * Qemuwrapper (option to listen on a IP/host and port). * Basic support for external hypervisors. * Some improvement for projects under GNS3 (still work to do). * Many small bugs fixes (graphical, cloud connection etc.) === v0.7 27.02.2010 === * Support & debugging on Windows 7. * Qemuwrapper improvements & Windows compatibility. * Integration of Cisco IDS/IPS, including a new symbol. * Qemu 0.11.0 patched and Putty have been added in the Windows all-in-one package. * An option to show the z coordinate of any object on the scene (View -> Show layers). * Interface labels follow their moving parent nodes. * Modified interface labels are saved in .net files. * Option to slow start nodes (wait x seconds between each start). * Links connected to Qemu based nodes are now removable (nodes have to be shutdown to do so). * Possibility to set an hypervisor for Ethernet switches, ATM switches, ATM bridges and Frame Relay switches. * New symbols for voice labs (Call manager, SIP server, IP phone, voice router, voice access server and PBX). * New dialog window to browse and change a router startup-config. * Undo/redo of actions is now supported. * Qemu & qemu-img paths are saved in .net files if needed. * Slight improvements for the snapshot system, including a new dialog window to manage it. * Wics description in tooptips. * Wics restoration from .net files. * Support of relative paths in .net files (if the base path is the same as the .net file). * Test button to validate you can launch Qemuwrapper, Qemu and qemu-img. * New translation in Czech (thanks to Ondrej Filip). * Lot of various small bug fixes and improvements. === v0.7RC1 23.12.2009 === * Qemu integration. * JunOS & ASA integration using Qemu. * An undo/redo framework (unstable). * Translations in Italian and Farsi. * Various bugs fixes and improvements. === v0.6.1 13.05.2009 === Improvements: * Copy an inserted image in the project's working directory and update its path in the .net file. * Prevent auto-generated interface notes to be recorded in the .net file. * Display an error msg box if a working directory can't be used by an hypervisor. * Check if a hostname has already been used when creating a new node. * Warn to use manual links when a user select a NM-16ESW module. * Check if GNS3 is running on a Windows 64 bits OS in order to choose the correct path to Putty. * Check IOS and working directories paths when creating new nodes and throw a warning to the user if something is wrong. * Button to edit project settings. Fixes: * Prevent notes to be deleted when typing the delete key while editing. * Prevent NM-16ESW modules to be removed from routers when using Ethernet/FastEthernet links. * Tooltips update when starting/stopping/suspending routers. * Bug with Qt 4.5 on selected filter when openning a project (getOpenFileName) * 99MB limit for pcmcia disks. * Unicode errors with TMP env variable on Windows. * AttributeError: value of `chassis' must be of type string. * Merge correct config paths when loading a .net create on a different platform. === v0.6 15.12.2008 === * Users can change the workspace size. * Possibility to draw rectangles and ellipses. * Feature to automatically create labels of interface names. * Multi-links drawing (no overlaps). * Snapshot feature. * Interface names are included in the Generic Ethernet NIO list on Windows. * New export to images (JPEG, PNG ...) that allows to export all the workspace (and not only what you see). * "Expand all" and "collapse all" features for the topology summary panel (contribution by beduev). * Annotations, rectangles and ellipses can be rotated. * On Windows, users can load an alternative gns3.ini by setting a path on command line, example: gns3.exe --configdir === v0.5 29.04.2008 === * Possibility to load .net files of other users (provided that there is a registered IOS image with the same model as the one used in the NET file). * New detailed tooltips for nodes. * A minimalist wizard raised when the configuration file is empty. * A button to insert a picture on the scene. * Decorative node support for creating network diagrams. * Ghostios is now supported on remote hypervisors. * A symbol manager with library support (a howto to create a symbol library will be released). * Z values can be changed for annotations and inserted pictures. * Automatic load-balancing on external hypervisors (choose multiple external hypervisors when recording an IOS image). * New option to bind the hypervisor manager with an address/name other than 'localhost': useful for labs which use local and remote hypervisors. === v0.4 21.03.2008 === * Dynamic mode (no design/emulation modes). * New .net import/export. * WICS support. * PEMU support. * GUI improvements. * ATM bridge. * Capture feature for links. * Annotation feature. * Project settings. * NULL NIO. * IDLE PC calculation from the GUI. * New languages. === v0.3 BETA === * Support of Ethernet, ATM and Frame-Relay switches * Included hub (Bridge of Dynamips) and cloud (external connections) devices * Added the Dynagen console (nearly all commands supported) * New GUI settings * Improved node configurator * Support of the Dynagen INI-like configuration file * Multi-language support (howto for translators soon) === v0.2 ALPHA === * Hypervisor load-balancing to address the per process limit problem (http://dynagen.org/tutorial.htm#_Toc165530762) * Configuration of multiple node. * Users can change hostnames. gns3-legacy-GNS3-0.8.6/COPYING000077500000000000000000000431031223163545200154130ustar00rootroot00000000000000 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. Copyright (C) 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. , 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. gns3-legacy-GNS3-0.8.6/GNS3.e4p000077500000000000000000000226141223163545200155100ustar00rootroot00000000000000 en Python Qt4 0.2 src/GNS3/Link/Ethernet.py src/GNS3/Link/__init__.py src/GNS3/Link/AbstractEdge.py src/GNS3/Link/Serial.py src/GNS3/NodeConfigurator.py src/GNS3/Main.py src/GNS3/Utils.py src/GNS3/Ui/Widget_nodesDock.py src/GNS3/Ui/Form_PreferencesDialog.py src/GNS3/Ui/ConfigurationPages/Form_HubPage.py src/GNS3/Ui/ConfigurationPages/Page_ETHSW.py src/GNS3/Ui/ConfigurationPages/Form_ETHSWPage.py src/GNS3/Ui/ConfigurationPages/Page_Hub.py src/GNS3/Ui/ConfigurationPages/Form_PreferencesGeneral.py src/GNS3/Ui/ConfigurationPages/Form_FRSWPage.py src/GNS3/Ui/ConfigurationPages/Page_PreferencesDynamips.py src/GNS3/Ui/ConfigurationPages/Form_ATMSWPage.py src/GNS3/Ui/ConfigurationPages/__init__.py src/GNS3/Ui/ConfigurationPages/Form_IOSRouterPage.py src/GNS3/Ui/ConfigurationPages/Page_FRSW.py src/GNS3/Ui/ConfigurationPages/Page_ATMSW.py src/GNS3/Ui/ConfigurationPages/Page_IOSRouter.py src/GNS3/Ui/ConfigurationPages/Page_PreferencesGeneral.py src/GNS3/Ui/ConfigurationPages/Form_CloudPage.py src/GNS3/Ui/ConfigurationPages/Form_PreferencesDynamips.py src/GNS3/Ui/ConfigurationPages/Page_Cloud.py src/GNS3/Ui/Form_NodeConfigurator.py src/GNS3/Ui/Widget_topologySummaryDock.py src/GNS3/Ui/Form_MainWindow.py src/GNS3/Ui/__init__.py src/GNS3/Ui/svg_resources_rc.py src/GNS3/Ui/Form_IOSDialog.py src/GNS3/Ui/Form_About.py src/GNS3/Langs/__init__.py src/GNS3/Langs/DynamicStrings.py src/GNS3/Application.py src/GNS3/__init__.py src/GNS3/IOSDialog.py src/GNS3/Topology.py src/GNS3/Telnet.py src/GNS3/HypervisorManager.py src/GNS3/Workspace.py src/GNS3/DynagenSub.py src/GNS3/Globals/__init__.py src/GNS3/Globals/Symbols.py src/GNS3/NETFile.py src/GNS3/Translations.py src/GNS3/External/__init__.py src/GNS3/External/PyCutExt.py src/GNS3/Console.py src/GNS3/Scene.py src/GNS3/Dynagen/dynagen.py src/GNS3/Dynagen/dynamips_lib.py src/GNS3/Dynagen/pemu_lib.py src/GNS3/Dynagen/console.py src/GNS3/Dynagen/confConsole.py src/GNS3/Dynagen/__init__.py src/GNS3/Dynagen/validate.py src/GNS3/Dynagen/configobj.py src/GNS3/Node/AbstractNode.py src/GNS3/Node/IOSRouter.py src/GNS3/Node/ATMSW.py src/GNS3/Node/__init__.py src/GNS3/Node/FRSW.py src/GNS3/Node/Cloud.py src/GNS3/Node/Hub.py src/GNS3/Node/ETHSW.py src/GNS3/Config/Config.py src/GNS3/Config/Preferences.py src/GNS3/Config/__init__.py src/GNS3/Config/Defaults.py src/GNS3/Config/Objects.py setup.py src/GNS3/Defaults/__init__.py src/GNS3/Defaults/AbstractDefaults.py src/GNS3/Defaults/IOSRouter3600Defaults.py src/GNS3/Defaults/IOSRouter1700Defaults.py src/GNS3/Node/IOSRouter3600.py src/GNS3/Defaults/IOSRouter3700Defaults.py src/GNS3/Defaults/IOSRouter2600Defaults.py src/GNS3/Defaults/IOSRouter7200Defaults.py src/GNS3/Node/IOSRouter1700.py src/GNS3/Node/IOSRouter2600.py src/GNS3/Node/IOSRouter3700.py src/GNS3/Node/IOSRouter7200.py src/GNS3/Node/IOSRouter2691.py src/GNS3/ProjectDialog.py src/GNS3/Ui/ConfigurationPages/Page_PreferencesCapture.py src/GNS3/Ui/ConfigurationPages/Form_PreferencesCapture.py src/GNS3/Ui/ConfigurationPages/Page_ATMBR.py src/GNS3/Ui/ConfigurationPages/Form_ATMBRPage.py src/GNS3/Node/ATMBR.py src/GNS3/Ui/ConfigurationPages/Form_FWPage.py src/GNS3/Ui/ConfigurationPages/Page_FW.py src/GNS3/PemuManager.py src/GNS3/Ui/ConfigurationPages/Page_PreferencesPemu.py src/GNS3/Ui/ConfigurationPages/Form_PreferencesPemu.py src/GNS3/Defaults/IOSRouterDefaults.py gns3 src/GNS3/Ui/ConfigurationPages/Page_DecorativeNode.py src/GNS3/Ui/ConfigurationPages/Form_DecorativeNodePage.py src/GNS3/Node/DecorativeNode.py src/GNS3/SymbolManager.py src/GNS3/Annotation.py src/GNS3/Pixmap.py src/GNS3/Ui/Form_Wizard.py src/GNS3/Wizard.py src/GNS3/StyleDialog.py src/GNS3/ShapeItem.py src/GNS3/Dynagen/simhost_lib.py src/GNS3/Node/SIMHOST.py src/GNS3/SimhostManager.py src/GNS3/Ui/ConfigurationPages/Page_SIMHOST.py src/GNS3/Ui/ConfigurationPages/Page_PreferencesSimhost.py src/GNS3/Ui/ConfigurationPages/Form_PreferencesSimhost.py src/GNS3/Ui/ConfigurationPages/Form_SIMHOSTPage.py src/GNS3/Unpack/unpack.py src/GNS3/Unpack/setup.py src/GNS3/Unpack/README.txt src/GNS3/UndoFramework.py src/GNS3/Node/AnyEmuDevice.py src/GNS3/Defaults/AnyEmuDefaults.py
src/GNS3/Ui/Form_NodeConfigurator.ui
src/GNS3/Ui/ConfigurationPages/Form_PreferencesDynamips.ui
src/GNS3/Ui/ConfigurationPages/Form_HubPage.ui
src/GNS3/Ui/ConfigurationPages/Form_ATMSWPage.ui
src/GNS3/Ui/ConfigurationPages/Form_CloudPage.ui
src/GNS3/Ui/ConfigurationPages/Form_IOSRouterPage.ui
src/GNS3/Ui/ConfigurationPages/Form_PreferencesGeneral.ui
src/GNS3/Ui/ConfigurationPages/Form_FRSWPage.ui
src/GNS3/Ui/ConfigurationPages/Form_ETHSWPage.ui
src/GNS3/Ui/Form_IOSDialog.ui
src/GNS3/Ui/Form_PreferencesDialog.ui
src/GNS3/Ui/Form_About.ui
src/GNS3/Ui/Form_MainWindow.ui
src/GNS3/Langs/Languages.qrc gns3 gns3 None ERIC4API ignoreFilePatterns outputFile //doc sourceExtensions
gns3-legacy-GNS3-0.8.6/README000077500000000000000000000053631223163545200152460ustar00rootroot00000000000000INSTALLATION * GNS3 dependencies: - Qt 4.5.1 (or higher) - Python 2.6 (or higher) - Sip 4.5 (or higher) - PyQt 4.5 (or higher) - Dynamips 0.2.8+ - VirtualBox 4.1.x - QEMU 1.1+ - PEMU - xdotool (on X11 UNIX-like platforms) - Wireshark * WINDOWS users: Download the GNS3 all-in-one for Windows on http://www.gns3.net This program will install a binary version of GNS3 as well as Dynamips, Qemu and WinPCAP. Recommendation: Dynamips has better performances on other platforms such as Linux or Mac OS X. * Linux users: On Linux you just need to install a package called python-qt4 (or similar). Instead, you can compile all the dependencies manually. You can run GNS3 from the source directory or install it using the following command: python setup.py install * MacOS X users: Method 1. 1. Install the Apple Devs Tools (on your Mac OS X DvD or download it on ADC account). Run and install XcodeTools.mpkg. 2. Download Python 2.6 for MacOS X on http://www.python.org/download/ and install it. 3. Download Qt librairies for Mac on http://qt.nokia.com/downloads and install it. 4. Download SIP on http://www.riverbankcomputing.com/software/sip/download, compile and install it: Open terminal and cd into the folder you downloaded the tar file and compile via the following commands (example for SIP 4.9.3): Macintosh:$ tar xvzf sip-4.9.3.tar.gz Macintosh:$ cd sip-4.9.3 Macintosh:sip-4.9.3$ python configure.py Macintosh:sip-4.9.3$ make Macintosh:sip-4.9.3$ make install 5. Download PyQt on http://www.riverbankcomputing.com/software/pyqt/download, compile and install it: Again, run the following commands to decompress and compile PyQt (example for PyQt 4.6.2): Macintosh:$ tar xvzf PyQt-mac-gpl-4.6.2.tar.gz Macintosh:$ cd PyQt-mac-gpl-4.6.2 Macintosh:PyQt-mac-gpl-4.6.2$ python configure.py Macintosh:PyQt-mac-gpl-4.6.2$ make Macintosh:PyQt-mac-gpl-4.6.2$ make install 6. Download and start GNS3. Method 2 (this can take a few hours as everything is compiled). 1. Download and install MacPorts http://guide.macports.org/#installing (you will need the Apple Devs Tools). 2. Open a terminal and install GNS3 dependencies. Macintosh:$ sudo port install python26 Macintosh:$ sudo port install py26-sip Macintosh:$ sudo port install py26-pyqt4 Macintosh:$ sudo port install qt4-mac Optionnal: to prevent MacPorts to install the last version of the dependencies (which may not work properly with GNS3), you can force a specified version with @. Example: Macintosh:$ sudo port install python26 Macintosh:$ sudo port install py26-sip @4.9.3_0 Macintosh:$ sudo port install py26-pyqt4 @4.6.2_0 Macintosh:$ sudo port install qt4-mac @4.5.3_0 3. Download and start GNS3 gns3-legacy-GNS3-0.8.6/TODO000077500000000000000000000115221223163545200150500ustar00rootroot00000000000000TODO LIST GUI * Add a Clear startup configuration button and/or add a Clear All Startup configurations option to the control menu. * Style options for node labels. * Option to draw dummy lines and arrows on the scene (http://forum.gns3.net/topic6622.html) * Create more 'Show advanced options' where there are too many options in Preferences. * New logo for GNS3? * Snap to grid would be a great option to align all routers in fixed and neat location * Ability to change and set a font type to be the default for all your projects (including interface font size and type) * Ability to centralise fonts (i.e description inside a project), align to the left, or align to the right (similar to notepad/Word) * Ability to slightly change the colour or shades of the routers to add more customisable options (blue-ish colour would be nice). * Ability to display the link bandwidth (right click then display bandwidth) which is read from the startup-config/running-config. I don't know how easy this can be, but studying routing and knowing what bandwidth each link, makes understanding routing protocols more interesting. * Activity lights (http://forum.gns3.net/topic5026.html) * Different color for link to match the Ethernet speed. * Animation to represent traffic activity? (http://forum.gns3.net/topic5257.html) * Hide/Show specific Map Layers (http://forum.gns3.net/topic5077.html) * IOS Images and hypervisors need rewriting (http://forum.gns3.net/topic5158.html) OSX * Open .net files from Finder on Mac OS X (http://www.gns3.net/phpBB/topic1817.html) * DMG installer for Mac OS X (http://chromasoft.blogspot.com/2010/02/building-dmg-installer-for-mac-simple.html) Dynamips * NIO Multicast support, is this useful? * Set system ID (can be useful for pageant IOS) * Automatic console login for IOS (idlepc is not effective until hitting returns in the IOS console), use expect scripts? (Putty/SecureCRT/TeraTerm have custom scripts that do this now). * Auto UDP: to simplify the UDP port mapping stuff and the binding problems that can occur -> The first command to use is: "nio create_udp_auto " -> It will return the allocated port number. local_addr is an IPv4/IPv6 address (0.0.0.0 on IPv4 and :: on IPv6 to listen on all addresses). local_port_start and local_port_end define a port range (it can be useful if you are behind a firewall). -> On the remote side: nio connect_udp_auto -> remote_host being the host where nio create_udp_auto was called, and remote_port the port number returned by it. Client/Server * Dynamips Management Server intended for teaching environments (not need to share an IOS image). * Client/Server protocol should become asynchronous, so for instance users won't wait until all VMs actually start. Misc. * Ostinato integration? (http://ostinato.org) * Load custom flash files (e.g. with cme etc.) * Device startup order with delay (http://forum.gns3.net/topic7000.html) * The add-a-link tool to recognise special EtherSwitch Routers (http://forum.gns3.net/topic6760.html) * Notes to support hyperlinks (http://forum.gns3.net/topic6621.html). Bugs. * c1700 not recognised (http://forum.gns3.net/topic6953.html) Misc. (by Technologov) * Investigate possibility of GuestIP address retrieval from Dynamips Routers by means of SNMP (+pre-configured SNMP startup-config + management interface) * libguestfs to read filesystem within Qemu/KVM guests. GNS3 related feature requests in 3rd party products: (by Technologov) * Qt4: [feature-request] Please add new GUI container element, that shows/hides others, "QIArrowButtonSwitch" (QTBUG-19984) * VirtualBox: serial port TCP / Telnet listener (Wish #1851) * VirtualBox: Direct Linux Boot (required for ASA guests; Wish #8401) * VirtualBox: PEMU key+serial injection (required for PIX guests) * VirtualBox: [feature-request] Please support 16 vNICs per VM (Wish #8805) * VirtualBox: [feature-request] GuestControl execute must automatically handle extensions, like shell does (Wish #9035) * VirtualBox: [feature-request] Guest Additions: Please provide clipboard copy paste for text-mode console VMs (without X.org) (Wish #9291) (jarle's case) * VirtualBox: Multicast support (many procotols use multicast, like OSPF, RIPv2 etc.) GNS3 related bugs in 3rd party products: (by Technologov) * VirtualBox: Guest IP retrieval works incorrectly if you have several IP addresses on the same NIC (bug #9006) * VirtualBox: Only first 4 out of 8 ethernet cards work with Windows XP guest (bug #8772) * VirtualBox: Critical bug(!!!): VBoxSVC locks up on Windows XP hosts; reproducible with my vboxtestcase.py (happens on VM stop and on netadp disable.) (VBox bug #9239) This leads to GNS3 lock-ups and crashes. * VirtualBox: GuestControl execution from python fails on Windows hosts. (Bug #9295) gns3-legacy-GNS3-0.8.6/baseconfig.txt000066400000000000000000000004011223163545200172100ustar00rootroot00000000000000! hostname %h ! no ip domain lookup no ip icmp rate-limit unreachable ip tcp synwait 5 ! line con 0 exec-timeout 0 0 logging synchronous privilege level 15 no login line aux 0 exec-timeout 0 0 logging synchronous privilege level 15 no login ! ! end gns3-legacy-GNS3-0.8.6/baseconfig_sw.txt000066400000000000000000000061151223163545200177310ustar00rootroot00000000000000! no service dhcp ! hostname %h-SW ! no ip routing no ip domain lookup no ip icmp rate-limit unreachable ip tcp synwait 5 vtp file nvram:vlan.dat ! ! interface FastEthernet0/0 description *** Unused for Layer2 SW *** no ip address shutdown ! interface FastEthernet0/1 description *** Unused for Layer2 SW *** no ip address shutdown ! interface FastEthernet1/0 no shutdown duplex full speed 100 ! interface FastEthernet1/1 no shutdown duplex full speed 100 ! interface FastEthernet1/2 no shutdown duplex full speed 100 ! interface FastEthernet1/3 no shutdown duplex full speed 100 ! interface FastEthernet1/4 no shutdown duplex full speed 100 ! interface FastEthernet1/5 no shutdown duplex full speed 100 ! interface FastEthernet1/6 no shutdown duplex full speed 100 ! interface FastEthernet1/7 no shutdown duplex full speed 100 ! interface FastEthernet1/8 no shutdown duplex full speed 100 ! interface FastEthernet1/9 no shutdown duplex full speed 100 ! interface FastEthernet1/10 no shutdown duplex full speed 100 ! interface FastEthernet1/11 no shutdown duplex full speed 100 ! interface FastEthernet1/12 no shutdown duplex full speed 100 ! interface FastEthernet1/13 no shutdown duplex full speed 100 ! interface FastEthernet1/14 no shutdown duplex full speed 100 ! interface FastEthernet1/15 no shutdown duplex full speed 100 ! interface Vlan1 no ip address shutdown ! ! line con 0 exec-timeout 0 0 logging synchronous privilege level 15 no login line aux 0 exec-timeout 0 0 logging synchronous privilege level 15 no login ! ! banner exec  *************************************************************** This is a normal Router with a SW module inside (NM-16ESW) It has been preconfigured with hard-code speed and duplex To create vlans use the command "vlan database" from exec mode After creating all desired vlans use "exit" to apply the config To view existing vlans use the command "show vlan-switch brief" Warning: You are using an old IOS image for this router. Please update the IOS to enable the "macro" command! ***************************************************************  ! !Warning: If the IOS is old and doesn't support macro, it will stop the configuration loading from this point! ! macro name add_vlan end vlan database vlan $v exit @ macro name del_vlan end vlan database no vlan $v exit @ ! ! banner exec  *************************************************************** This is a normal Router with a Switch module inside (NM-16ESW) It has been pre-configured with hard-coded speed and duplex To create vlans use the command "vlan database" in exec mode After creating all desired vlans use "exit" to apply the config To view existing vlans use the command "show vlan-switch brief" Alias(exec) : vl - "show vlan-switch brief" command Alias(configure): va X - macro to add vlan X Alias(configure): vd X - macro to delete vlan X ***************************************************************  ! alias configure va macro global trace add_vlan $v alias configure vd macro global trace del_vlan $v alias exec vl show vlan-switch brief ! ! end gns3-legacy-GNS3-0.8.6/broker/000077500000000000000000000000001223163545200156405ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/broker/server2.py000066400000000000000000000177121223163545200176120ustar00rootroot00000000000000#!/usr/bin/python # vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # server # this is a beta version of the dynamips image management server. # An ios image must be of the form 'router_type'.image (e.g. c7200.image) # It creates a dynamips instance and connect to its control port. # it then create router instances and define their control port and UDP stream ports. # The ios images must be in the working directory. import socket import sys import select from struct import * import subprocess import os import time import signal def handler(signum, frame): globalState._server._socket.close() print "\rSIGINT caught. Exciting gracefully" sys.exit(0) signal.signal(signal.SIGINT, handler) def getInfos(client): print 'getInfos' def sendData(client): clientOut = globalState._server._clients[globalState._negociator._socket] print client.getCurrentPayLoad() clientOut.feedWrite(client.getCurrentPayLoad()) print "client write buffer : ", clientOut._writeQueue globalState._server._outgoing.append(clientOut._socket) print globalState._server._outgoing #global vars funcsHash = { 1: getInfos, 2: sendData } globalState = None #----------- class GlobalState: _port = None _dynamipsPath = None _workingDirectory = None _instanceDesc = None _server = None _negociator = None def __init__(self, argv): self._port = argv[1] self._dynamipsPath = argv[2] self._workingDirectory = argv[3] i = 4 self._instanceDesc = [] while (i + 2) <= len(argv): self._instanceDesc.append([argv[i], argv[i + 1], int(argv[i + 1]) + 1]) i += 2 class DynamipsNegociator: _port = None _process = None _nullFd = None _socket = None def __init__(self, port): self._port = port self._nullFd = os.open(os.devnull, os.O_WRONLY) self._process = subprocess.Popen([globalState._dynamipsPath, "-H", str(self._port)], stdout = self._nullFd) # create connection to Dynamips Hypervisor console print "Trying to create socket on port", self._port, "for process' pid", self._process.pid while self._socket == None: for res in socket.getaddrinfo("127.0.0.1", self._port, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self._socket = socket.socket(af, socktype, proto) except socket.error, msg: self._socket = None continue try: self._socket.connect(sa) except socket.error, msg: self._socket.close() self._socket = None continue break if self._socket is None: print 'could not open socket' sys.exit(1) else: print 'connection to console successfully created' class Connection: TCP, UDP = range(2) def __init__(self, socket, type = TCP): self._queue = [] self._writeQueue = [] self._write = False self._socket = socket def feed(self, data): print "feeding with", data if len(data) == 0: return if len(self._queue) > 0: if len(self._queue[len(self._queue) - 1][0]) != self._queue[len(self._queue) - 1][1]: self._queue[len(self._queue) - 1][0] += data if self._queue[len(self._queue) - 1][1] == -1: self._queue[len(self._queue) - 1] = [self._queue[len(self._queue) - 1][0][calcsize('i'):], unpack('!i', self._queue[len(self._queue) - 1][0][:calcsize('i')])[0]] else: if len(data) > calcsize('i'): self._queue.append([data[calcsize('i'):], unpack('!i', data[:calcsize('i')])[0]]) else: self._queue.append([data, -1]) print self._queue if len(self._queue[len(self._queue) - 1][0]) == self._queue[len(self._queue) - 1][1]: #print 'Able to write data : ' + self._queue.pop()[0] self._write = True def feedWrite(self, data): self._writeQueue.append([data]) def getWriteData(self): if (len(self._writeQueue) > 0): return "".join(self._writeQueue[0]) + "\r\n" return "" def delWriteData(self, length): if length > 0: if len(self._writeQueue) > 0: if length >= len(self._writeQueue[0]): self._writeQueue.pop(0) else: self._writeQueue[0] = self._writeQueue[length:] def ready(self): return self._write def getCurrentCMD(self): return int(unpack('!c', self._queue[len(self._queue) - 1][0][:calcsize('c')])[0]) def getCurrentPayLoad(self): return self._queue[len(self._queue) - 1][0][calcsize('c'):] def pop(self): del self._queue[0] class Server: _socket = None _lineFeed = None _incoming = [] _outgoing = [] _clients = {} _instancePool = None _funcsHash = None def __init__(self, funcsHash, port, host=None, linefeed=None): self._socket = None self._lineFeed = linefeed self._funcsHash = funcsHash for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: self._socket = socket.socket(af, socktype, proto) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error, msg: self._socket = None continue try: self._socket.bind(sa) self._socket.listen(5) except socket.error, msg: self._socket.close() self._socket = None continue break if self._socket is None: print 'could not open socket' sys.exit(1) else: print 'Server ready' self._incoming.append(self._socket) self._incoming.append(globalState._negociator._socket) self._outgoing.append(globalState._negociator._socket) self._clients[globalState._negociator._socket] = Connection(globalState._negociator._socket) def run(self): while self._incoming: (readable, writeable, exceptionable) = select.select(self._incoming, self._outgoing, self._incoming) # reading for s in readable: #print s if s is self._socket: (conn, addr) = self._socket.accept() conn.setblocking(0) self._incoming.append(conn) #self._outgoing.append(conn) self._clients[conn] = Connection(conn) print 'successfully registered new connection' elif s is globalState._negociator._socket: print "Dynamips hypervisor read", s.recv(1024).rstrip(self._lineFeed) if len(self._clients[s]._writeQueue) > 0: self._outgoing.append(s) else: data = s.recv(1024) if data: self._clients[s].feed(data.rstrip(self._lineFeed)) if self._clients[s].ready(): if self._funcsHash[self._clients[s].getCurrentCMD()] != None: self._funcsHash[self._clients[s].getCurrentCMD()](self._clients[s]) self._clients[s].pop() else: self._incoming.remove(s) del self._clients[s] s.close() print 'client disconnected' for s in writeable: #print s client = self._clients[s] if len(client.getWriteData()) > 0: #print "Sending :", client.getWriteData() length = s.send(client.getWriteData()) client.delWriteData(length) #print "".join(client.getWriteData()) #if len(client._writeQueue) == 0: self._outgoing.remove(s) # do the server/instances setup, create classes and create a class to negociate the creation if __name__ == '__main__': if (len(sys.argv) < 6): print "Usage : port dynamips_binary working_directory [image port]*" sys.exit(1) globalState = GlobalState(sys.argv) negociator = DynamipsNegociator(7200) globalState._negociator = negociator server = Server(funcsHash, globalState._port, None, '\r\n') globalState._server = server client = globalState._server._clients[globalState._negociator._socket] client.feedWrite("hypervisor working_dir " + sys.argv[3]) client.feedWrite("vm create R" + str(sys.argv[5]) + " 0 c7200") client.feedWrite("vm set_con_tcp_port R" + str(sys.argv[5]) + " " + str(sys.argv[3])) client.feedWrite("vm set_ios R" + str(sys.argv[5]) + " " + sys.argv[3] + "/" + sys.argv[4] + ".image") client.feedWrite("c7200 set_npe R" + sys.argv[5] + " npe-400") client.feedWrite("vm slot_add_binding R" + sys.argv[5] + " 1 0 PA-2FE-TX") client.feedWrite("nio create_udp nio_udp0 " + str(int(sys.argv[5]) + 1) + " 127.0.0.1 " + str(int(sys.argv[5]) + 2)) client.feedWrite("vm slot_add_nio_binding R" + sys.argv[5] + " 1 0 nio_udp0") client.feedWrite("vm start R" + sys.argv[5]) print client._writeQueue server.run()gns3-legacy-GNS3-0.8.6/docs/000077500000000000000000000000001223163545200153045ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/docs/man/000077500000000000000000000000001223163545200160575ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/docs/man/gns3.1000077500000000000000000000033341223163545200170210ustar00rootroot00000000000000.Dd $Mdocdate: March 05 2012$ .Dt GNS3 1 .Os .Sh "NAME" .Nm gns3 .Nd a graphical network simulator .Sh "SYNOPSIS" .Nm gns3 .Op -cdh .Op file .Sh DESCRIPTION GNS3 is a graphical network simulator that allows simulation of complex networks and to launch simulations on them. It is an excellent complementary tool to real labs for administrators of Cisco networks or people wanting to pass their CCNA, CCNP, CCIP or CCIE certifications. It can also be used to experiment features of Cisco IOS or to check configurations that need to be deployed later on real routers. .Pp To allow complete simulations, GNS3 is strongly linked with : .Bl -bullet -offset 1c .It Dynamips, the core program that allows Cisco IOS emulation .It Dynagen, a text-based front-end for Dynamips .It Qemu, a generic and open source machine emulator and virtualizer .It VirtualBox, a free and powerful virtualization software. .El .Pp \fIImportant notice:\fP users have to provide their own images. .Pp You may have to install a patched version of some emulators, please read the online documentation. The options are as follows: .Bl -tag -width 3c .It Fl h Displays a help message .It Fl c Directory where gns3.ini is located (default: ~/gns3/) .It Fl d Display debug messages .It Fl -version Prints out the version and exits .El .Sh ONLINE DOCUMENTATION Check out the online documentation at http://www.gns3.net .Sh REPORTING BUGS Please send bug reports at http://redmine.gns3.net .Sh SEE ALSO .Xr qemu 1 , .Xr dynamips 1 .Sh "AUTHOR" GNS3 has been written by Jeremy Grossmann, David Ruiz, Romain Lamaison, Aurelien Levesque, Xavier Alt, Benjamin Marsili, Claire Goudjil and Alexey Eromenko "Technologov". The developers can be contacted using this form: http://www.gns3.net/contact gns3-legacy-GNS3-0.8.6/gns3000077700000000000000000000000001223163545200165572gns3.pywustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/gns3.icns000077500000000000000000000223641223163545200161160ustar00rootroot00000000000000icns$is32PPl:i`h[!JΈphAi:wPBmwfxmk\Gq#߽tsmv9]l/Jom#vmeN}csdY +LK˂LPP  e`h[!J CΈph #}\ɥ/:jHW /ɸdXe}zyjZ>M3QbZ7_a`hkiaZ\IZ^@ԋGutk]Jm˦tuuvxhDbHUuuwy5X {}vuu{zhN#\suuxҺɵ:LdkeuM;|& X޻S] ڀ [Lͱ;(o,"޳{mLt!B}"Ȟx\ )#,$5 /6\C2\ {'2 6."> ' 0CB4!AB\P $. (VQp U;vY\ /(ac>}Nct]'ɥ/:'(}ruHW Nt#Xe}zyjZ>M3׸S5_a`hkiaZ\IZSUutk]Jm+[}zwsnrtuuvxhDcH SLIFC@4'uuwy5V  }vuu{zkN[suuxֿLdkeuO= & wO>zgʶ^˟> ~  =ހ(Ǟ|^.9^E3]!~(4 80#B( 2ED5#\}-pYB 4mų aZ򲹎Nct]'CM '(}r$ Nt#4܌ ׸TS +[}zwsnq|҅  SLIFC@4<Z(  7ʀ^ /ödpb@iE J՗<{sspmicb,J(4o=IEB?<9(C|9 u;\^  &c       l8mk(G297 ^( F3{S+{oD[,!ll  G] W2Cr|jH8+V=ŏlL6 'ă2 'wDzԧq>S=' .Hɤꗿހ݀ wȾߨـ؀GȳTʺр/WkOL#umKKᙼޏS8DCޒ Jkvtd;QDAۂ ! _u@`<W8P#S)s.,c   ~ [ѨE  =kf2    ϓ9 31jyi,%5=_@͡8*8;CҨ?$4yu@@. <OyLp,Uā7075Â2  Jԥp>U ?( 6Dq .wdwթ׀݀܀EﳐՀ 4V &ԀyLDD QDB _uBb>Z9T$ T*v0/e ڂ ^լF  @oh3   W4x% cADŽ ~D^h1@.  A,Uā 70~1gZ  B͈(YӢ@&!$E)7PPN8~|zwySV[hfdb`^[YWW65"IDCA?<;862 $#  S 1C{ObbO" Շ̶|.z) F*cɗ4q '^+1uO' 2{|zywurolhh7w͢s^]^\[YVTROKE !}o:Nv)B@=;97532.1}é^%  ct$r  tnN   :U2  9           h8mk  1^nX(:%T;D$# Y5 Jł){#n # +9{O {- qo ; (mvD9WG B9Yt =62Pu 2R97?QaheO%~]KB;66Ww߿fSLG] Cۮ~ *hMN[r)Ax/"1ANbH!P/ %:U_ (Ow5 6i  $?iDZQ. !e  ):IQNA0R   g9 F& 0q!a>9q!L3 +X>-Qz>%@byS2  *:FLIA3" gns3-legacy-GNS3-0.8.6/gns3.pyw000077500000000000000000000052631223163545200160000ustar00rootroot00000000000000#!/usr/bin/env python # vim: expandtab ts=4 sw=4 sts=4: # -*- coding: utf-8 -*- # # Copyright (C) 2007-2011 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # code@gns3.net # import sys, os, time, traceback try: reload(sys) sys.setdefaultencoding('utf-8') except: sys.stderr.write("Can't set default encoding to utf-8\n") # current version of GNS3 VERSION = "0.8.6" try: from PyQt4 import QtCore, QtGui except ImportError: sys.stderr.write("Can't import Qt modules, PyQt is probably not installed ...\n") sys.exit(False) if QtCore.QT_VERSION < 0x040600: raise RuntimeError, "Need Qt v4.6 or higher, but got v%s" % QtCore.QT_VERSION_STR if QtCore.PYQT_VERSION < 0x040500: raise RuntimeError, "Need PyQt v4.5 or higher, but got v%s" % QtCore.PYQT_VERSION_STR if sys.version_info < (2, 6): raise RuntimeError, "Python 2.6 or higher is required" def exceptionHook(type, value, tb): lines = traceback.format_exception(type, value, tb) print "---------Traceback lines (saved in exception.log)----------" print "\n" . join(lines) print "-----------------------------------------------------------" try: curdate = time.strftime("%d %b %Y %H:%M:%S") logfile = open('exception.log','a') logfile.write("=== GNS3 " + VERSION + " traceback on " + curdate + " ===\n") logfile.write("\n" . join(lines)) logfile.close() except: pass # catch exceptions to write them in a file sys.excepthook=exceptionHook if __name__ == '__main__': # __file__ is not supported by py2exe and py2app if hasattr(sys, "frozen"): GNS3_RUN_PATH = os.path.dirname(os.path.abspath(sys.executable)) else: GNS3_RUN_PATH = os.path.dirname(os.path.abspath(__file__)) # change current working directory to GNS3_RUN_PATH for relative paths to work correctly os.chdir(GNS3_RUN_PATH) source_path = GNS3_RUN_PATH + os.sep + 'src' if os.access(source_path, os.F_OK): sys.path.append(source_path) if len(sys.argv) > 1 and sys.argv[1].startswith("-psn"): del sys.argv[1] import GNS3.Main gns3-legacy-GNS3-0.8.6/qemuwrapper/000077500000000000000000000000001223163545200167245ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/qemuwrapper/make-qemuwrapper-exe.py000066400000000000000000000002701223163545200233370ustar00rootroot00000000000000#!/usr/bin/env python # vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # make-exe.py from distutils.core import setup import py2exe setup(console=["qemuwrapper.py"],zipfile=None) gns3-legacy-GNS3-0.8.6/qemuwrapper/qemuwrapper.py000066400000000000000000001505221223163545200216530ustar00rootroot00000000000000#!/usr/bin/env python # vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (c) 2007-2012 Thomas Pani & Jeremy Grossmann # # Contributions by Pavel Skovajsa & Alexey Eromenko "Technologov" # # 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 module is used for actual control of VMs, sending commands to the hypervisor. #This is the server part, it can be started manually, or automatically from "QemuManager" #Client part is named "qemu_lib". (dynagen component) #debuglevel: 0=disabled, 1=default, 2=debug, 3=deep debug debuglevel = 0 #qemuprotocol: 0=old, 1=experimental qemuprotocol = 1 import csv import cStringIO import os import re import platform import select import socket import subprocess import sys import threading import SocketServer import time import random import ctypes import hashlib import shutil try: reload(sys) sys.setdefaultencoding('utf-8') except: sys.stderr.write("Can't set default encoding to utf-8\n") if debuglevel > 0: if platform.system() == 'Windows': debugfilename = "C:\TEMP\gns3-qemuwrapper-log.txt" else: debugfilename = "/tmp/gns3-qemuwrapper-log.txt" try: dfile = open(debugfilename, 'wb') except: dfile = 0 print "WARNING: log file cannot be created !" if dfile: print "Log file = %s" % str(debugfilename) def debugmsg(level, message): if debuglevel == 0: return if debuglevel >= level: print message if dfile: #In python 2.6, print with redirections always uses UNIX line-ending, # so I must add os-neutral line-endings. print >> dfile, message, dfile.write(os.linesep) dfile.flush() msg = "WELCOME to qemuwrapper.py" debugmsg(2, msg) __author__ = 'Thomas Pani and Jeremy Grossmann' __version__ = '0.8.6' if platform.system() == 'Windows': if os.path.exists('Qemu\qemu-system-i386w.exe'): QEMU_PATH = "Qemu\qemu-system-i386w.exe" QEMU_IMG_PATH = "Qemu\qemu-img.exe" else: # For now we ship Qemu 0.11.0 in the all-in-one QEMU_PATH = "qemu.exe" QEMU_IMG_PATH = "qemu-img.exe" else: QEMU_PATH = "qemu" QEMU_IMG_PATH = "qemu-img" PORT = 10525 IP = "" QEMU_INSTANCES = {} FORCE_IPV6 = False MONITOR_BASE_PORT = 5001 # set correctly the working directory for qemuwrapper WORKDIR = os.getcwdu() if os.environ.has_key("TEMP"): WORKDIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): WORKDIR = unicode(os.environ["TMP"], 'utf-8', errors='replace') # __file__ is not supported by py2exe and py2app if hasattr(sys, "frozen"): PEMU_DIR = os.path.dirname(os.path.abspath(sys.executable)) else: PEMU_DIR = os.path.dirname(os.path.abspath(__file__)) class UDPConnection: def __init__(self, saddr, sport, daddr, dport): self.saddr = saddr self.sport = sport self.daddr = daddr self.dport = dport def resolve_names(self): try: addr = socket.gethostbyname(self.daddr) self.daddr = addr except socket.error, e: print >> sys.stderr, "Unable to resolve hostname %s", self.daddr print >> sys.stderr, e except socket.herror, e: print >> sys.stderr, "Unable to resolve hostname %s", self.daddr print >> sys.stderr, e class xEMUInstance(object): def __init__(self, name): debugmsg(2, "xEMUInstance::__init__()") self.name = name self.ram = '256' self.console = '' self.image = '' self.nic = {} self.nics = '6' self.udp = {} self.usermod = False self.flavor = 'Default' self.capture = {} self.netcard = 'rtl8139' self.kvm = False self.options = '' self.process = None self.workdir = WORKDIR + os.sep + name self.valid_attr_names = ['image', 'ram', 'console', 'nics', 'netcard', 'kvm', 'options', 'usermod', 'flavor', 'monitor'] # For Qemu monitor mode self.monitor = False self.monitor_conn = None self.monitor_sock = None global MONITOR_BASE_PORT self.monitor_port = MONITOR_BASE_PORT MONITOR_BASE_PORT = MONITOR_BASE_PORT + 1 def create(self): debugmsg(2, "xEMUInstance::create()") if not os.path.exists(self.workdir): os.makedirs(self.workdir) def clean(self): pass def unbase_disk(self): pass def start(self): debugmsg(2, "xEMUInstance::start()") command = self._build_command() if bool(self.monitor): # Prepare the socket taking care of Qemu monitor mode for res in socket.getaddrinfo('localhost', self.monitor_port, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, cannonname, sa = res try: self.monitor_sock = socket.socket(af, socktype, proto) except socket.error, msg: self.monitor_sock = None continue try: self.monitor_sock.bind(sa) self.monitor_sock.listen(1) # Allow only one connection except socket.error, msg: self.monitor_sock.close() self.monitor_sock = None continue break if self.monitor_sock is None: print >> sys.stderr, 'Unable to open socket for monitor mode on localhost:' + self.monitor_port return False qemu_cmd = " ".join(command) print "Starting Qemu: ", qemu_cmd try: self.process = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, #stderr = subprocess.PIPE, cwd=self.workdir, shell=False) # MUST STAY FALSE except OSError, e: print >> sys.stderr, "Unable to start instance", self.name, "of", self.__class__ print >> sys.stderr, e print self.process.communicate() return False print "Qemu started with PID %i" % self.process.pid time.sleep(1) if bool(self.monitor): self.monitor_conn, addr = self.monitor_sock.accept() self.monitor_conn.setblocking(0) # consume the first lines of output of Qemu monitor mode output = '' while True: select.select([self.monitor_conn], [], [], 1) output += self.monitor_conn.recv(4096) if len(output) == 0 or 'monitor -'not in output: continue else: break if platform.system() == 'Windows': print "Setting priority class to BELOW_NORMAL" handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, self.process.pid) win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS) else: subprocess.call(['renice', '-n', '19', '-p', str(self.process.pid)]) return True def stop(self): if platform.system() == 'Windows': handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, self.process.pid) try: if win32api.TerminateProcess(handle, 0): return False except pywintypes.error, e: print >> sys.stderr, "Unable to stop Qemu instance", self.name print >> sys.stderr, e[2] # ignore and continue #return False else: import signal try: os.kill(self.process.pid, signal.SIGINT) except OSError, e: print >> sys.stderr, "Unable to stop Qemu instance", self.name print >> sys.stderr, e self.process = None return True def _net_options(self): global qemuprotocol options = [] # compute new MAC address based on VM name + vlan number mac = hashlib.md5(self.name).hexdigest() local_qemuprotocol = qemuprotocol if platform.system() == 'Windows': # On Windows, Qemu binaries don't return anything when using -help. So pick up the protocol based on the filename. binary_name = os.path.basename(self.bin) print "Binary: %s" % binary_name if binary_name == 'qemu-system-i386w.exe': local_qemuprotocol = 1 print "Using the new qemu syntax" else: local_qemuprotocol = 0 print "Using the old qemu syntax" else: # fallback on another syntax if the current one is not supported if qemuprotocol == 0: try: p = subprocess.Popen([self.bin, '-help'], stdout = subprocess.PIPE) qemustdout = p.communicate() except: print >> sys.stderr, "Unable to execute %s -help" % self.bin return options if not qemustdout[0].__contains__('for dynamips/pemu/GNS3'): print "Falling back to the new qemu syntax" local_qemuprotocol = 1 elif qemuprotocol == 1: try: p = subprocess.Popen([self.bin, '-net', 'socket'], stderr = subprocess.PIPE) qemustderr = p.communicate() except: print >> sys.stderr, "Unable to execute %s -net socket" % self.bin return options if not qemustderr[1].__contains__('udp='): print "Falling back to the old qemu syntax" local_qemuprotocol = 0 for vlan in range(int(self.nics)): if local_qemuprotocol == 1: if vlan in self.nic and vlan in self.udp: options.extend(['-device', '%s,mac=%s,netdev=gns3-%s' % (self.netcard, self.nic[vlan], vlan)]) else: options.extend(['-device', '%s,mac=00:00:ab:%02x:%02x:%02d' % (self.netcard, random.randint(0x00, 0xff), random.randint(0x00, 0xff), vlan)]) if vlan in self.udp: options.append('-netdev') options.append('socket,id=gns3-%s,udp=%s:%s,localaddr=%s:%s' % (vlan, self.udp[vlan].daddr, self.udp[vlan].dport, self.udp[vlan].saddr, self.udp[vlan].sport)) # FIXME: dump relies on vlans, incompatible with the new syntax: patch Qemu if vlan in self.capture: print 'Dump option is not available with the netdev syntax' #options.extend(['-net', 'dump,vlan=%s,file=%s' % (vlan, self.capture[vlan])]) else: options.append('-net') if vlan in self.nic: options.append('nic,vlan=%d,macaddr=%s,model=%s' % (vlan, self.nic[vlan], self.netcard)) else: # add a default NIC for Qemu options.append('nic,vlan=%d,macaddr=00:00:ab:%02x:%02x:%02d,model=%s' % (vlan, random.randint(0x00, 0xff), random.randint(0x00, 0xff), vlan, self.netcard)) if vlan in self.udp: options.extend(['-net', 'udp,vlan=%s,sport=%s,dport=%s,daddr=%s' % (vlan, self.udp[vlan].sport, self.udp[vlan].dport, self.udp[vlan].daddr)]) if vlan in self.capture: options.extend(['-net', 'dump,vlan=%s,file=%s' % (vlan, self.capture[vlan])]) if bool(self.usermod): options.extend(['-device', '%s,mac=00:00:ab:%02x:%02x:%02x,netdev=gns3-usermod' % (self.netcard, random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff))]) options.extend(['-netdev', 'user,id=gns3-usermod']) return options def _ser_options(self): if self.console: return ['-serial', 'telnet:' + IP + ':%s,server,nowait' % self.console] else: return [] class PEMUInstance(xEMUInstance): def __init__(self, name): debugmsg(2, "PEMUInstance::__init__()") super(PEMUInstance, self).__init__(name) if platform.system() == 'Windows': self.bin = 'pemu.exe' else: self.bin = 'pemu' self.serial = '0x12345678' self.key = '0x00000000,0x00000000,0x00000000,0x00000000' self.valid_attr_names += ['serial', 'key'] self.pemu_bin_path = os.path.join(PEMU_DIR, self.bin) debugmsg(1, "self.pemu_bin_path = %s" % self.pemu_bin_path) def _net_options(self): options = [] # compute new MAC address based on VM name + vlan number for vlan in range(int(self.nics)): options.append('-net') if vlan in self.nic: options.append('nic,vlan=%d,macaddr=%s,model=%s' % (vlan, self.nic[vlan], self.netcard)) else: # add a default NIC for Qemu options.append('nic,vlan=%d,macaddr=00:00:ab:%02x:%02x:%02d,model=%s' % (vlan, random.randint(0x00, 0xff), random.randint(0x00, 0xff), vlan, self.netcard)) if vlan in self.udp: options.extend(['-net', 'udp,vlan=%s,sport=%s,dport=%s,daddr=%s' % (vlan, self.udp[vlan].sport, self.udp[vlan].dport, self.udp[vlan].daddr)]) if vlan in self.capture: options.extend(['-net', 'dump,vlan=%s,file=%s' % (vlan, self.capture[vlan])]) return options def _build_command(self): debugmsg(2, "PEMUInstance::_build_command()") "Builds the command as a list of shell arguments." command = [os.path.join(PEMU_DIR, self.bin)] command.extend(self._net_options()) command.extend(['-m', str(self.ram), 'FLASH']) command.extend(self._ser_options()) return command def _write_config(self): debugmsg(2, "PEMUInstance::_write_config()") f = open(os.path.join(self.workdir, 'pemu.ini'), 'w') f.writelines(''.join(['%s=%s\n' % (attr, getattr(self, attr)) for attr in ('serial', 'key', 'image')])) f.close() def start(self): debugmsg(2, "PEMUInstance::start()") if not os.path.exists(self.pemu_bin_path): debugmsg(1, "ERROR: Cannot find PEMU !") print >> sys.stderr, "ERROR: Cannot find PEMU! (looking for %s)" % self.pemu_bin_path return False self._write_config() return super(PEMUInstance, self).start() class PIXInstance(PEMUInstance): pass class QEMUInstance(xEMUInstance): def __init__(self, name): debugmsg(3, "QEMUInstance::__init__()") super(QEMUInstance, self).__init__(name) self.bin = QEMU_PATH self.img_bin = QEMU_IMG_PATH self.valid_attr_names.extend(('flash_size', 'flash_name')) self.flash_size = '256M' self.flash_name = 'FLASH' def _build_command(self): debugmsg(3, "QEMUInstance::_build_command()") "Builds the command as a list of shell arguments." if 'qemu-system-' in self.bin and self.flavor != 'Default': self.bin = re.sub(r'qemu-system-.*', 'qemu-system' + self.flavor, self.bin) if sys.platform.startswith('win'): self.bin += 'w.exe' # We ship qemu-system-XXXw.exe on Windows command = [self.bin] # Qemu monitor mode through socket if bool(self.monitor): command.extend(['-monitor', 'stdio']) command.extend(['-chardev', 'socket,id=qemuwrapper-monitor,host=localhost,port=' + str(self.monitor_port)]) command.extend(['-mon', 'qemuwrapper-monitor']) command.extend(['-name', self.name]) command.extend(['-m', str(self.ram)]) command.extend(self._disk_options()) command.extend(self._image_options()) command.extend(self._kernel_options()) if bool(self.kvm) == True: command.extend(['-enable-kvm']) command.extend(self._net_options()) command.extend(self._ser_options()) self.options = self.options.strip() if self.options: #TODO: do not split inside double quotes => use re.split() command.extend(self.options.split()) return command def _disk_options(self): debugmsg(3, "QEMUInstance::_disk_options()") return [] def _kernel_options(self): debugmsg(3, "QEMUInstance::_kernel_options()") return [] def _image_options(self): debugmsg(3, "QEMUInstance::_image_options()") return [] class ASAInstance(QEMUInstance): def __init__(self, *args, **kwargs): debugmsg(3, "ASAInstance::__init__()") super(ASAInstance, self).__init__(*args, **kwargs) self.netcard = 'e1000' self.initrd = '' self.kernel = '' self.kernel_cmdline = '' self.valid_attr_names += ['initrd', 'kernel', 'kernel_cmdline'] def clean(self): debugmsg(3, "ASAInstance::clean()") flash = os.path.join(self.workdir, self.flash_name) if os.path.exists(flash): try: print "Deleting old flash file:", flash os.remove(flash) except (OSError, IOError), e: print >> sys.stderr, flash, "cannot be deleted:", e def _disk_options(self): debugmsg(3, "ASAInstance::_disk_options()") flash = os.path.join(self.workdir, self.flash_name) if not os.path.exists(flash): try: retcode = subprocess.call([self.img_bin, 'create', '-f', 'qcow2', flash, self.flash_size]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e return ('-hda', flash) def _image_options(self): debugmsg(3, "ASAInstance::_image_options()") return ('-kernel', self.kernel, '-initrd', self.initrd) def _kernel_options(self): debugmsg(3, "ASAInstance::_kernel_options()") return ('-append', self.kernel_cmdline) class AWPInstance(QEMUInstance): def __init__(self, *args, **kwargs): debugmsg(3, "AWPInstance::__init__()") super(AWPInstance, self).__init__(*args, **kwargs) self.netcard = 'virtio' self.initrd = '' self.kernel = '' self.kernel_cmdline = 'root=/dev/ram0 releasefile=0.0.0-test.rel console=ttyS0,0 no_autorestart loglevel=1' self.valid_attr_names += ['initrd', 'kernel', 'kernel_cmdline'] def clean(self): debugmsg(3, "AWPInstance::clean()") flash = os.path.join(self.workdir, self.flash_name) if os.path.exists(flash): try: print "Deleting old flash file:", flash os.remove(flash) except (OSError, IOError), e: print >> sys.stderr, flash, "cannot be deleted:", e def _disk_options(self): debugmsg(3, "AWPInstance::_disk_options()") flash = os.path.join(self.workdir, self.flash_name) if not os.path.exists(flash): try: retcode = subprocess.call([self.img_bin, 'create', '-f', 'qcow2', flash, self.flash_size]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e return ('-hda', flash) def _image_options(self): debugmsg(3, "AWPInstance::_image_options()") return ('-kernel', self.kernel, '-initrd', self.initrd) def _kernel_options(self): debugmsg(3, "AWPInstance::_kernel_options()") return ('-append', self.kernel_cmdline) class JunOSInstance(QEMUInstance): def __init__(self, *args, **kwargs): debugmsg(3, "JunOSInstance::__init__()") super(JunOSInstance, self).__init__(*args, **kwargs) self.swap_name= 'SWAP' self.swap_size = '1G' self.netcard = 'e1000' def clean(self): debugmsg(3, "JunOSInstance::clean()") flash = os.path.join(self.workdir, self.flash_name) if os.path.exists(flash): try: print "Deleting old flash file:", flash os.remove(flash) except (OSError, IOError), e: print >> sys.stderr, flash, "cannot be deleted:", e swap = os.path.join(self.workdir, self.swap_name) if os.path.exists(swap): try: print "Deleting old swap file:", swap os.remove(swap) except (OSError, IOError), e: print >> sys.stderr, swap, "cannot be deleted:", e def unbase_disk(self): debugmsg(3, "JunOSInstance::unbase_disk()") flash = os.path.join(self.workdir, self.flash_name) if os.path.exists(flash): try: print "Converting %s to have no base image" % flash retcode = subprocess.call([self.img_bin, 'convert', '-O', 'qcow2', flash, flash]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e def _disk_options(self): debugmsg(3, "JunOSInstance::_disk_options()") flash = os.path.join(self.workdir, self.flash_name) if not os.path.exists(flash): try: retcode = subprocess.call([self.img_bin, 'create', '-o', 'backing_file=' + self.image, '-f', 'qcow2', flash]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e swap = os.path.join(self.workdir, self.swap_name) if not os.path.exists(swap): try: retcode = subprocess.call([self.img_bin, 'create', '-f', 'qcow2', swap, self.swap_size]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e return (flash, '-hdb', swap) class IDSInstance(QEMUInstance): def __init__(self, *args, **kwargs): debugmsg(3, "IDSInstance::__init__()") super(IDSInstance, self).__init__(*args, **kwargs) self.netcard = 'e1000' self.image1 = '' self.image2 = '' self.valid_attr_names += ['image1', 'image2'] self.img1_name = 'DISK1' self.img2_name = 'DISK2' def clean(self): debugmsg(3, "IDSInstance::clean()") img1 = os.path.join(self.workdir, self.img1_name) if os.path.exists(img1): try: print "Deleting old image file:", img1 os.remove(img1) except (OSError, IOError), e: print >> sys.stderr, img1, "cannot be deleted:", e img2 = os.path.join(self.workdir, self.img2_name) if os.path.exists(img2): try: print "Deleting old image file:", img2 os.remove(img2) except (OSError, IOError), e: print >> sys.stderr, img2, "cannot be deleted:", e def unbase_disk(self): debugmsg(3, "IDSInstance::unbase_disk()") img1 = os.path.join(self.workdir, self.img1_name) if os.path.exists(img1): try: print "Converting %s to have no base image" % img1 retcode = subprocess.call([self.img_bin, 'convert', '-O', 'qcow2', img1, img1]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e img2 = os.path.join(self.workdir, self.img2_name) if os.path.exists(img2): try: print "Converting %s to have no base image" % img2 retcode = subprocess.call([self.img_bin, 'convert', '-O', 'qcow2', img2, img2]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e def _disk_options(self): debugmsg(3, "IDSInstance::_disk_options()") img1 = os.path.join(self.workdir, self.img1_name) if not os.path.exists(img1): try: retcode = subprocess.call([self.img_bin, 'create', '-o', 'backing_file=' + self.image1, '-f', 'qcow2', img1]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e img2 = os.path.join(self.workdir, self.img2_name) if not os.path.exists(img2): try: retcode = subprocess.call([self.img_bin, 'create', '-o', 'backing_file=' + self.image2, '-f', 'qcow2', img2]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e return ('-hda', img1, '-hdb', img2) class QemuDeviceInstance(QEMUInstance): def __init__(self, *args, **kwargs): debugmsg(3, "QemuDeviceInstance::__init__()") super(QemuDeviceInstance, self).__init__(*args, **kwargs) self.swap_name= 'SWAP' self.swap_size = '1G' self.netcard = 'rtl8139' def clean(self): debugmsg(3, "QemuDeviceInstance::clean()") flash = os.path.join(self.workdir, self.flash_name) if os.path.exists(flash): try: print "Deleting old flash file:", flash os.remove(flash) except (OSError, IOError), e: print >> sys.stderr, flash, "cannot be deleted:", e swap = os.path.join(self.workdir, self.swap_name) if os.path.exists(swap): try: print "Deleting old swap file:", swap os.remove(swap) except (OSError, IOError), e: print >> sys.stderr, swap, "cannot be deleted:", e def unbase_disk(self): debugmsg(3, "QemuDeviceInstance::unbase_disk()") flash = os.path.join(self.workdir, self.flash_name) if os.path.exists(flash): try: print "Converting %s to have no base image" % flash retcode = subprocess.call([self.img_bin, 'convert', '-O', 'qcow2', flash, flash]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e def _disk_options(self): debugmsg(3, "QemuDeviceInstance::_disk_options()") flash = os.path.join(self.workdir, self.flash_name) if not os.path.exists(flash): try: retcode = subprocess.call([self.img_bin, 'create', '-o', 'backing_file=' + self.image, '-f', 'qcow2', flash]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e swap = os.path.join(self.workdir, self.swap_name) if not os.path.exists(swap): try: retcode = subprocess.call([self.img_bin, 'create', '-f', 'qcow2', swap, self.swap_size]) print self.img_bin + ' returned with ' + str(retcode) except OSError, e: print >> sys.stderr, self.img_bin, "execution failed:", e debugmsg(3, "flash = %s" % str(flash)) debugmsg(3, "image = %s" % str(self.image)) debugmsg(3, "swap = %s" % str(swap)) return (flash, '-hdb', swap) class QemuWrapperRequestHandler(SocketServer.StreamRequestHandler): modules = { 'qemuwrapper' : { 'version' : (0, 0), 'parser_test' : (0, 10), 'module_list' : (0, 0), 'cmd_list' : (1, 1), 'qemu_path' : (1, 1), 'qemu_img_path' : (1, 1), #'qemu_base_mac' : (1, 1), 'working_dir' : (1, 1), 'reset' : (0, 0), 'close' : (0, 0), 'stop' : (0, 0), }, 'qemu' : { 'version' : (0, 0), 'create' : (2, 2), 'delete' : (1, 1), 'setattr' : (3, 3), 'create_nic' : (3, 3), 'create_udp' : (6, 6), 'delete_udp' : (2, 2), 'create_capture' : (3, 3), 'delete_capture' : (2, 2), 'start' : (1, 1), 'stop' : (1, 1), 'clean': (1, 1), 'unbase': (1, 1), 'monitor': (2, 2), 'rename' : (2, 2), } } qemu_classes = { 'qemu': QemuDeviceInstance, 'pix': PIXInstance, 'asa': ASAInstance, 'awprouter' : AWPInstance, 'junos': JunOSInstance, 'ids': IDSInstance, } # dynamips style status codes HSC_INFO_OK = 100 # ok HSC_INFO_MSG = 101 # informative message HSC_INFO_DEBUG = 102 # debugging message HSC_ERR_PARSING = 200 # parse error HSC_ERR_UNK_MODULE = 201 # unknown module HSC_ERR_UNK_CMD = 202 # unknown command HSC_ERR_BAD_PARAM = 203 # bad number of parameters HSC_ERR_INV_PARAM = 204 # invalid parameter HSC_ERR_BINDING = 205 # binding error HSC_ERR_CREATE = 206 # unable to create object HSC_ERR_DELETE = 207 # unable to delete object HSC_ERR_UNK_OBJ = 208 # unknown object HSC_ERR_START = 209 # unable to start object HSC_ERR_STOP = 210 # unable to stop object HSC_ERR_FILE = 211 # file error HSC_ERR_BAD_OBJ = 212 # bad object close_connection = 0 def send_reply(self, code, done, msg): debugmsg(3, "QemuWrapperRequestHandler::send_reply(code=%s, done=%s, msg=%s)" % (str(code), str(done), str(msg))) sep = '-' if not done: sep = ' ' self.wfile.write("%3d%s%s\r\n" % (code, sep, msg)) def handle(self): debugmsg(2, "QemuWrapperRequestHandler::handle()") print "Connection from", self.client_address try: self.handle_one_request() while not self.close_connection: self.handle_one_request() print "Disconnection from", self.client_address except socket.error, e: print >> sys.stderr, e self.request.close() return def __get_tokens(self, request): debugmsg(3, "QemuWrapperRequestHandler::__get_tokens(%s)" % str(request)) input_ = cStringIO.StringIO(request) tokens = [] try: tokens = csv.reader(input_, delimiter=' ', escapechar='\\').next() except StopIteration: pass return tokens def finish(self): pass def handle_one_request(self): debugmsg(3, "QemuWrapperRequestHandler::handle_one_request()") request = self.rfile.readline() request = request.rstrip() # Strip package delimiter. # Don't process empty strings (this creates Broken Pipe exceptions) #FIXME: this causes 100% cpu usage on Windows. #if request == "": # return # Parse request. tokens = self.__get_tokens(request) if len(tokens) < 2: try: self.send_reply(self.HSC_ERR_PARSING, 1, "At least a module and a command must be specified") except socket.error: self.close_connection = 1 return module, command = tokens[:2] data = tokens[2:] if not module in self.modules.keys(): self.send_reply(self.HSC_ERR_UNK_MODULE, 1, "Unknown module '%s'" % module) return # Prepare to call the do_ function. mname = 'do_%s_%s' % (module, command) if not hasattr(self, mname): self.send_reply(self.HSC_ERR_UNK_CMD, 1, "Unknown command '%s'" % command) return try: if len(data) < self.modules[module][command][0] or \ len(data) > self.modules[module][command][1]: self.send_reply(self.HSC_ERR_BAD_PARAM, 1, "Bad number of parameters (%d with min/max=%d/%d)" % (len(data), self.modules[module][command][0], self.modules[module][command][1]) ) return except Exception, e: # This can happen, if you add send command, but forget to define it in class modules self.send_reply(self.HSC_ERR_INV_PARAM, 1, "Unknown Exception") debugmsg(1, ("handle_one_request(), ERROR: Unknown Exception: ", e)) return # Call the function. method = getattr(self, mname) method(data) def do_qemuwrapper_version(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_version(%s)" % str(data)) self.send_reply(self.HSC_INFO_OK, 1, __version__) def do_qemuwrapper_parser_test(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_parser_test(%s)" % str(data)) for i in range(len(data)): self.send_reply(self.HSC_INFO_MSG, 0, "arg %d (len %u): \"%s\"" % \ (i, len(data[i]), data[i]) ) self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemuwrapper_module_list(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_module_list(%s)" % str(data)) for module in self.modules.keys(): self.send_reply(self.HSC_INFO_MSG, 0, module) self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemuwrapper_cmd_list(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_cmd_list(%s)" % str(data)) module, = data if not module in self.modules.keys(): self.send_reply(self.HSC_ERR_UNK_MODULE, 1, "unknown module '%s'" % module) return for command in self.modules[module].keys(): self.send_reply(self.HSC_INFO_MSG, 0, "%s (min/max args: %d/%d)" % \ (command, self.modules[module][command][0], self.modules[module][command][1]) ) self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemuwrapper_qemu_path(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_qemu_path(%s)" % str(data)) qemu_path, = data try: qemu_path = os.path.normpath(qemu_path) os.access(qemu_path, os.F_OK) global QEMU_PATH QEMU_PATH = qemu_path print "Qemu path is now %s" % QEMU_PATH for qemu_name in QEMU_INSTANCES.keys(): QEMU_INSTANCES[qemu_name].bin = os.path.join(os.getcwdu(), QEMU_INSTANCES[qemu_name].name) self.send_reply(self.HSC_INFO_OK, 1, "OK") except OSError, e: self.send_reply(self.HSC_ERR_INV_PARAM, 1, "access: %s" % e.strerror) def do_qemuwrapper_qemu_img_path(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_qemu_img_path(%s)" % str(data)) qemu_img_path, = data try: qemu_img_path = os.path.normpath(qemu_img_path) os.access(qemu_img_path, os.F_OK) global QEMU_IMG_PATH QEMU_IMG_PATH = qemu_img_path print "Qemu-img path is now %s" % QEMU_IMG_PATH for qemu_name in QEMU_INSTANCES.keys(): QEMU_INSTANCES[qemu_name].img_bin = os.path.join(os.getcwdu(), QEMU_INSTANCES[qemu_name].name) self.send_reply(self.HSC_INFO_OK, 1, "OK") except OSError, e: self.send_reply(self.HSC_ERR_INV_PARAM, 1, "access: %s" % e.strerror) def do_qemuwrapper_working_dir(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_working_dir(%s)" % str(data)) working_dir, = data try: working_dir = os.path.normpath(working_dir) os.chdir(working_dir) global WORKDIR WORKDIR = working_dir print "Working directory is now %s" % WORKDIR for qemu_name in QEMU_INSTANCES.keys(): QEMU_INSTANCES[qemu_name].workdir = os.path.join(working_dir, QEMU_INSTANCES[qemu_name].name) self.send_reply(self.HSC_INFO_OK, 1, "OK") except OSError, e: self.send_reply(self.HSC_ERR_INV_PARAM, 1, "chdir: %s" % e.strerror) def do_qemuwrapper_reset(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_reset(%s)" % str(data)) cleanup() self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemuwrapper_close(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_close(%s)" % str(data)) self.send_reply(self.HSC_INFO_OK, 1, "OK") self.close_connection = 1 def do_qemuwrapper_stop(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemuwrapper_stop(%s)" % str(data)) self.send_reply(self.HSC_INFO_OK, 1, "OK") self.close_connection = 1 self.server.stop() def do_qemu_version(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_version(%s)" % str(data)) self.send_reply(self.HSC_INFO_OK, 1, __version__) def __qemu_create(self, dev_type, name): debugmsg(2, "QemuWrapperRequestHandler::__qemu_create(dev_type=%s, name=%s)" % (str(dev_type), str(name))) try: devclass = self.qemu_classes[dev_type] except KeyError: print >> sys.stderr, "No device type %s" % dev_type return 1 if name in QEMU_INSTANCES.keys(): print >> sys.stderr, "Unable to create Qemu instance", name print >> sys.stderr, "%s already exists" % name return 1 qemu_instance = devclass(name) try: qemu_instance.create() except OSError, e: print >> sys.stderr, "Unable to create Qemu instance", name print >> sys.stderr, e return 1 QEMU_INSTANCES[name] = qemu_instance return 0 def do_qemu_create(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_create(%s)" % str(data)) dev_type, name = data if self.__qemu_create(dev_type, name) == 0: self.send_reply(self.HSC_INFO_OK, 1, "Qemu '%s' created" % name) else: self.send_reply(self.HSC_ERR_CREATE, 1, "unable to create Qemu instance '%s'" % name) def __qemu_delete(self, name): debugmsg(2, "QemuWrapperRequestHandler::__qemu_delete(%s)" % str(name)) if not name in QEMU_INSTANCES.keys(): return 1 if QEMU_INSTANCES[name].process and not QEMU_INSTANCES[name].stop(): return 1 del QEMU_INSTANCES[name] return 0 def do_qemu_delete(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_delete(%s)" % str(data)) name, = data if self.__qemu_delete(name) == 0: self.send_reply(self.HSC_INFO_OK, 1, "Qemu '%s' deleted" % name) else: self.send_reply(self.HSC_ERR_DELETE, 1, "unable to delete Qemu instance '%s'" % name) def do_qemu_setattr(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_setattr(%s)" % str(data)) name, attr, value = data try: instance = QEMU_INSTANCES[name] except KeyError: self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return if not attr in instance.valid_attr_names: self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "Cannot set attribute '%s' for '%s" % (attr, name)) return if attr in ("image", "initrd", "kernel", "image1", "image2"): value = os.path.normpath(value) print >> sys.stderr, '!! %s.%s = %s' % (name, attr, value) setattr(QEMU_INSTANCES[name], attr, value) self.send_reply(self.HSC_INFO_OK, 1, "%s set for '%s'" % (attr, name)) def do_qemu_create_nic(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_create_nic(%s)" % str(data)) name, vlan, mac = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return QEMU_INSTANCES[name].nic[int(vlan)] = mac self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemu_create_udp(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_create_udp(%s)" % str(data)) name, vlan, saddr, sport, daddr, dport = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return udp_connection = UDPConnection(saddr, sport, daddr, dport) udp_connection.resolve_names() QEMU_INSTANCES[name].udp[int(vlan)] = udp_connection self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemu_delete_udp(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_delete_udp(%s)" % str(data)) name, vlan = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return if QEMU_INSTANCES[name].udp.has_key(int(vlan)): del QEMU_INSTANCES[name].udp[int(vlan)] self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemu_create_capture(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_create_capture(%s)" % str(data)) name, vlan, path = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return QEMU_INSTANCES[name].capture[int(vlan)] = os.path.normpath(path) self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemu_delete_capture(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_delete_capture(%s)" % str(data)) name, vlan = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return if QEMU_INSTANCES[name].capture.has_key(int(vlan)): del QEMU_INSTANCES[name].capture[int(vlan)] self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemu_start(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_start(%s)" % str(data)) name, = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return if not QEMU_INSTANCES[name].start(): self.send_reply(self.HSC_ERR_START, 1, "unable to start instance '%s'" % name) else: self.send_reply(self.HSC_INFO_OK, 1, "Qemu '%s' started" % name) def do_qemu_stop(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_stop(%s)" % str(data)) name, = data if not QEMU_INSTANCES[name].process: self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return if not QEMU_INSTANCES[name].stop(): self.send_reply(self.HSC_ERR_STOP, 1, "unable to stop instance '%s'" % name) else: self.send_reply(self.HSC_INFO_OK, 1, "Qemu '%s' stopped" % name) def do_qemu_clean(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_clean(%s)" % str(data)) name, = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return QEMU_INSTANCES[name].clean() self.send_reply(self.HSC_INFO_OK, 1, "OK") def do_qemu_unbase(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_unbase(%s)" % str(data)) name, = data if not name in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % name) return QEMU_INSTANCES[name].unbase_disk() self.send_reply(self.HSC_INFO_OK, 1, "OK") # QEMU MONITOR MODE def do_qemu_monitor(self, data): debugmsg(2, "QemuWrapperRequestHandler::do_qemu_monitor(%s)" % (str(data))) name, command = data command += "\n" if not QEMU_INSTANCES[name].process: self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s', is it started?" % name) return if bool(QEMU_INSTANCES[name].monitor) == False: self.send_reply(self.HSC_ERR_UNK_CMD, 1, "Monitor mode is not activated for Qemu '%s'" % name) return # send the command to qemu monitor mode QEMU_INSTANCES[name].monitor_conn.send(command) output = '' while True: try: select.select([QEMU_INSTANCES[name].monitor_conn], [], [], 1) output += QEMU_INSTANCES[name].monitor_conn.recv(512) except: break output = output.replace("\r", "") # remove the first line (trash input and ESC sequence) output = output[output.find("\n") + 1:] # remove the qemu prompt output = output[:-9] # Serialize newlines: can only send a single line output = output.replace("\n", '\n') # Some commands don't generate any output, means it's OK if len(output) == 0: output = 'OK' self.send_reply(self.HSC_INFO_OK, 1, output) def do_qemu_rename(self, data): #FIXME: non-working code debugmsg(2, "QemuWrapperRequestHandler::do_qemu_rename(%s)" % str(data)) oldname, newname = data if not oldname in QEMU_INSTANCES.keys(): self.send_reply(self.HSC_ERR_UNK_OBJ, 1, "unable to find Qemu '%s'" % oldname) return QEMU_INSTANCES[newname] = QEMU_INSTANCES[oldname] QEMU_INSTANCES[newname].name = newname global WORKDIR new_workdir = os.path.join(WORKDIR, newname) try: shutil.move(QEMU_INSTANCES[oldname].workdir, new_workdir) except OSError, e: self.send_reply(self.HSC_ERR_INV_PARAM, 1, "rename: %s" % e.strerror) self.workdir = new_workdir del QEMU_INSTANCES[oldname] self.send_reply(self.HSC_INFO_OK, 1, "Qemu '%s' renamed to '%s'" % (oldname, newname)) class DaemonThreadingMixIn(SocketServer.ThreadingMixIn): daemon_threads = True class QemuWrapperServer(DaemonThreadingMixIn, SocketServer.TCPServer): allow_reuse_address = True def __init__(self, server_address, RequestHandlerClass): debugmsg(2, "QemuWrapperServer::__init__()") global FORCE_IPV6 if server_address[0].__contains__(':'): FORCE_IPV6 = True if FORCE_IPV6: # IPv6 address support self.address_family = socket.AF_INET6 SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass) self.stopping = threading.Event() self.pause = 0.1 def serve_forever(self): while not self.stopping.isSet(): if select.select([self.socket], [], [], self.pause)[0]: self.handle_request() cleanup() def stop(self): self.stopping.set() def cleanup(): print "Shutdown in progress..." for name in QEMU_INSTANCES.keys(): if QEMU_INSTANCES[name].process: QEMU_INSTANCES[name].stop() del QEMU_INSTANCES[name] print "Shutdown completed." def main(): debugmsg(2, "qemuwrapper.py main()") global IP from optparse import OptionParser usage = "usage: %prog [--listen ] [--port ] [--forceipv6 false] [--no-path-check]" parser = OptionParser(usage, version="%prog " + __version__) parser.add_option("-l", "--listen", dest="host", help="IP address or hostname to listen on (default is to listen on all interfaces)") parser.add_option("-p", "--port", type="int", dest="port", help="Port number (default is 10525)") parser.add_option("-w", "--workdir", dest="wd", help="Working directory (default is current directory)") parser.add_option("-6", "--forceipv6", dest="force_ipv6", help="Force IPv6 usage (default is false; i.e. IPv4)") parser.add_option("-n", "--no-path-check", action="store_true", dest="no_path_check", default=False, help="No path check for Qemu and Qemu-img") try: (options, args) = parser.parse_args() except SystemExit: sys.exit(1) if not options.no_path_check: try: p = subprocess.Popen([QEMU_PATH]) p.terminate() print "Qemu path (%s) is valid" % QEMU_PATH except OSError, e: print >> sys.stderr, "Unable to start Qemu:", e if not os.path.exists(QEMU_PATH): print >> sys.stderr, "Path to Qemu seems to be invalid, please check. Current path is", QEMU_PATH sys.exit(1) try: p = subprocess.Popen([QEMU_IMG_PATH]) p.terminate() print "Qemu-img path (%s) is valid" % QEMU_IMG_PATH except OSError, e: print >> sys.stderr, "Unable to start Qemu-img:", e if not os.path.exists(QEMU_IMG_PATH): print >> sys.stderr, "Path to Qemu seems invalid, please check. Current path is", QEMU_IMG_PATH sys.exit(1) if options.host and options.host != '0.0.0.0': host = options.host IP = host else: host = IP if options.port: port = options.port global PORT PORT = port else: port = PORT if options.wd: global WORKDIR WORKDIR = options.wd if options.force_ipv6 and not (options.force_ipv6.lower().__contains__("false") or options.force_ipv6.__contains__("0")): global FORCE_IPV6 FORCE_IPV6 = options.force_ipv6 server = QemuWrapperServer((host, port), QemuWrapperRequestHandler) print "Qemu TCP control server started (port %d)." % port if FORCE_IPV6: LISTENING_MODE = "Listening in IPv6 mode" else: LISTENING_MODE = "Listening" if IP: print "%s on %s" % (LISTENING_MODE, IP) else: print "%s on all network interfaces" % LISTENING_MODE try: server.serve_forever() except KeyboardInterrupt: cleanup() if __name__ == '__main__': print "Qemu Emulator Wrapper (version %s)" % __version__ print "Copyright (c) 2007-2011 Thomas Pani & Jeremy Grossmann" print sys.stdout.flush() if platform.system() == 'Windows': try: import pywintypes, win32api, win32con, win32process except ImportError: print >> sys.stderr, "You need pywin32 installed to run qemuwrapper!" sys.exit(1) main() gns3-legacy-GNS3-0.8.6/qemuwrapper/startqemuwrapper.bat000077500000000000000000000000661223163545200230470ustar00rootroot00000000000000C:\Python26\python.exe qemuwrapper.py -p 10525 pausegns3-legacy-GNS3-0.8.6/securecrt.vbs000077500000000000000000000027651223163545200171040ustar00rootroot00000000000000#$Language = "VBScript" #$Interface = "1.0" crt.Screen.Synchronous = False 'To be used only if those functions are called: "WaitForString, WaitForStrings, ReadString, or WaitForCursor" (Performance issue if "True") Sub main After_Connect() 'Do the magic for the first time :D Do 'Create a loop that will stay active and "guard" the connection status ;) crt.Sleep 1000 'Activate it every 1 second If Not crt.Session.Connected Then 'If the connection is down try to fix it, but after waiting 5 seconds... For i = 5 To 1 step -1 'Show the timeout in window title, while waiting 5 seconds crt.Window.Caption = crt.Arguments(0) & " - Reconnect in: " & i & "s" crt.Sleep 1000 Next On Error Resume Next 'Ignore errors when can't connect! crt.Session.Connect 'Will perform a reconnect After_Connect() 'Used again after the connection is reestablish End If Loop End Sub Function After_Connect() crt.Window.Caption = crt.Arguments(0) 'This can be done by CLI argument /N (from v6.7.5) crt.Sleep 1000 'Wait a second for the connection to be established 'crt.Screen.Send chr(13) & chr(10) 'Sends a new line into the terminal crt.Screen.Send vbcrlf 'Sends a new line into the terminal (Another way to do this) End Function gns3-legacy-GNS3-0.8.6/setup.py000066400000000000000000000345501223163545200160750ustar00rootroot00000000000000#!/usr/bin/env python # vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: """Setup script for the GNS3 packages.""" import sys, os, shutil, platform sys.path.append('./src') from distutils.core import setup, Extension from glob import glob # current version of GNS3 VERSION = "0.8.6" try: # delete previous build if os.access('./build', os.F_OK): shutil.rmtree('./build') if os.access('./dist', os.F_OK): shutil.rmtree('./dist') except: pass if sys.platform.startswith('win'): import struct bitness = struct.calcsize("P") * 8 # Set the path to Qt plugins directory if bitness == 32: # for 32-bit python PYQT4_DIR = r'C:\Python27-32bit\Lib\site-packages\PyQt4' elif bitness == 64: # for 64-bit python PYQT4_DIR = r'C:\Python27-64bit\Lib\site-packages\PyQt4' else: # should seriously not happen ... print "Fatal error: bitness cannot be detected!" sys.exit(1) try: import py2exe except ImportError: raise RuntimeError, "Cannot import py2exe" data_files = [("Langs", glob(r'src\GNS3\Langs\*.qm')), ('src\GNS3\Dynagen\configspec'), ('COPYING'), ('baseconfig.txt'), ('baseconfig_sw.txt'), (PYQT4_DIR + r'\QtXml4.dll'), ("iconengines", glob(PYQT4_DIR + r'\plugins\iconengines\*.dll')), ("imageformats", glob(PYQT4_DIR + r'\plugins\imageformats\*.dll'))] # Settings for py2exe, packages values are to tell to py2exe about hidden imports setup(windows=[{"script":"gns3.pyw", "icon_resources": [(1, r'..\gns3_icon.ico')]}], zipfile=None, data_files=data_files, options={"py2exe": { "includes": ["sip"], "dll_excludes": ["MSVCP90.dll", "POWRPROF.dll", "MSWSOCK.dll"], "optimize": 1, # CLSID for VirtualBox COM (http://www.py2exe.org/index.cgi/IncludingTypelibs) # Do not need this anymore because the typelib wrapper is dynamically generated. #"typelibs": [('{46137EEC-703B-4FE5-AFD4-7C9BBBBA0259}',0,1,3)], # "packages": ["GNS3.Ui.ConfigurationPages.Page_ATMSW", "GNS3.Ui.ConfigurationPages.Page_ATMBR", "GNS3.Ui.ConfigurationPages.Page_Cloud", "GNS3.Ui.ConfigurationPages.Page_ETHSW", "GNS3.Ui.ConfigurationPages.Page_Hub", "GNS3.Ui.ConfigurationPages.Page_FRSW", "GNS3.Ui.ConfigurationPages.Page_IOSRouter", "GNS3.Ui.ConfigurationPages.Page_PIX", "GNS3.Ui.ConfigurationPages.Page_ASA", "GNS3.Ui.ConfigurationPages.Page_AWP", "GNS3.Ui.ConfigurationPages.Page_JunOS", "GNS3.Ui.ConfigurationPages.Page_IDS", "GNS3.Ui.ConfigurationPages.Page_Qemu", "GNS3.Ui.ConfigurationPages.Page_VirtualBox", "GNS3.Ui.ConfigurationPages.Page_DecorativeNode", "GNS3.Ui.ConfigurationPages.Page_PreferencesDynamips", "GNS3.Ui.ConfigurationPages.Page_PreferencesGeneral", "GNS3.Ui.ConfigurationPages.Page_PreferencesCapture", "GNS3.Ui.ConfigurationPages.Page_PreferencesQemu", "GNS3.Ui.ConfigurationPages.Page_PreferencesVirtualBox", "GNS3.Ui.ConfigurationPages.Page_PreferencesDeployementWizard", ] } } ) # Compile qemuwrapper sys.path.append('./qemuwrapper') setup(console=['qemuwrapper/qemuwrapper.py'], options = {"py2exe": {"dll_excludes": ["POWRPROF.dll", "MSWSOCK.dll"]}}, zipfile=None) # Compile vboxwrapper sys.path.append('./vboxwrapper') setup(console=['vboxwrapper/vboxwrapper.py'], options = {"py2exe": {"dll_excludes": ["POWRPROF.dll", "MSWSOCK.dll"]}}, zipfile=None) elif sys.platform.startswith('darwin'): import setuptools QTDIR = r'/Developer/Applications/Qt' data_files = [('', glob(r'src/GNS3/Langs/*.qm')), ('src/GNS3/Dynagen/configspec'), ('qemuwrapper/qemuwrapper.py'), # ('vboxwrapper/vboxwrapper.py'), # ('vboxwrapper/vboxcontroller_4_1.py'), # ('vboxwrapper/tcp_pipe_proxy.py'), ('baseconfig.txt'), ('baseconfig_sw.txt'), ('COPYING'), ("../PlugIns/iconengines", [QTDIR + r'/plugins/iconengines/libqsvgicon.dylib']), ("../PlugIns/imageformats", [QTDIR + r'/plugins/imageformats/libqgif.dylib', QTDIR + r'/plugins/imageformats/libqjpeg.dylib', QTDIR + r'/plugins/imageformats/libqsvg.dylib']) ] APP = ['gns3.pyw'] OPTIONS = {'argv_emulation': False, 'semi_standalone': True, 'site_packages': True, 'optimize': 1, 'iconfile': 'gns3.icns', 'includes': ['sip', 'PyQt4.QtCore', 'PyQt4.QtGui', 'PyQt4.QtSvg', 'PyQt4.QtXml', 'PyQt4.QtNetwork', 'PyQt4.QtWebKit', 'GNS3.Ui.ConfigurationPages.Page_ATMSW', 'GNS3.Ui.ConfigurationPages.Page_ATMBR', 'GNS3.Ui.ConfigurationPages.Page_Cloud', 'GNS3.Ui.ConfigurationPages.Page_ETHSW', 'GNS3.Ui.ConfigurationPages.Page_Hub', 'GNS3.Ui.ConfigurationPages.Page_FRSW', 'GNS3.Ui.ConfigurationPages.Page_IOSRouter', 'GNS3.Ui.ConfigurationPages.Page_PIX', 'GNS3.Ui.ConfigurationPages.Page_ASA', 'GNS3.Ui.ConfigurationPages.Page_AWP', 'GNS3.Ui.ConfigurationPages.Page_JunOS', 'GNS3.Ui.ConfigurationPages.Page_IDS', 'GNS3.Ui.ConfigurationPages.Page_Qemu', 'GNS3.Ui.ConfigurationPages.Page_VirtualBox', 'GNS3.Ui.ConfigurationPages.Page_DecorativeNode', 'GNS3.Ui.ConfigurationPages.Page_PreferencesDynamips', 'GNS3.Ui.ConfigurationPages.Page_PreferencesGeneral', 'GNS3.Ui.ConfigurationPages.Page_PreferencesCapture', 'GNS3.Ui.ConfigurationPages.Page_PreferencesQemu', 'GNS3.Ui.ConfigurationPages.Page_PreferencesVirtualBox', 'GNS3.Ui.ConfigurationPages.Page_PreferencesDeployementWizard', ], 'plist' : { 'CFBundleName': 'GNS3', 'CFBundleDisplayName': 'GNS3', 'CFBundleGetInfoString' : 'GNS3, Graphical Network Simulator', 'CFBundleIdentifier':'net.gns3', 'CFBundleShortVersionString':VERSION, 'CFBundleVersion': 'GNS3 ' + VERSION, 'LSMinimumSystemVersion':'10.5', 'LSMultipleInstancesProhibited':'true', 'NSHumanReadableCopyright':'GNU General Public License (GPL), Jeremy Grossmann', 'CFBundleDocumentTypes': [{ 'CFBundleTypeExtensions': ['net'], 'CFBundleTypeName': 'GNS3 Topology', 'CFBundleTypeRole': 'Editor', 'CFBundleTypeIconFile': 'gns3.icns', }] } } setuptools.setup( name='GNS3', app=APP, data_files=data_files, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) print '*** Removing Qt debug libs ***' for root, dirs, files in os.walk('./dist'): for file in files: if 'debug' in file: print 'Deleting', file os.remove(os.path.join(root,file)) os.chdir('dist') print '*** Patching __boot__.py ***' # This adds sys.path = [os.path.join(os.environ['RESOURCEPATH'], 'lib', 'python2.x', 'lib-dynload')] + sys.path # to dist/GNS3.app/Contents/Resources/__boot__.py os.system('cp ../__boot__.py ./GNS3.app/Contents/Resources') print '*** Installing qt.conf ***' os.system('cp ../qt.conf ./GNS3.app/Contents/Resources') print '*** Installing Dynamips ***' os.system('cp ../dynamips-0.2.8-RC3-community-OSX.intel64.bin ./GNS3.app/Contents/Resources') os.system('cp ../dynamips-0.2.10-OSX.intel64.bin ./GNS3.app/Contents/Resources') print '*** Installing Qemu 0.11.0 ***' os.system('mkdir -p ./GNS3.app/Contents/Resources/Qemu-0.11.0') os.system('cp -R ../Qemu-0.11.0/* ./GNS3.app/Contents/Resources/Qemu-0.11.0') print '*** Installing Qemu 0.14.1 ***' os.system('mkdir -p ./GNS3.app/Contents/Resources/Qemu-0.14.1') os.system('cp -R ../Qemu-0.14.1/* ./GNS3.app/Contents/Resources/Qemu-0.14.1') print '*** Installing VPCS ***' os.system('cp ../vpcs ./GNS3.app/Contents/Resources') print '*** Applying permissions ***' #os.chmod('./GNS3.app/Contents/Resources/vboxwrapper.py', 0755) os.chmod('./GNS3.app/Contents/Resources/qemuwrapper.py', 0755) os.chmod('./GNS3.app/Contents/Resources/Qemu-0.11.0/bin/qemu', 0755) os.chmod('./GNS3.app/Contents/Resources/Qemu-0.11.0/bin/qemu-img', 0755) os.chmod('./GNS3.app/Contents/Resources/Qemu-0.14.1/bin/qemu-system-i386', 0755) os.chmod('./GNS3.app/Contents/Resources/Qemu-0.14.1/bin/qemu-system-x86_64', 0755) os.chmod('./GNS3.app/Contents/Resources/Qemu-0.14.1/bin/qemu-img', 0755) os.chmod('./GNS3.app/Contents/Resources/dynamips-0.2.8-RC3-community-OSX.intel64.bin', 0755) os.chmod('./GNS3.app/Contents/Resources/dynamips-0.2.10-OSX.intel64.bin', 0755) os.chmod('./GNS3.app/Contents/Resources/vpcs', 0755) print '*** Compiling & installing VBoxWrapper ***' setuptools.setup(name='VBoxWrapper', app=['../vboxwrapper/vboxwrapper.py'], options={'py2app': {'semi_standalone': True, 'site_packages': True, 'optimize': 1}}, setup_requires=['py2app']) os.system('cp -R ./dist/VBoxWrapper.app/ ./GNS3.app/Contents/Resources/VBoxWrapper') print '*** Making DMG ***' os.system("/usr/bin/macdeployqt GNS3.app -dmg -no-plugins") else: def normalizeWhitespace(s): return ' '.join(s.split()) if platform.system() == 'Linux': wrapper_dir = '/usr/share/gns3/' else: wrapper_dir = '/usr/local/libexec/gns3/' setup( # Distribution meta-data name = 'GNS3', version = VERSION, description = 'Network simulator that allows simulation of advanced networks', long_description = normalizeWhitespace(""" Based on Dynamips, an IOS emulator which allows users to run IOS binary images from Cisco Systems and Qemu/VirtualBox for emulating PIX & ASA firewalls as well as Juniper routers and Cisco IDS/IPS. Important: binary images are not part of this package."""), license = 'GNU General Public License (GPLv2)', author = 'Jeremy Grossmann', author_email = 'package-maintainer@gns3.net', maintainer = 'Jeremy Grossmann', maintainer_email = 'package-maintainer@gns3.net', keywords = ['network', 'simulator', 'cisco', 'junos', 'ios'], platforms = [ 'Windows', 'Linux', 'BSD', 'Mac OS X' ], url = 'http://www.gns3.net/', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: X11 Applications :: Qt', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Natural Language :: English', 'Programming Language :: Python', 'Topic :: System :: Networking'], scripts = [ 'gns3' ], package_dir = { '': 'src' }, packages = [ 'GNS3', 'GNS3.Awp', 'GNS3.Config', 'GNS3.Globals', 'GNS3.Dynagen', 'GNS3.Defaults', 'GNS3.External', 'GNS3.Export', 'GNS3.Link', 'GNS3.Node', 'GNS3.Ui', 'GNS3.Ui.ConfigurationPages', 'GNS3.Langs'], package_data = { 'GNS3': ['Langs/*.qm', 'Dynagen/configspec'] }, data_files = [ (wrapper_dir, ['qemuwrapper/qemuwrapper.py', 'vboxwrapper/vboxcontroller_4_1.py', 'vboxwrapper/vboxwrapper.py', 'vboxwrapper/tcp_pipe_proxy.py']), ('/usr/local/share/examples/gns3/', ['baseconfig.txt', 'baseconfig_sw.txt']), ('/usr/local/share/doc/gns3/', ['README', 'COPYING', 'CHANGELOG']), ('/usr/local/share/man/man1/', ['docs/man/gns3.1'])] ) gns3-legacy-GNS3-0.8.6/src/000077500000000000000000000000001223163545200151435ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/src/GNS3/000077500000000000000000000000001223163545200156555ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/src/GNS3/Annotation.py000066400000000000000000000106621223163545200203460ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from PyQt4 import QtGui, QtCore import GNS3.Globals as globals import GNS3.UndoFramework as undo class Annotation(QtGui.QGraphicsTextItem): """ Text annotation for the topology """ def __init__(self, parent=None): QtGui.QGraphicsTextItem.__init__(self, parent) self.setFont(QtGui.QFont("TypeWriter", 10, QtGui.QFont.Bold)) self.setFlag(self.ItemIsMovable) self.setFlag(self.ItemIsSelectable) self.rotation = 0 #self.autoGenerated = False self.deviceName = None self.deviceIf = None self.setZValue(2) self.prevText = None def keyPressEvent(self, event): key = event.key() modifiers = event.modifiers() if (key in (QtCore.Qt.Key_P, QtCore.Qt.Key_Plus, QtCore.Qt.Key_Equal) and modifiers & QtCore.Qt.AltModifier) \ or (key == QtCore.Qt.Key_Plus and modifiers & QtCore.Qt.AltModifier and modifiers & QtCore.Qt.KeypadModifier) \ and self.rotation > -360: if self.rotation: self.rotate(-self.rotation) self.rotation -= 1 self.rotate(self.rotation) elif (key in (QtCore.Qt.Key_M, QtCore.Qt.Key_Minus) and modifiers & QtCore.Qt.AltModifier) \ or (key == QtCore.Qt.Key_Minus and modifiers & QtCore.Qt.AltModifier and modifiers & QtCore.Qt.KeypadModifier) \ and self.rotation < 360: if self.rotation: self.rotate(-self.rotation) self.rotation += 1 self.rotate(self.rotation) else: QtGui.QGraphicsTextItem.keyPressEvent(self, event) def editText(self): self.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction) self.setSelected(True) self.setFocus() cursor = self.textCursor() cursor.select(QtGui.QTextCursor.Document) self.setTextCursor(cursor) def mouseDoubleClickEvent(self, event): self.prevText = self.toPlainText() self.editText() def focusOutEvent(self, event): self.setFlag(QtGui.QGraphicsItem.ItemIsFocusable, False) # unselect text cursor = self.textCursor() if (cursor.hasSelection()): cursor.clearSelection() self.setTextCursor(cursor) self.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) if self.toPlainText().isEmpty(): globals.GApp.topology.removeItem(self) return if self.prevText and self.prevText != self.toPlainText(): # if self.autoGenerated: # self.autoGenerated = False command = undo.NewAnnotationText(self, self.prevText) globals.GApp.topology.undoStack.push(command) return QtGui.QGraphicsTextItem.focusOutEvent(self, event) def paint(self, painter, option, widget=None): QtGui.QGraphicsTextItem.paint(self, painter, option, widget) # Don't draw if not activated if globals.GApp.workspace.flg_showLayerPos == False: return # Show layer level of this node brect = self.boundingRect() # Don't draw if the object is too small ... if brect.width() < 20 or brect.height() < 20: return center = self.mapFromItem(self, brect.width() / 2.0, brect.height() / 2.0) painter.setBrush(QtCore.Qt.red) painter.setPen(QtCore.Qt.red) painter.drawRect((brect.width() / 2.0) - 10, (brect.height() / 2.0) - 10, 20, 20) painter.setPen(QtCore.Qt.black) painter.setFont(QtGui.QFont("TypeWriter", 14, QtGui.QFont.Bold)) zval = str(int(self.zValue())) painter.drawText(QtCore.QPointF(center.x() - 4, center.y() + 4), zval) gns3-legacy-GNS3-0.8.6/src/GNS3/Application.py000066400000000000000000001171671223163545200205070ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # import sys, os, time import GNS3.Globals as globals import GNS3.Config.Defaults as Defaults import GNS3.Dynagen.dynamips_lib as lib import GNS3.Dynagen.portTracker_lib as tracker from distutils.version import LooseVersion from PyQt4.QtGui import QApplication, QSplashScreen, QPixmap, QMessageBox, QStyleFactory from PyQt4.QtCore import Qt, QVariant, QSettings, QEventLoop from GNS3.Utils import Singleton, translate from GNS3.Workspace import Workspace from GNS3.Config.Objects import systemDynamipsConf, systemGeneralConf, systemCaptureConf, systemQemuConf, systemVBoxConf, systemDeployementWizardConf from GNS3.Globals.Symbols import SYMBOLS, SYMBOL_TYPES from GNS3.Config.Config import ConfDB, GNS_Conf from GNS3.HypervisorManager import HypervisorManager from GNS3.QemuManager import QemuManager from GNS3.VBoxManager import VBoxManager from GNS3.Translations import Translator from GNS3.DynagenSub import DynagenSub from GNS3.ProjectDialog import ProjectDialog from GNS3.Wizard import Wizard from __main__ import VERSION class Application(QApplication, Singleton): """ GNS3 Application instance Used for containing global app variable, windows are other global objects. """ def __init__(self): """ Initilize the application instance and register GApp variable to ourself """ # call parent contructor QApplication.__init__(self, sys.argv) self.__mainWindow = None self.__workspace = None self.__scene = None self.__topology = None self.__dynagen = None self.__HypervisorManager = None self.__QemuManager = None self.__VBoxManager = None # Dict for storing config self.__systconf = {} self.__projconf = {} self.__iosimages = {} self.__hypervisors = {} self.__libraries = {} self.__qemuimages = {} self.__vboximages = {} self.__piximages = {} self.__junosimages = {} self.__asaimages = {} self.__awprouterimages = {} self.__idsimages = {} self.__recentfiles = [] self.iosimages_ids = 0 self.hypervisors_ids = 0 self.qemuimages_ids = 0 self.vboximages_ids = 0 self.piximages_ids = 0 self.junosimages_ids = 0 self.asaimages_ids = 0 self.awprouterimages_ids = 0 self.idsimages_ids = 0 # set global app to ourself globals.GApp = self # Force SystemScope init file to Defaults.SysConfigDir if not sys.platform.startswith('win'): QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, Defaults.SysConfigDir) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, os.path.expanduser(Defaults.UsrConfigDir)) #self.setStyle(QStyleFactory.create("cleanlooks")) def __setMainWindow(self, mw): """ register the MainWindow instance """ self.__mainWindow = mw def __getMainWindow(self): """ return the MainWindow instance """ return self.__mainWindow mainWindow = property(__getMainWindow, __setMainWindow, doc='MainWindow instance') def __setWorkspace(self, wkspc): """ register the Workspace instance """ self.__workspace = wkspc def __getWorkspace(self): """ return the Workspace instance """ return self.__workspace workspace = property(__getWorkspace, __setWorkspace, doc='Workspace instance') def __setScene(self, scene): """ register the Scene instance """ self.__scene = scene def __getScene(self): """ return the Scene instance """ return self.__scene scene = property(__getScene, __setScene, doc='Scene instance') def __setTopology(self, topology): """ register the Topology instance """ self.__topology = topology def __getTopology(self): """ return the Topology instance """ return self.__topology topology = property(__getTopology, __setTopology, doc='Topology instance') def __setSystConf(self, systconf): """ register the systconf instance """ self.__systconf = systconf def __getSystConf(self): """ return the systconf instance """ return self.__systconf systconf = property(__getSystConf, __setSystConf, doc='System config instance') def __setIOSImages(self, iosimages): """ register the sysconf instance """ self.__iosimages = iosimages def __getIOSImages(self): """ return the sysconf instance """ return self.__iosimages iosimages = property(__getIOSImages, __setIOSImages, doc='IOS images dictionnary') def __setQemuImages(self, qemuimages): """ register the sysconf instance """ self.__qemuimages = qemuimages def __getQemuImages(self): """ return the sysconf instance """ return self.__qemuimages qemuimages = property(__getQemuImages, __setQemuImages, doc='Qemu images dictionnary') def __setVBoxImages(self, vboximages): """ register the sysconf instance """ self.__vboximages = vboximages def __getVBoxImages(self): """ return the sysconf instance """ return self.__vboximages vboximages = property(__getVBoxImages, __setVBoxImages, doc='VBox images dictionnary') def __setPIXImages(self, piximages): """ register the sysconf instance """ self.__piximages = piximages def __getPIXImages(self): """ return the sysconf instance """ return self.__piximages piximages = property(__getPIXImages, __setPIXImages, doc='PIX images dictionnary') def __setJunOSImages(self, junosimages): """ register the sysconf instance """ self.__junosimages = junosimages def __getJunOSImages(self): """ return the sysconf instance """ return self.__junosimages junosimages = property(__getJunOSImages, __setJunOSImages, doc='JunOS images dictionnary') def __setASAImages(self, asaimages): """ register the sysconf instance """ self.__asaimages = asaimages def __getASAImages(self): """ return the sysconf instance """ return self.__asaimages asaimages = property(__getASAImages, __setASAImages, doc='ASA images dictionnary') def __setAWPImages(self, awprouterimages): """ register the sysconf instance """ self.__awprouterimages = awprouterimages def __getAWPImages(self): """ return the sysconf instance """ return self.__awprouterimages awprouterimages = property(__getAWPImages, __setAWPImages, doc='AWP images dictionary') def __setIDSImages(self, idsimages): """ register the sysconf instance """ self.__idsimages = idsimages def __getIDSImages(self): """ return the sysconf instance """ return self.__idsimages idsimages = property(__getIDSImages, __setIDSImages, doc='IDS images dictionnary') def __setLibraries(self, libraries): """ register the sysconf instance """ self.__libraries = libraries def __getLibraries(self): """ return the sysconf instance """ return self.__libraries libraries = property(__getLibraries, __setLibraries, doc='Libraries dictionnary') def __setRecentFiles(self, recentfiles): """ register the sysconf instance """ self.__recentfiles = recentfiles def __getRecentFiles(self): """ return the sysconf instance """ return self.__recentfiles recentfiles = property(__getRecentFiles, __setRecentFiles, doc='Recent files array') def __setHypervisors(self, hypervisors): """ register the sysconf instance """ self.__hypervisors = hypervisors def __getHypervisors(self): """ return the sysconf instance """ return self.__hypervisors hypervisors = property(__getHypervisors, __setHypervisors, doc='Hypervisors dictionnary') def __setDynagen(self, dynagen): """ register the dynagen instance """ self.__dynagen = dynagen def __getDynagen(self): """ return the systconf instance """ return self.__dynagen dynagen = property(__getDynagen, __setDynagen, doc='Dynagen instance') def __setHypervisorManager(self, HypervisorManager): """ register the HypervisorManager instance """ self.__HypervisorManager = HypervisorManager def __getHypervisorManager(self): """ return the HypervisorManager instance """ return self.__HypervisorManager HypervisorManager = property(__getHypervisorManager, __setHypervisorManager, doc='HypervisorManager instance') def __setQemuManager(self, QemuManager): """ register the QemuManager instance """ self.__QemuManager = QemuManager def __getQemuManager(self): """ return the QemuManager instance """ return self.__QemuManager QemuManager = property(__getQemuManager, __setQemuManager, doc='QemuManager instance') def __setVBoxManager(self, VBoxManager): """ register the VBoxManager instance """ self.__VBoxManager = VBoxManager def __getVBoxManager(self): """ return the VBoxManager instance """ return self.__VBoxManager VBoxManager = property(__getVBoxManager, __setVBoxManager, doc='VBoxManager instance') def processSplashScreen(self): """ Processes the splash screen, Prints a loading picture before entering the application """ self.splashMessage = translate("Application", "Starting Graphical Network Simulator...") self.splashSleepTime = 1 self.splashPath = ':/images/logo_gns3_splash.png' pixmap = QPixmap(self.splashPath) self.splash = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint) self.splash.show() self.splash.showMessage(self.splashMessage, Qt.AlignRight | Qt.AlignTop, Qt.black) # make sure Qt really display the splash screen and message self.processEvents(QEventLoop.AllEvents, 500) time.sleep(self.splashSleepTime) self.splash.finish(self.__mainWindow) return def showTipsDialog(self): self.mainWindow.tips_dialog.setModal(True) self.mainWindow.tips_dialog.show() self.mainWindow.tips_dialog.loadWebPage() self.mainWindow.tips_dialog.raise_() self.mainWindow.tips_dialog.activateWindow() self.mainWindow.raise_() self.mainWindow.tips_dialog.raise_() def run(self, file): # Display splash screen while waiting for the application to open self.processSplashScreen() # Instantiation of Dynagen self.__dynagen = DynagenSub() self.systconf['dynamips'] = systemDynamipsConf() confo = self.systconf['dynamips'] confo.path = ConfDB().get('Dynamips/hypervisor_path', Defaults.DYNAMIPS_DEFAULT_PATH) confo.port = int(ConfDB().get('Dynamips/hypervisor_port', 7200)) confo.baseUDP = int(ConfDB().get('Dynamips/hypervisor_baseUDP', 10001)) confo.baseConsole = int(ConfDB().get('Dynamips/hypervisor_baseConsole', 2101)) confo.baseAUX = int(ConfDB().get('Dynamips/hypervisor_baseAUX', 2501)) confo.workdir = ConfDB().get('Dynamips/hypervisor_working_directory', Defaults.DYNAMIPS_DEFAULT_WORKDIR) confo.clean_workdir = ConfDB().value("Dynamips/clean_working_directory", QVariant(True)).toBool() confo.ghosting = ConfDB().value("Dynamips/dynamips_ghosting", QVariant(True)).toBool() confo.mmap = ConfDB().value("Dynamips/dynamips_mmap", QVariant(True)).toBool() confo.sparsemem = ConfDB().value("Dynamips/dynamips_sparsemem", QVariant(True)).toBool() confo.jitsharing = ConfDB().value("Dynamips/dynamips_jitsharing", QVariant(False)).toBool() if sys.platform.startswith('win'): confo.memory_limit = int(ConfDB().get("Dynamips/hypervisor_memory_usage_limit", 512)) else: confo.memory_limit = int(ConfDB().get("Dynamips/hypervisor_memory_usage_limit", 1024)) confo.udp_incrementation = int(ConfDB().get("Dynamips/hypervisor_udp_incrementation", 100)) confo.detected_version = ConfDB().get('Dynamips/detected_version', unicode('')) confo.import_use_HypervisorManager = ConfDB().value("Dynamips/hypervisor_manager_import", QVariant(True)).toBool() confo.HypervisorManager_binding = ConfDB().get('Dynamips/hypervisor_manager_binding', unicode('127.0.0.1')) confo.allocateHypervisorPerIOS = ConfDB().value("Dynamips/allocate_hypervisor_per_IOS", QVariant(True)).toBool() # Expand user home dir and environment variables confo.path = os.path.expandvars(os.path.expanduser(confo.path)) confo.workdir = os.path.expandvars(os.path.expanduser(confo.workdir)) # Qemu config self.systconf['qemu'] = systemQemuConf() confo = self.systconf['qemu'] confo.qemuwrapper_path = ConfDB().get('Qemu/qemuwrapper_path', Defaults.QEMUWRAPPER_DEFAULT_PATH) confo.qemuwrapper_workdir = ConfDB().get('Qemu/qemuwrapper_working_directory', Defaults.QEMUWRAPPER_DEFAULT_WORKDIR) confo.qemu_path = ConfDB().get('Qemu/qemu_path', Defaults.QEMU_DEFAULT_PATH) confo.qemu_img_path = ConfDB().get('Qemu/qemu_img_path', Defaults.QEMU_IMG_DEFAULT_PATH) confo.external_hosts = ConfDB().get('Qemu/external_hosts', unicode('127.0.0.1:10525')).split(',') confo.enable_QemuWrapperAdvOptions = ConfDB().value("Qemu/enable_QemuWrapperAdvOptions", QVariant(False)).toBool() confo.enable_QemuManager = ConfDB().value("Qemu/enable_QemuManager", QVariant(True)).toBool() confo.import_use_QemuManager = ConfDB().value("Qemu/qemu_manager_import", QVariant(True)).toBool() confo.send_path_external_QemuWrapper = ConfDB().value("Qemu/send_paths_external_Qemuwrapper", QVariant(False)).toBool() confo.QemuManager_binding = ConfDB().get('Qemu/qemu_manager_binding', unicode('127.0.0.1')) confo.qemuwrapper_port = int(ConfDB().get('Qemu/qemuwrapper_port', 10525)) confo.qemuwrapper_baseUDP = int(ConfDB().get('Qemu/qemuwrapper_baseUDP', 40000)) confo.qemuwrapper_baseConsole = int(ConfDB().get('Qemu/qemuwrapper_baseConsole', 3001)) # Expand user home dir and environment variables confo.qemuwrapper_path = os.path.expandvars(os.path.expanduser(confo.qemuwrapper_path)) confo.qemuwrapper_workdir = os.path.expandvars(os.path.expanduser(confo.qemuwrapper_workdir)) # VBox config self.systconf['vbox'] = systemVBoxConf() confo = self.systconf['vbox'] confo.vboxwrapper_path = ConfDB().get('VBox/vboxwrapper_path', Defaults.VBOXWRAPPER_DEFAULT_PATH) confo.vboxwrapper_workdir = ConfDB().get('VBox/vboxwrapper_working_directory', Defaults.VBOXWRAPPER_DEFAULT_WORKDIR) confo.external_hosts = ConfDB().get('VBox/external_hosts', unicode('127.0.0.1:11525')).split(',') confo.use_VBoxVmnames = ConfDB().value("VBox/use_VBoxVmnames", QVariant(True)).toBool() confo.enable_VBoxWrapperAdvOptions = ConfDB().value("VBox/enable_VBoxWrapperAdvOptions", QVariant(False)).toBool() confo.enable_VBoxAdvOptions = ConfDB().value("VBox/enable_VBoxAdvOptions", QVariant(False)).toBool() confo.enable_GuestControl = ConfDB().value("VBox/enable_GuestControl", QVariant(False)).toBool() confo.enable_VBoxManager = ConfDB().value("VBox/enable_VBoxManager", QVariant(True)).toBool() confo.import_use_VBoxManager = ConfDB().value("VBox/vbox_manager_import", QVariant(True)).toBool() confo.VBoxManager_binding = ConfDB().get('VBox/vbox_manager_binding', unicode('127.0.0.1')) confo.vboxwrapper_port = int(ConfDB().get('VBox/vboxwrapper_port', 11525)) confo.vboxwrapper_baseUDP = int(ConfDB().get('VBox/vboxwrapper_baseUDP', 20900)) confo.vboxwrapper_baseConsole = int(ConfDB().get('VBox/vboxwrapper_baseConsole', 3501)) # Expand user home dir and environment variables confo.vboxwrapper_path = os.path.expandvars(os.path.expanduser(confo.vboxwrapper_path)) confo.vboxwrapper_workdir = os.path.expandvars(os.path.expanduser(confo.vboxwrapper_workdir)) # Capture config self.systconf['capture'] = systemCaptureConf() confo = self.systconf['capture'] confo.workdir = ConfDB().get('Capture/working_directory', Defaults.CAPTURE_DEFAULT_WORKDIR) confo.cap_cmd = ConfDB().get('Capture/capture_reader_cmd', Defaults.CAPTURE_DEFAULT_CMD) confo.auto_start = ConfDB().value('Capture/auto_start_cmd', QVariant(False)).toBool() # Expand user home dir and environment variables confo.cap_cmd = os.path.expandvars(os.path.expanduser(confo.cap_cmd)) confo.workdir = os.path.expandvars(os.path.expanduser(confo.workdir)) # Deployement Wizard config self.systconf['deployement wizard'] = systemDeployementWizardConf() confo = self.systconf['deployement wizard'] confo.deployementwizard_path = ConfDB().get('DeployementWizard/deployementwizard_path', Defaults.DEPLOYEMENTWIZARD_DEFAULT_PATH) confo.deployementwizard_filename = ConfDB().get('DeployementWizard/deployementwizard_filename', unicode('Topology.pdf')) # Expand user home dir and environement variable confo.deployementwizard_path = os.path.expandvars(os.path.expanduser(confo.deployementwizard_path)) confo.deployementwizard_filename = os.path.expandvars(os.path.expanduser(confo.deployementwizard_filename)) # System general config self.systconf['general'] = systemGeneralConf() confo = self.systconf['general'] confo.lang = ConfDB().get('GNS3/lang', unicode('en')) confo.slow_start = int(ConfDB().get('GNS3/slow_start', 1)) confo.autosave = int(ConfDB().get('GNS3/autosave', 0)) confo.project_startup = ConfDB().value("GNS3/project_startup", QVariant(True)).toBool() confo.relative_paths = ConfDB().value("GNS3/relative_paths", QVariant(True)).toBool() confo.auto_screenshot = ConfDB().value("GNS3/auto_screenshot", QVariant(True)).toBool() if sys.platform.startswith('win'): confo.use_shell = ConfDB().value("GNS3/use_shell", QVariant(False)).toBool() else: confo.use_shell = ConfDB().value("GNS3/use_shell", QVariant(True)).toBool() confo.bring_console_to_front = ConfDB().value("GNS3/bring_console_to_front", QVariant(False)).toBool() confo.term_cmd = ConfDB().get('GNS3/console', Defaults.TERMINAL_DEFAULT_CMD) confo.term_serial_cmd = ConfDB().get('GNS3/serial_console', Defaults.TERMINAL_SERIAL_DEFAULT_CMD) confo.term_close_on_delete = ConfDB().value("GNS3/term_close_on_delete", QVariant(True)).toBool() confo.project_path = ConfDB().get('GNS3/project_directory', Defaults.PROJECT_DEFAULT_DIR) confo.ios_path = ConfDB().get('GNS3/ios_directory', Defaults.IOS_DEFAULT_DIR) confo.status_points = ConfDB().value("GNS3/gui_show_status_points", QVariant(True)).toBool() confo.manual_connection = ConfDB().value("GNS3/gui_use_manual_connection", QVariant(True)).toBool() confo.draw_selected_rectangle = ConfDB().value("GNS3/gui_draw_selected_rectangle", QVariant(False)).toBool() confo.scene_width = int(ConfDB().get('GNS3/scene_width', 2000)) confo.scene_height = int(ConfDB().get('GNS3/scene_height', 1000)) confo.console_delay = float(ConfDB().get('GNS3/console_delay', 1)) if sys.platform.startswith('win') or sys.platform.startswith('darwin'): # by default auto check for update only on Windows or OSX confo.auto_check_for_update = ConfDB().value("GNS3/auto_check_for_update", QVariant(True)).toBool() else: confo.auto_check_for_update = ConfDB().value("GNS3/auto_check_for_update", QVariant(False)).toBool() confo.last_check_for_update = int(ConfDB().get('GNS3/last_check_for_update', 0)) # Expand user home dir and environment variables confo.term_cmd = os.path.expandvars(os.path.expanduser(confo.term_cmd)) confo.project_path = os.path.expandvars(os.path.expanduser(confo.project_path)) confo.ios_path = os.path.expandvars(os.path.expanduser(confo.ios_path)) # Restore debug level globals.debugLevel = int(ConfDB().get('GNS3/debug_level', 0)) if globals.debugLevel == 1 or globals.debugLevel == 3: lib.setdebug(True) tracker.setdebug(True) # Now systGeneral settings are loaded, load the translator self.translator = Translator() self.translator.switchLangTo(self.systconf['general'].lang) # HypervisorManager if globals.GApp.systconf['dynamips'].path: self.__HypervisorManager = HypervisorManager() # QemuManager self.__QemuManager = QemuManager() # VBoxManager self.__VBoxManager = VBoxManager() GNS_Conf().VBOX_images() GNS_Conf().IOS_images() GNS_Conf().IOS_hypervisors() GNS_Conf().QEMU_images() GNS_Conf().PIX_images() GNS_Conf().JUNOS_images() GNS_Conf().ASA_images() GNS_Conf().AWP_images() GNS_Conf().IDS_images() GNS_Conf().Libraries() GNS_Conf().Symbols() GNS_Conf().RecentFiles() # Workspace create a ` Scene' object, # so it also set self.__topology self.__workspace = Workspace() # seems strange to have mainWindow = Workspace, but actually, # we don't use MDI style, so there not so much difference. self.__mainWindow = self.__workspace # In GNS3, the `scene' represent the widget where all graphical stuff # are done (drawing Node, Animation), and in Qt, it's the QGraphicsView # which handle all this stuff. self.__scene = self.__mainWindow.graphicsView # Restore the geometry & state of the GUI self.mainWindow.restoreGeometry(ConfDB().value("GUIState/Geometry").toByteArray()) self.mainWindow.restoreState(ConfDB().value("GUIState/State").toByteArray()) self.mainWindow.action_DisableMouseWheel.setChecked(ConfDB().value("GUIState/DisableMouseWheel", QVariant(False)).toBool()) self.mainWindow.action_ZoomUsingMouseWheel.setChecked(ConfDB().value("GUIState/ZoomUsingMouseWheel", QVariant(False)).toBool()) if self.mainWindow.tips_dialog: self.mainWindow.tips_dialog.checkBoxDontShowAgain.setChecked(ConfDB().value("GUIState/DoNotShowTipsDialog", QVariant(False)).toBool()) # By default, don't show the NodeTypes dock self.mainWindow.dockWidget_NodeTypes.setVisible(False) self.mainWindow.show() force_clear_configuration = True version = ConfDB().get('GNS3/version', '0.0.1') try: # trick to test old version format (integer), before 0.8.2.1 release int(version) except ValueError: force_clear_configuration = False #for future releases if LooseVersion(VERSION) > str(version): # reset the tips dialog if self.mainWindow.tips_dialog: self.mainWindow.tips_dialog.checkBoxDontShowAgain.setChecked(False) if force_clear_configuration: self.mainWindow.raise_() reply = QMessageBox.question(self.mainWindow, translate("Application", "GNS3 configuration file"), translate("Application", "You have installed a new GNS3 version.\nIt is recommended to clear your old configuration, do you want to proceed?"), QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: ConfDB().clear() c = ConfDB() c.set('GNS3/version', VERSION) c.sync() globals.recordConfiguration = False QMessageBox.information(self.mainWindow, translate("Application", "GNS3 configuration file"), translate("Application", "Configuration cleared!\nPlease restart GNS3")) else: # if we cannot find our config file, we start the Wizard dialog configFile = unicode(ConfDB().fileName(), 'utf-8', errors='replace') if not os.access(configFile, os.F_OK): dialog = Wizard(parent=self.mainWindow) dialog.show() self.mainWindow.centerDialog(dialog) dialog.raise_() dialog.activateWindow() self.mainWindow.raise_() dialog.raise_() else: if file: self.mainWindow.load_netfile(file, load_instructions=True) elif confo.project_startup and os.access(configFile, os.F_OK): dialog = ProjectDialog(parent=self.mainWindow, newProject=True) dialog.setModal(True) dialog.show() self.mainWindow.centerDialog(dialog) dialog.raise_() dialog.activateWindow() self.mainWindow.raise_() dialog.raise_() if self.mainWindow.tips_dialog and self.mainWindow.tips_dialog.checkBoxDontShowAgain.isChecked() == False: self.showTipsDialog() else: self.mainWindow.createProject((None, None, None, False, False)) self.mainWindow.raise_() if self.mainWindow.tips_dialog and self.mainWindow.tips_dialog.checkBoxDontShowAgain.isChecked() == False: self.showTipsDialog() retcode = QApplication.exec_() self.__HypervisorManager = None self.__QemuManager = None self.__VBoxManager = None if globals.recordConfiguration: # Save the geometry & state of the GUI ConfDB().set("GUIState/Geometry", self.mainWindow.saveGeometry()) ConfDB().set("GUIState/State", self.mainWindow.saveState()) ConfDB().set("GUIState/DisableMouseWheel", self.mainWindow.action_DisableMouseWheel.isChecked()) ConfDB().set("GUIState/ZoomUsingMouseWheel", self.mainWindow.action_ZoomUsingMouseWheel.isChecked()) if self.mainWindow.tips_dialog: ConfDB().set("GUIState/DoNotShowTipsDialog", self.mainWindow.tips_dialog.checkBoxDontShowAgain.isChecked()) self.syncConf() sys.exit(retcode) def syncConf(self): """ Sync current application config with config file (gns3.{ini,conf}) """ c = ConfDB() c.set('GNS3/version', VERSION) # Apply general settings confo = self.systconf['general'] c.set('GNS3/lang', confo.lang) c.set('GNS3/project_startup', confo.project_startup) c.set('GNS3/relative_paths', confo.relative_paths) c.set('GNS3/auto_screenshot', confo.auto_screenshot) c.set('GNS3/slow_start', confo.slow_start) c.set('GNS3/autosave', confo.autosave) c.set('GNS3/console', confo.term_cmd) c.set('GNS3/serial_console', confo.term_serial_cmd) c.set('GNS3/term_close_on_delete', confo.term_close_on_delete) c.set('GNS3/use_shell', confo.use_shell) c.set('GNS3/bring_console_to_front', confo.bring_console_to_front) c.set('GNS3/gui_show_status_points', confo.status_points) c.set('GNS3/gui_use_manual_connection', confo.manual_connection) c.set('GNS3/gui_draw_selected_rectangle', confo.draw_selected_rectangle) c.set('GNS3/project_directory', confo.project_path) c.set('GNS3/ios_directory', confo.ios_path) c.set('GNS3/scene_width', confo.scene_width) c.set('GNS3/scene_height', confo.scene_height) c.set('GNS3/auto_check_for_update', confo.auto_check_for_update) c.set('GNS3/last_check_for_update', confo.last_check_for_update) c.set('GNS3/console_delay', confo.console_delay) c.set('GNS3/debug_level', globals.debugLevel) # Dynamips settings confo = self.systconf['dynamips'] c.set('Dynamips/hypervisor_path', confo.path) c.set('Dynamips/hypervisor_port', confo.port) c.set('Dynamips/hypervisor_baseUDP', confo.baseUDP) c.set('Dynamips/hypervisor_baseConsole', confo.baseConsole) c.set('Dynamips/hypervisor_baseAUX', confo.baseAUX) c.set('Dynamips/hypervisor_working_directory', confo.workdir) c.set('Dynamips/clean_working_directory', confo.clean_workdir) c.set('Dynamips/dynamips_ghosting', confo.ghosting) c.set('Dynamips/dynamips_sparsemem', confo.sparsemem) c.set('Dynamips/dynamips_jitsharing', confo.jitsharing) c.set('Dynamips/dynamips_mmap', confo.mmap) c.set('Dynamips/hypervisor_memory_usage_limit', confo.memory_limit) c.set('Dynamips/detected_version', confo.detected_version) c.set('Dynamips/hypervisor_udp_incrementation', confo.udp_incrementation) c.set('Dynamips/hypervisor_manager_import', confo.import_use_HypervisorManager) c.set('Dynamips/allocate_hypervisor_per_IOS', confo.allocateHypervisorPerIOS) c.set('Dynamips/hypervisor_manager_binding', confo.HypervisorManager_binding) # Qemu config confo = self.systconf['qemu'] c.set('Qemu/qemuwrapper_path', confo.qemuwrapper_path) c.set('Qemu/qemuwrapper_working_directory', confo.qemuwrapper_workdir) c.set('Qemu/qemu_path', confo.qemu_path) c.set('Qemu/qemu_img_path', confo.qemu_img_path) external_hosts = ','.join(confo.external_hosts) c.set('Qemu/external_hosts', external_hosts) c.set('Qemu/enable_QemuWrapperAdvOptions', confo.enable_QemuWrapperAdvOptions) c.set('Qemu/enable_QemuManager', confo.enable_QemuManager) c.set('Qemu/qemu_manager_import', confo.import_use_QemuManager) c.set('Qemu/qemu_manager_binding', confo.QemuManager_binding) c.set('Qemu/send_paths_external_Qemuwrapper', confo.send_path_external_QemuWrapper) c.set('Qemu/qemuwrapper_port', confo.qemuwrapper_port) c.set('Qemu/qemuwrapper_baseUDP', confo.qemuwrapper_baseUDP) c.set('Qemu/qemuwrapper_baseConsole', confo.qemuwrapper_baseConsole) # VBox config confo = self.systconf['vbox'] c.set('VBox/vboxwrapper_path', confo.vboxwrapper_path) c.set('VBox/vboxwrapper_working_directory', confo.vboxwrapper_workdir) external_hosts = ','.join(confo.external_hosts) c.set('VBox/external_hosts', external_hosts) c.set('VBox/use_VBoxVmnames', confo.use_VBoxVmnames) c.set('VBox/enable_VBoxWrapperAdvOptions', confo.enable_VBoxWrapperAdvOptions) c.set('VBox/enable_VBoxAdvOptions', confo.enable_VBoxAdvOptions) c.set('VBox/enable_GuestControl', confo.enable_GuestControl) c.set('VBox/enable_VBoxManager', confo.enable_VBoxManager) c.set('VBox/vbox_manager_import', confo.import_use_VBoxManager) c.set('VBox/vbox_manager_binding', confo.VBoxManager_binding) c.set('VBox/vboxwrapper_port', confo.vboxwrapper_port) c.set('VBox/vboxwrapper_baseUDP', confo.vboxwrapper_baseUDP) c.set('VBox/vboxwrapper_baseConsole', confo.vboxwrapper_baseConsole) # Capture settings confo = self.systconf['capture'] c.set('Capture/working_directory', confo.workdir) c.set('Capture/capture_reader_cmd', confo.cap_cmd) c.set('Capture/auto_start_cmd', confo.auto_start) # Clear IOS.hypervisors, IOS.images and QEMU.images group c.beginGroup("IOS.images") c.remove("") c.endGroup() c.beginGroup("IOS.hypervisors") c.remove("") c.endGroup() c.beginGroup("QEMU.images") c.remove("") c.endGroup() c.beginGroup("VBOX.images") c.remove("") c.endGroup() c.beginGroup("PIX.images") c.remove("") c.endGroup() c.beginGroup("JUNOS.images") c.remove("") c.endGroup() c.beginGroup("ASA.images") c.remove("") c.endGroup() c.beginGroup("AWP.images") c.remove("") c.endGroup() c.beginGroup("IDS.images") c.remove("") c.endGroup() # Clear Symbol.libraries group c.beginGroup("Symbol.libraries") c.remove("") c.endGroup() # Clear Recent.files group c.beginGroup("Recent.files") c.remove("") c.endGroup() # Clear Symbol.libraries group c.beginGroup("Symbol.settings") c.remove("") c.endGroup() # IOS Images for (key, o) in self.__iosimages.iteritems(): basekey = "IOS.images/" + str(o.id) c.set(basekey + "/filename", o.filename) c.set(basekey + "/chassis", o.chassis) c.set(basekey + "/platform", o.platform) c.set(basekey + "/baseconfig", o.baseconfig) hypervisors = '' for hypervisor in o.hypervisors: hypervisors += hypervisor + ' ' c.set(basekey + "/hypervisors", hypervisors.strip()) c.set(basekey + "/default_ram", o.default_ram) c.set(basekey + "/idlepc", o.idlepc) c.set(basekey + "/idlemax", o.idlemax) c.set(basekey + "/idlesleep", o.idlesleep) c.set(basekey + "/default", o.default) # Hypervisors for (key, o) in self.__hypervisors.iteritems(): basekey = "IOS.hypervisors/" + str(o.id) c.set(basekey + "/host", o.host) c.set(basekey + "/port", o.port) c.set(basekey + "/working_directory", o.workdir) c.set(basekey + "/base_udp", o.baseUDP) c.set(basekey + "/base_console", o.baseConsole) c.set(basekey + "/base_aux", o.baseAUX) # Qemu images for (key, o) in self.__qemuimages.iteritems(): basekey = "QEMU.images/" + str(o.id) c.set(basekey + "/name", o.name) c.set(basekey + "/filename", o.filename) c.set(basekey + "/memory", o.memory) c.set(basekey + "/nic_nb", o.nic_nb) c.set(basekey + "/usermod", o.usermod) c.set(basekey + "/nic", o.nic) c.set(basekey + "/flavor", o.flavor) c.set(basekey + "/options", o.options) c.set(basekey + "/kvm", o.kvm) c.set(basekey + "/monitor", o.monitor) # VBox images for (key, o) in self.__vboximages.iteritems(): basekey = "VBOX.images/" + str(o.id) c.set(basekey + "/name", o.name) c.set(basekey + "/filename", o.filename) c.set(basekey + "/nic_nb", o.nic_nb) c.set(basekey + "/nic", o.nic) c.set(basekey + "/first_nic_managed", o.first_nic_managed) c.set(basekey + "/headless_mode", o.headless_mode) c.set(basekey + "/console_support", o.console_support) c.set(basekey + "/console_telnet_server", o.console_telnet_server) c.set(basekey + "/guestcontrol_user", o.guestcontrol_user) c.set(basekey + "/guestcontrol_password", o.guestcontrol_password) # PIX images for (key, o) in self.__piximages.iteritems(): basekey = "PIX.images/" + str(o.id) c.set(basekey + "/name", o.name) c.set(basekey + "/filename", o.filename) c.set(basekey + "/memory", o.memory) c.set(basekey + "/nic_nb", o.nic_nb) c.set(basekey + "/nic", o.nic) c.set(basekey + "/options", o.options) c.set(basekey + "/key", o.key) c.set(basekey + "/serial", o.serial) # JunOS images for (key, o) in self.__junosimages.iteritems(): basekey = "JUNOS.images/" + str(o.id) c.set(basekey + "/name", o.name) c.set(basekey + "/filename", o.filename) c.set(basekey + "/memory", o.memory) c.set(basekey + "/nic_nb", o.nic_nb) c.set(basekey + "/usermod", o.usermod) c.set(basekey + "/nic", o.nic) c.set(basekey + "/options", o.options) c.set(basekey + "/kvm", o.kvm) c.set(basekey + "/monitor", o.monitor) # ASA images for (key, o) in self.__asaimages.iteritems(): basekey = "ASA.images/" + str(o.id) c.set(basekey + "/name", o.name) c.set(basekey + "/memory", o.memory) c.set(basekey + "/nic_nb", o.nic_nb) c.set(basekey + "/usermod", o.usermod) c.set(basekey + "/nic", o.nic) c.set(basekey + "/options", o.options) c.set(basekey + "/kvm", o.kvm) c.set(basekey + "/monitor", o.monitor) c.set(basekey + "/initrd", o.initrd) c.set(basekey + "/kernel", o.kernel) c.set(basekey + "/kernel_cmdline", o.kernel_cmdline) # AWP images for (key, o) in self.__awprouterimages.iteritems(): basekey = "AWP.images/" + str(o.id) c.set(basekey + "/name", o.name) c.set(basekey + "/memory", o.memory) c.set(basekey + "/nic_nb", o.nic_nb) c.set(basekey + "/nic", o.nic) c.set(basekey + "/options", o.options) c.set(basekey + "/kvm", o.kvm) c.set(basekey + "/initrd", o.initrd) c.set(basekey + "/kernel", o.kernel) c.set(basekey + "/rel", o.rel) c.set(basekey + "/kernel_cmdline", o.kernel_cmdline) # IDS images for (key, o) in self.__idsimages.iteritems(): basekey = "IDS.images/" + str(o.id) c.set(basekey + "/name", o.name) c.set(basekey + "/image1", o.image1) c.set(basekey + "/image2", o.image2) c.set(basekey + "/memory", o.memory) c.set(basekey + "/nic_nb", o.nic_nb) c.set(basekey + "/usermod", o.usermod) c.set(basekey + "/nic", o.nic) c.set(basekey + "/options", o.options) c.set(basekey + "/kvm", o.kvm) c.set(basekey + "/monitor", o.monitor) # Libraries id = 0 for (key, o) in self.__libraries.iteritems(): basekey = "Symbol.libraries/" + str(id) c.set(basekey + "/path", o.path) id += 1 # Recent Files id = 0 for o in self.__recentfiles: basekey = "Recent.files/" + str(id) c.set(basekey + "/path", o.path) id += 1 # Symbols id = 0 for symbol in SYMBOLS: if not symbol['translated']: basekey = "Symbol.settings/" + str(id) c.set(basekey + "/name", symbol['name']) c.set(basekey + "/type", SYMBOL_TYPES[symbol['object']]) c.set(basekey + "/normal_svg_file", symbol['normal_svg_file']) c.set(basekey + "/selected_svg_file", symbol['select_svg_file']) id += 1 c.sync() gns3-legacy-GNS3-0.8.6/src/GNS3/Awp/000077500000000000000000000000001223163545200164045ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/src/GNS3/Awp/AwpImage.py000066400000000000000000000023531223163545200204530ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: import struct import os def awp_image_parse(rel_file, output_path, img_path_dict): """ Implementation of a parser that extracts kernel image and initrd from the given .rel file. Return a dictionary containing the path to the extracted files. """ rel_name = os.path.splitext(os.path.basename(rel_file))[0] # parse release header file = open(rel_file, "rb") file.seek(24) kernelo = struct.unpack('>i', file.read(4))[0] file.seek(28) kernels = struct.unpack('>i', file.read(4))[0] file.seek(48) initrdo = struct.unpack('>i', file.read(4))[0] file.seek(52) initrds = struct.unpack('>i', file.read(4))[0] # create kernel image kernel = output_path + os.sep + rel_name + '-bzImage' file.seek(kernelo) kernel_img = file.read(kernels) output = open(kernel, 'wb') output.write(kernel_img) output.close() # create initrd initrd = output_path + os.sep + rel_name + '-initrd' file.seek(initrdo) initrd_img = file.read(initrds) output = open(initrd, 'wb') output.write(initrd_img) output.close() img_path_dict['kernel'] = kernel img_path_dict['initrd'] = initrd file.close() gns3-legacy-GNS3-0.8.6/src/GNS3/Awp/__init__.py000066400000000000000000000000651223163545200205160ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: gns3-legacy-GNS3-0.8.6/src/GNS3/CalcIDLEPCDialog.py000066400000000000000000000371161223163545200211020ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # import sys, os, re, time import subprocess as sub import GNS3.Globals as globals import GNS3.Dynagen.dynamips_lib as lib from PyQt4 import QtCore, QtGui, QtSvg from GNS3.Utils import translate from GNS3.Ui.Form_CalcIDLEPCDialog import Ui_CalcIDLEPCDialog from GNS3.Node.IOSRouter import IOSRouter, init_router_id from GNS3.Node.AnyEmuDevice import AnyEmuDevice from GNS3.Node.AnyVBoxEmuDevice import AnyVBoxEmuDevice from GNS3.Globals.Symbols import SYMBOLS class CalcIDLEPCDialog(QtGui.QDialog, Ui_CalcIDLEPCDialog): """ CalcIDLEPCDialog class """ def __init__(self, iosDialog): if globals.GApp.HypervisorManager.preloadDynamips() == False: iosDialog.label_IdlePCWarning.setText('' + translate("IOSDialog", "Couldn't preload Dynamips. Check configuration.")) QtGui.QDialog.__init__(self, iosDialog) self.setupUi(self) self.iosDialog = iosDialog globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) self.show() globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) self.calcIdlePC() def calcIdlePC(self): """ Calculate optimal IdlePC value """ timeout = 4 # time in seconds for testing the cpu usage of an idlepc value success = False # Stop all nodes to gather CPU statistics self.textEdit.append('' + translate("CalcIDLEPCDialog", "Stopping all devices and creating test node...") + '') globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) for item in globals.GApp.topology.nodes.values(): if isinstance(item, IOSRouter) or isinstance(item, AnyEmuDevice) or isinstance(item, AnyVBoxEmuDevice): item.stopNode() self.iosDialog.slotSaveIOS() for symbol in SYMBOLS: if symbol['name'] == "Router " + str(self.iosDialog.comboBoxPlatform.currentText()): self.router = symbol['object'](QtSvg.QSvgRenderer(symbol['normal_svg_file']), QtSvg.QSvgRenderer(symbol['select_svg_file'])) selected_image_name = unicode(self.iosDialog.lineEditIOSImage.text()).strip() self.textEdit.append('' + translate("CalcIDLEPCDialog", "Starting calculation to find an Idle PC value for IOS image: %s" % selected_image_name) + '') image_to_use = None for (image, conf) in globals.GApp.iosimages.iteritems(): if conf.filename == selected_image_name: image_to_use = image if image_to_use == None: self.textEdit.append('' + translate("CalcIDLEPCDialog", "IOS image %s is not registered! Please save the settings first" % selected_image_name) + '') break globals.GApp.topology.addNode(self.router, False, image_to_use) try: self.router.startNode() except: self.iosDialog.label_IdlePCWarning.setText('' + translate("IOSDialog", "Cannot start the test node...") + '') break globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) self.textEdit.append('' + translate("CalcIDLEPCDialog", "Giving some time for the router to boot...") + '') globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) time.sleep(20) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) if globals.GApp.dynagen.devices[self.router.hostname].idlepc != None: reply = QtGui.QMessageBox.question(self, translate("CalcIDLEPCDialog", "Message"), translate("CalcIDLEPCDialog", "There is already an Idle PC value specified for this IOS, do you want to test it?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.textEdit.append('' + translate("CalcIDLEPCDialog", "Checking CPU usage with current Idle PC value...") + '') globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) start = time.time() cpuStart = self.findDynamipsCpuUsage() count = 0 while count < timeout: time.sleep(1) self.progressBar.setValue(self.progressBar.value() + (100 / timeout)) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) count += 1 self.progressBar.setValue(100) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) elapsed = time.time() - start cpuElapsed = self.findDynamipsCpuUsage() - cpuStart cpuUsage = abs(cpuElapsed * 100.0 / elapsed) if cpuUsage > 100: cpuUsage = 100 self.textEdit.append('' + translate("CalcIDLEPCDialog", "CPU usage: " + str(int(cpuUsage)) + "%") + '') if cpuUsage < 85.0: globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) reply = QtGui.QMessageBox.question(self, translate("CalcIDLEPCDialog", "Message"), translate("CalcIDLEPCDialog", "This Idle PC value seems to work, do you want to keep it?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.cleanUp() self.reject() return else: self.textEdit.append('' + translate("CalcIDLEPCDialog", "This value doesn't seem to work. Continuing...") + '') globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) # reset Idle PC value lib.send(globals.GApp.dynagen.devices[self.router.hostname].dynamips, 'vm set_idle_pc_online %s 0 %s' % (self.router.hostname, '0x00000000')) self.textEdit.append('' + translate("CalcIDLEPCDialog", "Getting Idle PC values from Dynamips...") + '') self.progressBar.setValue(0) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) # getting dynagen's idlepc calculation results result = globals.GApp.dynagen.devices[self.router.hostname].idleprop(lib.IDLEPROPGET) # remove the '100-OK' line result.pop() idles = [] for line in result: (value, count) = line.split()[1:] # Sort table, best values first - if existing iCount = int(count[1:-1]) if 50 < iCount < 60: idles.insert(0, value) else: idles.append(value) length = len(idles) if length == 0: QtGui.QMessageBox.critical(globals.GApp.mainWindow, 'CalcIDLEPCDialog', "Dynamips didn't find any Idle PC value. It happens sometimes, please try again.") self.iosDialog.label_IdlePCWarning.setText('' + translate("IOSDialog", "Dynamips didn't find any Idle PC value. It happens sometimes, please try again.")) self.cleanUp() self.reject() return self.textEdit.append('' + translate("CalcIDLEPCDialog", "Found " + str(length) + " possible values. The test will last at most " + str(length * timeout) + " seconds.") + '') globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) # Apply the IDLE PC to the router progress = 0.0 self.progressBar.setValue(0) incr = 100.0 / float(length) / float(timeout) for line in idles: globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) try: for node in globals.GApp.topology.nodes.values(): if success == True: break if isinstance(node, IOSRouter) and node.hostname == self.router.hostname: dyn_router = node.get_dynagen_device() if globals.GApp.systconf['dynamips'].HypervisorManager_binding == '0.0.0.0': host = '0.0.0.0' else: host = dyn_router.dynamips.host if globals.GApp.iosimages.has_key(host + ':' + dyn_router.image): image = globals.GApp.iosimages[host + ':' + dyn_router.image] image.idlepc = line self.textEdit.append('' + translate("CalcIDLEPCDialog", "Applying Idle PC value " + line + " and monitoring CPU usage...") + '') globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) lib.send(globals.GApp.dynagen.devices[self.router.hostname].dynamips, 'vm set_idle_pc_online %s 0 %s' % (self.router.hostname, line)) start = time.time() cpuStart = self.findDynamipsCpuUsage() count = 0 while count < timeout: time.sleep(1) progress += incr self.progressBar.setValue(int(progress)) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) count += 1 globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) cpuUsage = 100.0 elapsed = time.time() - start cpuElapsed = self.findDynamipsCpuUsage() - cpuStart cpuUsage = abs(cpuElapsed * 100.0 / elapsed) if cpuUsage > 100: cpuUsage = 100 self.textEdit.append('' + translate("CalcIDLEPCDialog", "CPU usage: " + str(int(cpuUsage)) + "%") + '') if cpuUsage < 70.0: self.iosDialog.lineEditIdlePC.setText(line) self.textEdit.append('' + translate("CalcIDLEPCDialog", "Working Idle PC value found. Applying to other devices using this IOS image...") + '') # Apply idle pc to devices with the same IOS image for device in globals.GApp.topology.nodes.values(): if isinstance(device, IOSRouter) and device.config['image'] == image.filename: device.get_dynagen_device().idlepc = line config = device.get_config() config['idlepc'] = line device.set_config(config) device.setCustomToolTip() success = True except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("CalcIDLEPCDialog", "Dynamips error"), unicode(msg)) return self.progressBar.setValue(100) self.pushButton.setText(QtGui.QApplication.translate("CalcIDLEPCDialog", "Close", None, QtGui.QApplication.UnicodeUTF8)) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) if success == True: self.iosDialog.slotSaveIOS() self.textEdit.append('' + translate("CalcIDLEPCDialog", "Working Idle PC value found.") + '') else: self.textEdit.append('' + translate("CalcIDLEPCDialog", "Failed to find a working Idle PC value.") + '') self.cleanUp() def findDynamipsCpuUsage(self): """ Asks Dynamips for its CPU usage """ ret = long(0.0) usage = lib.send(globals.GApp.dynagen.devices[self.router.hostname].dynamips, 'vm cpu_usage %s 0' % self.router.hostname) if usage[1] == "100-OK": if usage[0].lstrip('101 '): ret = long(usage[0].lstrip('101 ')) else: ret = 0.0 else: ret = -1 if ret < 0: QtGui.QMessageBox.critical(globals.GApp.mainWindow, "CalcIDLEPCDialog", "Negative return") return ret def cleanUp(self): """ Clean up method """ self.textEdit.append('' + translate("CalcIDLEPCDialog", "Cleaning up...") + '') globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) globals.GApp.topology.deleteNode(self.router.id) init_router_id(self.router.id) self.router.__del__() def cancel(self): """ Clean cancel or close """ if self.pushButton.text() == "Cancel": self.iosDialog.label_IdlePCWarning.setText('' + translate("IOSDialog", "Operation canceled")) self.cleanUp() self.reject() else: self.accept() gns3-legacy-GNS3-0.8.6/src/GNS3/Config/000077500000000000000000000000001223163545200170625ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/src/GNS3/Config/Config.py000066400000000000000000000475231223163545200206540ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # import os import GNS3.Globals as globals from GNS3.Config.Objects import iosImageConf, hypervisorConf, libraryConf, recentFilesConf, qemuImageConf, pixImageConf, junosImageConf, asaImageConf, awprouterImageConf, idsImageConf, vboxImageConf from GNS3.Globals.Symbols import SYMBOLS, SYMBOL_TYPES from GNS3.Node.DecorativeNode import DecorativeNode from PyQt4 import QtCore from GNS3.Utils import Singleton, translate class ConfDB(Singleton, QtCore.QSettings): def __init__(self): QtCore.QSettings.__init__(self, QtCore.QSettings.IniFormat, QtCore.QSettings.UserScope, "gns3") def __del__(self): self.sync() def delete(self, key): """ Delete a config key Same as QSettings.remove() """ self.remove(key) def get(self, key, default_value = None): """ Get a config value for a specific key Get the config value for `key' key If no value exists: 1) try to return default_value (if provided) 2) try to find a default value into apps _ConfigDefaults dict. 3) return None """ value = self.value(key).toString() # if value not found is user/system config, or is empty if value == "": # return default_value if provided if default_value is not None: return default_value # or return the app default if it exist if ConfigDefaults.has_key(key): return _ConfigDefaults[key] # or finally, return None return None # if conf exist, return it. return unicode(value) def set(self, key, value): """ Set a value from a specific key """ self.setValue(key, QtCore.QVariant(value)) def getGroupNewNumChild(self, key): """ Get the maximum+1 numeric key from the specified config key group. Under config group `key', find the key with the max numeric value, then return max+1 """ self.beginGroup(key) childGroups = self.childGroups() self.endGroup() max = 0 for i in childGroups: if int(i) + 1 > max: max = int(i) + 1 return (key + '/' + str(max)) def getGroupDict(self, key, fields_dict = None): """ Get all keys from a given `key' config group If fields_dict is providen, like { 'key': 'int' }, only theses keys will be return. Moreover in this dictionnary, values represent the 'convertion' type that will be applied. """ __values = {} self.beginGroup(key) childKeys = self.childKeys() for child in childKeys: # child key need to be a string child = str(child) # If fields_dict providen, check if the current # value is wanted or not if fields_dict != None and not fields_dict.has_key(child): continue child_value = self.value(child) # Try to find a suitable method for converting # conf value to desired type # default: provide a string conv_to = "string" if fields_dict != None \ and fields_dict.has_key(child) and fields_dict[child] != '': conv_to = fields_dict[child] # Do the convertion, and assign the value if conv_to == "string": __values[child] = str(child_value.toString()) elif conv_to == "int": __values[child] = int(child_value.toInt()) else: # convertion type not implemented pass self.endGroup() return __values def setGroupDict(self, key, dict_values): """ Set config keys/values under a specific config group All key/value pair present in `dict_values' will be saved in config under `key' group """ self.beginGroup(key) for key in dict_values.keys(): key_str = str(key) value_str = str(dict_values[key]) if value_str == "None": value_str = "" self.set(key_str, value_str) self.endGroup() class GNS_Conf(object): """ GNS_Conf provide static class method for loading user config """ def IOS_images(self): """ Load IOS images settings from config file """ # Loading IOS images conf basegroup = "IOS.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for img_num in childGroups: cgroup = basegroup + '/' + img_num img_filename = c.get(cgroup + "/filename", unicode('')) img_hypervisors = c.get(cgroup + "/hypervisors", unicode('')).split() if img_filename == '': continue if len(img_hypervisors) == 0: #if globals.GApp.systconf['dynamips'].HypervisorManager_binding == '0.0.0.0': # img_ref = "127.0.0.1:" + img_filename #else: img_ref = globals.GApp.systconf['dynamips'].HypervisorManager_binding + ":" + img_filename else: if len(img_hypervisors) > 1: img_ref = 'load-balanced-on-external-hypervisors:' + img_filename else: (host, port) = img_hypervisors[0].rsplit(':', 1) img_ref = host + ":" + img_filename conf = iosImageConf() conf.id = int(img_num) conf.filename = img_filename conf.baseconfig = unicode(c.get(cgroup + "/baseconfig", 'baseconfig.txt')) conf.platform = str(c.get(cgroup + "/platform", '')) conf.chassis = str(c.get(cgroup + "/chassis", '')) conf.idlepc = str(c.get(cgroup + "/idlepc", '')) conf.idlemax = int(c.get(cgroup + "/idlemax", 1500)) conf.idlesleep = int(c.get(cgroup + "/idlesleep", 30)) conf.default_ram = int(c.get(cgroup + "/default_ram", 0)) conf.default = c.value(cgroup + "/default", QtCore.QVariant(False)).toBool() conf.hypervisors = img_hypervisors globals.GApp.iosimages[img_ref] = conf if conf.id >= globals.GApp.iosimages_ids: globals.GApp.iosimages_ids = conf.id + 1 def IOS_hypervisors(self): """ Load IOS hypervisors settings from config file """ # Loading IOS images conf basegroup = "IOS.hypervisors" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for img_num in childGroups: cgroup = basegroup + '/' + img_num hyp_port = c.get(cgroup + "/port", '7200') hyp_host = c.get(cgroup + "/host", unicode('')) hyp_wdir = c.get(cgroup + "/working_directory", unicode('')) hyp_baseUDP = c.get(cgroup + "/base_udp", '10001') hyp_baseConsole = c.get(cgroup + "/base_console", '2000') hyp_baseAUX = c.get(cgroup + "/base_aux", '0') # We need at least `hyp_host' and `hyp_port' to be set if hyp_host == '' or hyp_port == '': continue img_ref = hyp_host + ':' + hyp_port conf = hypervisorConf() conf.id = int(img_num) conf.host = hyp_host conf.port = int(hyp_port) conf.workdir = hyp_wdir conf.baseUDP = int(hyp_baseUDP) conf.baseConsole = int(hyp_baseConsole) conf.baseAUX = int(hyp_baseAUX) globals.GApp.hypervisors[img_ref] = conf if conf.id >= globals.GApp.hypervisors_ids: globals.GApp.hypervisors_ids = conf.id + 1 def QEMU_images(self): """ Load Qemu images settings from config file """ # Loading Qemu image conf basegroup = "QEMU.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id conf = qemuImageConf() conf.id = int(id) conf.name = c.get(cgroup + "/name", unicode('')) conf.filename = c.get(cgroup + "/filename", unicode('')) conf.memory = int(c.get(cgroup + "/memory", 256)) conf.nic_nb = int(c.get(cgroup + "/nic_nb", 6)) conf.usermod = c.value(cgroup + "/usermod", QtCore.QVariant(False)).toBool() conf.nic = str(c.get(cgroup + "/nic", 'rtl8139')) conf.flavor = str(c.get(cgroup + "/flavor", 'Default')) conf.options = str(c.get(cgroup + "/options", '')) conf.kvm = c.value(cgroup + "/kvm", QtCore.QVariant(False)).toBool() conf.monitor = c.value(cgroup + "/monitor", QtCore.QVariant(False)).toBool() globals.GApp.qemuimages[conf.name] = conf if conf.id >= globals.GApp.qemuimages_ids: globals.GApp.qemuimages_ids = conf.id + 1 def VBOX_images(self): """ Load VBox images settings from config file """ # Loading Qemu image conf basegroup = "VBOX.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id conf = vboxImageConf() conf.id = int(id) conf.name = c.get(cgroup + "/name", unicode('')) conf.filename = c.get(cgroup + "/filename", unicode('')) conf.nic_nb = int(c.get(cgroup + "/nic_nb", 6)) conf.nic = str(c.get(cgroup + "/nic", 'automatic')) conf.first_nic_managed = c.value(cgroup + "/first_nic_managed", QtCore.QVariant(False)).toBool() conf.headless_mode = c.value(cgroup + "/headless_mode", QtCore.QVariant(False)).toBool() conf.console_support = c.value(cgroup + "/console_support", QtCore.QVariant(False)).toBool() conf.console_telnet_server = c.value(cgroup + "/console_telnet_server", QtCore.QVariant(False)).toBool() conf.guestcontrol_user = str(c.get(cgroup + "/guestcontrol_user", '')) conf.guestcontrol_password = str(c.get(cgroup + "/guestcontrol_password", '')) globals.GApp.vboximages[conf.name] = conf if conf.id >= globals.GApp.vboximages_ids: globals.GApp.vboximages_ids = conf.id + 1 def PIX_images(self): """ Load PIX images settings from config file """ # Loading PIX image conf basegroup = "PIX.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id conf = pixImageConf() conf.id = int(id) conf.name = c.get(cgroup + "/name", unicode('')) conf.filename = c.get(cgroup + "/filename", unicode('')) conf.memory = int(c.get(cgroup + "/memory", 128)) conf.nic_nb = int(c.get(cgroup + "/nic_nb", 6)) conf.nic = str(c.get(cgroup + "/nic", 'e1000')) conf.options = str(c.get(cgroup + "/options", '')) conf.key = str(c.get(cgroup + "/key", '')) conf.serial = str(c.get(cgroup + "/serial", '')) globals.GApp.piximages[conf.name] = conf if conf.id >= globals.GApp.piximages_ids: globals.GApp.piximages_ids = conf.id + 1 def JUNOS_images(self): """ Load JunOS images settings from config file """ # Loading JunOS image conf basegroup = "JUNOS.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id conf = junosImageConf() conf.id = int(id) conf.name = c.get(cgroup + "/name", unicode('')) conf.filename = c.get(cgroup + "/filename", unicode('')) conf.memory = int(c.get(cgroup + "/memory", 128)) conf.nic_nb = int(c.get(cgroup + "/nic_nb", 6)) conf.usermod = c.value(cgroup + "/usermod", QtCore.QVariant(False)).toBool() conf.nic = str(c.get(cgroup + "/nic", 'e1000')) conf.options = str(c.get(cgroup + "/options", '')) conf.kvm = c.value(cgroup + "/kvm", QtCore.QVariant(False)).toBool() conf.monitor = c.value(cgroup + "/monitor", QtCore.QVariant(False)).toBool() globals.GApp.junosimages[conf.name] = conf if conf.id >= globals.GApp.junosimages_ids: globals.GApp.junosimages_ids = conf.id + 1 def ASA_images(self): """ Load ASA images settings from config file """ # Loading ASA image conf basegroup = "ASA.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id conf = asaImageConf() conf.id = int(id) conf.name = c.get(cgroup + "/name", unicode('')) conf.memory = int(c.get(cgroup + "/memory", 256)) conf.nic_nb = int(c.get(cgroup + "/nic_nb", 6)) conf.usermod = c.value(cgroup + "/usermod", QtCore.QVariant(False)).toBool() conf.nic = str(c.get(cgroup + "/nic", 'e1000')) conf.options = str(c.get(cgroup + "/options", '')) conf.kvm = c.value(cgroup + "/kvm", QtCore.QVariant(False)).toBool() conf.monitor = c.value(cgroup + "/monitor", QtCore.QVariant(False)).toBool() conf.initrd = c.get(cgroup + "/initrd", unicode('')) conf.kernel = c.get(cgroup + "/kernel", unicode('')) conf.kernel_cmdline = c.get(cgroup + "/kernel_cmdline", unicode('')) globals.GApp.asaimages[conf.name] = conf if conf.id >= globals.GApp.asaimages_ids: globals.GApp.asaimages_ids = conf.id + 1 def AWP_images(self): """ Load AWP images settings from config file """ # Loading AWP image conf basegroup = "AWP.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id conf = awprouterImageConf() conf.id = int(id) conf.name = c.get(cgroup + "/name", unicode('')) conf.memory = int(c.get(cgroup + "/memory", 256)) conf.nic_nb = int(c.get(cgroup + "/nic_nb", 6)) conf.usermod = c.value(cgroup + "/usermod", QtCore.QVariant(False)).toBool() conf.nic = str(c.get(cgroup + "/nic", 'virtio')) conf.options = str(c.get(cgroup + "/options", '')) conf.kvm = c.value(cgroup + "/kvm", QtCore.QVariant(False)).toBool() conf.initrd = c.get(cgroup + "/initrd", unicode('')) conf.kernel = c.get(cgroup + "/kernel", unicode('')) conf.rel = c.get(cgroup + "/rel", unicode('')) conf.kernel_cmdline = c.get(cgroup + "/kernel_cmdline", unicode('')) globals.GApp.awprouterimages[conf.name] = conf if conf.id >= globals.GApp.awprouterimages_ids: globals.GApp.awprouterimages_ids = conf.id + 1 def IDS_images(self): """ Load IDS images settings from config file """ # Loading IDS image conf basegroup = "IDS.images" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id conf = idsImageConf() conf.id = int(id) conf.image1 = c.get(cgroup + "/image1", unicode('')) conf.image2 = c.get(cgroup + "/image2", unicode('')) conf.name = c.get(cgroup + "/name", unicode('')) conf.memory = int(c.get(cgroup + "/memory", 512)) conf.nic_nb = int(c.get(cgroup + "/nic_nb", 3)) conf.usermod = c.value(cgroup + "/usermod", QtCore.QVariant(False)).toBool() conf.nic = str(c.get(cgroup + "/nic", 'e1000')) conf.options = str(c.get(cgroup + "/options", '')) conf.kvm = c.value(cgroup + "/kvm", QtCore.QVariant(False)).toBool() conf.monitor = c.value(cgroup + "/monitor", QtCore.QVariant(False)).toBool() globals.GApp.idsimages[conf.name] = conf if conf.id >= globals.GApp.idsimages_ids: globals.GApp.idsimages_ids = conf.id + 1 def RecentFiles(self): """ Load recent file paths from config file """ # Loading recent files conf basegroup = "Recent.files" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id path = c.get(cgroup + "/path", unicode('')) conf = recentFilesConf() conf.path = unicode(path) globals.GApp.recentfiles.append(conf) def Libraries(self): """ Load libraries settings from config file """ # Loading libraries conf basegroup = "Symbol.libraries" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() for id in childGroups: cgroup = basegroup + '/' + id path = c.get(cgroup + "/path", unicode('')) library_name = os.path.basename(unicode(path)) if not QtCore.QResource.registerResource(path, ":/" + library_name): print translate("Config", "Can't open library: %s") % path continue conf = libraryConf() conf.path = path globals.GApp.libraries[library_name] = conf def Symbols(self): """ Load symbols settings from config file """ # Loading symbols conf basegroup = "Symbol.settings" c = ConfDB() c.beginGroup(basegroup) childGroups = c.childGroups() c.endGroup() loaded_symbols = [] for id in childGroups: cgroup = basegroup + '/' + id name = str(c.get(cgroup + "/name", 'default')) type = str(c.get(cgroup + "/type", 'DecorativeNode')) object = DecorativeNode for (object_class, type_name) in SYMBOL_TYPES.iteritems(): if type_name == type: object = object_class break normal_svg_file = str(c.get(cgroup + "/normal_svg_file", ':/icons/default.svg')) selected_svg_file = str(c.get(cgroup + "/selected_svg_file", ':/icons/default.svg')) SYMBOLS.append( {'name': name, 'object': object, 'normal_svg_file': normal_svg_file, 'select_svg_file': selected_svg_file, 'translated': False}) # Static Methods stuffs load_IOSimages = classmethod(IOS_images) load_IOShypervisors = classmethod(IOS_hypervisors) load_Libraries = classmethod(Libraries) load_Symbols = classmethod(Symbols) gns3-legacy-GNS3-0.8.6/src/GNS3/Config/Defaults.py000066400000000000000000000724461223163545200212200ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # import os, sys, platform from GNS3.Utils import translate # Default path to Dynamips executable if sys.platform.startswith('win'): DYNAMIPS_DEFAULT_PATH = unicode('dynamips.exe') elif sys.platform.startswith('darwin'): if hasattr(sys, "frozen"): DYNAMIPS_DEFAULT_PATH = os.getcwdu() + os.sep + '../Resources/dynamips-0.2.10-OSX.intel64.bin' else: DYNAMIPS_DEFAULT_PATH = os.getcwdu() + os.sep + 'dynamips-0.2.10-OSX.intel64.bin' else: DYNAMIPS_DEFAULT_PATH = unicode('dynamips') # Default path to Dynamips working directory if os.environ.has_key("TEMP"): DYNAMIPS_DEFAULT_WORKDIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): DYNAMIPS_DEFAULT_WORKDIR = unicode(os.environ["TMP"], 'utf-8', errors='replace') else: DYNAMIPS_DEFAULT_WORKDIR = unicode('/tmp') if sys.platform.startswith('darwin'): if hasattr(sys, "frozen"): BASECONFIG_DIR = os.getcwdu() + os.sep + '../Resources/' else: BASECONFIG_DIR = '' elif sys.platform.startswith('win'): BASECONFIG_DIR = '' else: BASECONFIG_DIR = '/usr/local/share/examples/gns3/' # Default path to qemuwrapper if sys.platform.startswith('win'): QEMUWRAPPER_DEFAULT_PATH = unicode('qemuwrapper.exe') elif sys.platform.startswith('darwin') and hasattr(sys, "frozen"): QEMUWRAPPER_DEFAULT_PATH = os.getcwdu() + os.sep + '../Resources/qemuwrapper.py' else: # look for qemuwrapper in the current working directory qemuwrapper_path = os.getcwdu() + os.sep + 'qemuwrapper/qemuwrapper.py' if os.path.exists(qemuwrapper_path): QEMUWRAPPER_DEFAULT_PATH = qemuwrapper_path elif platform.system() == 'Linux': QEMUWRAPPER_DEFAULT_PATH = unicode("/usr/share/gns3/qemuwrapper.py") else: QEMUWRAPPER_DEFAULT_PATH = unicode("/usr/local/libexec/gns3/qemuwrapper.py") # Default path to qemuwrapper working directory if os.environ.has_key("TEMP"): QEMUWRAPPER_DEFAULT_WORKDIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): QEMUWRAPPER_DEFAULT_WORKDIR = unicode(os.environ["TMP"], 'utf-8', errors='replace') else: QEMUWRAPPER_DEFAULT_WORKDIR = unicode('/tmp') # Default paths to Qemu and qemu-img if sys.platform.startswith('win'): if os.path.exists('Qemu\qemu-system-i386w.exe'): QEMU_DEFAULT_PATH = unicode('Qemu\qemu-system-i386w.exe') QEMU_IMG_DEFAULT_PATH = unicode('Qemu\qemu-img.exe') else: # For now we ship Qemu 0.11.0 in the all-in-one QEMU_DEFAULT_PATH = unicode('qemu.exe') QEMU_IMG_DEFAULT_PATH = unicode('qemu-img.exe') elif sys.platform.startswith('darwin') and hasattr(sys, "frozen"): QEMU_DEFAULT_PATH = os.getcwdu() + os.sep + '../Resources/Qemu-0.11.0/bin/qemu' QEMU_IMG_DEFAULT_PATH = os.getcwdu() + os.sep + '../Resources/Qemu-0.11.0/bin/qemu-img' else: QEMU_IMG_DEFAULT_PATH = unicode('qemu-img') QEMU_DEFAULT_PATH = unicode('qemu') # Default path to vboxwrapper if sys.platform.startswith('win'): VBOXWRAPPER_DEFAULT_PATH = unicode('vboxwrapper.exe') elif sys.platform.startswith('darwin') and hasattr(sys, "frozen"): VBOXWRAPPER_DEFAULT_PATH = os.getcwdu() + os.sep + '../Resources/VBoxWrapper/Contents/MacOS/VBoxWrapper' else: # look for vboxwrapper in the current working directory vboxwrapper_path = os.getcwdu() + os.sep + 'vboxwrapper/vboxwrapper.py' if os.path.exists(qemuwrapper_path): VBOXWRAPPER_DEFAULT_PATH = vboxwrapper_path elif platform.system() == 'Linux': VBOXWRAPPER_DEFAULT_PATH = unicode("/usr/share/gns3/vboxwrapper.py") else: VBOXWRAPPER_DEFAULT_PATH = unicode("/usr/local/libexec/gns3/vboxwrapper.py") # Default path to vboxwrapper working directory if os.environ.has_key("TEMP"): VBOXWRAPPER_DEFAULT_WORKDIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): VBOXWRAPPER_DEFAULT_WORKDIR = unicode(os.environ["TMP"], 'utf-8', errors='replace') else: VBOXWRAPPER_DEFAULT_WORKDIR = unicode('/tmp') Traditional_Capture_String = translate("Defaults", 'Wireshark Traditional Capture') Live_Traffic_Capture_String = translate("Defaults", 'Wireshark Live Traffic Capture') Pipe_Traffic_Capture_String = translate("Defaults", 'Wireshark Live Pipe Traffic Capture (experimental)') # Default predefined sets of Wireshark commands on various OSes: if platform.system() == 'Linux': CAPTURE_PRESET_CMDS = { Traditional_Capture_String + ' (Linux)': "wireshark %c", Live_Traffic_Capture_String + ' (Linux)': "tail -f -c +0b %c | wireshark -k -i -" } elif platform.system() == 'FreeBSD': CAPTURE_PRESET_CMDS = { Traditional_Capture_String + ' (FreeBSD)': "wireshark %c", Live_Traffic_Capture_String + ' (FreeBSD)': "gtail -f -c +0b %c | wireshark -k -i -" } elif platform.system() == 'Windows' and os.path.exists("C:\Program Files (x86)\Wireshark\wireshark.exe"): CAPTURE_PRESET_CMDS = { Traditional_Capture_String + ' (Windows 64 bit)': "C:\Program Files (x86)\Wireshark\wireshark.exe %c", Traditional_Capture_String + ' (Windows)': "C:\Program Files\Wireshark\wireshark.exe %c", Live_Traffic_Capture_String + ' (Windows 64-bit)': 'tail.exe -f -c +0b %c | "C:\Program Files (x86)\Wireshark\wireshark.exe" -k -i -', Live_Traffic_Capture_String + ' (Windows)': 'tail.exe -f -c +0b %c | "C:\Program Files\Wireshark\wireshark.exe" -k -i -', Pipe_Traffic_Capture_String + ' (Windows)': "C:\Program Files\Wireshark\wireshark.exe -k -i %p", Pipe_Traffic_Capture_String + ' (Windows 64-bit)': "C:\Program Files (x86)\Wireshark\wireshark.exe -k -i %p", } elif platform.system() == 'Windows': CAPTURE_PRESET_CMDS = { Traditional_Capture_String + ' (Windows)': "C:\Program Files\Wireshark\wireshark.exe %c", Live_Traffic_Capture_String + ' (Windows)': 'tail.exe -f -c +0b %c | "C:\Program Files\Wireshark\wireshark.exe" -k -i -', Pipe_Traffic_Capture_String + ' (Windows)': "C:\Program Files\Wireshark\wireshark.exe -k -i %p", } elif platform.system() == 'Darwin': CAPTURE_PRESET_CMDS = { Traditional_Capture_String + ' (Mac OS X)': "/usr/bin/open -a /Applications/Wireshark.app %c", Live_Traffic_Capture_String + ' (Mac OS X)': "tail -f -c +0 %c | /Applications/Wireshark.app/Contents/Resources/bin/wireshark -k -i -", } else: # For unknown platforms, or if detection failed, we list all options. CAPTURE_PRESET_CMDS = { Traditional_Capture_String + ' (Linux)': "wireshark %c", Live_Traffic_Capture_String + ' (Linux)': "tail -f -c +0b %c | wireshark -k -i -", Traditional_Capture_String + ' (Windows)': "C:\Program Files\Wireshark\wireshark.exe %c", Traditional_Capture_String + ' (Windows 64 bit)': "C:\Program Files (x86)\Wireshark\wireshark.exe %c", Live_Traffic_Capture_String + ' (Windows)': 'tail.exe -f -c +0b %c | "C:\Program Files\Wireshark\wireshark.exe" -k -i -', Live_Traffic_Capture_String + ' (Windows 64-bit)': 'tail.exe -f -c +0b %c | "C:\Program Files (x86)\Wireshark\wireshark.exe" -k -i -', Traditional_Capture_String + ' (Mac OS X)': "/usr/bin/open -a /Applications/Wireshark.app %c", Live_Traffic_Capture_String + ' (Mac OS X)': "tail -f -c +0 %c | /Applications/Wireshark.app/Contents/Resources/bin/wireshark -k -i -", } # Default capture command if platform.system() == 'Darwin': CAPTURE_DEFAULT_CMD = unicode(CAPTURE_PRESET_CMDS[Live_Traffic_Capture_String + ' (Mac OS X)']) elif platform.system() == 'Windows' and os.path.exists("C:\Program Files (x86)\Wireshark\wireshark.exe"): CAPTURE_DEFAULT_CMD = unicode(CAPTURE_PRESET_CMDS[Live_Traffic_Capture_String + ' (Windows 64-bit)']) elif platform.system() == 'Windows': CAPTURE_DEFAULT_CMD = unicode(CAPTURE_PRESET_CMDS[Live_Traffic_Capture_String + ' (Windows)']) elif platform.system() == 'Linux': CAPTURE_DEFAULT_CMD = unicode(CAPTURE_PRESET_CMDS[Live_Traffic_Capture_String + ' (Linux)']) elif platform.system() == 'FreeBSD': CAPTURE_DEFAULT_CMD = unicode(CAPTURE_PRESET_CMDS[Live_Traffic_Capture_String + ' (FreeBSD)']) else: CAPTURE_DEFAULT_CMD = unicode("wireshark %c") # Default path to capture working directory if os.environ.has_key("TEMP"): CAPTURE_DEFAULT_WORKDIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): CAPTURE_DEFAULT_WORKDIR = unicode(os.environ["TMP"], 'utf-8', errors='replace') else: CAPTURE_DEFAULT_WORKDIR = unicode('/tmp') # Default predefined sets of Terminal commands on various OSes: if platform.system() == 'Linux' or platform.system().__contains__("BSD"): TERMINAL_PRESET_CMDS = { 'xterm (Linux/BSD)': 'xterm -T %d -e \'telnet %h %p\' >/dev/null 2>&1 &', 'Putty (Linux/BSD)': 'putty -telnet %h %p -title %d -sl 2500 -fg SALMON1 -bg BLACK', 'Gnome Terminal (Linux/BSD)': 'gnome-terminal -t %d -e \'telnet %h %p\' >/dev/null 2>&1 &', 'KDE Konsole (Linux/BSD)': 'konsole --new-tab -p tabtitle=%d -e telnet %h %p >/dev/null 2>&1 &', 'SecureCRT (Linux)': 'SecureCRT /T /N "%d" /TELNET %h %p', 'Mate Terminal (Linux Mint)': 'mate-terminal --tab -e \'telnet %h %p\' -t %d >/dev/null 2>&1 & ', } elif platform.system() == 'Windows' and os.path.exists("C:\Program Files (x86)\\"): TERMINAL_PRESET_CMDS = { 'Putty (Windows, included with GNS3)': 'putty.exe -telnet %h %p -wt "%d" -gns3 5 -skin 4', 'SuperPutty (Windows)': 'SuperPutty.exe -telnet "%h -P %p -wt \"%d\" -gns3 5 -skin 4"', 'SecureCRT (Windows)': '"C:\Program Files\\VanDyke Software\\SecureCRT\\SecureCRT.EXE" /SCRIPT securecrt.vbs /ARG %d /T /TELNET %h %p', 'TeraTerm or TeraTerm Pro (Windows 64-bit)': r'"C:\Program Files (x86)\teraterm\ttermpro.exe" /W="%d" /M="C:\Program Files\GNS3\ttstart.macro" /T=1 %h %p', 'TeraTerm or TeraTerm Pro (Windows 32-bit)': r'"C:\Program Files\teraterm\ttermpro.exe" /W="%d" /M="C:\Program Files\GNS3\ttstart.macro" /T=1 %h %p"', 'Telnet (Windows)': 'telnet %h %p', 'Xshell 4 (Windows)': 'C:\Program Files (x86)\\NetSarang\\Xshell 4\\xshell.exe -url telnet://%h:%p' } elif platform.system() == 'Windows': TERMINAL_PRESET_CMDS = { 'Putty (Windows, included with GNS3)': 'putty.exe -telnet %h %p -wt "%d" -gns3 5 -skin 4', 'SuperPutty (Windows)': 'SuperPutty.exe -telnet "%h -P %p -wt \"%d\" -gns3 5 -skin 4"', 'SecureCRT (Windows)': '"C:\Program Files\\VanDyke Software\\SecureCRT\\SecureCRT.EXE" /SCRIPT securecrt.vbs /ARG %d /T /TELNET %h %p', 'TeraTerm or TeraTerm Pro (Windows)': r'"C:\Program Files\teraterm\ttermpro.exe" /W="%d" /M="C:\Program Files\GNS3\ttstart.macro" /T=1 %h %p"', 'Telnet (Windows)': 'telnet %h %p', 'Xshell 4 (Windows)': 'C:\Program Files\\NetSarang\\Xshell 4\\xshell.exe -url telnet://%h:%p' } elif platform.system() == 'Darwin': TERMINAL_PRESET_CMDS = { 'Terminal (Mac OS X)': "/usr/bin/osascript -e 'tell application \"terminal\" to do script with command \"telnet %h %p ; exit\"'", 'iTerm or iTerm2 (Mac OS X)': "/usr/bin/osascript -e 'tell app \"iTerm\"' -e 'activate' -e 'set myterm to the first terminal' -e 'tell myterm' -e 'set mysession to (make new session at the end of sessions)' -e 'tell mysession' -e 'exec command \"telnet %h %p\"' -e 'set name to \"%d\"' -e 'end tell' -e 'end tell' -e 'end tell'", 'SecureCRT (Mac OS X)': '/Applications/SecureCRT.app/Contents/MacOS/SecureCRT /ARG %d /T /TELNET %h %p' } else: # For unknown platforms, or if detection failed, we list all options. TERMINAL_PRESET_CMDS = { 'Putty (Windows, included with GNS3)': 'putty.exe -telnet %h %p -wt "%d" -gns3 5 -skin 4', 'SuperPutty (Windows)': 'SuperPutty.exe -telnet "%h -P %p -wt \"%d\" -gns3 5 -skin 4"', 'SecureCRT (Windows)': '"C:\Program Files\\VanDyke Software\\SecureCRT\\SecureCRT.EXE" /SCRIPT securecrt.vbs /ARG %d /T /TELNET %h %p', 'TeraTerm or TeraTerm Pro (Windows 64-bit)': r'"C:\Program Files (x86)\teraterm\ttermpro.exe" /W="%d" /M="C:\Program Files\GNS3\ttstart.macro" /T=1 %h %p', 'TeraTerm or TeraTerm Pro (Windows 32-bit)': r'"C:\Program Files\teraterm\ttermpro.exe" /W="%d" /M="C:\Program Files\GNS3\ttstart.macro" /T=1 %h %p"', 'Telnet (Windows)': 'telnet %h %p', 'Xshell 4 (Windows 32-bit)': 'C:\Program Files\\NetSarang\\Xshell 4\\xshell.exe -url telnet://%h:%p', 'Xshell 4 (Windows 64-bit)': 'C:\Program Files (x86)\\NetSarang\\Xshell 4\\xshell.exe -url telnet://%h:%p', 'xterm (Linux/BSD)': 'xterm -T %d -e \'telnet %h %p\' >/dev/null 2>&1 &', 'Putty (Linux/BSD)': 'putty -telnet %h %p -title %d -sl 2500 -fg SALMON1 -bg BLACK', 'Gnome Terminal (Linux/BSD)': 'gnome-terminal -t %d -e \'telnet %h %p\' >/dev/null 2>&1 &', 'KDE Konsole (Linux/BSD)': 'konsole --new-tab -p tabtitle=%d -e telnet %h %p >/dev/null 2>&1 &', 'SecureCRT (Linux)': 'SecureCRT /T /N "%d" /TELNET %h %p', 'Mate Terminal (Linux Mint)': 'mate-terminal --tab -e \'telnet %h %p\' -t %d >/dev/null 2>&1 & ', 'Terminal (Mac OS X)': "/usr/bin/osascript -e 'tell application \"terminal\" to do script with command \"telnet %h %p ; exit\"'", 'iTerm or iTerm2 (Mac OS X)': "/usr/bin/osascript -e 'tell app \"iTerm\"' -e 'activate' -e 'set myterm to the first terminal' -e 'tell myterm' -e 'set mysession to (make new session at the end of sessions)' -e 'tell mysession' -e 'exec command \"telnet %h %p\"' -e 'set name to \"%d\"' -e 'end tell' -e 'end tell' -e 'end tell'", 'SecureCRT (Mac OS X)': '/Applications/SecureCRT.app/Contents/MacOS/SecureCRT /ARG %d /T /TELNET %h %p' } # Default terminal command if sys.platform.startswith('darwin'): TERMINAL_DEFAULT_CMD = unicode(TERMINAL_PRESET_CMDS['Terminal (Mac OS X)']) elif sys.platform.startswith('win'): if os.path.exists(os.getcwdu() + os.sep + "SuperPutty.exe"): TERMINAL_DEFAULT_CMD = unicode(TERMINAL_PRESET_CMDS['SuperPutty (Windows)']) else: TERMINAL_DEFAULT_CMD = unicode(TERMINAL_PRESET_CMDS['Putty (Windows, included with GNS3)']) else: TERMINAL_DEFAULT_CMD = unicode(TERMINAL_PRESET_CMDS['xterm (Linux/BSD)']) # Default terminal serial command if sys.platform.startswith('win'): if os.path.exists(os.getcwdu() + os.sep + "SuperPutty.exe"): TERMINAL_SERIAL_DEFAULT_CMD = unicode('SuperPutty.exe -serial "%s -wt \"%d\" -gns3 5 -skin 4"') else: TERMINAL_SERIAL_DEFAULT_CMD = unicode('putty.exe -serial %s -wt "%d [Local Console]" -gns3 5') elif sys.platform.startswith('darwin'): #/usr/bin/osascript -e 'tell application "terminal" to do script with command "socat UNIX-CONNECT:\"%s\" stdio,raw,echo=0 ; exit"' TERMINAL_SERIAL_DEFAULT_CMD = unicode("/usr/bin/osascript -e 'tell application \"terminal\" to do script with command \"socat UNIX-CONNECT:\\\"%s\\\" stdio,raw,echo=0 ; exit\"'") else: TERMINAL_SERIAL_DEFAULT_CMD = unicode('xterm -T %d -e \'socat UNIX-CONNECT:"%s" stdio,raw,echo=0\' > /dev/null 2>&1 &') # Default projects directory if sys.platform.startswith('win') and os.environ.has_key("HOMEDRIVE") and os.environ.has_key("HOMEPATH"): PROJECT_DEFAULT_DIR = unicode(os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + os.sep + 'GNS3' + os.sep + 'Projects', 'utf-8', errors='replace') elif os.environ.has_key("HOME"): PROJECT_DEFAULT_DIR = unicode(os.environ["HOME"] + os.sep + 'GNS3' + os.sep + 'Projects', 'utf-8', errors='replace') elif os.environ.has_key("TEMP"): PROJECT_DEFAULT_DIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): PROJECT_DEFAULT_DIR = unicode(os.environ["TMP"], 'utf-8', errors='replace') else: PROJECT_DEFAULT_DIR = unicode('/tmp') # Default IOS images directory if sys.platform.startswith('win') and os.environ.has_key("HOMEDRIVE") and os.environ.has_key("HOMEPATH"): IOS_DEFAULT_DIR = unicode(os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + os.sep + 'GNS3' + os.sep + 'Images', 'utf-8', errors='replace') elif os.environ.has_key("HOME"): IOS_DEFAULT_DIR = unicode(os.environ["HOME"] + os.sep + 'GNS3' + os.sep + 'Images', 'utf-8', errors='replace') elif os.environ.has_key("TEMP"): IOS_DEFAULT_DIR = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): IOS_DEFAULT_DIR = unicode(os.environ["TMP"], 'utf-8', errors='replace') else: IOS_DEFAULT_DIR = unicode('/tmp') # Default path to dot executable if sys.platform.startswith('win'): DOT_DEFAULT_PATH = unicode('dot.exe') elif sys.platform.startswith('darwin'): if hasattr(sys, "frozen"): DOT_DEFAULT_PATH = os.getcwdu() + os.sep + '../Resources/dot.bin' else: DOT_DEFAULT_PATH = os.getcwdu() + os.sep + 'dot.bin' else: DOT_DEFAULT_PATH = unicode('dot') # Default reportlab directory if sys.platform.startswith('win'): REPORTLAB_DEFAULT_DIR = unicode(sys.prefix + os.sep + 'Lib' + os.sep + 'site-packages' + os.sep + 'reportlab', 'utf-8', errors='replace') else: REPORTLAB_DEFAULT_DIR = unicode(sys.prefix + os.sep + 'lib' + os.sep + 'python' + sys.version[0] + sys.version[1] + sys.version[2] + os.sep + 'site-packages' + os.sep + 'reportlab', 'utf-8', errors='replace') # Default PIL directory if sys.platform.startswith('win'): PIL_DEFAULT_DIR = unicode(sys.prefix + os.sep + 'Lib' + os.sep + 'site-packages' + os.sep + 'PIL', 'utf-8', errors='replace') else: PIL_DEFAULT_DIR = unicode(sys.prefix + os.sep + 'lib' + os.sep + 'python' + sys.version[0] + sys.version[1] + sys.version[2] + os.sep + 'site-packages' + os.sep + 'PIL', 'utf-8', errors='replace') # Default deployement wizard directory if sys.platform.startswith('win') and os.environ.has_key("HOMEDRIVE") and os.environ.has_key("HOMEPATH"): DEPLOYEMENTWIZARD_DEFAULT_PATH = unicode(os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] + os.sep + 'GNS3' + os.sep + 'Projects', 'utf-8', errors='replace') elif os.environ.has_key("HOME"): DEPLOYEMENTWIZARD_DEFAULT_PATH = unicode(os.environ["HOME"] + os.sep + 'GNS3' + os.sep + 'Projects', 'utf-8', errors='replace') elif os.environ.has_key("TEMP"): DEPLOYEMENTWIZARD_DEFAULT_PATH = unicode(os.environ["TEMP"], 'utf-8', errors='replace') elif os.environ.has_key("TMP"): DEPLOYEMENTWIZARD_DEFAULT_PATH = unicode(os.environ["TMP"], 'utf-8', errors='replace') else: DEPLOYEMENTWIZARD_DEFAULT_PATH = unicode('/tmp') SysConfigDir = "/etc/gns3" UsrConfigDir = "~/.gns3" conf_library_defaults = { 'path': '', } conf_library_types = { 'path': unicode, } conf_recentfiles_defaults = { 'path': '', } conf_recentfiles_types = { 'path': unicode, } conf_iosImage_defaults = { 'id': -1, 'filename': '', 'baseconfig': '', 'platform': '', 'chassis': '', 'idlepc': '', 'idlemax': 1500, 'idlesleep': 30, 'default_ram': 0, 'hypervisors': [], 'default': False } conf_iosImage_types = { 'id': int, 'filename': unicode, 'baseconfig': unicode, 'platform': str, 'chassis': str, 'idlepc': str, 'idlemax': int, 'idlesleep': int, 'default_ram': int, 'hypervisors': list, 'default': bool } conf_hypervisor_defaults = { 'id': -1, 'host': '', 'port': 7200, 'workdir': '', 'baseUDP': 10001, 'baseConsole': 2101, 'baseAUX': 2501, 'used_ram':0, } conf_hypervisor_types = { 'id': int, 'host': unicode, 'port': int, 'workdir': unicode, 'baseUDP': int, 'baseConsole': int, 'baseAUX': int, 'used_ram': int, } conf_qemuImage_defaults = { 'id': -1, 'name': '', 'filename': '', 'memory': 256, 'nic_nb': 6, 'usermod': False, 'nic': 'rtl8139', 'flavor': 'Default', 'options': '', 'kvm': False, 'monitor': False } conf_qemuImage_types = { 'id': int, 'name': unicode, 'filename': unicode, 'memory': int, 'nic_nb': int, 'usermod': bool, 'nic': str, 'flavor': str, 'options': str, 'kvm': bool, 'monitor': bool } conf_vboxImage_defaults = { 'id': -1, 'name': '', 'filename': '', 'nic_nb': 6, 'nic': 'automatic', 'guestcontrol_user': '', 'guestcontrol_password': '', 'first_nic_managed': True, 'headless_mode': False, 'console_support': False, 'console_telnet_server': False, } conf_vboxImage_types = { 'id': int, 'name': unicode, 'filename': unicode, 'nic_nb': int, 'nic': str, 'guestcontrol_user': str, 'guestcontrol_password': str, 'first_nic_managed': bool, 'headless_mode': bool, 'console_support': bool, 'console_telnet_server': bool, } conf_pixImage_defaults = { 'id': -1, 'name': '', 'filename': '', 'memory': 128, 'nic_nb': 6, 'nic': 'e1000', 'options': '', 'key': '', 'serial': '' } conf_pixImage_types = { 'id': int, 'name': unicode, 'filename': unicode, 'memory': int, 'nic_nb': int, 'nic': str, 'options': str, 'key': str, 'serial': str } conf_junosImage_defaults = { 'id': -1, 'name': '', 'filename': '', 'memory': 512, 'nic_nb': 6, 'usermod' : False, 'nic': 'e1000', 'options': '', 'kvm': False, 'monitor': False } conf_junosImage_types = { 'id': int, 'name': unicode, 'filename': unicode, 'memory': int, 'nic_nb': int, 'usermod' : bool, 'nic': str, 'options': str, 'kvm': bool, 'monitor': bool } conf_asaImage_defaults = { 'id': -1, 'name': '', 'memory': 256, 'nic_nb': 6, 'usermod' : False, 'nic': 'e1000', 'options': '', 'kvm': False, 'monitor': False, 'kernel': '', 'initrd': '', 'kernel_cmdline': '' } conf_asaImage_types = { 'id': int, 'name': unicode, 'memory': int, 'nic_nb': int, 'usermod' : bool, 'nic': str, 'options': str, 'kvm': bool, 'monitor': bool, 'kernel': unicode, 'initrd': unicode, 'kernel_cmdline': unicode, } conf_awprouterImage_defaults = { 'id': -1, 'name': '', 'memory': 256, 'nic_nb': 6, 'usermod' : False, 'nic': 'virtio', 'options': '', 'kvm': False, 'kernel': '', 'initrd': '', 'rel': '', 'kernel_cmdline': 'root=/dev/ram0 releasefile=0.0.0-test.rel console=ttyS0,0 no_autorestart loglevel=1' } conf_awprouterImage_types = { 'id': int, 'name': unicode, 'memory': int, 'nic_nb': int, 'usermod' : bool, 'nic': str, 'options': str, 'kvm': bool, 'kernel': unicode, 'initrd': unicode, 'rel': unicode, 'kernel_cmdline': unicode, } conf_idsImage_defaults = { 'id': -1, 'name': '', 'image1': '', 'image2': '', 'memory': 512, 'nic_nb': 3, 'usermod' : False, 'nic': 'e1000', 'options': '', 'kvm': False, 'monitor': False } conf_idsImage_types = { 'id': int, 'name': unicode, 'image1': unicode, 'image2': unicode, 'memory': int, 'nic_nb': int, 'usermod' : bool, 'nic': str, 'options': str, 'kvm': bool, 'monitor': bool } conf_systemDynamips_defaults = { 'path': '', 'port': 7200, 'workdir': '', 'clean_workdir': True, 'baseUDP': 10001, 'baseConsole': 2101, 'baseAUX': 2501, 'ghosting': True, 'jitsharing': False, 'sparsemem': True, 'mmap': True, 'memory_limit': 512, 'udp_incrementation': 100, 'detected_version': '', 'import_use_HypervisorManager': True, 'allocateHypervisorPerIOS': True, 'HypervisorManager_binding': u'localhost', } conf_systemDynamips_types = { 'path': unicode, 'port': int, 'workdir': unicode, 'clean_workdir': bool, 'baseUDP': int, 'baseConsole': int, 'baseAUX': int, 'ghosting': bool, 'jitsharing': bool, 'sparsemem': bool, 'mmap': bool, 'memory_limit': int, 'udp_incrementation': int, 'detected_version': unicode, 'import_use_HypervisorManager': bool, 'allocateHypervisorPerIOS': bool, 'HypervisorManager_binding': unicode, } conf_systemGeneral_defaults = { 'lang': 'en', 'project_startup': True, 'relative_paths': True, 'auto_screenshot': True, 'slow_start': 1, 'autosave': 60, 'term_cmd': '', 'use_shell': True, 'bring_console_to_front': False, 'term_serial_cmd': '', 'term_close_on_delete': True, 'project_path': '.', 'ios_path': '.', 'status_points': True, 'manual_connection': False, 'scene_width': 2000, 'scene_height': 1000, 'auto_check_for_update': True, 'last_check_for_update': 0, 'console_delay': 1, } conf_systemGeneral_types = { 'lang': unicode, 'project_startup': bool, 'relative_paths': bool, 'auto_screenshot': bool, 'slow_start': int, 'autosave': int, 'use_shell': bool, 'bring_console_to_front': bool, 'term_cmd': unicode, 'term_serial_cmd': unicode, 'term_close_on_delete': bool, 'project_path': unicode, 'ios_path': unicode, 'status_points': bool, 'manual_connection': bool, 'scene_width': int, 'scene_height': int, 'auto_check_for_update': bool, 'last_check_for_update': int, 'console_delay': float, } conf_systemCapture_defaults = { 'workdir': '', 'cap_cmd': '', 'auto_start': False, } conf_systemCapture_types = { 'workdir': unicode, 'cap_cmd': unicode, 'auto_start': bool } conf_systemQemu_defaults = { 'qemuwrapper_path':'', 'qemuwrapper_workdir':'', 'qemu_path':'qemu', 'qemu_img_path':'qemu-img', 'external_hosts':[], 'enable_QemuWrapperAdvOptions' : False, 'enable_QemuManager': True, 'import_use_QemuManager': True, 'send_paths_external_Qemuwrapper': False, 'QemuManager_binding': u'localhost', 'qemuwrapper_port': 10525, 'qemuwrapper_baseUDP': 40000, 'qemuwrapper_baseConsole': 3001, } conf_systemQemu_types = { 'qemuwrapper_path': unicode, 'qemuwrapper_workdir': unicode, 'qemu_path': unicode, 'qemu_img_path': unicode, 'external_hosts': list, 'enable_QemuWrapperAdvOptions' : bool, 'enable_QemuManager': bool, 'import_use_QemuManager': bool, 'send_paths_external_Qemuwrapper': bool, 'QemuManager_binding': unicode, 'qemuwrapper_port': int, 'qemuwrapper_baseUDP': int, 'qemuwrapper_baseConsole': int, } conf_systemVBox_defaults = { 'vboxwrapper_path':'', 'vboxwrapper_workdir':'', 'external_hosts':[], 'use_VBoxVmnames': True, 'enable_VBoxWrapperAdvOptions' : False, 'enable_VBoxAdvOptions' : False, 'enable_GuestControl': False, 'enable_VBoxManager': True, 'import_use_VBoxManager': True, 'VBoxManager_binding': u'localhost', 'vboxwrapper_port': 11525, 'vboxwrapper_baseUDP': 20900, 'vboxwrapper_baseConsole': 3501, } conf_systemVBox_types = { 'vboxwrapper_path': unicode, 'vboxwrapper_workdir': unicode, 'external_hosts': list, 'use_VBoxVmnames': bool, 'enable_VBoxWrapperAdvOptions' : bool, 'enable_VBoxAdvOptions' : bool, 'enable_GuestControl': bool, 'enable_VBoxManager': bool, 'import_use_VBoxManager': bool, 'VBoxManager_binding': unicode, 'vboxwrapper_port': int, 'vboxwrapper_baseUDP': int, 'vboxwrapper_baseConsole': int, } conf_systemDeployementWizard_defaults = { 'deployementwizard_path': '', 'deployementwizard_filename': '', } conf_systemDeployementWizard_types = { 'deployementwizard_path': unicode, 'deployementwizard_filename': unicode, } gns3-legacy-GNS3-0.8.6/src/GNS3/Config/Objects.py000066400000000000000000000153741223163545200210370ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Config import Defaults class ConfigObject(object): def __init__(self): self.conf = {} self.types = {} def __getPropertiesFunctions(self, cls, name): obj = dir(cls) def __getattr__(self, name): #if constants.debuglevel > 1: # print "ADEBUG: Objects.py: ConfigObject::__getattr__(%s)" % str(name) if self.__dict__['conf'].has_key(name): # Call the getter function, if there is one, else # return the value directly from the `conf' dictionnary. try: method_name = "get_" + name method = getattr(self, method_name) if callable(method): return method() except: return self.__dict__['conf'][name] else: # In case the attribute is not part of the conf, # behave like the normal __getattr__ #try: super(ConfigObject, self).__getattr__(name) #except: # print "WARNING: object" + str(name) + "doesn't have __getattr__ attribute" def __setattr__(self, name, value): # We must bypass `conf' and `types' attributes, because we use # it in this function ! if name == 'conf' or not self.__dict__['conf'].has_key(name): return super(ConfigObject, self).__setattr__(name, value) if self.__dict__['conf'].has_key(name): # Check the `value' type if not type(value) == self.__dict__['types'][name]: raise AttributeError, "value of `%s' must be of type: %s" \ % (name, str(self.__dict__['types'][name])) # Call the setter function is one, else assign the value directly try: method_name = "set_" + name method = getattr(self, method_name) if callable(method): return method(value) except: self.__dict__['conf'][name] = value else: # In case the attribute is not part of the conf, # behave like the normal __setattr__ super(ConfigObject, self).__setattr__(name, value) # Post `set' function try: method_name = "postset_all" method = getattr(self, method_name) if callable(method): return method(name, value) except: # silently ignore errors pass class libraryConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_library_defaults.copy() self.types = Defaults.conf_library_types class recentFilesConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_recentfiles_defaults.copy() self.types = Defaults.conf_recentfiles_types class iosImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_iosImage_defaults.copy() self.types = Defaults.conf_iosImage_types class hypervisorConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_hypervisor_defaults.copy() self.types = Defaults.conf_hypervisor_types class qemuImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_qemuImage_defaults.copy() self.types = Defaults.conf_qemuImage_types class vboxImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_vboxImage_defaults.copy() self.types = Defaults.conf_vboxImage_types class pixImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_pixImage_defaults.copy() self.types = Defaults.conf_pixImage_types class junosImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_junosImage_defaults.copy() self.types = Defaults.conf_junosImage_types class asaImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_asaImage_defaults.copy() self.types = Defaults.conf_asaImage_types class awprouterImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_awprouterImage_defaults.copy() self.types = Defaults.conf_awprouterImage_types class idsImageConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_idsImage_defaults.copy() self.types = Defaults.conf_idsImage_types class systemDynamipsConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_systemDynamips_defaults.copy() self.types = Defaults.conf_systemDynamips_types class systemGeneralConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_systemGeneral_defaults.copy() self.types = Defaults.conf_systemGeneral_types class systemCaptureConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_systemCapture_defaults.copy() self.types = Defaults.conf_systemCapture_types class systemQemuConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_systemQemu_defaults.copy() self.types = Defaults.conf_systemQemu_types class systemVBoxConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_systemVBox_defaults.copy() self.types = Defaults.conf_systemVBox_types class systemDeployementWizardConf(ConfigObject): def __init__(self): ConfigObject.__init__(self) self.conf = Defaults.conf_systemDeployementWizard_defaults.copy() self.types = Defaults.conf_systemDeployementWizard_types gns3-legacy-GNS3-0.8.6/src/GNS3/Config/Preferences.py000066400000000000000000000133161223163545200217010ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # #print "WELCOME to Preferences.py" from PyQt4 import QtGui, QtCore from GNS3.Ui.Form_PreferencesDialog import Ui_PreferencesDialog from GNS3.Utils import translate import GNS3.Globals as globals class PreferencesDialog(QtGui.QDialog, Ui_PreferencesDialog): def __init__(self): """ Initilize a preferences dialog """ # force the translation of Capture translate('PreferencesDialog', 'Capture') self.__prefsList = [ 'General', 'Dynamips', 'Capture', 'Qemu', 'VirtualBox', #'DeployementWizard' #FIXME: TEMP DISABLED FOR GNS3 0.8.4 RC1. ] QtGui.QDialog.__init__(self) self.setupUi(self) self.connect(self.listWidget, QtCore.SIGNAL('currentItemChanged(QListWidgetItem *, QListWidgetItem *)'), self.configItemChanged) self.connect(self.buttonBox.button(QtGui.QDialogButtonBox.Apply), QtCore.SIGNAL('clicked()'), self.__applyChanges) # self.connect(self.buttonBox.button(QtGui.QDialogButtonBox.Ok), QtCore.SIGNAL('clicked()'), self.__applyChanges) # Init dialog self.__initDialog() # Raise a element in list self.__raiseWidgetByNum(0) def retranslateUi(self, MainWindow): # Call parent retranslateUi Ui_PreferencesDialog.retranslateUi(self, self) # Update titleLabel currIdx = self.stackedWidget.currentIndex() if currIdx > -1 and len(self.__prefsList) > currIdx: self.titleLabel.setText(translate('PreferencesDialog', self.__prefsList[currIdx])) # For each widget retranslate too lnum = 0 for itemName in self.__prefsList: try: widget = self.stackedWidget.widget(lnum) widget.retranslateUi(widget) self.listWidget.item(lnum).setText(translate('PreferencesDialog', self.__prefsList[lnum])) except Exception: # In case widgets don't have restranslateUi method pass lnum += 1 def __applyChanges(self): """ Save change for all item present into the Dialog All widget need to implement a method `saveConf' for this to work. """ lnum = 0 for itemName in self.__prefsList: widget = self.stackedWidget.widget(lnum) if widget.saveConf() == False: return False lnum += 1 return True def __loadWidget(self, widgetPrefix, widgetName): """ Load a config widget from GNS3.Ui.ConfigurationPages """ widgetCompleteName = widgetPrefix + widgetName modName = "GNS3.Ui.ConfigurationPages.Page_%s" % (widgetCompleteName) try: # Import module mod = __import__(modName) # Walk into module tree components = modName.split('.') for comp in components[1:]: mod = getattr(mod, comp) # Finally, get the class mod = getattr(mod, 'UiConfig_' + widgetPrefix + widgetName) return mod except ImportError, err: print "Error while importing %s: %s" % (modName, err) return None def __initDialog(self): # Insert config pages... lnum = 0 for itemName in self.__prefsList: cls = self.__loadWidget('Preferences', itemName) widget = cls() item = QtGui.QListWidgetItem(translate('PreferencesDialog', itemName), self.listWidget) # Insert widget / item into the dialog self.listWidget.insertItem(lnum, item) self.stackedWidget.insertWidget(lnum, widget) # increment for next item / widget lnum += 1 def __raiseWidgetByNum(self, num): self.titleLabel.setText( translate('PreferencesDialog', self.__prefsList[num])) # Set stackedWidget minimum size widget = self.stackedWidget.widget(num) self.stackedWidget.setMinimumSize(widget.size()) self.stackedWidget.resize(widget.size()) # Raise the demanded widget self.stackedWidget.setCurrentIndex(num) def configItemChanged(self, widget_curr, widget_prev): if widget_curr is None: widget_curr = widget_prev self.__raiseWidgetByNum(self.listWidget.row(widget_curr)) def reject(self): """ Refresh devices list when closing the window """ globals.GApp.mainWindow.nodesDock.populateNodeDock(globals.GApp.workspace.dockWidget_NodeTypes.windowTitle()) QtGui.QDialog.reject(self) def accept(self): """ Refresh devices list when closing the window """ globals.GApp.mainWindow.nodesDock.populateNodeDock(globals.GApp.workspace.dockWidget_NodeTypes.windowTitle()) if self.__applyChanges(): QtGui.QDialog.accept(self) gns3-legacy-GNS3-0.8.6/src/GNS3/Config/__init__.py000066400000000000000000000000651223163545200211740ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: gns3-legacy-GNS3-0.8.6/src/GNS3/Console.py000066400000000000000000000653631223163545200176460ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2011 GNS3 Development Team (http://www.gns3.net/team). # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # #class Console is basically overloading of "Dynagen/console.py", and of "Dynagen/confConsole.py" # with many functions redefined. #it allows you to type-in commands via GNS3 Dynagen console. import os, sys, cmd, socket import GNS3.Globals as globals import GNS3.Dynagen.dynagen as Dynagen_Namespace import GNS3.Dynagen.dynamips_lib as lib import GNS3.Dynagen.portTracker_lib as tracker import GNS3.NETFile as netfile from PyQt4 import QtCore, QtGui from GNS3.Utils import translate from GNS3.Dynagen.console import Console as Dynagen_Console, getItems, error from GNS3.External.PyCutExt import PyCutExt from GNS3.Node.IOSRouter import IOSRouter from GNS3.Node.AnyEmuDevice import AnyEmuDevice from GNS3.Node.AnyVBoxEmuDevice import AnyVBoxEmuDevice class Console(PyCutExt, Dynagen_Console): # list of keywords to color keywords = set(["aux", "capture", "clear", "console", "export", "filter", "help", "hist", "idlepc", "import", "list", "no", "push", "reload", "resume", "save", "send", "show", "start", "stop", "suspend", "telnet", "vboxexec", "qmonitor", "ver"]) def __init__(self, parent): """ Initialise the Console widget """ from __main__ import VERSION # Set the prompt, for Dynagen.Console and PyCutExt self.prompt = '=> ' sys.ps1 = '=> ' # Set introduction message self.intro = "GNS3 management console. Running GNS3 version %s.\nCopyright (c) 2006-2013 GNS3 Project." % VERSION # Parent class initialisation try: PyCutExt.__init__(self, None, self.intro, parent=parent) # put our own keywords list self.colorizer.keywords = self.keywords self._Dynagen_Console_init() except Exception, e: sys.stderr.write(e.message) def _Dynagen_Console_init(self): """ Dynagen Console class initialisation (i) Copy-Pasted from original Dynagen's console init function, as we need to re-order / modify some code """ cmd.Cmd.__init__(self) self.namespace = Dynagen_Namespace self.dynagen = globals.GApp.dynagen def onKeyPress_Tab(self): """ Imitate cmd.Cmd.complete(self, text, state) function """ line = str(self.line).lstrip() cmd = line args = '' if len(self.line) > 0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completenames else: compfunc = self.completenames self.completion_matches = compfunc(cmd, line, 0, 0) if self.completion_matches is not None: # Eliminate repeating values matches = [] for m in self.completion_matches: try: v = matches.index(m) except ValueError: matches.append(m) # Update original list self.completion_matches = matches # In case we only have one possible value replace it on cmdline if len(self.completion_matches) == 1: newLine = self.completion_matches[0] + " " + args self.line = QtCore.QString(newLine) self.point = len(newLine) # Else, display possible values else: self.write("\n") self.columnize(self.completion_matches) # In any case, reprint promt + line self.write("\n" + sys.ps1 + str(self.line)) def _run(self): """ Run as command as the cmd.Cmd class would do. PyCutExt was originaly using as Interpreter to exec user's commands. Here we use directly the cmd.Cmd class. """ self.pointer = 0 if len(self.line): self.history.append(QtCore.QString(self.line)) try: self.lines.append(str(self.line)) source = '\n'.join(self.lines) # Exec! self.more = self.onecmd(source) except Exception, e: print e self.write(self.prompt) self.lines = [] self._clearLine() def do_ver(self, args): """Print hypervisors, dynagen, GNS3, libs versions and credits""" import sip import struct from __main__ import VERSION, GNS3_RUN_PATH bitness = struct.calcsize("P") * 8 pythonver = str(sys.version_info[0]) + '.' +str(sys.version_info[1])+'.'+str(sys.version_info[2]) if hasattr(sys, "frozen"): print 'GNS3 version is ' + VERSION + " (compiled)" else: print 'GNS3 version is ' + VERSION print 'Qt version is ' + QtCore.QT_VERSION_STR print 'PyQt version is ' + QtCore.PYQT_VERSION_STR print 'SIP version is ' + sip.SIP_VERSION_STR print "Python version is %s (%d-bit)" % (pythonver, bitness) print "Python default encoding is " + sys.getdefaultencoding() print unicode("\nGNS3 run path is %s\n" % GNS3_RUN_PATH) try: Dynagen_Console.do_ver(self, args) except Exception, e: print e def do_start(self, args): """start {/all | device1 [device2] ...}\nstart all or a specific device(s)""" try: Dynagen_Console.do_start(self, args) devices = args.split(' ') for node in globals.GApp.topology.nodes.values(): if (isinstance(node, IOSRouter) or isinstance(node, AnyEmuDevice) or isinstance(node, AnyVBoxEmuDevice)) and (node.hostname in devices or '/all' in devices): node.startupInterfaces() globals.GApp.mainWindow.treeWidget_TopologySummary.changeNodeStatus(node.hostname, 'running') except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, unicode(msg)) except lib.DynamipsWarning, msg: QtGui.QMessageBox.warning(self, translate("Console", "%s: Dynamips warning") % node.hostname, unicode(msg)) except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, translate("Console", "Connection lost")) def do_stop(self, args): """stop {/all | device1 [device2] ...}\nstop all or a specific device(s)""" try: Dynagen_Console.do_stop(self, args) devices = args.split(' ') for node in globals.GApp.topology.nodes.values(): if (isinstance(node, IOSRouter) or isinstance(node, AnyEmuDevice) or isinstance(node, AnyVBoxEmuDevice)) and (node.hostname in devices or '/all' in devices): node.shutdownInterfaces() globals.GApp.mainWindow.treeWidget_TopologySummary.changeNodeStatus(node.hostname, 'stopped') except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, unicode(msg)) except lib.DynamipsWarning, msg: QtGui.QMessageBox.warning(self, translate("Console", "%s: Dynamips warning") % node.hostname, unicode(msg)) except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, translate("Console", "Connection lost")) def do_suspend(self, args): """suspend {/all | device1 [device2] ...}\nsuspend all or a specific device(s)""" try: Dynagen_Console.do_suspend(self, args) devices = args.split(' ') for node in globals.GApp.topology.nodes.values(): if (isinstance(node, IOSRouter) or isinstance(node, AnyVBoxEmuDevice)) and (node.hostname in devices or '/all' in devices): node.suspendInterfaces() globals.GApp.mainWindow.treeWidget_TopologySummary.changeNodeStatus(node.hostname, 'suspended') except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, unicode(msg)) except lib.DynamipsWarning, msg: QtGui.QMessageBox.warning(self, translate("Console", "%s Dynamips warning") % node.hostname, unicode(msg)) except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical(self, translate("Console", "%s Dynamips error") % node.hostname, translate("Console", "Connection lost")) def do_resume(self, args): """resume {/all | device1 [device2] ...}\nresume all or a specific device(s)""" try: Dynagen_Console.do_resume(self, args) devices = args.split(' ') for node in globals.GApp.topology.nodes.values(): if (isinstance(node, IOSRouter) or isinstance(node, AnyVBoxEmuDevice)) and (node.hostname in devices or '/all' in devices): node.startupInterfaces() globals.GApp.mainWindow.treeWidget_TopologySummary.changeNodeStatus(node.hostname, 'running') except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, unicode(msg)) except lib.DynamipsWarning, msg: QtGui.QMessageBox.warning(self, translate("Console", "%s: Dynamips warning") % node.hostname, unicode(msg)) except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, translate("Console", "Connection lost")) def do_reload(self, args): """reload {/all | device1 [device2] ...}\nreboots all or a specific device(s)""" self.do_stop(args) self.do_start(args) def do_vboxexec(self, args): """vboxexec \nVirtualBox GuestControl execute sends a command to VirtualBox guest and prints it's output (experimental feature). This requires VirtualBox Guest Additions to be installed inside the guest VM. Example for Windows guest: vboxexec VBOX1 ping.exe 127.0.0.1 Example for Linux guest: vboxexec VBOX1 /bin/ping 127.0.0.1 -c4""" if '?' in args or args.strip() == '': print self.do_vboxexec.__doc__ return if not globals.GApp.systconf['vbox'].enable_GuestControl: print "VirtualBox GuestControl execution is disabled in preferences" return try: node_name = args.split(' ')[0] for node in globals.GApp.topology.nodes.values(): if isinstance(node, AnyVBoxEmuDevice) and node.hostname == node_name: break Dynagen_Console.do_vboxexec(self, args) except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, unicode(msg)) except lib.DynamipsWarning, msg: QtGui.QMessageBox.warning(self, translate("Console", "%s: Dynamips warning") % node.hostname, unicode(msg)) except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, translate("Console", "Connection lost")) def do_qmonitor(self, args): """qmonitor \nCommunicate with qemu monitor mode.\nDisplay available commands: qmonitor help""" if '?' in args or args.strip() == '': print self.do_qmonitor.__doc__ return try: Dynagen_Console.do_qmonitor(self, args) except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("Console", "Dynamips error"), unicode(msg)) except lib.DynamipsWarning, msg: QtGui.QMessageBox.warning(self, translate("Console", "Dynamips warning"), unicode(msg)) except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical(self, translate("Console", "Dynamips error"), translate("Console", "Connection lost")) def do_show(self, args): """show mac \tshow the mac address table of an ethernet switch show device \tshow detail information about every device in current lab show device \tshow detail information about a device show start \tshow startup lab configuration show run \tshow running configuration of current lab show run \tshow running configuration of a router show hypervisors \tshow allocated memory for hypervisors by Hypervisor Manager show ports \tshow all TCP ports allocated by GNS3 show project_info \tshow the current project path """ if '?' in args or args.strip() == '': print self.do_show.__doc__ return command = args.split()[0].lower() if command == 'hypervisors' and globals.GApp.HypervisorManager: globals.GApp.HypervisorManager.showHypervisors() return elif command == 'ports': track = tracker.portTracker() track.showTcpPortAllocation() return elif command == 'project_info': print print "Project File:\t\t\t" + globals.GApp.mainWindow.projectFile if globals.GApp.workspace.projectWorkdir: print "Project Working directory:\t\t" + globals.GApp.workspace.projectWorkdir print "Project Config directory:\t\t" + globals.GApp.workspace.projectConfigs print qemu_flash_drives_directory = os.path.dirname(globals.GApp.workspace.projectFile) + os.sep + 'qemu-flash-drives' if os.access(qemu_flash_drives_directory, os.F_OK): workdir = qemu_flash_drives_directory elif globals.GApp.systconf['qemu'].qemuwrapper_workdir: workdir = globals.GApp.systconf['qemu'].qemuwrapper_workdir else: realpath = os.path.realpath(self.dynagen.global_filename) workdir = os.path.dirname(realpath) print "Qemuwrapper working directory:\t" + workdir if globals.GApp.systconf['vbox'].enable_VBoxManager: if globals.GApp.workspace.projectWorkdir: workdir = globals.GApp.workspace.projectWorkdir elif globals.GApp.systconf['vbox'].vboxwrapper_workdir: workdir = globals.GApp.systconf['vbox'].vboxwrapper_workdir else: realpath = os.path.realpath(self.dynagen.global_filename) workdir = os.path.dirname(realpath) print "Vboxwrapper working directory:\t" + workdir else: print "VBoxManager is disabled" print "Dynamips working directory:\t\t" + globals.GApp.systconf['dynamips'].workdir else: Dynagen_Console.do_show(self, args) def do_clear(self, args): """clear [item] Examples: clear mac -- clear the mac address table of an ethernet switch clear topology -- clear the network topology""" if '?' in args or args.strip() == '': print self.do_clear.__doc__ return try: command = args.split()[0].lower() params = args.split()[1:] if command == 'topology': globals.GApp.topology.clear() return if command == 'mac': try: Dynagen_Console.do_clear(self, args) except Exception, e: print e except ValueError: print translate("Console", "Incorrect number of paramaters or invalid parameters") return except KeyError: print translate("Console", "Unknown device: %s") % device return except lib.DynamipsError, e: print e return def do_hist(self, args): """print a list of commands that have been entered""" for entry in self.history: print unicode(entry, 'utf-8', errors='replace') def do_idlepc(self, args): """idlepc {get|set|show|save|idlemax|idlesleep|showdrift} device [value] idlepc save device [default] get, set, or show the online idlepc value(s) Examples: idlepc get r1 -- Get a list of the possible idlepc value(s) for router r1 idlepc show r1 -- Show the previously determined idlepc values for router r1 idlepc set r1 0x12345 -- Manually set r1's idlepc to 0x12345 idlepc save r1 -- Save r1's current idlepc value to the "router r1" section of your network file idlepc save r1 default -- Save r1's current idlepc value to the device defaults section of your network file (i.e. [[7200]]) idlepc save r1 db -- Save r1's current idlepc value to the idlepc database idlepc idlemax r1 1500 -- Commands for advanced manipulation of idlepc idlepc idlesleep r1 30 settings idlepc showdrift r1 """ if '?' in args or args.strip() == '': print Dynagen_Console.do_idlepc.__doc__ return try: command = args.split()[0] command = command.lower() params = args.split()[1:] if len(params) < 1: print Dynagen_Console.do_idlepc.__doc__ return if command == 'save': print translate("Console", "Sorry, not implemented in GNS3") return if command == 'get' or command == 'show': device = params[0] if command == 'get': current_idlepc = self.dynagen.devices[device].idlepc if (len(params) < 2 or params[1] != 'force') and current_idlepc: print translate("Console", "%s already has an idlepc value applied (%s).") % (device, current_idlepc) return print translate("Console", "Please wait while gathering statistics...") globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) result = self.dynagen.devices[device].idleprop(lib.IDLEPROPGET) elif command == 'show': result = self.dynagen.devices[device].idleprop(lib.IDLEPROPSHOW) result.pop() # Remove the '100-OK' line idles = {} i = 1 output = '' for line in result: (value, count) = line.split()[1:] # Flag potentially "best" idlepc values (between 50 and 60) iCount = int(count[1:-1]) if 50 < iCount < 60: flag = '*' else: flag = ' ' output += "%s %2i: %s %s\n" % (flag, i, value, count) idles[i] = value i += 1 # Allow user to choose a value by number if len(idles) == 0: print translate("Console", "No idlepc values found") else: output = translate("Console", "Potentially better idlepc values marked with '*'\nEnter the number of the idlepc value to apply [1-%i] or ENTER for no change:\n") % len(idles) + output globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) (selection, ok) = QtGui.QInputDialog.getText(globals.GApp.mainWindow, 'idlepc', output, QtGui.QLineEdit.Normal) if not ok: print translate("Console", "No changes made") return selection = str(selection) if selection == "": print translate("Console", "No changes made") return try: self.dynagen.devices[device].idleprop(lib.IDLEPROPSET, idles[int(selection)]) print translate("Console", "Applied idlepc value %s to %s\n") % (idles[int(selection)], device) for node in globals.GApp.topology.nodes.values(): if isinstance(node, IOSRouter) and node.hostname == device: router = node.get_dynagen_device() if globals.GApp.iosimages.has_key(router.dynamips.host + ':' + router.image): image = globals.GApp.iosimages[router.dynamips.host + ':' + router.image] image.idlepc = idles[int(selection)] except: print translate("Console", "Can't apply idlepc value") else: Dynagen_Console.do_idlepc(self, args) except ValueError: print translate("Console", "Incorrect number of paramaters or invalid parameters") return except KeyError: print translate("Console", "Unknown device: %s") % device return except lib.DynamipsError, e: print e return def do_save(self, args): """save {/all | router1 [router2] ...}\nstores router configs in the network file""" if not globals.GApp.workspace.projectFile: print translate("Console", "You have to save your topology before using save") else: Dynagen_Console.do_save(self, args) def do_push(self, args): """push {/all | router1 [router2] ...}\npushes router configs from the network file to the router's nvram""" if not globals.GApp.workspace.projectFile: print translate("Console", "You have to save your topology before using push") else: Dynagen_Console.do_push(self, args) def do_telnet(self, args): """telnet {/all | router1 [router2] ...}\nconnect to the console(s) of all or a specific router(s)\nThis is identical to the console command.""" self.do_console(args) def do_console(self, args): """console {/all | router1 [router2] ...}\nconnect to the console(s) of all or a specific router(s)\n""" devices = args.split(' ') for node in globals.GApp.topology.nodes.values(): if isinstance(node, IOSRouter) and (node.hostname in devices or '/all' in devices): node.console() def do_aux(self, args): """aux {/all | router1 [router2] ...}\nconnect to the AUX port(s) of all or a specific router(s)\n""" devices = args.split(' ') for node in globals.GApp.topology.nodes.values(): if isinstance(node, IOSRouter) and (node.hostname in devices or '/all' in devices): node.aux() def do_export(self, args): """export {/all | router1 [router2] ...} \"directory\"\nsaves router configs individual files in \"directory\"\nEnclose the directory in quotes if there are spaces in the filespec.""" if '?' in args or args.strip() == '': print Dynagen_Console.do_export.__doc__ return try: items = getItems(args) except lib.DynamipsError, e: error(e) return if len(items) < 2: print Dynagen_Console.do_export.__doc__ return # The last item is the directory (or should be anyway) directory = items.pop().strip('"') if not os.access(directory, os.F_OK): try: os.mkdir(directory) except (OSError, IOError), e: print translate("Console", "Cannot create %s: %s") % (directory, e.strerror) return if '/all' in items: # Set devices to all the devices devices = self.dynagen.devices.values() else: devices = [] for device in items: # Create a list of all the device objects try: devices.append(self.dynagen.devices[device]) except KeyError: print 'unknown device: ' + device return save = globals.GApp.workspace.projectConfigs globals.GApp.workspace.projectConfigs = directory net = netfile.NETFile() for device in devices: if isinstance(device, lib.Router): try: net.export_router_config(device) except lib.DynamipsErrorHandled: continue globals.GApp.workspace.projectConfigs = save def do_import(self, args): """import {/all | router1 [router2] \"directory\"\nimport all or individual configuration files \nEnclose the directory or filename in quotes if there are spaces in the filespec.""" Dynagen_Console.do_import(self, args) def do_debug(self, args): """debug [level]\nActivate/Deactivate debugs\nLevel 0: no debugs\nLevel 1: dynamips lib debugs only\nLevel 2: GNS3 debugs only\nLevel 3: GNS3 debugs and dynamips lib debugs""" if len(args) == 1: try: level = int(args[0]) if level == 1 or level == 3: globals.debugLevel = level lib.setdebug(True) tracker.setdebug(True) if level == 0 or level == 2: globals.debugLevel = level lib.setdebug(False) tracker.setdebug(False) except: print self.do_debug.__doc__ else: print self.do_debug.__doc__ print "Current debug level is %i" % globals.debugLevel gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/000077500000000000000000000000001223163545200174245ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/AbstractDefaults.py000066400000000000000000000033171223163545200232350ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # import GNS3.Globals as globals class AbstractDefaults(object): """ Abstract class for managing the device defaults """ model = None def __init__(self): self.dynagen = globals.GApp.dynagen self.config = None def set_int_option(self, option, argument): """ Set integer type option in config """ option_value = int(argument) if getattr(self, 'default_' + option) == option_value: if self.config.has_key(option): del self.config[option] else: self.config[option] = option_value def set_string_option(self, option, argument): """ Set string type option in config """ option_value = argument if getattr(self, 'default_' + option) == option_value: if self.config.has_key(option): del self.config[option] else: self.config[option] = option_value gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/AnyEmuDefaults.py000066400000000000000000000062661223163545200226760ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Defaults.AbstractDefaults import AbstractDefaults class AnyEmuDefaults(AbstractDefaults): """Abstract class for managing the emulated device defaults""" def __init__(self): AbstractDefaults.__init__(self) self.default_image = 'None' self.default_netcard = 'rtl8139' self.default_flavor = 'Default' self.default_nics = 6 self.default_usermod = False self.default_kvm = False self.default_monitor = False self.default_options = '' self.default_ram = 256 self.qemu = None self.d = None def set_hypervisor(self, qemu): """ Records an Qemu hypervisor qemu: Qemu object """ self.qemu = qemu self.d = 'qemu ' + unicode(self.qemu.host) + ':' + str(self.qemu.port) self.config = self.dynagen.defaults_config[self.d] def set_image(self, image, model): """ Set a image path image: string model: string """ self.model = model if model in self.config: self.config = self.config[model] else: self.config[model] = {} self.config = self.config[model] if self.default_image == image: if self.config.has_key('image'): del self.config['image'] else: self.config['image'] = image class QemuDefaults(AnyEmuDefaults): def __init__(self): AnyEmuDefaults.__init__(self) class PIXDefaults(AnyEmuDefaults): def __init__(self): AnyEmuDefaults.__init__(self) self.default_serial = '0x12345678' self.default_key = '0x00000000,0x00000000,0x00000000,0x00000000' class ASADefaults(AnyEmuDefaults): def __init__(self): AnyEmuDefaults.__init__(self) self.default_initrd = 'None' self.default_kernel = 'None' self.default_kernel_cmdline = 'None' class JunOSDefaults(AnyEmuDefaults): def __init__(self): AnyEmuDefaults.__init__(self) class AWPDefaults(AnyEmuDefaults): def __init__(self): AnyEmuDefaults.__init__(self) self.default_initrd = 'None' self.default_kernel = 'None' self.default_rel = 'None' self.default_kernel_cmdline = 'None' class IDSDefaults(AnyEmuDefaults): def __init__(self): AnyEmuDefaults.__init__(self) self.default_image1 = 'None' self.default_image2 = 'None' gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/AnyVBoxEmuDefaults.py000066400000000000000000000044231223163545200234660ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2011 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Defaults.AbstractDefaults import AbstractDefaults class AnyVBoxEmuDefaults(AbstractDefaults): """Abstract class for managing the vitualized device defaults""" def __init__(self): AbstractDefaults.__init__(self) self.default_image = 'None' self.default_netcard = 'automatic' self.default_nics = 6 self.default_guestcontrol_user = '' self.default_first_nic_managed = True self.default_headless_mode = False self.default_console_support = False self.default_console_telnet_server = False self.default_guestcontrol_password = '' self.vbox = None self.d = None def set_hypervisor(self, vbox): """ Records an VBox hypervisor vbox: VBox object """ self.vbox = vbox self.d = 'vbox ' + unicode(self.vbox.host) + ':' + str(self.vbox.port) self.config = self.dynagen.defaults_config[self.d] def set_image(self, image, model): """ Set a image path image: string model: string """ self.model = model if model in self.config: self.config = self.config[model] else: self.config[model] = {} self.config = self.config[model] if self.default_image == image: if self.config.has_key('image'): del self.config['image'] else: self.config['image'] = image class VBoxDefaults(AnyVBoxEmuDefaults): pass gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/IOSRouter1700Defaults.py000066400000000000000000000022631223163545200236340ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Defaults.IOSRouterDefaults import IOSRouterDefaults class IOSRouter1700Defaults(IOSRouterDefaults): """ Class for managing the defaults of Cisco 1700 platform """ def __init__(self): IOSRouterDefaults.__init__(self) #fill 1700 defaults self.default_ram = 64 self.default_nvram = 32 self.default_disk0 = 0 self.default_disk1 = 0 gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/IOSRouter2600Defaults.py000066400000000000000000000022641223163545200236350ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Defaults.IOSRouterDefaults import IOSRouterDefaults class IOSRouter2600Defaults(IOSRouterDefaults): """ Class for managing the defaults of Cisco 2600 platform """ def __init__(self): IOSRouterDefaults.__init__(self) #fill 2600 defaults self.default_ram = 128 self.default_nvram = 64 self.default_disk0 = 8 self.default_disk1 = 8 gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/IOSRouter3600Defaults.py000066400000000000000000000023321223163545200236320ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Defaults.IOSRouterDefaults import IOSRouterDefaults class IOSRouter3600Defaults(IOSRouterDefaults): """ Class for managing the defaults of Cisco 3600 platform """ def __init__(self): IOSRouterDefaults.__init__(self) #fill 3600 defaults self.default_ram = 128 self.default_nvram = 128 self.default_disk0 = 0 self.default_disk1 = 0 self.default_iomem = 'None' gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/IOSRouter3700Defaults.py000066400000000000000000000027411223163545200236370ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Defaults.IOSRouterDefaults import IOSRouterDefaults class IOSRouter3700Defaults(IOSRouterDefaults): """ Class for managing the defaults of Cisco 3700 platform """ def __init__(self): IOSRouterDefaults.__init__(self) #fill 3700 defaults self.default_ram = 128 self.default_nvram = 55 self.default_disk0 = 16 self.default_disk1 = 0 def set_image(self, image, model): """ Set a image path image: string model: string """ IOSRouterDefaults.set_image(self, image, model) # 3745 has a different default nvram if model == '3745': self.default_nvram = 151 gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/IOSRouter7200Defaults.py000066400000000000000000000024011223163545200236270ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # from GNS3.Defaults.IOSRouterDefaults import IOSRouterDefaults class IOSRouter7200Defaults(IOSRouterDefaults): """ Class for managing the defaults of Cisco 7200 platform """ def __init__(self): IOSRouterDefaults.__init__(self) #fill 7200 defaults self.default_ram = 256 self.default_nvram = 128 self.default_disk0 = 64 self.default_disk1 = 0 self.default_npe = 'npe-200' self.default_midplane = 'vxr' gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/IOSRouterDefaults.py000066400000000000000000000072311223163545200233240ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # import sys, os from GNS3.Defaults.AbstractDefaults import AbstractDefaults class IOSRouterDefaults(AbstractDefaults): """Abstract class for managing the IOSRouter defaults""" def __init__(self): AbstractDefaults.__init__(self) self.chassis = 'None' self.default_image = 'None' self.default_ghostios = 'False' self.default_jitsharing = 'False' self.default_cnfg = 'None' self.default_conf = 'None' self.default_confreg = '0x2102' self.default_aux = 'None' self.default_idlepc = 'None' self.default_idlemax = 1500 self.default_idlesleep = 30 self.default_exec_area = 'None' self.default_mmap = True self.default_sparsemem = 'False' self.hypervisor = None self.d = None def set_hypervisor(self, hypervisor): """ Records a hypervisor hypervisor: Dynamips object """ self.hypervisor = hypervisor self.d = self.hypervisor.host + ':' + str(self.hypervisor.port) self.config = self.dynagen.defaults_config[self.d] def set_image(self, image, model): """ Set a image path image: string model: string """ self.model = model if model in self.config: self.config = self.config[model] else: self.config[model] = {} self.config = self.config[model] if self.default_image == image: if self.config.has_key('image'): del self.config['image'] else: self.config['image'] = image # basename doesn't work on Unix with Windows paths, so let's use this little trick if not sys.platform.startswith('win') and image[1] == ":": image = image[2:] image = image.replace("\\", "/") imagename = os.path.basename(image) #try to find idlepc value for this image in idlepc db if self.dynagen.useridledb: if imagename in self.dynagen.useridledb: print imagename + ' found in user idlepc database\nSetting idlepc value to ' + self.dynagen.useridledb[imagename] self.config['idlepc'] = self.dynagen.useridledb[imagename] def set_ghostios(self, ghostios): """ Enable or disable ghostios feature """ if self.default_ghostios == ghostios: if self.config.has_key('ghostios'): del self.config['ghostios'] else: self.config['ghostios'] = bool(ghostios) def set_jitsharing(self, jitsharing): """ Enable or disable JIT blocks sharing feature """ if self.default_jitsharing == jitsharing: if self.config.has_key('jitsharing'): del self.config['jitsharing'] else: self.config['jitsharing'] = bool(jitsharing) gns3-legacy-GNS3-0.8.6/src/GNS3/Defaults/__init__.py000066400000000000000000000000651223163545200215360ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: gns3-legacy-GNS3-0.8.6/src/GNS3/DragDropMultipleDevicesDialog.py000066400000000000000000000037001223163545200240700ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: expandtab ts=4 sw=4 sts=4: # # Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team). # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # http://www.gns3.net/contact # #debuglevel: 0=disabled, 1=default, 2=debug, 3=deep debug debuglevel = 0 def debugmsg(level, message): if debuglevel == 0: return if debuglevel >= level: print message import sys, time import GNS3.Globals as globals from PyQt4 import QtCore, QtGui, QtSvg, Qt from GNS3.Topology import Topology from GNS3.Utils import translate, debug from GNS3.Ui.Form_DragAndDropMultiDevices import Ui_DragDropMultipleDevices class DragDropMultipleDevicesDialog(QtGui.QDialog, Ui_DragDropMultipleDevices): """Allows the user to drag & drop several identical items (multi-drop feature) on the topology """ def __init__(self): QtGui.QDialog.__init__(self) self.setupUi(self) self.connect(self.OKButton, QtCore.SIGNAL('clicked()'), self.__dropItems) def __dropItems(self): QtGui.QDialog.accept(self) def getNbOfDevices(self): return self.nbOfDevices.value() def getArrangement(self): if self.LineArrangement_radioButton.isChecked(): return "Line" else: return "Circle" gns3-legacy-GNS3-0.8.6/src/GNS3/Dynagen/000077500000000000000000000000001223163545200172425ustar00rootroot00000000000000gns3-legacy-GNS3-0.8.6/src/GNS3/Dynagen/COPYING000077500000000000000000000434051223163545200203060ustar00rootroot00000000000000NOTE: This licensing information applies to Dynagen only. For licensing information on Dynamips (which may or may not be included with this distribution) refer to the Dynamips web site. 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. Copyright (C) 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. , 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. gns3-legacy-GNS3-0.8.6/src/GNS3/Dynagen/README.txt000077500000000000000000000517261223163545200207560ustar00rootroot00000000000000Dynagen README Version 0.11.1.091203 For documentation, refer to the tutorial in the docs directory, and the sample network files in the sample_labs directory. To see usage examples for all options, refer to the "all_config_options.txt" file in the sample_labs directory. Also be sure to visit the Dynamips web site at http://www.ipflow.utc.fr/index.php/Cisco_7200_Simulator. This version of Dynagen requires at least version 0.2.8-RC1 of Dynamips. The Windows installer package requires at least Windows XP SP2. For earlier versions of Windows, replace the Dynamips binary with the Windows 2000 version as described in the Dynagen FAQ section of the tutorial. Known Issues ============ * "save" and "idlepc save" commands may reformat the indentation of your network file and add an explicit "model" definition in the router section * Gig interfaces on the NPE-G2 cannot currently be used. Changelog ========= Version 0.11.1.091203 * "delay" option added to dynagen.ini. Allows you to globally set the default delay between device startups. * Added a progress bar which is displayed during the delay between device startups. * Sync with GNS3, which includes: - Some ghosting changes made by Pavel - Unicode support - Quick JIT blocks sharing support - Allows use of "monitor" filter provided by dynamips - Pavel's automatic unused slot removal Version 0.11.0 * Merge of the features of confDynagen (dynamic reconfiguration, pemu support, and many other features). Big thanks to Pavel Skovajsa for performing the merge work and other significant contributions. * Addition of a pemu server for Cisco PIX emulation. Thanks to Thomas Pani for writing the wrapper, and to mmm123 for writing pemu. NOTE: A Pemu instance will always consume 100% of a CPU core. There is no "idlepc". Use a tool like BES (Windows) or cpulimit (Linux) if you wish to reduce CPU usage. * Could not specify a model of 1751 or 1760 in a router definition * WIC interfaces on 1751s and 1760s could not be used * On Windows platforms, Network Device list changes to the temp dir before executing Dynamips (helps Vista users). * Added a delay option to start /all. This introduces a pause between starting devices. * Filter command was broken in 0.10.x * FS#217 - fixed the connect method for switches. Only effected 3rd party developers using the library, Dynagen does not use these methods. * FS#211 - Dynagen crash when specifying invalid port * 7200 instances now default to using an NPE-400 rather than an NPE-200. This is because the C7200-IO-2FE is not compatible with the NPE-200 and this was causing confusion. You can override this new behavior with "npe = NPE-200". * Referencing f0/0 or f0/1 with 7200s now automatically inserts a C7200-IO-2FE in slot 0 rather than a C7200-IO-FE. You can override this behavior by specifying "slot0=PA-C7200-IO-FE". * Support for ATM to Ethernet bridge introduced in Dynamips 0.2.8-RC2. Provision using ATMBR. * idlemax issue fixed (see http://7200emu.hacki.at/viewtopic.php?p=13676) * Resolves crash when invalid port specified on adapter (http://7200emu.hacki.at/viewtopic.php?p=15685) * Dynagen now warns if a router does not have an image set * The prefix "PA-" for the 7200 IO adapters is optional (i.e. "PA-C7200-IO-2FE" or "C7200-IO-2FE"). * Multisever config with two instances on the same system no longer requires use of the UDP configuration option workaround. * The adapter "PA-4T+" should now be specified as "PA-4T+". "PA-4T" is still supported so as not to break compatibility with existing labs. * Added a "start-pemu.sh" script to launch pemuwrapper, writing temp files to a temp directory. To be used on Linux systems. * Throws a warning for the infamous "using localhost with multiserver" misconfiguration. * Change of base udp port for pemuwrapper to 40000 so that we do not conflict with vpc * "idlepc show" now shows the current idlepc value if one has already been applied * idlepc commands now warn that pemu instances are not supported * Added "ghostsize" command to dynamic configuration mode * Ignores GNS3-DATA section. Caution: Issuing a "copy run start" from inside of Dynagen will obliterate this section. Version 0.10.1 * Accidentally only gave the NM-16ESW 15 interfaces. Version 0.10.0 * Support for the 1700 platform new to Dynamips 0.8.0-RC1. See the tutorial for supported platforms and modules. * Support for WIC-1T, WIC-2T, and WIC-1ENET. See the tutorial for supported router platforms and usage. * Support for NM-CIDS and NM-NAM. Note these are just "stubs" (at least as of this version of Dynamips). You can connect to them using "IDS-Sensorx/0 = ..." or "Analysis-Modulex/0 = ..." but they don't actually do anything. See the tutorial for platform support. * FS#154 - added "confreg" command to set the configuration register of router(s) from Dynagen. e.g. "confreg r1 0x2142" followed by "reload r1". Note changes to the config register will not be displayed in a "show ver" until the router is reloaded. * FS#182 - Second port of PA-C7200-IO-2FE was not usable * FS#177 - crash on malformed interface entry in net file * Dynagen now automatically picks a PA-2FE-TX rather than a PA-FE-TX when referencing a FastEthernet on ports 1-6 on a 7200. You can override this to mimic the old behavior with "slotx = PA-FE-TX". * the vbs file that launches SecureCRT sessions was missing from the Windows installer package * Changed the state shown with the "list" command for virtual switches from "n/a" to "always on" to avoid confusion. * Added an up-to-date list of hardware emulated by Dynamips to the tutorial. Thanks to ggee for performing the initial documentation in this post: http://7200emu.hacki.at/viewtopic.php?t=1831 Version 0.9.3 * No longer prints a warning for unused switchports * Added "MAC" option to set base MAC address of a router. See all_config_options.txt for usage. * Eliminated unnecessary Leopard-2FE insertion on 3660s resulting in "a NM already exists in slot 0" warnings from Dynamips. * Fix bug that caused crash when trying to capture packets on an unconnected interface * Dynamips temp files are now written to the user's temp dir rather than \Program Files\Dynamips. Might make it work better under Vista. * Dynagen allows POS to frame-relay switch connections. But there seems to be a bug in dynamips 0.2.7 that prevents it from functioning. * Console entries in dynagen.ini for use with iTerm on OS X and SecureCRT on Windows. The SecureCRT one is a little glitchy but generally works. * Entering "no ?" caused a crash * Including a new Network Device list script for Windows that includes interface descriptions in the output contributed by Volker Semken. Version 0.9.2 * Fixed required version string * Removed false warning message when autostart is used at the router level * Added some info and fixed some misspellings in all_config_options.txt * Added the console command. It is identical to the telnet command. It occurred to me that "telnet" is a misleading command since a connection to the console is actually being made. But you can use which ever one you prefer, and you can abbreviate "console" as "con" if you wish. Version 0.9.1 * added "oldidle" option for use in network files. Setting this to true allows you to use pre-0.2.7-RC2 idlepc values. This disables direct jumps between JIT blocks (new to 0.2.7 RC2). Use this a the top level of your network file, or in the defaults or specific router definition. * sparsemem was misspelled in all_config_options.txt * Built-in motherboard Ethernet/fastethernet interfaces now are automatically created on 2600 platforms. * Improved checking for attempts to insert network modules into unsupported slots, and the error now indicates the offending router name. * I totally neglected to include the 2611XM. Sorry 2611XM! * 2621, 2621XM, and 2651XM mistakenly only got one integrated FE instead of two. * Could not use gigabit adapters properly on 7200s * This version performs much more rigorous checking for the validity of adapters against routers, and now outputs warnings for config items that it cannot parse and ignores. This should help with troubleshooting network files. * Added a check for minimum required version of dynamips * Added a check for trying to run idlepcget when an idlepc value has already been applied * Fixed misc idlepc get/save bugs. BTS 143, BTS 111 and BTS 116 * "save" only saved configs on the first server of a multiserver config when both instances of dynamips were running on the same system * fixed NPE-G2 with ghostios bug * Other misc general error handling and message improvements Version 0.9.0 * Added packet capture, via the "capture" command. Capture files are written to the host on which the dynamips server is running in PCAP format (i.e. can be opened with tcpdump, Wireshark, etc.) * Added support for all the new 2600 models Chris added in 0.2.7. * Added support for sparsemem. Enable with "sparsemem = true" at either the top level of the network file or in the device defaults or device section * New adapters for 7200s: PA-2FE-TX, PA-GE, C7200-IO-2FE, C7200-IO-GE-E. Specify the new IO cards with "slot0" options, and the new adapters with "slotx" options, where x is 1-6. * New NPEs for 7200s: npe-g1, npe-g2 Version 0.8.3 * Added a "--notelnet" command line option to make integration with gDynagen easier. See http://gdynagen.sourceforge.net Version 0.8.2 * Ghost instances are now deleted once the mmap file has been created. This means there is no longer a ghost instance consuming process VM space. * Ghost size is automatically calculated. Use of the "ghostsize" option should no longer be necessary. Thanks to this and the previous bugfix, I don't think there are any situations (other than using compressed images) that should cause ghostios to break otherwise functioning labs. * When using multiple dynamips servers running on the same host, ghost files are shared among the dynamips processes if possible. * Added "idlemax", "idlesleep', and "showdrift" idlepc commands for advanced manipulation and diagnostics of idlepc. Added "idlemax" and "idlesleep" network file options to go along with the CLI commands. The network file options aren't supported with in dynamips yet (as of 0.2.6-RC4), so don't try to use them. * Rewrote send() to fix BTS #94. * Added check for non-running routers in telnet command. BTS #102 Version 0.8.1 * So, as great as the Ghost RAM feature is, it does have the potential to break existing labs (for example, if the lab uses compressed images.) So for safety and to preserve backwards compatibility ghostios now defaults to False. You can turn it on with "ghostios = true" in either the router definition, the device defaults section, or at the top level of your network file. As usual, see all_config_options.txt for more info. * Fixed bug that caused crash when using ghostios and image paths that do not include any directory separator characters. * Trying to manually start a nonexistent router caused dynagen to crash. * Ghost instances are only created if two or more routers on the same dynamips host use the same IOS image. This optimization eliminates unnecessary host virtual memory consumption, so as not to run into process vm size limits unnecessarily. * Added an option to manually tweak the virtual ram allocated to Ghost images. Set this with "ghostsize = ..." in either the router definition, the device defaults section, or at the top level of your network file. The default is whatever that class of router would normally use. Version 0.8.0 * 2691, 3725, and 3745 support. Usage is as you would expect, but see all_config_options.txt for documentation. * Support for the IOS ghosting feature added in 0.2.6-RC3. IOS ghosting takes advantage of the mmap() "MAP_PRIVATE" flag to allocate a shared memory mapped file for IOS images. So instead of each virtual router storing an identical copy of IOS in its virtual RAM, the host will allocate one shared region of memory that they will all share. If you are running 10 routers all with the same IOS image, and that image is 60 MB in size you will save 9*60 = 540 MB of real RAM when running your lab with this feature. If you are using mmap (which is on by default) then IOS ghosting will automatically be implemented and you don't need to make any changes to your labs to take advantage of it. You can turn it off on a per router (or per device default section) with "ghostios = False" if you so desire. If you are using more than one IOS image in your lab then the feature still works, but the sharing will only occur among routers that are using the same image. The ghost file created is based on the name of your IOS image, so be sure that all your images have different names in a given lab (all the more reason to use the image naming convention recommended in the tutorial.) * Corrected some minor typos in all_config_options.txt (thanks Dmitry M) * Added error checks for malformed or non-existent devices specified in push/save/import/export commands. BTS #94 * ctrl-c then return now exits the CLI instead of crashing. BTS #89 * With RC3 push / extract are much improved so import/export/push/save should all work much better. I removed the workaround code that ensured routers were started before push / extract operations since that is no longer necessary with 0.2.6-RC3. * The Windows installer no longer overwrites dynagen.ini if it exists (so as not to obliterate customizations). In all cases it creates a file dynagen.ini.new that might contain additional options. You should manually compare your dynagen.ini and this file to see if any of the new options are useful to you. Version 0.7.0 * Added idlepc commands, for generating, testing, and saving idlepc values from Dynagen. See the tutorial for example usage. * Also includes a system for maintaining your idlepc values in a "database" indexed by the image name. Again, see the tutorial for an example of how to use this feature. * Added import / export CLI commands that store / retrieve IOS configs in a directory. Can be used as an alternative to save / push for packaging up labs, for creating "snapshots" for later retrieval, importing configurations from "the real world", etc. Note this feature is experimental and is still being refined. Garbled import / exports have been observed. (Thanks to "solo" for assistance with patch). * Network files and CLI commands (should) now also support two letter interface type designations (e.g. Fa0/1 or. F0/1) * Added "send" CLI command for sending raw hypervisor commands. Here is some rope, try not to hang yourself with it... * Dynagen checks for console selection conflicts. BTS #92 * Added a "debug" top level option to turn on debugging from network files. Usage is "debug = " and a number from 0 - 9. Right now 0 means disabled, 1 means the same thing as using the -d command line switch, and 2 - 3 provide increasing levels of debugging verbosity * Added a udp option to dynagen.ini to set the base udp NIO port. Can still be overridden in the network file. * Fixed bug using "-n" option that caused dynamips to crash * Trying to use iomem option resulted in "invalid iomem type, must be an integer". Fixed. * Fixed bug parsing bad interfaces on filter command * Fixed a bug in the "save" command that sometimes wrote the configuration in the wrong network file section * Fixed bug that caused save command to crash dynagen when the port was specified in the dynamips server section BTS #73 * Fixed bug that caused some hypervisor commands that returned errors to cause a hang * Due to some Dynamips / Dynagen "branding" confusion, the Start menu folder is now named "Dynagen". You may want to manually delete the old "Dynamips" program group. The programs are still installed in C:\Program Files\Dynamips for now. * Windows uninstaller now correctly deletes all files except the Images directory (for safety) * The dynamips.exe included with the Windows installer package is now built against Winpcap 4.0 beta 2. It doesn't seem to be necessary to upgrade from previous betas to use, but you might wish to anyway. Version 0.6.0 * Added support for NM-16ESW. Specify with "slotx = NM-16ESW" * Added "save" / "push" CLI commands for storing IOS configurations in network files. Pretty experimental, and currently only works with 7200s. * Added support for dynamips filters with the "filter" CLI command. See the online help for usage. * "ver" CLI command now also shows dynamips server version(s) * Fixed command line switch bug that falsely reported crashes. BTS #66 * Fixed a bug that prevented manually specifying NM-4T and NM-4E on 3620s and 3640s * Dynagen should now function on Windows 2000 after replacing dynamips.exe and cygwin1.dll with the ones compiled against Windows 2000 (downloaded from the dynamips site) Version 0.5.2 * Fixed a bug that broke model selection on non US OSs that represented strings as Unicode. * Only the first 4 interfaces of a PA-8E were usable. * Pause if the Dynagen crashes so the user can see the Python traceback for support purposes. No more "I click on a net file, Dynagen flashes and goes away." * Gracefully handle a malformed section rather than crash * Crashed poorly if it couldn't find the network file. BTS #62 * Eliminated the depreciated "ROM" option and associated library support. BTS #61 * Gracefully handle attempts to establish connections to nonexistant devices * Defining a switchport but not using it now just issues a warning and continues * Console "ver" command also shows the version(s) of the dynamips server(s) * Added iomem config option to set the iomem size on 3600s Version 0.5.1: * Fixed many occurrences of a stupid "s/false/False" typo * Corrected the bug that prevented the manual specification of "NM-4T" Version 0.5.0: * 3620, 3640, and 3660 router support for use with dynamips 0.2.5-RC4 and later. See all_config_options.txt and the tutorial for usage. * Simpler syntax for specifying dynamips server control port makes using multiple dynamips processes on the same server easier. See the FAQ in the tutorial for an example. * Added a setup.py for unix installations and dynagen now looks in "unix friendly" places (i.e. /etc and /usr/local/etc) as well as the same directory as dynagen for dynagen.ini and CONFSPEC (thanks for Erik Wenzel for providing patches!) * Dynamips 0.2.5-RC4 and later uses a new hypervisor syntax for many commands, so that version of Dynamips or later requires Dynagen 0.4.4 or later, and vice versa. * Dynamips for Windows/Cygwin now requires Winpcap 4.0 (currently in beta) * Dynamips 0.2.5 now uses the router name in the nvram, bootflash, logfiles etc. This means that when existing Dynagen labs are changed, nvram files will continue to match the correct router. However it also means that labs made with previous versions that use instance ID will be incompatible. To convert old lab data to the new format, you can manually rename nvram, disk, bootflash, etc files from c7200_ix_blah (where x is the instance id) to c7200_routername_blah (where routername is the name of the router as defined in the dynagen lab). Version 0.4.3: * Added "disk0" and "disk1" options to set the ATA sizes (set to 0 for none) (BTS #49) * Added a "udp" option to change the default starting UDP port for UDP NIOs * Added "show mac " and "clear mac " CLI commands to support the new dynamips hypervisor commands that show / clear Ethernet switch mac address tables * Supports spaces in filespec (e.g. with "workingdir", "image", etc.). Because of this change, dynagen 0.4.3 now requires dynamips 0.2.5-RC2 or later which added this feature. * mmap now defaults to true, to match the default behavior of dynamips. This causes dynamips to use disk files for router virtual memory rather than RAM. To return to the previous behavior, set "mmap = false" in your [[7200]] sections. (BTS #41) * Fixed several connect bugs relating to connections between devices distributed across multiple dynamips instances on the same or different servers * Fixed a bug in exec_area that caused it to botch the idlepc value instead (BTS #46) * Fixed a bug in ETHSW config that prevented the use of any manual NIO other than NIO_gen_eth Version 0.4.2: * Removed "clock" option from labs and the tutorial, because as of dynamips 0.2.5 RC1 the clock skew is automatically calculated (yay!) Version 0.4.1: * Added "idlepc" and "exec_area" options. idlepc was introduced in 0.2.5-pre25, see the dynamips web site or the dynamips readme for usage Version 0.4.0: * Implicit distributed Dynamips server support. (BTS #12) See multiserver sample lab. * Added Ethernet switch support (introduced in dynamips 0.2.5-pre22). See ethernet_switch sample lab. * Added a telnet command to launch connections to router consoles from the CLI (BTS #12). Added dynagen.ini file to support this feature. The "telnet" option in the INI specifies the telnet client to launch and needs to be customized for your OS (see examples for Windows, Linux, and OS X) * Fixed the frame-relay lab (missing [[7200]] section. Doh!) * Fixed NIO_vde issue (BTS #25) Open Caveats ============ See the Bug Tracking System at http://www.ipflow.utc.fr/bts/ for a list of open issues. Greg Anuzelli (dynagen@gmail.com) gns3-legacy-GNS3-0.8.6/src/GNS3/Dynagen/__init__.py000066400000000000000000000000661223163545200213550ustar00rootroot00000000000000# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: gns3-legacy-GNS3-0.8.6/src/GNS3/Dynagen/confConsole.py000066400000000000000000002657041223163545200221020ustar00rootroot00000000000000#!/usr/bin/python # vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8: """ confConsole.py Copyright (C) 2007-2010 Pavel Skovajsa 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. """ import os import cmd import re import time from dynamips_lib import DynamipsError, DynamipsWarning, GENERIC_7200_PAS, GENERIC_3600_NMS, GENERIC_1700_NMS, GENERIC_2600_NMS, GENERIC_3700_NMS # Regex matching slot definitions. Used in pre_cmd() function in confRouterConsole SLOT_RE = re.compile('^slot[0-7]', re.IGNORECASE) # True = Dynagen text-mode, False = GNS3 GUI-mode. if __name__ == 'confConsole': PureDynagen = True else: PureDynagen = False # determine if we are in the debugger try: DBGPHideChildren except NameError: DEBUGGER = False else: DEBUGGER = True ###some functions from console.py################## def error(msg): """Print out an error message""" print '*** Error:', unicode(msg) def debug(string): """ Print string if debugging is true""" import __main__ # Debug level 2, console debugs if __main__.dynagen.debuglevel >= 2: curtime = time.strftime("%H:%M:%S") print "%s: DEBUG (2): %s" % (curtime, unicode(string)) ##############end of some functions from console.py################## class AbstractConsole(cmd.Cmd): """abstract console class, all other console and confconsole classes inherit behavior from it""" def __init__(self): cmd.Cmd.__init__(self) # Import the main namespace for use in this module # Yes, normally this is bad mojo, but I'm doing this to provide the console # access to the entire namespace in case the user wants to futz with stuff import __main__ self.namespace = __main__ self.debuglevel = self.namespace.dynagen.debuglevel ## Override methods in Cmd object ## def preloop(self): """Initialization before prompting user for commands. Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub. """ cmd.Cmd.preloop(self) ## sets up command completion self._hist = [] ## No history yet self._locals = {} ## Initialize execution namespace for user self._globals = {} # Give the console access to the namespace self._globals['namespace'] = self.namespace def postloop(self): """Take care of any unfinished business. Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub. """ cmd.Cmd.postloop(self) ## Clean up command completion print 'Exiting...' def precmd(self, line): """ This method is called after the line has been input but before it has been interpreted. If you want to modifdy the input line before execution (for example, variable substitution) do it here. """ self._hist += [line.strip()] tokens = line.split() try: if tokens[0].lower() == 'con': tokens[0] = 'console' line = (' ').join(tokens) except IndexError: pass return line def postcmd(self, stop, line): """If you want to stop the console, return something that evaluates to true. If you want to do some post command processing, do it here. """ return stop def emptyline(self): """Do nothing on empty input line""" pass if PureDynagen: def do_py(self, line): """py \tExecute python statements""" if line == '?': print self.do_py.__doc__ return try: exec line in self._locals, self._globals except Exception, e: print e.__class__, ':', e def default(self, line): """Called on an input line when the command prefix is not recognized. In that case we execute the line as Python code. """ error('unknown command') def do_hist(self, args): """Print a list of commands that have been entered""" print self._hist if PureDynagen: def do_exit(self, args): """Exits from the console""" return -1 def do_end(self, args): """Exits from the console""" return -1 def do_help(self, args): """Get help on commands 'help' or '?' with no arguments prints a list of commands for which help is available 'help ' or '? ' gives help on """ ## The only reason to define this method is for the help text in the doc string cmd.Cmd.do_help(self, args) class confDefaultsConsole(AbstractConsole): """console class for managing the device Defaults console""" def __init__(self, prompt, dynagen, dynamips_server): AbstractConsole.__init__(self) self.prompt = prompt[:-1] + '-)' self.dynagen = dynagen self.dynamips_server = dynamips_server self.d = self.dynamips_server.host + ':' + str(self.dynamips_server.port) self.config = self.dynagen.defaults_config[self.d] self.adaptertuple = () self.max_slots = 7 self.min_slot = 0 self.chassis = 'None' self.default_image = 'None' self.default_ghostios = 'False' self.default_jitsharing = 'False' self.default_cnfg = 'None' self.default_conf = 'None' self.default_confreg = '0x2102' self.default_aux = 'None' self.default_image = 'None' self.default_idlepc = 'None' self.default_exec_area = 'None' self.default_mmap = True self.default_sparsemem = 'False' self.default_ghostsize = None def do_exit(self, args): """Exits from the console""" #if there are no scalars in self.config delete it if self.config.keys() == []: del self.dynagen.defaults_config[self.d][self.chassis] self.dynamips_server.configchange = True return -1 def precmd(self, line): ''' This method is called after the line has been input but before it has been interpreted. If you want to modifdy the input line before execution (for example, variable substitution) do it here. This is the tricky part how we use this method over here in confDefaultsRouterCOnsole. By entering "slot1 = NM-16ESW" the method do_slot will not be called just because there is that number 1 over there. So we will do a trick - change the line internally to "slot 1 = NM-16ESW". ''' self._hist += [line.strip()] if len(line) <= 4: return line first_four_letters = line[:4] if first_four_letters == 'slot': return 'slot ' + line[4:] else: return line def clean_args(self, args): """clean the arguments from spaces and stuff""" #get rid of that '=' argument = args.strip('=') #get rid of starting space argument = argument.strip() return argument def set_int_option(self, option, args): """set integer type option in config""" if '?' in args or args.strip() == '': print getattr(self, 'do_' + option).__doc__ return argument = self.clean_args(args) try: option_value = int(argument) if getattr(self, 'default_' + option) == option_value: if self.config.has_key(option): del self.config[option] else: self.config[option] = option_value except (TypeError, ValueError): error('enter number, not: ' + argument) self.dynamips_server.configchange = True def set_string_option(self, option, args): """set string type option in config""" if '?' in args or args.strip() == '': print getattr(self, 'do_' + option).__doc__ return option_value = self.clean_args(args) if getattr(self, 'default_' + option) == option_value: if self.config.has_key(option): del self.config[option] else: self.config[option] = option_value self.dynamips_server.configchange = True def do_no(self, args): """no