repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
adrian-tech-enthusiast/Bot
|
src/tasks/do_say_hello.c
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : do_say_hello.c
* Description : Bot Task - Say Hello.
*/
#include "do_say_hello.h"
#include "../messenger/messenger.h"
/**
* {@inheritdoc}
*/
task_response do_say_hello() {
success("_> Hello There from Bot!");
return task_response_create(1);
}
|
adrian-tech-enthusiast/Bot
|
src/tasks/do_sample_data.h
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : sample_data.h
* Description : Bot Task - sample data.
*/
#ifndef BOT_TASK_SAMPLE_DATA_H
#define BOT_TASK_SAMPLE_DATA_H
#include "task_response.h"
/**
* Sample data callback-function.
*/
task_response do_sample_data();
#endif
|
adrian-tech-enthusiast/Bot
|
src/tasks/task_response.c
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : task_response.h
* Description : Task response struct and helper functions implementation.
*/
#include <stdlib.h>
#include "task_response.h"
/**
* {@inheritdoc}
*/
task_response task_response_create(int const succeeded) {
size_t storage_amount = sizeof(struct task_response_item);
task_response item = (task_response) malloc(storage_amount);
if (item != NULL) {
item->succeeded = succeeded;
}
return item;
}
|
adrian-tech-enthusiast/Bot
|
src/tasks/task_list.h
|
#include "do_fetch_data.h"
#include "do_sample_data.h"
#include "do_say_hello.h"
#include "do_show_messages.h"
#include "do_exit.h"
|
adrian-tech-enthusiast/Bot
|
src/tasks/do_exit.h
|
<filename>src/tasks/do_exit.h
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : do_exit.h
* Description : Bot Task - Do Exit.
*/
#ifndef BOT_TASK_EXIT_H
#define BOT_TASK_EXIT_H
#include "task_response.h"
/**
* Exit callback-function.
*/
task_response do_exit();
#endif
|
adrian-tech-enthusiast/Bot
|
src/tasks/do_fetch_data.h
|
<gh_stars>0
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : fetch_data.h
* Description : Bot Task - fetch data.
*/
#ifndef BOT_TASK_FETCH_DATA_H
#define BOT_TASK_FETCH_DATA_H
#include "task_response.h"
/**
* Fetch data from the server callback-function.
*/
task_response do_fetch_data();
#endif
|
adrian-tech-enthusiast/Bot
|
src/tasks/do_show_messages.c
|
<gh_stars>0
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : do_show_log_messages.c
* Description : Bot Task - Show dummy messages.
*/
#include "do_show_messages.h"
#include "../messenger/messenger.h"
/**
* {@inheritdoc}
*/
task_response do_show_messages() {
info("---------------------------------");
info("[info] _> This is a info message.");
success("_> This is a success message.");
warning("_> This is a warning message.");
error("_> This is a error message.");
info("---------------------------------");
return task_response_create(1);
}
|
adrian-tech-enthusiast/Bot
|
src/messenger/messenger.c
|
<reponame>adrian-tech-enthusiast/Bot
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : messenger.c
* Description : Messenger helper functions, sends formatted messages to stdout.
*/
#include <stdio.h>
#include "messenger.h"
/**
* {@inheritdoc}
*/
void info(const char *message) {
printf(RESET "%s" "\n" RESET, message);
}
/**
* {@inheritdoc}
*/
void success(const char *message) {
printf(BACKGROUND_GREEN "[success]" RESET " " GREEN "%s" RESET "\n" RESET, message);
}
/**
* {@inheritdoc}
*/
void warning(const char *message) {
printf(BACKGROUND_YELLOW "[warning]" RESET " " YELLOW "%s" RESET "\n", message);
}
/**
* {@inheritdoc}
*/
void error(const char *message) {
printf(BACKGROUND_RED "[error]" RESET " " RED "%s" RESET "\n", message);
}
|
adrian-tech-enthusiast/Bot
|
src/bot/bot.h
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : bot.h
* Description : Bot function definitions.
*/
#ifndef BOT
#define BOT
/**
* Create a new bot instance.
*/
int bot_init();
#endif
|
adrian-tech-enthusiast/Bot
|
src/tasks/do_exit.c
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : do_exit.c
* Description : Bot Task - Do Exit.
*/
#include "do_show_messages.h"
#include "../messenger/messenger.h"
/**
* {@inheritdoc}
*/
task_response do_exit() {
success("_> Bye!");
return task_response_create(1);
}
|
adrian-tech-enthusiast/Bot
|
src/tasks/task_response.h
|
<reponame>adrian-tech-enthusiast/Bot
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : task_response.h
* Description : Task response struct definition and helper functions.
*/
#ifndef BOT_TASK_RESPONSE_H
#define BOT_TASK_RESPONSE_H
/**
* The task response that is received after processing a specific task.
*/
struct task_response_item {
/**
* The flag to check if the task succeeded in its execution.
* 1 when the task execution was succeeded, otherwise 0.
*
* @var int
*/
int succeeded;
};
/**
* Definition of the date type task_response.
*
* @var task_response_item task_response
* The task response data type.
*/
typedef struct task_response_item *task_response;
/**
* Create a new task response instance.
*
* @param int const succeeded
* The flag indicating whether the task was successful in its execution.
*
* @return task_response
* The task response.
*/
task_response task_response_create(int const succeeded);
#endif
|
adrian-tech-enthusiast/Bot
|
src/tasks/task_manager.h
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : task_manager.h
* Description : Task manager helper functions and structs definitions.
*/
#ifndef BOT_TASK_MANAGER_H
#define BOT_TASK_MANAGER_H
#include "task_list.h"
#include "task_response.h"
/**
* Callable type-definition.
*
* The callback function that will be executed when the specified task
* is dispatched. 'Callable' now can be used as type.
*/
typedef task_response (*Callable)();
/**
* Traversable Task Item struct.
*/
struct traversable_task_item {
/**
* The unique identifier for this task.
*
* @var *char[] task_id
*/
char *task_id;
/**
* The task description.
*
* @var *char[] task_description
*/
char *task_description;
/**
* Pointer to the next task item in the list.
*
* @var callable callback
* The callback function that will be executed when the specified task is dispatched.
*/
Callable callback;
/**
* Pointer to the next task item in the list.
*
* @var *traversable_task_item next
* The pointer to the next task item.
*/
struct traversable_task_item *next;
};
/**
* Definition of the date type task_item.
*
* @var traversable_task_item task_item
* The task-item data type.
*/
typedef struct traversable_task_item *task_item;
/**
* Task Manager struct.
*/
struct traversable_task_manager {
/**
* Number of task registered in the manager.
*
* @var int number_of_tasks
*/
volatile int number_of_tasks;
/**
* Pointer to the next task item.
*
* @var task_item next
* The pointer to the next task item.
*/
task_item next;
};
/**
* Definition of the date type task_manager.
*
* @var traversable_task_manager task_manager
* The task manager data type.
*/
typedef struct traversable_task_manager *task_manager;
/**
* Get the global task manager service.
*
* @return task_manager
* The task manager service.
*/
task_manager get_task_manager();
/**
* Clear memory associated with the task manager service.
*/
void task_manager_destroy();
/**
* Create a new Task Item instance.
*
* @param char const *task_id
* The unique identifier for this task.
* @param char const *task_description
* The task description.
* @param Callable callable
* Callable function that will be executed when the specified event is dispatched.
*
* @return task_item
* The task item instance.
*/
task_item task_item_create(char const *task_id, char const *task_description, Callable callback);
/**
* Add a task to the list of possible operations the bot can perform.
*
* @param task_manager dispatcher
* The task manager service.
* @param char const *task_id
* The unique identifier for this task.
* @param char const *task_description
* The task description.
* @param Callable callable
* Callable function that will be executed when the specified event is dispatched.
*/
void add_task(task_manager dispatcher, char const *task_id, char const *task_description, Callable callback);
/**
* Dispatches an task.
*
* @param task_manager dispatcher
* The task manager service.
* @param char const *task_id
* The unique identifier of the event to dispatch.
*
* @return task_response
* The task response.
*/
task_response dispatch_task(task_manager const dispatcher, char const *task_id);
/**
* Show task response.
*
* @param task_response const response
* The task response to show.
*/
void show_task_response(task_response const response);
#endif
|
adrian-tech-enthusiast/Bot
|
src/tasks/task_manager.c
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : task_manager.h
* Description : Task manager helper functions implementation.
*/
#include <stdlib.h>
#include <string.h>
#include "task_manager.h"
#include "../messenger/messenger.h"
/**
* {@inheritdoc}
*/
task_manager get_task_manager() {
static task_manager instance;
if (instance == NULL) {
// Create the global instance.
size_t storage_amount = sizeof(struct traversable_task_manager);
instance = (task_manager) malloc(storage_amount);
if (instance != NULL) {
instance->next = NULL;
instance->number_of_tasks = (int) 0U;
}
}
return instance;
}
/**
* {@inheritdoc}
*/
void task_manager_destroy() {
task_manager dispatcher = get_task_manager();
if (dispatcher == NULL) {
// Uninitialized service.
return;
}
// Releases the specified block of memory booked for the base dispatcher service.
free(dispatcher);
}
/**
* {@inheritdoc}
*/
task_item task_item_create(char const *task_id, char const *task_description, Callable callback) {
size_t storage_amount = sizeof(struct traversable_task_item);
task_item item = (task_item) malloc(storage_amount);
if (item != NULL) {
item->callback = callback;
item->task_id = (char *) task_id;
item->task_description = (char *) task_description;
item->next = NULL;
}
return item;
}
/**
* {@inheritdoc}
*/
void add_task(task_manager const dispatcher, char const *task_id, char const *task_description, Callable callback) {
// Create the task item.
task_item item = task_item_create(task_id, task_description, callback);
// Add the task item to the task manager.
if (dispatcher->number_of_tasks == 0) {
// Task manager is empty.
dispatcher->next = item;
} else {
// Task manager is not empty.
task_item index = dispatcher->next;
while (index->next != NULL) {
index = index->next;
}
index->next = item;
}
// Increment the size ot the task manager.
(dispatcher->number_of_tasks)++;
}
/**
* {@inheritdoc}
*/
task_response dispatch_task(task_manager const dispatcher, char const *task_id) {
int i;
task_item task = dispatcher->next;
for (i = 1; i <= dispatcher->number_of_tasks; ++i) {
if (strcmp(task->task_id, task_id) == 0) {
return task->callback();
}
// Move to the next task.
task = task->next;
}
return task_response_create(0);
}
/**
* {@inheritdoc}
*/
void show_task_response(task_response const response) {
if (response->succeeded) {
success("Task completed successfully.");
} else {
error("An error has occurred while executing task.");
}
}
|
adrian-tech-enthusiast/Bot
|
src/bot/bot.c
|
/**
* Author : <NAME>.
* Version : 1.0.0
* Copyright : © 2021 <NAME>, All Rights Reserved.
* Title : bot.c
* Description : Bot function definitions.
*/
#include "bot.h"
#include <stdlib.h>
#include <string.h>
#include "../tasks/task_manager.h"
#include "../question/choice_question.h"
/**
* {@inheritdoc}
*/
char *ask_user_task_to_dispatch(task_manager const dispatcher) {
choice_question question = create_choice_question("Please select option:");
task_item index = dispatcher->next;
while (index->next != NULL) {
add_choice_option(question, index->task_id, index->task_description);
index = index->next;
}
add_choice_option(question, index->task_id, index->task_description);
return ask_choice_question(question);
}
/**
* {@inheritdoc}
*/
int bot_init() {
// The Task manger: It is the central object of the task dispatcher system.
// In general, a single task manger is created, which maintains a registry
// of tasks. When a task is dispatched via the dispatcher, it
// notifies the callback registered with that task.
task_manager dispatcher = get_task_manager();
// Connecting Tasks: To take advantage of an existing event, you need
// to connect a listener to the dispatcher so that it can be notified when
// the event is dispatched. A call to the dispatcher’s addListener() method
// associates any valid C callable to an event.
add_task(dispatcher, "bot.say.hello", "Say Hello.", &do_say_hello);
add_task(dispatcher, "bot.fetch.data", "Fetch Data.", &do_fetch_data);
add_task(dispatcher, "bot.sample.data", "Sample Data.", &do_sample_data);
add_task(dispatcher, "bot.show.messages", "Show Messages.", &do_show_messages);
add_task(dispatcher, "bot.exit", "Bot Exit.", &do_exit);
// Ask the user what to do until the user wants to halt the bot.
char *task_id;
task_response response;
while (strcmp(task_id, "bot.exit") != 0) {
// Let the user decide what to do.
task_id = ask_user_task_to_dispatch(dispatcher);
// Dispatch the task user requested.
response = dispatch_task(dispatcher, task_id);
// Show the task result.
show_task_response(response);
}
// Clear memory.
task_manager_destroy();
// Stop bot execution.
return EXIT_SUCCESS;
}
|
ryandancy/cellular-automata
|
src/GraphicsProperties.h
|
<reponame>ryandancy/cellular-automata
#ifndef GAME_OF_LIFE_GRAPHICSPROPERTIES_H
#define GAME_OF_LIFE_GRAPHICSPROPERTIES_H
#include <QColor>
// A singleton to hold Qt graphics constants, but changeable.
class GraphicsProperties {
public:
static GraphicsProperties& instance();
GraphicsProperties(const GraphicsProperties&) = delete;
GraphicsProperties(const GraphicsProperties&&) = delete;
GraphicsProperties& operator=(const GraphicsProperties&) = delete;
GraphicsProperties& operator=(const GraphicsProperties&&) = delete;
bool showChunkBoxes = false;
enum class Theme {
LIGHT, DARK, HACKER, CANADIAN, VIOLET
};
void setTheme(Theme theme);
const QColor& deadColor() const noexcept; // the colour of dead cells and the background
const QColor& liveColor() const noexcept; // the colour of live cells
const QColor& outOfBoundsColor() const noexcept; // the colour of out-of-bound chunks
private:
GraphicsProperties();
Theme theme_;
QColor deadColor_;
QColor liveColor_;
QColor outOfBoundsColor_;
};
#endif //GAME_OF_LIFE_GRAPHICSPROPERTIES_H
|
ryandancy/cellular-automata
|
src/AutomatonScene.h
|
<reponame>ryandancy/cellular-automata<filename>src/AutomatonScene.h<gh_stars>1-10
#ifndef GAME_OF_LIFE_AUTOMATONSCENE_H
#define GAME_OF_LIFE_AUTOMATONSCENE_H
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QWidget>
#include "Automaton.h"
// The QGraphicsScene subclass which handles mouse events and formally represents the Automaton on-screen.
class AutomatonScene : public QGraphicsScene {
Q_OBJECT
public:
// Initialize with the given automaton pointer. We do not own this pointer. Update it with updateAutomaton(Automaton*)
// whenever it is invalidated.
explicit AutomatonScene(Automaton* automaton, QWidget* parent = nullptr);
~AutomatonScene() override;
// Update the background colour (and the topology edge colour).
void updateBackground();
// Change the old automaton's reference for this one and update. Use when the old automaton pointer was invalidated.
void updateAutomaton(Automaton* automaton);
signals:
// Emitted when the user clicks on the specified cell.
void cellUpdated(int chunkX, int chunkY, int cellX, int cellY);
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override;
private:
Automaton* automaton_; // we hold a pointer to the automaton in order to add chunks, but don't own it
QGraphicsRectItem* validRect_ = nullptr; // the rectangle where cells are valid; we own this
};
#endif //GAME_OF_LIFE_AUTOMATONSCENE_H
|
ryandancy/cellular-automata
|
src/Topology.h
|
#ifndef GAME_OF_LIFE_TOPOLOGY_H
#define GAME_OF_LIFE_TOPOLOGY_H
// A Topology represents how Chunks are related to each other in space. It defines valid chunks and allows
// transformation of invalid chunk coordinates into their equivalent valid ones - i.e. which chunk a chunk with
// invalid coordinates should behave like for the purpose of interacting with other chunks.
// All coordinates in this class are given in terms of chunk coordinate, *not* cell coordinates.
class Topology {
public:
// Is (x, y) a valid set of coordinates for a real Chunk in this Topology?
virtual bool valid(int x, int y) const = 0;
// Transform a possibly-invalid set of coordinates (x, y) to a valid set and return true, or return false if this
// cannot be done and the chunk should be treated as fully empty.
virtual bool transform(int& x, int& y) const = 0;
virtual ~Topology() = default;
virtual bool bounded() const noexcept; // Does the topology have an edge?
virtual int width() const noexcept; // If bounded(), get the width in chunks. Else, get -1.
virtual int height() const noexcept; // If bounded(), get the height in chunks. Else, get -1.
};
// This is an abstract Topology with bounds, meaning it has a width and a height. Chunks are valid iff they are within
// (0, 0) and (width, height), inclusive.
class BoundedTopology : public Topology {
public:
// Initialize the bounds with a width and height, in units of chunks.
// Will throw std::out_of_range if the width or height are negative or zero.
BoundedTopology(int width, int height);
// Simply return whether 0 <= x <= width and 0 <= y <= height.
bool valid(int x, int y) const override;
bool bounded() const noexcept override;
int width() const noexcept override;
int height() const noexcept override;
protected:
// Note: width and height are signed to prevent headaches with arithmetic with signed coordinates
const int width_; // The width of the boundary of the topology, in chunks
const int height_; // The height of the boundary of the topology, in chunks
};
// This is a Topology with a fixed size - it simply stops after a certain number of Chunks.
// All other chunks should be treated as completely empty/dead.
class FixedTopology : public BoundedTopology {
using BoundedTopology::BoundedTopology;
public:
// If (x, y) is valid, this method will do nothing and return true. If not, it will return false, signifying
// that the chunk should be treated as fully empty.
bool transform(int& x, int& y) const override;
};
// This is a Topology which wraps around in both the x and y directions. Topologically, it forms a torus.
class WrappingTopology : public BoundedTopology {
using BoundedTopology::BoundedTopology;
public:
// This implementation will wrap x and y as many times as necessary. It will always return true.
bool transform(int& x, int& y) const override;
};
// This is a Topology with no restrictions whatsoever. All chunks are valid and no transformations are performed.
class UnboundedTopology : public Topology {
public:
bool valid(int x, int y) const override; // Always returns true - all chunks are valid.
bool transform(int& x, int& y) const override; // Always returns true and does not modify x and y.
};
#endif //GAME_OF_LIFE_TOPOLOGY_H
|
ryandancy/cellular-automata
|
src/util.h
|
#ifndef GAME_OF_LIFE_UTIL_H
#define GAME_OF_LIFE_UTIL_H
#include <utility>
#include <functional>
// template hash function for std::pair for use in maps, works with all types defined in <functional>
struct pair_hash {
template<typename A, typename B>
std::size_t operator()(const std::pair<A, B>& pair) const {
std::size_t hash = std::hash<A>()(pair.first);
// this magic is used to combine the hashes from the first and second elements
// apparently, it's better than a simple xor; this implementation is from boost
return hash ^ (std::hash<B>()(pair.second) + 0x9e3779b9 + (hash<<6u) + (hash>>2u));
}
};
#endif //GAME_OF_LIFE_UTIL_H
|
ryandancy/cellular-automata
|
src/RulesDialog.h
|
#ifndef GAME_OF_LIFE_RULESDIALOG_H
#define GAME_OF_LIFE_RULESDIALOG_H
#include <vector>
#include <QCheckBox>
#include <QDialog>
#include <QGridLayout>
#include <QWidget>
#include "Ruleset.h"
namespace Ui {
class RulesDialog;
}
// A dialog which allows the user to change the automaton's rules. It has two groups of checkboxes, one for the rules
// on cells being born, and one for the rules on cells surviving.
class RulesDialog : public QDialog {
Q_OBJECT
public:
explicit RulesDialog(Ruleset& ruleset, QWidget* parent = nullptr); // initialize with the given ruleset
~RulesDialog() override;
private:
// Set the rule for born or survives with the given number of neighbours to the given value. Throw
// std::invalid_argument if numNeighbours > the number of neighbours in the neighbourhood.
// These could be slots, but they're never connected to precisely as such, so they aren't.
void setBornRule(unsigned int numNeighbours, bool value);
void setSurvivesRule(unsigned int numNeighbours, bool value);
static constexpr unsigned int CHECKBOXES_PER_ROW = 4;
Ui::RulesDialog* ui_;
Ruleset& ruleset_;
QGridLayout* bornGrid_; // the layouts for the check boxes
QGridLayout* survivesGrid_;
std::vector<QCheckBox*> bornCheckboxes_; // these hold the check boxes
std::vector<QCheckBox*> survivesCheckBoxes_;
};
#endif //GAME_OF_LIFE_RULESDIALOG_H
|
ryandancy/cellular-automata
|
src/Neighbourhood.h
|
<gh_stars>1-10
#ifndef GAME_OF_LIFE_NEIGHBOURHOOD_H
#define GAME_OF_LIFE_NEIGHBOURHOOD_H
#include "Side.h"
// we only have references to ChunkArray so it's safe to forward declare it without including Chunk.h
// this resolves a circular dependency chain: Neighbourhood->ChunkArray->Chunk->Neighbourhood
class ChunkArray;
// This is an abstract base class representing the neighbourhood of a cell. Neighbourhoods can be moved around a
// ChunkArray in order to save time. One Neighbourhood is created for each generation. Note that after creating a
// Neighbourhood, you must call Neighbourhood::moveTo in order to initialize it before using the other methods.
class Neighbourhood {
public:
// Move this Neighbourhood to (x, y) in the chunk at coordinates (chunkX, chunkY) in the ChunkArray.
// Throw std::invalid_argument if x or y are not in [0, CHUNK_SIZE), or if there is no Chunk at (chunkX, chunkY).
void moveTo(int chunkX, int chunkY, int x = 0, int y = 0);
int getX() const noexcept; // Get the x coordinate of the Neighbourhood in its chunk. Return <= CHUNK_SIZE.
int getY() const noexcept; // Get the y coordinate of the Neighbourhood in its chunk. Return <= CHUNK_SIZE.
// Move the Neighbourhood one cell to the right in its chunk, updating the live count. Return the new x coordinate.
// Throw std::range_error if the x coordinate is already CHUNK_SIZE and we try to move out of the chunk.
// Throw std::logic_error if the Neighbourhood is not ready (i.e. moveTo has not been called).
void moveRight();
// Move the Neighbourhood one cell to the left in its chunk, updating the live count.
// Throw std::range_error if the x coordinate is already 0 and we try to move out of the chunk.
// Throw std::logic_error if the Neighbourhood is not ready (i.e. moveTo has not been called).
void moveLeft();
// Move the Neighbourhood one cell down in its chunk, updating the live count.
// Throw std::range_error if the y coordinate is already CHUNK_SIZE and we try to move out of the chunk.
// Throw std::logic_error if the Neighbourhood is not ready (i.e. moveTo has not been called).
void moveDown();
// Move the Neighbourhood one cell up in its chunk, updating the live count.
// Throw std::range_error if the y coordinate is already 0 and we try to move out of the chunk.
// Throw std::logic_error if the Neighbourhood is not ready (i.e. moveTo has not been called).
void moveUp();
// Move the Neighbourhood one cell towards the given side, updating the live count.
// depending on which side is moved towards. Throw std::range_error if this call tries to move out of the chunk.
// Throw std::logic_error if the Neighbourhood is not ready (i.e. moveTo has not been called).
void moveToSide(const Side& side);
// Get the live count of the Neighbourhood, i.e. the number of live cells in the Neighbourhood.
unsigned int getLiveCount() const noexcept;
virtual ~Neighbourhood() = default;
protected:
// Initialize the Neighbourhood with the given ChunkArray. This Neighbourhood must be destroyed before the
// ChunkArray passed here.
explicit Neighbourhood(ChunkArray& chunkArray);
// Check the Neighbourhood::ready_ flag and throw std::logic_error if it is not true.
void verifyReady() const;
// Take stock of the Neighbourhood's surroundings from scratch. Recreate the live count.
// This is called from moveTo(int, int, int, int) to update from scratch.
virtual void reinitialize() = 0;
// These are the implementations of move[L/R/U/D], called after error checking and before changing x_ and y_.
// They must update the live count, except for the centre cell. move[Left|Right|Down] takes care of that.
virtual void translateRight() = 0;
virtual void translateLeft() = 0;
virtual void translateDown() = 0;
virtual void translateUp() = 0;
// Get the value of a cell by its offset from (x_, y_).
bool getCell(int dx, int dy) const;
int x_;
int y_;
int chunkX_;
int chunkY_;
unsigned int liveCount_;
ChunkArray& chunkArray_;
bool ready_; // are we in a valid state to do anything (i.e. has moveTo() been called)? If not, error.
};
// This abstract class represents the *type* of a Neighbourhood (i.e. von Neumann, Moore, or something else).
// It functions as a factory class with NeighbourhoodType::makeNeighbourhood(ChunkArray&), but also provides
// type-level information about the Neighbourhood type, such as the total number of cells it has and the maximum
// distance away a cell which could affect the centre cell could be. Objects of this type are immutable.
class NeighbourhoodType {
public:
// Create a Neighbourhood of this type. Caller is responsible for managing the pointer. Note that the returned
// Neighbourhood must be destroyed before the ChunkArray passed here - otherwise, the Neighbourhood will error.
virtual Neighbourhood* makeNeighbourhood(ChunkArray& chunkArray) const = 0;
// Get the total number of cells in Neighbourhoods of this type.
unsigned int getNumCells() const noexcept;
// Get the maximum distance at which the centre cell in the Neighbourhood could possibly be affected by
// a cell at this distance. Used to determine how far into empty chunks to evaluate - a cell in an empty chunk
// is evaluated if both its x and y coordinates are no more than this far from a non-empty chunk.
int getAffectingDistance() const noexcept;
// Get the radius of the neighbourhood. This is the same as getAffectingDistance() but semantically different.
int getRadius() const noexcept;
// Clone method for polymorphic copying.
virtual NeighbourhoodType* clone() const = 0;
virtual ~NeighbourhoodType() = default; // prevent memory leaks! save lives!
protected:
NeighbourhoodType(unsigned int numCells, int affectingDistance, int radius);
const int radius_;
private:
const unsigned int numCells_;
const int affectingDistance_;
};
// MooreNeighbourhood
class MooreNeighbourhood; // forward declaration for MooreNeighbourhoodType
// The NeighbourhoodType representing MooreNeighbourhoods.
class MooreNeighbourhoodType : public NeighbourhoodType {
public:
// Initialize a MooreNeighbourhoodType creating neighbourhoods with the specified radius.
// Throw std::invalid_argument if radius is not positive.
explicit MooreNeighbourhoodType(int radius);
// Make a MooreNeighbourhood with the radius specified in the constructor.
// (It's not covariant because of compiler weirdness, and we'll never use covariance anyways.)
Neighbourhood* makeNeighbourhood(ChunkArray& chunkArray) const override;
MooreNeighbourhoodType* clone() const override;
};
// A Moore neighbourhood includes diagonal adjacencies. It includes all cells in a square of side length 2r+1
// centred on the centre cell (except the centre cell itself), where r is the radius.
// Formally, if this neighbourhood is at (x, y), this neighbourhood includes all points (a, b), a != x and b != y, such
// that abs(a-x) <= r OR abs(b-y) <= r.
class MooreNeighbourhood : public Neighbourhood {
friend Neighbourhood* MooreNeighbourhoodType::makeNeighbourhood(ChunkArray& chunkArray) const;
protected:
// Initialize the MooreNeighbourhood with the given ChunkArray and radius.
// Throw std::invalid_argument if the radius is negative or zero.
MooreNeighbourhood(ChunkArray& chunkArray, int radius);
// Regenerate the live count.
void reinitialize() override;
// Update the live count right, left, up, or down.
void translateRight() override;
void translateLeft() override;
void translateDown() override;
void translateUp() override;
private:
const int radius_;
};
// VonNeumannNeighbourhood
class VonNeumannNeighbourhood; // forward declaration for VonNeumannNeighbourhoodType
// The NeighbourhoodType representing VonNeumannNeighbourhoods.
class VonNeumannNeighbourhoodType : public NeighbourhoodType {
public:
// Initialize the VonNeumannNeighbourhoodType creating neighbourhoods with the specified radius.
// Throw std::invalid_argument if the radius is negative or zero.
explicit VonNeumannNeighbourhoodType(int radius);
// Make a VonNeumannNeighbourhood with the radius specified in the constructor.
Neighbourhood* makeNeighbourhood(ChunkArray& chunkArray) const override;
VonNeumannNeighbourhoodType* clone() const override;
};
// A von Neumann neighbourhood does not include diagonal adjacencies. In my interpretation, it resembles a square on its
// corner of side length radius+1 centred on the centre cell. Formally, a von Neumann neighbourhood of radius r centred
// on (x, y) includes all points (a, b), a != x and b != y, such that abs(a-x) + abs(b-y) <= r.
class VonNeumannNeighbourhood : public Neighbourhood {
friend Neighbourhood* VonNeumannNeighbourhoodType::makeNeighbourhood(ChunkArray& chunkArray) const;
protected:
// Initialize the VonNeumannNeighbourhood with the given ChunkArray and radius.
// Throw std::invalid_argument if the radius is negative or zero.
VonNeumannNeighbourhood(ChunkArray& chunkArray, int radius);
// Regenerate the live count.
void reinitialize() override;
// Update the live count left, right, up, or down.
void translateRight() override;
void translateLeft() override;
void translateDown() override;
void translateUp() override;
private:
// Get the distance that the neighbourhood extends sideways in the a-th row or column.
inline int getSideDist(int a);
const int radius_;
};
#endif //GAME_OF_LIFE_NEIGHBOURHOOD_H
|
ryandancy/cellular-automata
|
src/Automaton.h
|
#ifndef GAME_OF_LIFE_AUTOMATON_H
#define GAME_OF_LIFE_AUTOMATON_H
#include <memory>
#include "Chunk.h"
#include "Ruleset.h"
#include "Neighbourhood.h"
// An Automaton encapsulates the entire cellular automaton. It owns a Topology*, a Ruleset, and
// a ChunkArray. It can advance the generation of the automaton by calling Automaton::tick().
class Automaton {
public:
// Initialize the Automaton with a given topology (fixed) and neighbourhood type (can be modified later).
// Take ownership of both pointers - the user must not delete them.
// Throw std::invalid_argument if either pointer is null.
Automaton(Topology* topology, NeighbourhoodType* initialNeighbourhoodType);
// Initialize the Automaton with a given topology (fixed) and by moving from the given ruleset.
// Take ownership of the topology. Throw std::invalid_argument if the pointer is null.
Automaton(Topology* topology, Ruleset&& ruleset);
// Set a new neighbourhood type. Take ownership of it, so the user mustn't delete it.
// Throw std::invalid_argument if it is null.
void setNeighbourhoodType(NeighbourhoodType* neighbourhoodType);
// Advance the entire automaton to the next generation.
void tick();
// Reset the entire automaton. Remove all Chunks and reset the generation count.
void reset();
// Get the current generation. The first generation is 0.
int generation() const noexcept;
// Get the total number of live cells in the automaton.
int population() const noexcept;
// Add delta to the current population. If the population is brought to below 0, silently set it to 0.
void addToPopulation(int delta);
// Get the chunk array behind the automaton.
ChunkArray& chunkArray() noexcept;
// Get the Ruleset managing the automaton. (What's an encapsulation? Why not just have them be public?)
Ruleset& ruleset() noexcept;
// Get the Topology of the automaton.
Topology& topology() noexcept;
private:
// Call the appropriate generation functions for the given chunk, which is assumed to be empty.
void generateEmptyChunk(int x, int y, Chunk& chunk, Neighbourhood& neighbourhood, int affectingDistance);
ChunkArray chunkArray_;
Ruleset ruleset_;
int generation_ = 0;
int population_ = 0;
};
#endif //GAME_OF_LIFE_AUTOMATON_H
|
ryandancy/cellular-automata
|
src/Ruleset.h
|
<reponame>ryandancy/cellular-automata
#ifndef GAME_OF_LIFE_RULESET_H
#define GAME_OF_LIFE_RULESET_H
#include "Neighbourhood.h"
// A Ruleset represents the rules of the current cellular automaton, including the neighbourhood type and whether
// a dead cell is born (becomes alive), and whether a live cell survives, with each number of live neighbours.
// For the standard Conway's Game of Life, pass in a new MooreNeighbourhoodType, and call setBornWith(3, true),
// setSurvivesWith(2, true), and setSurvivesWith(3, true).
// This class owns a NeighbourhoodType* passed in during the constructor, as well as two dynamic bool arrays
// representing whether a cell is born or survives with each number of neighbours.
class Ruleset {
public:
// Initialize the Ruleset with a NeighbourhoodType*. This Ruleset takes ownership of the NeighbourhoodType*
// and so the object pointed to must not be deleted except by this class. Initialize the born and survive rules
// to false.
explicit Ruleset(NeighbourhoodType* neighbourhoodType);
// Rule of Five destructor and copy and move constructors and assignment operators.
// Needed for management of the NeighbourhoodType* and dynamic bool arrays.
~Ruleset();
Ruleset(Ruleset& toCopy);
Ruleset& operator=(const Ruleset& toCopy);
Ruleset(Ruleset&& toMove) noexcept;
Ruleset& operator=(Ruleset&& toMove) noexcept;
// NeighbourhoodType management
// Retrieve the NeighbourhoodType passed in, as a reference. Callers must not delete or (somehow) modify it.
NeighbourhoodType& getNeighbourhoodType();
// Set the NeighbourhoodType. Destroy the old NeighbourhoodType and take ownership of this one.
// Reinitialize the born and survive rules to false.
void setNeighbourhoodType(NeighbourhoodType* neighbourhoodType);
// Retrieving and setting rules
// Should a dead cell with this number of live neighbours become alive?
// Throw std::invalid_argument if numNeighbours is greater than the total number of cells of the neighbourhood.
bool isBornWith(unsigned int numNeighbours) const;
// Should a live cell with this number of live neighbours survive?
// Throw std::invalid_argument if numNeighbours is greater than the total number of cells of the neighbourhood.
bool survivesWith(unsigned int numNeighbours) const;
// Set whether a dead cell with this number of live neighbours becomes alive.
// Throw std::invalid_argument if numNeighbours is greater than the total number of cells of the neighbourhood.
void setBornWith(unsigned int numNeighbours, bool value);
// Set whether a live cell with this number of live neighbours survives.
// Throw std::invalid_argument if numNeighbours is greater than the total number of cells of the neighbourhood.
void setSurvivesWith(unsigned int numNeighbours, bool value);
private:
// Check that numNeighbours <= total number of cells of neighbourhood, throw std::invalid_argument otherwise.
void checkNumNeighboursInRange(unsigned int numNeighbours) const;
// Note: we *probably* should use smart pointers, but I want to implement the memory management, so whatever.
// The NeighbourhoodType owned by this class.
NeighbourhoodType* neighbourhoodType_;
// These arrays are the same size as neighbourhoodType_->getNumCells() + 1.
bool* born_; // born_[i]: should a dead cell with i live neighbours become alive?
bool* survive_; // survive_[i]: should a live cell with i live neighbours survive?
};
#endif //GAME_OF_LIFE_RULESET_H
|
ryandancy/cellular-automata
|
src/ChunkGraphicsItem.h
|
#ifndef GAME_OF_LIFE_CHUNKGRAPHICSITEM_H
#define GAME_OF_LIFE_CHUNKGRAPHICSITEM_H
#include <QBrush>
#include <QGraphicsItem>
#include <QObject>
#include "Chunk.h"
// TODO a singleton to hold graphics preferences (colours of background, live/dead cells)
// This GraphicsItem paints a Chunk's cells.
class ChunkGraphicsItem : public QObject, public QGraphicsItem {
Q_OBJECT
public:
static constexpr qreal SIZE = 150.0; // A chunk's size on-screen. A cell is ChunkGraphicsItem::SIZE / CHUNK_SIZE.
// Initialize a ChunkGraphicsItem representing the specified Chunk. Connect the Chunk's signals to our slots.
explicit ChunkGraphicsItem(const Chunk& chunk);
QRectF boundingRect() const override;
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override;
public slots:
void updateCells(bool newCells[CHUNK_SIZE][CHUNK_SIZE]);
private:
const int x_, y_; // the coordinates of the Chunk
bool (* cells_)[CHUNK_SIZE]; // the Chunk's array of cells; for some reason it wants to be bool (*)[CHUNK_SIZE]?
// we don't delete cells_ in a destructor because it's actually owned by the Chunk
};
#endif //GAME_OF_LIFE_CHUNKGRAPHICSITEM_H
|
ryandancy/cellular-automata
|
src/Side.h
|
<filename>src/Side.h<gh_stars>1-10
#ifndef GAME_OF_LIFE_SIDE_H
#define GAME_OF_LIFE_SIDE_H
// Transforms coordinates relative to bottom to those relative to any side.
// This class is like an enum; use Side::TOP, Side::BOTTOM, Side::LEFT, and Side::RIGHT
class Side {
public:
enum Value : unsigned int {
BOTTOM, TOP, LEFT, RIGHT
};
constexpr Side(Value value) noexcept; // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
operator Value() const noexcept { return value_; } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
explicit operator bool() const = delete; // don't allow if (side)
constexpr bool operator==(const Side& side) const;
constexpr bool operator!=(const Side& side) const;
// Transform x and y, relative to the bottom, to relative to this Side.
void transform(int& x, int& y, int width, int height) const;
// "Rotate" the side. Names are assuming that BOTTOM is the default, so clockwise is left.
const Side& right() const noexcept; // Get the side obtained by rotating this side 90 degrees counterclockwise.
const Side& left() const noexcept; // Get the side obtained by rotating this side 90 degrees clockwise.
// These constants are to allow passing around Sides without constructing additional ones
static const Side CONST_BOTTOM, CONST_TOP, CONST_LEFT, CONST_RIGHT;
private:
Value value_;
};
#endif //GAME_OF_LIFE_SIDE_H
|
ryandancy/cellular-automata
|
src/mainwindow.h
|
<reponame>ryandancy/cellular-automata<filename>src/mainwindow.h
#ifndef GAME_OF_LIFE_MAINWINDOW_H
#define GAME_OF_LIFE_MAINWINDOW_H
#include <unordered_map>
#include <utility>
#include <QActionGroup>
#include <QGraphicsItem>
#include <QMainWindow>
#include <QSlider>
#include <QTimer>
#include <QWidget>
#include "Automaton.h"
#include "AutomatonScene.h"
#include "ChunkGraphicsItem.h"
#include "GraphicsProperties.h"
#include "util.h"
// TODO Separate UI from model via file structure, also figure out namespaces
// TODO Put the model on a separate thread from the UI
// TODO Add "painting" live cells
// TODO Allow scrolling beyond edge of ChunkGraphicsItems - https://stackoverflow.com/q/19207153?
namespace Ui {
class MainWindow; // Qt will fill this in from mainwindow.ui
}
// The main window of the application.
class MainWindow : public QMainWindow {
Q_OBJECT // Qt macro
public:
explicit MainWindow(QWidget* parent = nullptr);
~MainWindow() override;
public slots:
void addChunkGraphicsItem(int x, int y);
void removeChunkGraphicsItem(int x, int y);
// Handle all the messy parts of updating the automaton to a new one passed here.
void updateAutomaton(Automaton* newAutomaton);
private slots:
void nextGeneration();
void play();
void pause();
void reset();
void updatePlaySpeed(int value);
void launchChangeRulesDialog();
void launchChangeNeighbourhoodTypeDialog();
void launchChangeTopologyDialog();
void toggleChunkBoxes();
private:
void setTheme(GraphicsProperties::Theme theme);
void connectAutomaton(); // setup connections between the MainWindow and automaton_
void pauseIfRunning();
void updateStatusBar() const; // Update "Generation: X" in the status bar
static constexpr int MAX_PLAY_DELAY = 400; // min is 0; time in ms between updates when playing
int playDelay_ = 200;
Ui::MainWindow* ui_;
AutomatonScene* scene_; // where we draw the actual automaton
Automaton* automaton_; // the model itself
QTimer* tickTimer_; // for playing
QSlider* speedSlider_; // for controlling play speed
QActionGroup* themeGroup_; // make the theme actions mutually exclusive
// Analogous to ChunkArray's map, but for ChunkGraphicsItems
std::unordered_map<std::pair<int, int>, ChunkGraphicsItem*, pair_hash> chunkGIMap_;
};
#endif //GAME_OF_LIFE_MAINWINDOW_H
|
ryandancy/cellular-automata
|
src/Chunk.h
|
<reponame>ryandancy/cellular-automata<gh_stars>1-10
#ifndef GAME_OF_LIFE_CHUNK_H
#define GAME_OF_LIFE_CHUNK_H
#include <memory>
#include <unordered_set>
#include <unordered_map>
#include <utility>
#include <QDebug>
#include <QObject>
#include "Neighbourhood.h"
#include "Ruleset.h"
#include "Side.h"
#include "Topology.h"
#include "util.h"
#define CHUNK_SIZE 20
// A "chunk" of cells which are all processed at once.
// To update a cell, first call Chunk::generate(Ruleset&, Neighbourhood&) (or call the overloaded Side& version with
// as many sides as needed), then call Chunk::update() to process the next generation.
// TODO can we get any performance boost by somehow not having the virtual methods be virtual?
class Chunk : public QObject {
Q_OBJECT
public:
// Initialize the Chunk with the specified coordinates
Chunk(int x, int y) noexcept;
// Evaluate all the cells in the Chunk using the specified ruleset and prime the chunk to update.
// If side and affectingDistance are specified, evaluate only the cells within affectingDistance of side.
// (Note: this is overloaded instead of using default arguments because they're not allowed on virtual methods.)
virtual void generate(const Ruleset& ruleset, Neighbourhood& neighbourhood, const Side& side,
unsigned int affectingDistance);
virtual void generate(const Ruleset& ruleset, Neighbourhood& neighbourhood);
// Move to the next generation which was generated by Chunk::generate. You must call Chunk::generate first for
// this to have any effect. Update what will be returned by Chunk::getCell(x, y).
virtual void update();
// Get the value of the cell at (x, y).
// Throw std::invalid_argument if x >= CHUNK_SIZE, y >= CHUNK_SIZE, x < 0, or y < 0.
virtual bool getCell(int x, int y) const;
// Set the value of the cell at (x, y).
// Throw std::invalid_argument if x >= CHUNK_SIZE, y >= CHUNK_SIZE, x < 0, or y < 0.
virtual void setCell(int x, int y, bool value);
virtual bool isEmpty() const noexcept; // Is the whole Chunk empty?
virtual bool isNextGenEmpty() const noexcept; // Is the next generation currently empty? TODO necessary?
virtual int population() const noexcept; // Get the total number of live cells in the chunk.
const int chunkX, chunkY; // The coordinates of this Chunk.
signals:
void chunkChanged(bool newCells[CHUNK_SIZE][CHUNK_SIZE]);
private:
// Check that 0 <= x < CHUNK_SIZE and 0 <= y < CHUNK_SIZE, throwing std::invalid_argument otherwise.
static void checkInBounds(int x, int y);
// Update the cell at (x, y), assuming the neighbourhood is centred at (x, y), using the ruleset.
void updateNewCell(const Ruleset& ruleset, Neighbourhood& neighbourhood, int x, int y,
const Side& side = Side::BOTTOM);
// Scan a single line left or right with reference to the optionally given side. Modifies x.
void scanLine(const Ruleset& ruleset, Neighbourhood& neighbourhood, int& x, int y, const Side& side = Side::BOTTOM);
bool cells_[CHUNK_SIZE][CHUNK_SIZE] = {}; // the cells in the Chunk; index like cells_[x][y]
bool newCells_[CHUNK_SIZE][CHUNK_SIZE] = {}; // the cells of the next generation
int liveCellCount_ = 0; // count the number of live cells, currently; used for determining if it's empty
int nextLiveCellCount_ = 0; // same for the next generation
};
// A 2D-indexed list of Chunks - a thin wrapper over std::unordered_map.
// This isn't just a typedef for std::unordered_map<std::pair<int, int>, Chunk> because it encapsulates a Topology.
// If the Topology deems a coordinate invalid, a blank Chunk is returned.
// The Topology may modify coordinates as it wishes.
// All hail the great and mighty Topology.
// TODO I feel like there's something semantically wrong with returning a reference in get() and pointers via iterators
// TODO Do we really need the bool return types on insertOrNoop and erase?
class ChunkArray : public QObject {
Q_OBJECT
public:
typedef std::unordered_map<std::pair<int, int>, Chunk*, pair_hash>::iterator iterator;
typedef std::unordered_map<std::pair<int, int>, Chunk*, pair_hash>::size_type size_type;
typedef std::unordered_set<std::pair<int, int>, pair_hash>::iterator queue_iterator;
// Initialize this ChunkArray with the specified Topology
explicit ChunkArray(Topology* topology);
~ChunkArray() override; // we need to clear the map; QObject disables copy/move constructors/assignment operators
// Get a reference to this ChunkArray's topology.
Topology& topology() const noexcept;
// How many Chunks are stored?
size_type size();
// Get a reference to the Chunk at (x, y), throwing std::out_of_range if not present
Chunk& at(int x, int y) const;
// Does this ChunkArray contain a Chunk at (x, y)?
bool contains(int x, int y) const;
// Does this ChunkArray contain a non-empty Chunk at (x, y)?
bool hasNonEmpty(int x, int y);
// Attempt to insert an empty Chunk at (x, y). Return whether a Chunk was inserted. Does nothing otherwise.
bool insertOrNoop(int x, int y);
// Queue a chunk position (x, y) such that the next time insertAllInQueue() is called, a Chunk will be inserted at
// (x, y). This is useful when insertion must be delayed until iterating over the current chunks is done.
void queueForInsertion(int x, int y);
// Insert all chunk positions previously queued via queueForInsertion(x, y). Do not clear the queue.
void insertAllInQueue();
// If you call setIgnoringQueueInsertions(true), until you call setIgnoringQueueInsertions(false), queueForInsertion()
// will ignore all calls. This is useful when you know no useful chunks will be queued.
void setIgnoringQueueInsertions(bool ignore);
// Clear the queue of coordinates to insert.
void clearQueue();
// Iterators over the queue of coordinates to insert.
queue_iterator queueBegin() noexcept;
queue_iterator queueEnd() noexcept;
// Erase the Chunk at (x, y) if present, returning whether a Chunk was erased.
bool erase(int x, int y);
// Erase all Chunks and clear the queue.
void clear();
// Iterators, iterating over pairs of coordinate pairs and pointers to corresponding Chunks.
iterator begin() noexcept;
iterator end() noexcept;
signals:
void chunkAdded(int x, int y);
void chunkRemoved(int x, int y);
private:
// Empty Chunk for use when the Topology specifies a chunk is to be treated as empty
struct : public Chunk {
using Chunk::Chunk;
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void generate(const Ruleset&, Neighbourhood&, const Side&, unsigned int) override {}
void generate(const Ruleset&, Neighbourhood&) override {}
void update() override {}
bool getCell(int, int) const override { return false; }
void setCell(int, int, bool) override {} // prevent emitting signals
bool isEmpty() const noexcept override { return true; }
bool isNextGenEmpty() const noexcept override { return true; }
#pragma clang diagnostic pop
} static EMPTY;
std::unordered_map<std::pair<int, int>, Chunk*, pair_hash> map_;
std::unique_ptr<Topology> topology_;
std::unordered_set<std::pair<int, int>, pair_hash> coordinateQueue_; // holds coordinates queued for insertion
bool ignoreQueueInsertion_ = false;
};
#endif //GAME_OF_LIFE_CHUNK_H
|
ryandancy/cellular-automata
|
src/TopologyDialog.h
|
<gh_stars>1-10
#ifndef GAME_OF_LIFE_TOPOLOGYDIALOG_H
#define GAME_OF_LIFE_TOPOLOGYDIALOG_H
#include <QDialog>
#include <QWidget>
#include "Automaton.h"
#include "AutomatonScene.h"
namespace Ui {
class TopologyDialog;
}
// A dialog which can change the topology of the field.
class TopologyDialog : public QDialog {
Q_OBJECT
public:
// We modify, but do not own, the Automaton referenced here
explicit TopologyDialog(Automaton& automaton, QWidget* parent = nullptr);
~TopologyDialog() override;
signals:
void automatonUpdated(Automaton* newAutomaton);
private slots:
void apply(); // change the topology and exit
private:
Ui::TopologyDialog* ui_;
Automaton& automaton_; // the automaton whose topology we're changing, to steal the Ruleset from
};
#endif //GAME_OF_LIFE_TOPOLOGYDIALOG_H
|
ryandancy/cellular-automata
|
src/NeighbourhoodDialog.h
|
<filename>src/NeighbourhoodDialog.h
#ifndef GAME_OF_LIFE_NEIGHBOURHOODDIALOG_H
#define GAME_OF_LIFE_NEIGHBOURHOODDIALOG_H
#include <QButtonGroup>
#include <QDialog>
#include <QWidget>
#include "Automaton.h"
#include "Neighbourhood.h"
namespace Ui {
class NeighbourhoodDialog;
}
// A dialog in which the user can choose and customize a neighbourhood type.
class NeighbourhoodDialog : public QDialog {
Q_OBJECT
public:
NeighbourhoodDialog(NeighbourhoodType& current, Automaton* automaton, QWidget* parent = nullptr);
~NeighbourhoodDialog() override;
private slots:
void apply();
private:
Ui::NeighbourhoodDialog* ui_;
QButtonGroup* typeGroup_; // for making the neighbourhood type radio buttons mutually exclusive
Automaton* automaton_; // to modify if the user clicks ok
NeighbourhoodType& current_; // the current neighbourhood type
};
#endif //GAME_OF_LIFE_NEIGHBOURHOODDIALOG_H
|
poke19962008/Machine-Laerning-Projects
|
XOR Problem/Model 3/xor.h
|
/* -*- C++ -*- */
#include <iostream>
#include <array>
#include <ctime>
using namespace std;
const int tSetLen = 4;
class XOR {
private:
int testSet[tSetLen][3] = {{0, 0, 0}, {0, 1, 1}, {1, 0, 1}, {1, 1, 0}};
public:
int stepFunction(int x) {
return (x >= 0)? 1:0;
}
int nandNeuron(int x1, int x2){
const int bias = 3;
const int weight = -2;
int Yin = x1*weight + x2*weight + bias;
return stepFunction(Yin);
}
int andNeuron(int x1, int x2){
const int bias = -3;
const int weight = 1;
int Yin = x1*weight + x2+weight + bias;
return stepFunction(Yin);
}
int orNeuron(int x1, int x2){
const int bias = -2;
const int weight = 1;
int Yin = x1*weight + x2+weight + bias;
return stepFunction(Yin);
}
int compute(int x1, int x2){
int A1 = nandNeuron(x1, x2);
int A2 = orNeuron(x1, x2);
int B1 = andNeuron(A1, A2);
return B1;
}
void test(){
int correct = 0;
cout<<"Starting test over "<<tSetLen<<" test cases."<<endl;
int start_s=clock();
for (size_t i = 0; i < tSetLen; i++) {
int hyp = compute(testSet[i][0], testSet[i][1]);
if(hyp == testSet[i][2]) correct++;
}
int stop_s=clock();
cout<<"Model Analysis\nAccuracy: "<<(float)(correct/tSetLen)*100<<"\%\n";
cout<<"Error: "<<(float)(1-correct/tSetLen)*100<<"\%\n";
cout<<"Total Time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;
}
};
|
ismailbozkurt77/ZendeskUIKit
|
ZendeskUIKit/ZendeskUIKit/ZendeskUIKit.h
|
//
// ZendeskUIKit.h
// ZendeskUIKit
//
// Created by Ismail on 04/01/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for ZendeskUIKit.
FOUNDATION_EXPORT double ZendeskUIKitVersionNumber;
//! Project version string for ZendeskUIKit.
FOUNDATION_EXPORT const unsigned char ZendeskUIKitVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <ZendeskUIKit/PublicHeader.h>
|
phraemer/Celero
|
include/celero/Console.h
|
<reponame>phraemer/Celero
#ifndef H_CELERO_CONSOLE_H
#define H_CELERO_CONSOLE_H
///
/// \author <NAME>
///
/// \copyright Copyright 2015-2021 <NAME>
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
#include <celero/Export.h>
namespace celero
{
///
/// \namespace console
///
/// \author <NAME>
///
namespace console
{
///
/// \enum ConsoleColor
///
/// \author <NAME>
///
enum class ConsoleColor
{
Default,
Red,
Red_Bold,
Green,
Green_Bold,
Blue,
Blue_Bold,
Cyan,
Cyan_Bold,
Yellow,
Yellow_Bold,
White,
White_Bold,
WhiteOnRed,
WhiteOnRed_Bold,
Purple_Bold
};
///
/// Set the color of std::out on the console.
///
CELERO_EXPORT void SetConsoleColor(const celero::console::ConsoleColor x);
} // namespace console
} // namespace celero
#endif
|
phraemer/Celero
|
include/celero/UserDefinedMeasurementTemplate.h
|
#ifndef H_CELERO_USERDEFINEDMEASUREMENTTEMPLATE_H
#define H_CELERO_USERDEFINEDMEASUREMENTTEMPLATE_H
///
/// \author <NAME>, <NAME>
///
/// \copyright Copyright 2015-2021 <NAME>
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
#include <celero/Statistics.h>
#include <celero/UserDefinedMeasurement.h>
#include <numeric>
#include <type_traits>
namespace celero
{
///
/// \class UserDefinedMeasurementTemplate
///
/// Base class that the user must derive user-defined measurements from.
///
/// \author <NAME>, <NAME>
///
template <typename T>
class UserDefinedMeasurementTemplate : public UserDefinedMeasurement
{
static_assert(std::is_arithmetic<T>::value, "UserDefinedMeasurementTemplate requres an arithmetic type.");
public:
///
/// Default constructor
///
UserDefinedMeasurementTemplate() = default;
///
/// Default destructor
///
virtual ~UserDefinedMeasurementTemplate() = default;
///
/// \brief Must be implemented by the user. Must return a specification which aggregations the user wants to be computed.
///
UDMAggregationTable getAggregationInfo() const override
{
UDMAggregationTable table;
if(this->reportSize() == true)
{
table.push_back({"# Samp", [this]() { return static_cast<double>(this->getStatistics().getSize()); }});
}
if(this->reportMean() == true)
{
table.push_back({"Mean", [this]() { return this->getStatistics().getMean(); }});
}
if(this->reportVariance() == true)
{
table.push_back({"Var", [this]() { return this->getStatistics().getVariance(); }});
}
if(this->reportStandardDeviation() == true)
{
table.push_back({"StdDev", [this]() { return this->getStatistics().getStandardDeviation(); }});
}
if(this->reportSkewness() == true)
{
table.push_back({"Skew", [this]() { return this->getStatistics().getSkewness(); }});
}
if(this->reportKurtosis() == true)
{
table.push_back({"Kurtosis", [this]() { return this->getStatistics().getKurtosis(); }});
}
if(this->reportZScore() == true)
{
table.push_back({"ZScore", [this]() { return this->getStatistics().getZScore(); }});
}
if(this->reportMin() == true)
{
table.push_back({"Min", [this]() { return static_cast<double>(this->getStatistics().getMin()); }});
}
if(this->reportMax() == true)
{
table.push_back({"Max", [this]() { return static_cast<double>(this->getStatistics().getMax()); }});
}
return table;
}
///
/// \brief You must call this method from your fixture to add a measurement
///
void addValue(T x)
{
this->stats.addSample(x);
}
///
/// Preserve measurements within a group/experiment/problem space set.
///
void merge(const UserDefinedMeasurement* const x) override
{
const auto toMerge = dynamic_cast<const UserDefinedMeasurementTemplate<T>* const>(x);
this->stats += toMerge->stats;
}
protected:
virtual bool reportSize() const
{
return true;
}
virtual bool reportMean() const
{
return true;
}
virtual bool reportVariance() const
{
return true;
}
virtual bool reportStandardDeviation() const
{
return true;
}
virtual bool reportSkewness() const
{
return true;
}
virtual bool reportKurtosis() const
{
return true;
}
virtual bool reportZScore() const
{
return true;
}
virtual bool reportMin() const
{
return true;
}
virtual bool reportMax() const
{
return true;
}
const Statistics<T>& getStatistics() const
{
return this->stats;
}
private:
/// Continuously gathers statistics without having to retain data history.
Statistics<T> stats;
};
} // namespace celero
#endif
|
JuliaPackageMirrors/Gallium.jl
|
src/Hooking/callback.c
|
// clang -fPIC -c callback.c
// clang -shared -o hooking.so elfjump.o elfhook.o callback.o
void *hooking_jl_callback = 0;
void __attribute__ ((visibility ("default"))) hooking_jl_set_callback(void *fptr)
{
hooking_jl_callback = fptr;
}
void test()
{
((void(*)())hooking_jl_callback)();
}
|
walbourn/directxtktest
|
PrimitivesTest/Game.h
|
//--------------------------------------------------------------------------------------
// File: Game.h
//
// Developer unit test for DirectXTK Geometric Primitives
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include "DirectXTKTest.h"
#include "StepTimer.h"
// A basic game implementation that creates a D3D11 device and
// provides a game loop.
class Game
#ifdef LOSTDEVICE
final : public DX::IDeviceNotify
#endif
{
public:
Game() noexcept(false);
~Game() = default;
Game(Game&&) = default;
Game& operator= (Game&&) = default;
Game(Game const&) = delete;
Game& operator= (Game const&) = delete;
// Initialization and management
#ifdef COREWINDOW
void Initialize(IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation);
#else
void Initialize(HWND window, int width, int height, DXGI_MODE_ROTATION rotation);
#endif
// Basic game loop
void Tick();
#ifdef LOSTDEVICE
// IDeviceNotify
virtual void OnDeviceLost() override;
virtual void OnDeviceRestored() override;
#endif
// Messages
void OnActivated();
void OnDeactivated();
void OnSuspending();
void OnResuming();
#ifdef PC
void OnWindowMoved();
#endif
#ifndef XBOX
void OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation);
#endif
#ifdef UWP
void ValidateDevice();
#endif
// Properties
void GetDefaultSize( int& width, int& height ) const;
const wchar_t* GetAppName() const { return L"PrimitivesTest (DirectX 11)"; }
bool RequestHDRMode() const { return m_deviceResources ? (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_EnableHDR) != 0 : false; }
private:
void Update(DX::StepTimer const& timer);
void Render();
void Clear();
void CreateDeviceDependentResources();
void CreateWindowSizeDependentResources();
// Device resources.
std::unique_ptr<DX::DeviceResources> m_deviceResources;
// Rendering loop timer.
DX::StepTimer m_timer;
// Input devices.
std::unique_ptr<DirectX::GamePad> m_gamePad;
std::unique_ptr<DirectX::Keyboard> m_keyboard;
DirectX::GamePad::ButtonStateTracker m_gamePadButtons;
DirectX::Keyboard::KeyboardStateTracker m_keyboardButtons;
// DirectXTK Test Objects
#ifdef XBOX
std::unique_ptr<DirectX::GraphicsMemory> m_graphicsMemory;
#endif
std::unique_ptr<DirectX::CommonStates> m_states;
std::unique_ptr<DirectX::GeometricPrimitive> m_cube;
std::unique_ptr<DirectX::GeometricPrimitive> m_box;
std::unique_ptr<DirectX::GeometricPrimitive> m_sphere;
std::unique_ptr<DirectX::GeometricPrimitive> m_geosphere;
std::unique_ptr<DirectX::GeometricPrimitive> m_cylinder;
std::unique_ptr<DirectX::GeometricPrimitive> m_cone;
std::unique_ptr<DirectX::GeometricPrimitive> m_torus;
std::unique_ptr<DirectX::GeometricPrimitive> m_teapot;
std::unique_ptr<DirectX::GeometricPrimitive> m_tetra;
std::unique_ptr<DirectX::GeometricPrimitive> m_octa;
std::unique_ptr<DirectX::GeometricPrimitive> m_dodec;
std::unique_ptr<DirectX::GeometricPrimitive> m_iso;
std::unique_ptr<DirectX::GeometricPrimitive> m_customBox;
std::unique_ptr<DirectX::GeometricPrimitive> m_customBox2;
std::unique_ptr<DirectX::BasicEffect> m_customEffect;
std::unique_ptr<DirectX::NormalMapEffect> m_instancedEffect;
Microsoft::WRL::ComPtr<ID3D11InputLayout> m_customIL;
Microsoft::WRL::ComPtr<ID3D11InputLayout> m_instancedIL;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_cat;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_dxlogo;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_reftxt;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_normalMap;
DirectX::SimpleMath::Matrix m_view;
DirectX::SimpleMath::Matrix m_projection;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_instancedVB;
UINT m_instanceCount;
std::unique_ptr<DirectX::XMFLOAT3X4[]> m_instanceTransforms;
bool m_spinning;
float m_pitch;
float m_yaw;
};
|
walbourn/directxtktest
|
ShaderTest/Game.h
|
//--------------------------------------------------------------------------------------
// File: Game.h
//
// Developer unit test for DirectXTK - HLSL shader coverage
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include "DirectXTKTest.h"
#include "StepTimer.h"
#include "RenderTexture.h"
// A basic game implementation that creates a D3D11 device and
// provides a game loop.
class Game
#ifdef LOSTDEVICE
final : public DX::IDeviceNotify
#endif
{
public:
Game() noexcept(false);
~Game() = default;
Game(Game&&) = default;
Game& operator= (Game&&) = default;
Game(Game const&) = delete;
Game& operator= (Game const&) = delete;
// Initialization and management
#ifdef COREWINDOW
void Initialize(IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation);
#else
void Initialize(HWND window, int width, int height, DXGI_MODE_ROTATION rotation);
#endif
// Basic game loop
void Tick();
#ifdef LOSTDEVICE
// IDeviceNotify
virtual void OnDeviceLost() override;
virtual void OnDeviceRestored() override;
#endif
// Messages
void OnActivated();
void OnDeactivated();
void OnSuspending();
void OnResuming();
#ifdef PC
void OnWindowMoved();
#endif
#ifndef XBOX
void OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation);
#endif
#ifdef UWP
void ValidateDevice();
#endif
// Properties
void GetDefaultSize( int& width, int& height ) const;
const wchar_t* GetAppName() const { return L"ShaderTest (DirectX 11)"; }
bool RequestHDRMode() const { return m_deviceResources ? (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_EnableHDR) != 0 : false; }
private:
void Update(DX::StepTimer const& timer);
void Render();
void Clear();
void CreateDeviceDependentResources();
void CreateWindowSizeDependentResources();
void CycleRenderMode();
// Device resources.
std::unique_ptr<DX::DeviceResources> m_deviceResources;
// Rendering loop timer.
DX::StepTimer m_timer;
// Input devices.
std::unique_ptr<DirectX::GamePad> m_gamePad;
std::unique_ptr<DirectX::Keyboard> m_keyboard;
DirectX::GamePad::ButtonStateTracker m_gamePadButtons;
DirectX::Keyboard::KeyboardStateTracker m_keyboardButtons;
// DirectXTK Test Objects
#ifdef XBOX
std::unique_ptr<DirectX::GraphicsMemory> m_graphicsMemory;
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Woverloaded-virtual"
#endif
template<typename T>
class EffectWithDecl : public T
{
public:
EffectWithDecl(ID3D11Device* device, std::function<void(T*)> setEffectParameters)
: T(device)
{
setEffectParameters(this);
CreateTestInputLayout(device, this, &inputLayout, &compressedInputLayout, nullptr, nullptr);
}
void Apply(ID3D11DeviceContext* context, DirectX::CXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection, bool showCompressed)
{
T::SetMatrices(world, view, projection);
auto ibasic = dynamic_cast<BasicEffect*>(this);
if (ibasic)
ibasic->SetBiasedVertexNormals(showCompressed);
auto ienvmap = dynamic_cast<EnvironmentMapEffect*>(this);
if (ienvmap)
ienvmap->SetBiasedVertexNormals(showCompressed);
auto inmap = dynamic_cast<NormalMapEffect*>(this);
if (inmap)
{
inmap->SetBiasedVertexNormals(showCompressed);
inmap->SetInstancingEnabled(false);
}
auto ipbr = dynamic_cast<PBREffect*>(this);
if (ipbr)
{
ipbr->SetBiasedVertexNormals(showCompressed);
ipbr->SetInstancingEnabled(false);
}
auto iskin = dynamic_cast<SkinnedEffect*>(this);
if (iskin)
iskin->SetBiasedVertexNormals(showCompressed);
auto idbg = dynamic_cast<DebugEffect*>(this);
if (idbg)
{
idbg->SetBiasedVertexNormals(showCompressed);
idbg->SetInstancingEnabled(false);
}
T::Apply(context);
context->IASetInputLayout((showCompressed) ? compressedInputLayout.Get() : inputLayout.Get());
}
private:
Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
Microsoft::WRL::ComPtr<ID3D11InputLayout> compressedInputLayout;
};
template<typename T>
class InstancedEffectWithDecl : public T
{
public:
InstancedEffectWithDecl(ID3D11Device* device, std::function<void(T*)> setEffectParameters)
: T(device)
{
setEffectParameters(this);
CreateTestInputLayout(device, this, nullptr, nullptr, &inputLayout, &compressedInputLayout);
}
void Apply(ID3D11DeviceContext* context, DirectX::CXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection, bool showCompressed)
{
T::SetMatrices(world, view, projection);
auto inmap = dynamic_cast<NormalMapEffect*>(this);
if (inmap)
{
inmap->SetBiasedVertexNormals(showCompressed);
inmap->SetInstancingEnabled(true);
}
auto ipbr = dynamic_cast<PBREffect*>(this);
if (ipbr)
{
ipbr->SetBiasedVertexNormals(showCompressed);
ipbr->SetInstancingEnabled(true);
}
auto idbg = dynamic_cast<DebugEffect*>(this);
if (idbg)
{
idbg->SetBiasedVertexNormals(showCompressed);
idbg->SetInstancingEnabled(true);
}
T::Apply(context);
context->IASetInputLayout((showCompressed) ? compressedInputLayout.Get() : inputLayout.Get());
}
private:
Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
Microsoft::WRL::ComPtr<ID3D11InputLayout> compressedInputLayout;
};
template<typename T>
class DGSLEffectWithDecl : public T
{
public:
DGSLEffectWithDecl(ID3D11Device* device, std::function<void(T*)> setEffectParameters)
: T(device, nullptr)
{
setEffectParameters(this);
CreateTestInputLayout(device, this, &inputLayout, nullptr, nullptr, nullptr);
}
void Apply(ID3D11DeviceContext* context, DirectX::CXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection)
{
T::SetMatrices(world, view, projection);
T::Apply(context);
context->IASetInputLayout(inputLayout.Get());
}
private:
Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
std::unique_ptr<DirectX::CommonStates> m_states;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::BasicEffect>>> m_basic;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::SkinnedEffect>>> m_skinning;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::EnvironmentMapEffect>>> m_envmap;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::DualTextureEffect>>> m_dual;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::AlphaTestEffect>>> m_alphTest;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::NormalMapEffect>>> m_normalMap;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::SkinnedNormalMapEffect>>> m_skinningNormalMap;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::PBREffect>>> m_pbr;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::SkinnedPBREffect>>> m_skinningPbr;
std::vector<std::unique_ptr<EffectWithDecl<DirectX::DebugEffect>>> m_debug;
std::vector<std::unique_ptr<DGSLEffectWithDecl<DirectX::DGSLEffect>>> m_dgsl;
std::vector<std::unique_ptr<DGSLEffectWithDecl<DirectX::SkinnedDGSLEffect>>> m_dgslSkinned;
std::vector<std::unique_ptr<InstancedEffectWithDecl<DirectX::NormalMapEffect>>> m_normalMapInstanced;
std::vector<std::unique_ptr<InstancedEffectWithDecl<DirectX::PBREffect>>> m_pbrInstanced;
std::vector<std::unique_ptr<InstancedEffectWithDecl<DirectX::DebugEffect>>> m_debugInstanced;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_compressedVB;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_instancedVB;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_cat;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_cubemap;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_envball;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_envdual;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_overlay;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_defaultTex;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_brickDiffuse;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_brickNormal;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_brickSpecular;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_pbrAlbedo;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_pbrNormal;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_pbrRMA;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_pbrEmissive;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_radianceIBL;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_irradianceIBL;
std::unique_ptr<DX::RenderTexture> m_velocityBuffer;
DirectX::SimpleMath::Matrix m_view;
DirectX::SimpleMath::Matrix m_projection;
UINT m_indexCount;
UINT m_instanceCount;
std::unique_ptr<DirectX::XMFLOAT3X4[]> m_instanceTransforms;
enum RenderMode
{
Render_Normal,
Render_Compressed,
Render_Instanced,
Render_CompressedInstanced,
Render_Max
};
unsigned int m_renderMode;
float m_delay;
static void CreateTestInputLayout(
_In_ ID3D11Device* device,
DirectX::IEffect* effect,
_Outptr_opt_ ID3D11InputLayout** pInputLayout,
_Outptr_opt_ ID3D11InputLayout** pCompresedInputLayout,
_Outptr_opt_ ID3D11InputLayout** pInstancedLayout,
_Outptr_opt_ ID3D11InputLayout** pCompresedInstancedLayout);
};
|
walbourn/directxtktest
|
SimpleMathTest/SimpleMathTest.h
|
//-------------------------------------------------------------------------------------
// SimpleMathTest.h
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation.
//-------------------------------------------------------------------------------------
#pragma once
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <DirectXColors.h>
#include <stdio.h>
#include <functional>
#include <iterator>
#include <map>
#include <memory>
#include <type_traits>
#include <vector>
constexpr float EPSILON = 0.000001f;
constexpr float EPSILON2 = 0.00001f;
constexpr float EPSILON3 = 0.001f;
XMGLOBALCONST DirectX::XMVECTORF32 VEPSILON = { { { EPSILON, EPSILON, EPSILON, EPSILON } } };
XMGLOBALCONST DirectX::XMVECTORF32 VEPSILON2 = { { { EPSILON2, EPSILON2, EPSILON2, EPSILON2 } } };
XMGLOBALCONST DirectX::XMVECTORF32 VEPSILON3 = { { { EPSILON3, EPSILON3, EPSILON3, EPSILON3 } } };
inline void FormatValue(bool value, char* output, size_t outputSize)
{
strcpy_s(output, outputSize, value ? "true" : "false");
}
inline void FormatValue(float value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "%f", value);
}
inline void FormatValue(uint32_t value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "%08x", value);
}
inline void FormatValue(DirectX::SimpleMath::Vector3 const& value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "%f %f %f", value.x, value.y, value.z);
}
inline void FormatValue(DirectX::SimpleMath::Vector4 const& value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "%f %f %f %f", value.x, value.y, value.z, value.w);
}
inline void FormatValue(DirectX::SimpleMath::Color const& value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "%f %f %f %f", value.x, value.y, value.z, value.w);
}
inline void FormatValue(DirectX::SimpleMath::Plane const& value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "%f %f %f %f", value.x, value.y, value.z, value.w);
}
inline void FormatValue(DirectX::SimpleMath::Quaternion const& value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "%f %f %f %f", value.x, value.y, value.z, value.w);
}
inline void FormatValue(DirectX::SimpleMath::Matrix const& value, char* output, size_t outputSize)
{
sprintf_s(output, outputSize, "\n %f %f %f %f\n %f %f %f %f\n %f %f %f %f\n %f %f %f %f\n", value._11, value._12, value._13, value._14, value._21, value._22, value._23, value._24, value._31, value._32, value._33, value._34, value._41, value._42, value._43, value._44);
}
struct near_equal_to
{
bool operator() (float a, float b) const
{
return DirectX::XMScalarNearEqual(a, b, EPSILON);
}
bool operator() (DirectX::FXMVECTOR a, DirectX::FXMVECTOR b) const
{
return DirectX::XMVector4NearEqual(a, b, VEPSILON);
}
bool operator() (DirectX::CXMMATRIX a, DirectX::CXMMATRIX b) const
{
return DirectX::XMVector4NearEqual(a.r[0], b.r[0], VEPSILON) &&
DirectX::XMVector4NearEqual(a.r[1], b.r[1], VEPSILON) &&
DirectX::XMVector4NearEqual(a.r[2], b.r[2], VEPSILON) &&
DirectX::XMVector4NearEqual(a.r[3], b.r[3], VEPSILON);
}
};
template<typename TValue, typename TCompare>
inline bool VerifyValue(TValue const& value, TValue const& expected, TCompare const& compare, char const* file, int line)
{
if (compare(value, expected))
return true;
char valueString[256] = {};
char expectedString[256] = {};
FormatValue(value, valueString, sizeof(valueString));
FormatValue(expected, expectedString, sizeof(expectedString));
printf("ERROR: %s:%d: %s (expecting %s)\n", file, line, valueString, expectedString);
return false;
}
#define VerifyEqual(value, expected) \
success &= VerifyValue(value, expected, std::equal_to<decltype(value)>(), __FUNCTION__, __LINE__)
#define VerifyNearEqual(value, expected) \
success &= VerifyValue(value, expected, near_equal_to(), __FUNCTION__, __LINE__)
|
vakuras/moleculardynamics
|
cpu/equi/Host.h
|
///
/// Host Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef HOST_HEADER
#define HOST_HEADER
#include "..\..\common\Global.h"
#include "..\..\common\NeighborList.h"
#include "..\common\Device.h"
#include "..\..\common\ConfigParser.h"
#include "..\..\common\Constants.h"
#include "..\..\common\DebugCalculations.h"
#include "Statistics.h"
#include "..\..\common\Loader.h"
#include "..\..\common\results.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define MD_RANDMAX (RAND_MAX + 2)
int hostMain(configuration * config);
void readyList(real4 * posArray, real3 * velocityArray, int NumberOfParticles, real & highestVelocity, real & boxSize);
void buildList(real4 * posArray, listSettings * listsettings, real boxSize, int buckets, real highestVelocity, int NumberOfParticles, int & nextBuild, int currentTimestep, int ** list, real dt);
bool choosePositionsNoble(real4 * posArray, real boxl, configuration * config);
bool choosePositionsManyBody(real4 * posArray, real boxl, configuration * config);
void chooseVelocities(real4 * posArray, real3 * velocityArray, real temp, configuration * config);
#endif
|
vakuras/moleculardynamics
|
ui/ui/PlotWindow.h
|
<filename>ui/ui/PlotWindow.h
///
/// Plot window controller definition.
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#pragma once
#ifndef PLOTH
#define PLOTH
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Collections::Generic;
#include "..\NovaFX\NovaFX.h"
#include "TitleBar.h"
namespace ui
{
public ref class PlotWindow : public System::Windows::Forms::UserControl
{
private:
NovaFX::NovaFX * _nova;
NovaFX::NovaCamera::Camera * _camera;
configuration * _config;
int _lastMX;
int _lastMY;
System::Windows::Forms::PictureBox^ _pnlDC;
System::Windows::Forms::Timer^ _tmrDC;
TitleBar ^ _titleBar;
Dictionary<String^, List<int>^>^ _particles;
TableLayoutPanel^ _tablePlot;
TableLayoutPanel^ _tableControls;
CheckBox^ _chkVec;
TrackBar^ _animBar;
Button^ _btnPrev;
Button^ _btnNext;
Button^ _btnBrowse;
System::ComponentModel::IContainer^ components;
System::Windows::Forms::Button^ _btnPlayStop;
System::Windows::Forms::CheckBox^ _chkReverse;
bool _leftButtonState;
bool _play;
private:
System::Void _titleBarEvent(System::Object^ , System::EventArgs^ );
System::Void PlotWindow_Resize(System::Object^ , System::EventArgs^ );
System::Void _tmrDC_Tick(System::Object^ , System::EventArgs^ );
System::Void _pnlDC_MouseMove(System::Object^ , System::Windows::Forms::MouseEventArgs^ );
System::Void PlotWindow::_btnBrowse_Click(System::Object^ , System::EventArgs^ );
System::Void _pnlDC_MouseDown(System::Object^ , System::Windows::Forms::MouseEventArgs^ );
System::Void _pnlDC_MouseUp(System::Object^ , System::Windows::Forms::MouseEventArgs^ );
System::String ^ PlotWindow::ChooseFile(System::String ^ title, System::String ^ filter);
System::Void _btnPlayStop_Click(System::Object^ , System::EventArgs^ );
System::Void _animBar_Scroll(System::Object^ , System::EventArgs^ );
System::Void _chkVec_CheckedChanged(System::Object^ , System::EventArgs^ );
void PlotWindow::flushVectors();
void PlotWindow::LoadIndex(int index, int nop);
public:
void PlotWindow::LoadSimpleFile(string filename);
void PlotWindow::LoadAnimationFile(string filename);
PlotWindow(configuration * );
void Init();
void Destroy();
protected:
~PlotWindow();
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->_pnlDC = (gcnew System::Windows::Forms::PictureBox());
this->_tmrDC = (gcnew System::Windows::Forms::Timer(this->components));
this->_tablePlot = (gcnew System::Windows::Forms::TableLayoutPanel());
this->_tableControls = (gcnew System::Windows::Forms::TableLayoutPanel());
this->_btnPrev = (gcnew System::Windows::Forms::Button());
this->_btnNext = (gcnew System::Windows::Forms::Button());
this->_btnBrowse = (gcnew System::Windows::Forms::Button());
this->_chkVec = (gcnew System::Windows::Forms::CheckBox());
this->_animBar = (gcnew System::Windows::Forms::TrackBar());
this->_btnPlayStop = (gcnew System::Windows::Forms::Button());
this->_chkReverse = (gcnew System::Windows::Forms::CheckBox());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->_pnlDC))->BeginInit();
this->_tablePlot->SuspendLayout();
this->_tableControls->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->_animBar))->BeginInit();
this->SuspendLayout();
//
// _pnlDC
//
this->_pnlDC->Dock = System::Windows::Forms::DockStyle::Fill;
this->_pnlDC->Location = System::Drawing::Point(3, 3);
this->_pnlDC->Name = L"_pnlDC";
this->_pnlDC->Size = System::Drawing::Size(574, 447);
this->_pnlDC->TabIndex = 17;
this->_pnlDC->TabStop = false;
this->_pnlDC->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &PlotWindow::_pnlDC_MouseMove);
this->_pnlDC->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &PlotWindow::_pnlDC_MouseDown);
this->_pnlDC->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &PlotWindow::_pnlDC_MouseUp);
//
// _tmrDC
//
this->_tmrDC->Enabled = true;
this->_tmrDC->Interval = 30;
this->_tmrDC->Tick += gcnew System::EventHandler(this, &PlotWindow::_tmrDC_Tick);
//
// _tablePlot
//
this->_tablePlot->ColumnCount = 1;
this->_tablePlot->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 100)));
this->_tablePlot->Controls->Add(this->_pnlDC, 0, 0);
this->_tablePlot->Controls->Add(this->_tableControls, 0, 1);
this->_tablePlot->Dock = System::Windows::Forms::DockStyle::Fill;
this->_tablePlot->Location = System::Drawing::Point(0, 0);
this->_tablePlot->Name = L"_tablePlot";
this->_tablePlot->RowCount = 2;
this->_tablePlot->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 100)));
this->_tablePlot->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Absolute, 40)));
this->_tablePlot->Size = System::Drawing::Size(580, 493);
this->_tablePlot->TabIndex = 18;
//
// _tableControls
//
this->_tableControls->ColumnCount = 7;
this->_tableControls->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
30)));
this->_tableControls->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
30)));
this->_tableControls->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
50)));
this->_tableControls->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
80)));
this->_tableControls->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
100)));
this->_tableControls->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
110)));
this->_tableControls->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
40)));
this->_tableControls->Controls->Add(this->_btnPrev, 0, 0);
this->_tableControls->Controls->Add(this->_btnNext, 1, 0);
this->_tableControls->Controls->Add(this->_btnBrowse, 6, 0);
this->_tableControls->Controls->Add(this->_chkVec, 5, 0);
this->_tableControls->Controls->Add(this->_animBar, 4, 0);
this->_tableControls->Controls->Add(this->_btnPlayStop, 2, 0);
this->_tableControls->Controls->Add(this->_chkReverse, 3, 0);
this->_tableControls->Dock = System::Windows::Forms::DockStyle::Fill;
this->_tableControls->Location = System::Drawing::Point(3, 456);
this->_tableControls->Name = L"_tableControls";
this->_tableControls->RowCount = 1;
this->_tableControls->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 100)));
this->_tableControls->Size = System::Drawing::Size(574, 34);
this->_tableControls->TabIndex = 18;
//
// _btnPrev
//
this->_btnPrev->Dock = System::Windows::Forms::DockStyle::Fill;
this->_btnPrev->Enabled = false;
this->_btnPrev->Font = (gcnew System::Drawing::Font(L"Lucida Console", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->_btnPrev->Location = System::Drawing::Point(3, 3);
this->_btnPrev->Name = L"_btnPrev";
this->_btnPrev->Size = System::Drawing::Size(24, 28);
this->_btnPrev->TabIndex = 4;
this->_btnPrev->Text = L"<";
this->_btnPrev->UseVisualStyleBackColor = true;
//
// _btnNext
//
this->_btnNext->Dock = System::Windows::Forms::DockStyle::Fill;
this->_btnNext->Enabled = false;
this->_btnNext->Font = (gcnew System::Drawing::Font(L"Lucida Console", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->_btnNext->Location = System::Drawing::Point(33, 3);
this->_btnNext->Name = L"_btnNext";
this->_btnNext->Size = System::Drawing::Size(24, 28);
this->_btnNext->TabIndex = 5;
this->_btnNext->Text = L">";
this->_btnNext->UseVisualStyleBackColor = true;
//
// _btnBrowse
//
this->_btnBrowse->Dock = System::Windows::Forms::DockStyle::Fill;
this->_btnBrowse->Font = (gcnew System::Drawing::Font(L"Lucida Console", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->_btnBrowse->Location = System::Drawing::Point(537, 3);
this->_btnBrowse->Name = L"_btnBrowse";
this->_btnBrowse->Size = System::Drawing::Size(34, 28);
this->_btnBrowse->TabIndex = 6;
this->_btnBrowse->Text = L"..";
this->_btnBrowse->UseVisualStyleBackColor = true;
this->_btnBrowse->Click += gcnew System::EventHandler(this, &PlotWindow::_btnBrowse_Click);
//
// _chkVec
//
this->_chkVec->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Left | System::Windows::Forms::AnchorStyles::Right));
this->_chkVec->AutoSize = true;
this->_chkVec->Checked = true;
this->_chkVec->CheckState = System::Windows::Forms::CheckState::Checked;
this->_chkVec->Enabled = false;
this->_chkVec->Location = System::Drawing::Point(427, 8);
this->_chkVec->Name = L"_chkVec";
this->_chkVec->Size = System::Drawing::Size(104, 17);
this->_chkVec->TabIndex = 1;
this->_chkVec->Text = L"Show Velocities";
this->_chkVec->UseVisualStyleBackColor = true;
this->_chkVec->CheckedChanged += gcnew System::EventHandler(this, &PlotWindow::_chkVec_CheckedChanged);
//
// _animBar
//
this->_animBar->Dock = System::Windows::Forms::DockStyle::Fill;
this->_animBar->Enabled = false;
this->_animBar->Location = System::Drawing::Point(193, 3);
this->_animBar->Name = L"_animBar";
this->_animBar->Size = System::Drawing::Size(228, 28);
this->_animBar->TabIndex = 3;
this->_animBar->Scroll += gcnew System::EventHandler(this, &PlotWindow::_animBar_Scroll);
//
// _btnPlayStop
//
this->_btnPlayStop->Dock = System::Windows::Forms::DockStyle::Fill;
this->_btnPlayStop->Enabled = false;
this->_btnPlayStop->Location = System::Drawing::Point(63, 3);
this->_btnPlayStop->Name = L"_btnPlayStop";
this->_btnPlayStop->Size = System::Drawing::Size(44, 28);
this->_btnPlayStop->TabIndex = 7;
this->_btnPlayStop->Text = L"Play";
this->_btnPlayStop->UseVisualStyleBackColor = true;
this->_btnPlayStop->Click += gcnew System::EventHandler(this, &PlotWindow::_btnPlayStop_Click);
//
// _chkReverse
//
this->_chkReverse->Anchor = System::Windows::Forms::AnchorStyles::Left;
this->_chkReverse->AutoSize = true;
this->_chkReverse->Enabled = false;
this->_chkReverse->Location = System::Drawing::Point(113, 8);
this->_chkReverse->Name = L"_chkReverse";
this->_chkReverse->Size = System::Drawing::Size(66, 17);
this->_chkReverse->TabIndex = 8;
this->_chkReverse->Text = L"Reverse";
this->_chkReverse->UseVisualStyleBackColor = true;
//
// PlotWindow
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->Controls->Add(this->_tablePlot);
this->Name = L"PlotWindow";
this->Size = System::Drawing::Size(580, 493);
this->Resize += gcnew System::EventHandler(this, &PlotWindow::PlotWindow_Resize);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->_pnlDC))->EndInit();
this->_tablePlot->ResumeLayout(false);
this->_tableControls->ResumeLayout(false);
this->_tableControls->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->_animBar))->EndInit();
this->ResumeLayout(false);
}
#pragma endregion
};
}
#endif
|
vakuras/moleculardynamics
|
ui/ui/AboutWindow.h
|
<gh_stars>0
///
/// About window definition.
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef ABOUTWIN
#define ABOUTWIN
#pragma once
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
#include "TitleBar.h"
namespace ui
{
public ref class AboutWindow : public Form
{
public:
AboutWindow();
protected:
~AboutWindow();
void InitializeComponent();
private:
System::ComponentModel::Container ^components;
PictureBox^ _picAuthor;
Button^ _btnOk;
Label^ _lblText;
TitleBar ^ _titleBar;
bool drag;
Panel^ _pnlWin;
Point start;
private:
Void _titleBar_MouseDown(Object^ , MouseEventArgs^ e );
Void _titleBar_MouseMove(Object^ , MouseEventArgs^ e);
Void _titleBar_MouseUp(Object^ , MouseEventArgs^ );
Void _titleBarEvent(Object^ , EventArgs^ );
};
}
#endif
|
vakuras/moleculardynamics
|
ui/NovaFX/NovaFX.h
|
<gh_stars>0
///
/// NovaFX GL Header
///
/// Written by <NAME>. 2010.
///
#ifndef NOVAFX_H
#define NOVAFX_H
#include <vector>
#include "NovaCamera.h"
using namespace std;
namespace NovaFX
{
class NovaFX
{
private:
HWND m_hWnd;
int m_Bits;
HDC m_hDC;
HGLRC m_hRC;
UINT m_Height;
UINT m_Width;
NovaCamera::Camera* m_Camera;
GLUquadricObj* m_Quadric;
vector<NSphere*> m_Spheres;
vector<NCylinder*> m_Cylinders;
bool m_DrawSpheres;
bool m_DrawCylinders;
public:
void HideSpheres();
void ShowSpheres();
void HideCylinders();
void ShowCylinders();
NovaFX(HWND hWnd, int width, int height, int bits);
~NovaFX();
bool Initialize(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
bool Render();
void Resize(int newWidth, int newHeight);
size_t AddSphere(NSphere * sphere);
NSphere * GetSphere(size_t index);
size_t AddCylinder(NCylinder * sphere);
NCylinder * GetCylinder(size_t index);
void RemoveSphere(size_t index);
void RemoveCylinder(size_t index);
void RemoveAllSpheres();
void RemoveAllCylinders();
void SetCamera(NovaCamera::Camera * camera);
NovaCamera::Camera * GetCamera();
protected:
bool Error(LPCTSTR msg);
};
}
#endif
|
vakuras/moleculardynamics
|
ui/NovaFX/NovaCamera.h
|
///
/// NovaCamera Header
///
/// Written by <NAME>. 2010.
///
#ifndef NOVACAMERA_H
#define NOVACAMERA_H
#include "NovaVariables.h"
namespace NovaFX
{
namespace NovaCamera
{
class Camera
{
private:
Nfloat3 m_Position;
Nfloat3 m_ViewDirection;
Nfloat3 m_RightVector;
Nfloat3 m_UpVector;
Nfloat3 m_Rotated;
GLfloat m_ForwardSpeed;
GLfloat m_StrafeSpeed;
GLfloat m_UpwardSpeed;
GLfloat m_UpwardDevide;
GLfloat m_StrafeDevide;
GLfloat m_ForwardDevide;
public:
Camera(GLfloat forwardDevide, GLfloat strafeDevide, GLfloat upwardDevide);
void Move(Nfloat3 direction);
void RotateX(GLfloat angle);
void RotateY(GLfloat angle);
void RotateZ(GLfloat angle);
void Render();
void MoveForward(GLfloat speed);
void StrafeRight(GLfloat speed);
void MoveUpward(GLfloat speed);
};
}
}
#endif
|
vakuras/moleculardynamics
|
cpu/cpumd/Host.h
|
<filename>cpu/cpumd/Host.h
///
/// Host Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef HOST_HEADER
#define HOST_HEADER
#include "..\..\common\Global.h"
#include "..\..\common\ConfigParser.h"
#include "..\..\common\NeighborList.h"
#include "..\..\common\Constants.h"
#include "..\..\common\Loader.h"
#include "..\..\common\DebugCalculations.h"
#include "..\common\Device.h"
#include "..\..\common\results.h"
int hostMain(configuration * config);
void readyList(real4 * posArray, real3 * velocityArray, int NumberOfParticles, real & highestVelocity, real & boxSize);
void buildList(real4 * posArray, listSettings * listsettings, real boxSize, int buckets, real highestVelocity, int NumberOfParticles, int & nextBuild, int currentTimestep, int ** list, real dt);
#endif
|
vakuras/moleculardynamics
|
common/Global.h
|
<gh_stars>0
///
/// Global Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef GLOBAL_HEADER
#define GLOBAL_HEADER
#include <cmath>
#include <iostream>
#include <string>
#include <windows.h>
#include <fstream>
#include <vector>
#include <iomanip>
#include <ctime>
#include <cmath>
#include <sstream>
using namespace std;
#ifdef EQUI //euqilibrate
typedef double real;
#elif CPUMD //cpu simulation
typedef float real;
#elif CUDAMD //cuda simulation
typedef float real;
#elif UI //ui
typedef double real;
#endif
#ifdef CUDAMD
#include <cutil.h>
#include <cuda.h>
#include <cuda_runtime_api.h>
//add libraries from cuda
#pragma comment(lib, "cuda.lib")
#pragma comment(lib, "cudart.lib")
#ifdef _DEBUG
#pragma comment(lib, "cutil64d.lib")
#else
#pragma comment(lib, "cutil64.lib")
#endif
#else
struct int3
{
int x;
int y;
int z;
};
#endif
struct real4
{
real x;
real y;
real z;
real w;
};
struct real3
{
real x;
real y;
real z;
};
//configuration structure
struct configuration
{
int LennardJonesParticles; //number of lennard jones particles in the simulation
int ManyBodyParticles; //number of many body particles
float DT; //delta-t
int Timesteps; //timesteps to make
float Temperature; //temperature
float LennardJonesRS; //LennardJones rs
float LennardJonesRCUT; //LennardJones rcut
float ManyBodyRS; //many body rs
float ManyBodyRCUT; //many body rcut
int CudaBlocks; //amount of blocks for cuda
bool UseCuda; // use cuda - ui only
bool useLennardJones; //to use the lennard-jones force
bool useManyBody; //to use the many-body force
bool lennardJonesBPP; //use the block per particle version of lennard jones forces
bool manyBodyBPP; //use the block per particle version of many body forces
int OutputTimesteps; //when to perform output
bool Debug; //to output during simulation
bool Fallback; //to change back to tpp version if bpp is inperformable
float vxcmFrom; //velocity to add - x direction (from)
float vxcmTo; //velocity to add - x direction (to)
float vxcmStep; //velocity to add - x direction (step)
float energyLoss; //energyLoss for box hits
int animts; //each ts to save animation data
string Input; //input file
string Output; //output file
string Filename; //filename template for results
string AnimFile; //filename for animation data
};
//safe calls
#ifdef UI
#include <msclr/marshal.h>
#ifndef CFGPARSER_H
#define MSGERR(msg) MessageBox::Show(msg, "Error", MessageBoxButtons::OK, MessageBoxIcon::Error)
#define TC(newcode) try {newcode;}catch(::bad_alloc){ MSGERR("Unable to allocate memory"); return (false);}
#define CPPSAFE_CALL(code,err) if(code) { MSGERR(err); return (false);}
#endif
#else
#define TC(newcode) try {newcode;}catch(bad_alloc){cerr << "Error: Unable to allocate memory.\nFile: '" << __FILE__ << "'\n:Line: " << __LINE__ << endl; exit(EXIT_FAILURE);}
#define CPPSAFE_CALL(code,err) if(code) {cerr << "Error: " << err << "\nFile: '" << __FILE__ << "'\nLine: " << __LINE__ << endl; exit(EXIT_FAILURE);}
#endif
#endif
|
vakuras/moleculardynamics
|
ui/NovaFX/NovaVariables.h
|
<reponame>vakuras/moleculardynamics
///
/// NovaFX Variables Header
///
/// Written by <NAME>. 2010.
///
#ifndef NOVAVARS_H
#define NOVAVARS_H
#include <Windows.h>
#include <gl\GL.h>
#include <gl\GLU.h>
#include <cmath>
namespace NovaFX
{
struct Nfloat3
{
GLfloat x;
GLfloat y;
GLfloat z;
Nfloat3() {}
Nfloat3(GLfloat x, GLfloat y, GLfloat z);
Nfloat3 operator+(const Nfloat3 & other);
Nfloat3 operator-(const Nfloat3 & other);
Nfloat3 operator*(const GLfloat & other);
GLfloat operator*(const Nfloat3 & other);
GLfloat Length(Nfloat3 * v);
Nfloat3 CrossProduct(const Nfloat3 & other);
Nfloat3 Normalize();
};
struct Nfloat4
{
GLfloat x;
GLfloat y;
GLfloat z;
GLfloat w;
};
struct GLRGBA
{
GLfloat r;
GLfloat g;
GLfloat b;
GLfloat a;
GLRGBA(){}
GLRGBA(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
};
struct NSphere
{
Nfloat4 * pos;
GLuint slices;
GLuint stacks;
GLRGBA color;
NSphere();
~NSphere();
};
struct NCylinder
{
Nfloat4 * pos;
Nfloat3 * left;
Nfloat3 * up;
Nfloat3 * forward;
GLuint slices;
GLuint stacks;
GLfloat baseRadius;
GLfloat topRadius;
GLRGBA color;
NCylinder();
~NCylinder();
};
}
#endif
|
vakuras/moleculardynamics
|
ui/ui/global.h
|
<reponame>vakuras/moleculardynamics
///
/// Global definitions.
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef GLOBALH
#define GLOBALH
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <msclr/marshal.h>
using namespace std;
//config file reader
#define NOP "Lennard Jones Particles"
#define MBP "Many Body Particles"
#define TIMESTEPS "Timesteps"
#define DTQ "DT"
#define TEMP "Temperature"
#define LJRSQ "LennardJonesRS"
#define LJRCUTQ "LennardJonesRCUT"
#define MBRSQ "ManyBodyRS"
#define MBRCUTQ "ManyBodyRCUT"
#define INPUT "Input"
#define OUTPUT "Output"
#define FILENAME "Filename"
#define CUDABLOCKS "CUDA Blocks"
#define USECUDA "Use Cuda"
#define USELJ "UseLennardJones"
#define USEMB "UseManyBody"
#define LJBPP "LennardJonesBPP"
#define MBBPP "ManyBodyBPP"
#define OUTPUTTS "OutputTimesteps"
#define QDEBUG "Debug"
#define FALLBACK "Fallback"
#define VXCMFROM "VXCMFROM"
#define VXCMTO "VXCMTO"
#define VXCMSTEP "VXCMSTEP"
#define ENERGYLOSS "EnergyLoss"
#define ANIMTS "AnimationTimesteps"
#define ANIMDATA "AnimationData"
//safe calls
#define MSGERR(msg) MessageBox::Show(msg, "Error", MessageBoxButtons::OK, MessageBoxIcon::Error)
#define TC(newcode) try {newcode;}catch(::bad_alloc){ MSGERR("Unable to allocate memory"); return (false);}
#define CPPSAFE_CALL(code,err) if(code) { MSGERR(err); return (false);}
struct configuration
{
int LennardJonesParticles; //number of particles in the simulation
int ManyBodyParticles; //number of many body particles
float DT; //delta-t
int Timesteps; //timesteps to make
float Temperature; //temperature
float LennardJonesRS; //LennardJones rs
float LennardJonesRCUT; //LennardJones rcut
float ManyBodyRS; //many body rs
float ManyBodyRCUT; //many body rcut
int CudaBlocks; //amount of blocks for cuda
bool UseCuda; // use cuda - ui only
bool useLennardJones; //to use the lennard-jones force
bool useManyBody; //to use the many-body force
bool lennardJonesBPP; //use the block per particle version of lennard jones forces
bool manyBodyBPP; //use the block per particle version of many body forces
int OutputTimesteps; //when to perform output
bool Debug; //to output during simulation
bool Fallback; //to change back to tpp version if bpp is inperformable
float vxcmFrom; //velocity to add - x direction (from)
float vxcmTo; //velocity to add - x direction (to)
float vxcmStep; //velocity to add - x direction (step)
float energyLoss; //energyLoss for box hits
int animts; //each ts to save animation data
string Input; //input file
string Output; //output file
string Filename; //result filename template
string AnimFile; //filename for animation data
};
namespace ui
{
//
// Native functions (NOT .NET)
//
string MakeCSTR(System::String ^ ); //.NET String to C++ String
bool ReadConfiguration(string filename, configuration * pconfig); //Read configuration from ini file
bool WriteConfiguration(string filename, configuration * pconfig); //Write configuration to ini file
bool ReadInput(const char * filename, int nop, float * posArray, float * velocityArray); //Read input file
};
#endif
|
vakuras/moleculardynamics
|
ui/ui/ResultsWindow.h
|
///
/// Result window controller definition.
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#pragma once
#ifndef RESULTH
#define RESULTH
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Collections::Generic;
#include "TitleBar.h"
namespace ui
{
public ref class DrawingPanel : public Panel
{
public:
DrawingPanel();
};
public ref class ResultsWindow : public UserControl
{
public:
ResultsWindow();
bool GetResults(String ^);
protected:
~ResultsWindow();
void InitializeComponent();
private:
Void _tmrDraw_Tick(Object^ , EventArgs^ );
Void _pnlView_MouseMove(Object^ , MouseEventArgs^ );
Void _pnlView_Paint(Object^ , PaintEventArgs ^ );
Void ResultsWindow_Resize(Object^ sender, EventArgs^ e);
Void _titleBarEvent(Object^ , EventArgs^ );
private:
DrawingPanel^ _pnlView;
Timer^ _tmrDraw;
Label^ _lblSize;
System::ComponentModel::IContainer^ components;
float _movementx;
float _movementy;
float _zoom;
int _lastMX;
int _lastMY;
TitleBar ^ _titleBar;
};
}
#endif
|
vakuras/moleculardynamics
|
cpu/common/LennardJones.h
|
<reponame>vakuras/moleculardynamics<filename>cpu/common/LennardJones.h
///
/// CPU Device Lennard Jones Function
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
///
/// Lennard-Jones potentional
///
void lennardJones(real3 & force, real dist, real3 ij, real sig, real eps)
{
real sigsq = sig*sig;
real con = 24.0f*eps/sigsq;
real dist2 = dist * dist;
dist2 /= sigsq;
real dist4 = dist2*dist2;
real dist8 = dist4*dist4;
real dist14 = dist2*dist4*dist8;
real invdist8= 1.0f/dist8;
real invdist14= 1.0f/dist14;
real s = __fmul_rn(2,invdist14)-invdist8;
real fij = s * con;
force.x += ij.x * fij;
force.y += ij.y * fij;
force.z += ij.z * fij;
}
///
/// Lennard Jones Forces
///
void lennardJonesForces(real4 * posArray, real3 * forceArray, int NumberOfParticles, int nlargestsize, int nlistsize, int * list, real rcutsq)
{
real3 force;
real3 ij;
for(int i=0; i<NumberOfParticles; i++)
{
force.x = force.y = force.z = 0.0;
for(int j=0; j<nlargestsize && list[nlistsize*i+j]!=-1; j++)
{
int jp = list[nlistsize*i+j];
ij.x = posArray[i].x - posArray[jp].x;
ij.y = posArray[i].y - posArray[jp].y;
ij.z = posArray[i].z - posArray[jp].z;
real rij = ij.x*ij.x + ij.y*ij.y + ij.z*ij.z;
if (rij>=rcutsq)
continue;
rij = sqrt(rij);
ij.x = posArray[i].x - posArray[jp].x;
ij.y = posArray[i].y - posArray[jp].y;
ij.z = posArray[i].z - posArray[jp].z;
int jtype = (int)posArray[jp].w;
if (jtype == NG || (int)posArray[i].w == NG)
{
int select = ((int)posArray[i].w == NG) ? jtype : (int)posArray[i].w;
real sig;
real eps;
if (select==N)
{
eps = epsNGN;
sig = sigNGN;
}
else if (select==O)
{
eps = epsNGO;
sig = sigNGO;
}
else
{
eps = epsNG;
sig = sigNG;
}
lennardJones(force, rij, ij, sig, eps);
}
}
forceArray[i] = force;
}
}
|
vakuras/moleculardynamics
|
cpu/equi/Statistics.h
|
<filename>cpu/equi/Statistics.h
#include <cmath>
#include <limits>
#include <cerrno>
double erf(double x);
double erfc(double x);
double inverfc(const double z);
double inverf(const double z);
|
vakuras/moleculardynamics
|
common/Getters.h
|
///
/// Getter Funtions Definitions
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef GF_HEADER
#define GF_HEADER
#include "global.h"
#include "constants.h"
template <typename T>
T getMass(int id);
template <typename T>
T getRE(int ti, int tj);
template <typename T>
T getDE(int ti, int tj);
template <typename T>
T getbeta(int ti, int tj);
template <typename T>
T getR0V(int ti, int tj);
#include "getters.cpp" //c++ templates can't have companion cpp files... so we just include it in the header
#endif
|
vakuras/moleculardynamics
|
cuda/cudamd/Host.h
|
///
/// Host Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef HOST_HEADER
#define HOST_HEADER
#include "..\..\common\Global.h"
#include "..\..\common\ConfigParser.h"
#include "..\..\common\Constants.h"
#include "..\..\common\Loader.h"
#include "..\..\common\NeighborList.h"
#include "..\..\common\results.h"
//#define USECUDADEBUG
#ifndef USECUDADEBUG
#include "..\..\common\DebugCalculations.h"
#endif
int hostMain(CUdevice device, char * module_path, configuration * config);
void readyList(real4 * posArray, real3 * velocityArray, int NumberOfParticles, float & highestVelocity, float & boxSize);
void buildList(real4 * posArray, listSettings * listsettings, float boxSize, int buckets, float highestVelocity, int NumberOfParticles, int & nextBuild, int currentTimestep, int ** list, float dt, char * lpTexRef, CUarray * cu_array, CUtexref * cu_texref, CUmodule * module);
#ifdef USECUDADEBUG
void performOutput(vector<results> & resultVec, int BlocksPerGrid, int informationSize, float * informationMemory, CUdeviceptr & devInformation, CUfunction & performCalculations, CUfunction & calculatePotentional, int timesteps, float dt, bool print);
#else
void performOutput(vector<results> * resultVec, int NumberOfParticles, real4 * posArray, real3 * velocityArray, CUdeviceptr & devPosArray, CUdeviceptr & devVelocityArray, int timesteps, real dt, bool print);
#endif
//cude func-build macros
#define CUDA_DEF_SET(v) offset = (offset + __alignof(v) - 1) & ~(__alignof(v) - 1)
#define OFFSET_ADD(v) offset += sizeof(v)
#define CUDA_RESET_OFFSET offset=0
#define CUDA_SET_OFFSET(x) offset = x
#define CUDA_GET_OFFSET(x) x = offset
#define CUDA_POINTER_ALLOC(f,p) ptr = (void*)(size_t)p; offset = (offset + __alignof(ptr) - 1) & ~(__alignof(ptr) - 1); CU_SAFE_CALL(cuParamSetv(f, offset, &ptr, sizeof(ptr)); offset+=sizeof(ptr))
#define CUDA_FLOAT_ALLOC(f,v) CUDA_DEF_SET(v); CU_SAFE_CALL(cuParamSetf( f, offset, v )); OFFSET_ADD(v)
#define CUDA_UINT_ALLOC(f,v) CUDA_DEF_SET(v); CU_SAFE_CALL(cuParamSeti( f, offset, v )); OFFSET_ADD(v)
#define THREADSPERBLOCK 512
#endif
|
vakuras/moleculardynamics
|
ui/ui/stdafx.h
|
<reponame>vakuras/moleculardynamics<gh_stars>0
///
/// Stdafx.h
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#pragma once
#include <windows.h>
#include "global.h"
#include "MainWindow.h"
#include "TitleBar.h"
|
vakuras/moleculardynamics
|
common/ConfigParser.h
|
<reponame>vakuras/moleculardynamics
///
/// Configuration Parser Definitions
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef CFGPARSER_H
#define CFGPARSER_H
#include <string>
#include <unordered_map>
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
using namespace tr1;
#ifdef UI
#define MSGERR(msg) MessageBox::Show(msg, "Error", MessageBoxButtons::OK, MessageBoxIcon::Error)
#define CPPSAFE_CALL(code,err) if(code) { MSGERR(err);}
#else
#define CPPSAFE_CALL(code,err) if(code) {cerr << "Error: " << err << "\nFile: '" << __FILE__ << "'\nLine: " << __LINE__ << endl; exit(EXIT_FAILURE);}
#endif
typedef unordered_map<string, string> datamap;
class ConfigParser
{
private:
datamap * data; //data holder
public:
ConfigParser(); //constructor
bool Parse(string filename); //parse configuration file
bool GetString(string key, string & value); //gets a string from the data holder
bool GetInt(string key, int & value); //gets an int from the data holder
bool GetFloat(string key, float & value); //gets a float from the data holder
bool GetFloats(string key, float ** value); //gets a set of floats from the data holder
bool GetBoolean(string key, bool & value); //gets a boolean from the data holder
~ConfigParser();
private:
//extracts values from c++ string
template <class T> bool from_string(T& t, const string& s, ios_base& (*f)(ios_base&));
};
#endif
|
vakuras/moleculardynamics
|
common/DebugCalculations.h
|
///
/// Output Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef DEBUGCALCULATIONS_HEADER
#define DEBUGCALCULATIONS_HEADER
#include "results.h"
#include "Global.h"
#include "Constants.h"
#include "arvdwfc.h"
#include "getters.h"
void PerformCalculations(real4 * posArray, real3 * velocityArray, int NumberOfParticles, double & centerOfMassx, double & centerOfMassy, double & centerOfMassz, double & kineticEnergy, double & momentumx, double & momentumy, double & momentumz, double & temperature);
void performOutput(vector<results> * resultVec, int NumberOfParticles, real4 * posArray, real3 * velocityArray, int timesteps, real dt, bool print);
void calculatePotentional(real4 * posArray, double * vibLJ, double * vibMB, int NumberOfParticles);
#endif
|
vakuras/moleculardynamics
|
common/arvdwfc.h
|
///
/// Attractive, Repulsive, van der Waals & Cutoff Definitions
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef ARVDWFC_HEADER
#define ARVDWFC_HEADER
#include "global.h"
#include "constants.h"
template <typename T>
inline void attractive(T & va, T & dva, T rij, T De, T beta, T re);
template <typename T>
void repulsive(T & vr, T & dvr, T rij, T De, T beta, T re);
template <typename T>
void vanderWaals(T & vdw, T & dvdw, T rij, T r0v);
template <typename T>
void cutoff(T rij, T & fc, T & dfc);
#include "arvdwfc.cpp" //c++ templates can't have companion cpp files... so we just include it in the header
#endif
|
vakuras/moleculardynamics
|
cpu/common/Device.h
|
///
/// Device Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef DEVICE_HEADER
#define DEVICE_HEADER
#include "..\..\common\Global.h"
#include "..\..\common\Constants.h"
#include "..\..\common\arvdwfc.h"
#include "..\..\common\getters.h"
#define __fmul_rn(a,b) (a*b) //cuda redefine
void predict(real4 *r,real3 *v,real3 *a,real3 *b,real3 *c, real dt, int nop);
void correct(real4 *r,real3 *v,real3 *f,real3 *a, real3 *b,real3 *c, real dt, int nop, real nPos, bool & flag, float energyLoss);
void lennardJonesForces(real4 * posArray, real3 * forceArray, int NumberOfParticles, int nlargestsize, int nlistsize, int * list, real rcutsq);
void manyBodyForces(real4 * posArray, real3 * forceArray, int NumberOfParticles, int nlargestsize, int nlistsize, int * list, real rcutsq, bool ljexist);
void calculateAccelerations(real4 * posArray, real3 * accelerationArray, real3 * forceArray, int NumberOfParticles);
#endif
|
vakuras/moleculardynamics
|
ui/ui/resource.h
|
<filename>ui/ui/resource.h
///
/// Resource.h
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
|
vakuras/moleculardynamics
|
cuda/cudamd/NeighborList.h
|
<filename>cuda/cudamd/NeighborList.h
///
/// Neighbor List Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef NEIGHBORLIST_HEADER
#define NEIGHBORLIST_HEADER
#define H1 2971215073
#define H2 433494437
#define H3 1073807359
int * buildNeighborList(float4 * posArray, listSettings * listsettings, float boxSize, int buckets, int NumberOfParticles);
int computeBucket(int cx, int cy, int cz, int3 * bucketlist, int buckets, bool pop);
#endif
|
vakuras/moleculardynamics
|
common/Loader.h
|
///
/// Loader Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef LOADER_HEADER
#define LOADER_HEADER
#include "Global.h"
#include "ConfigParser.h"
#ifdef UI
using namespace System::Windows::Forms;
#endif
void readConfiguration(string filename, configuration * pconfig);
void writeOutput(configuration * config, real * posArray, real * velocityArray);
void readInput(configuration * config, real * posArray, real * velocityArray);
void Loader(int argc, char ** argv, char * appexe, configuration & config);
//config file reader
#define NOP "Lennard Jones Particles"
#define MBP "Many Body Particles"
#define TIMESTEPS "Timesteps"
#define DTQ "DT"
#define TEMP "Temperature"
#define LJRSQ "LennardJonesRS"
#define LJRCUTQ "LennardJonesRCUT"
#define MBRSQ "ManyBodyRS"
#define MBRCUTQ "ManyBodyRCUT"
#define INPUT "Input"
#define OUTPUT "Output"
#define FILENAME "Filename"
#define CUDABLOCKS "CUDA Blocks"
#define USECUDA "Use Cuda"
#define USELJ "UseLennardJones"
#define USEMB "UseManyBody"
#define LJBPP "LennardJonesBPP"
#define MBBPP "ManyBodyBPP"
#define OUTPUTTS "OutputTimesteps"
#define QDEBUG "Debug"
#define FALLBACK "Fallback"
#define VXCMFROM "VXCMFROM"
#define VXCMTO "VXCMTO"
#define VXCMSTEP "VXCMSTEP"
#define ENERGYLOSS "EnergyLoss"
#define ANIMTS "AnimationTimesteps"
#define ANIMDATA "AnimationData"
#endif
|
vakuras/moleculardynamics
|
common/Constants.h
|
<reponame>vakuras/moleculardynamics
///
/// Constants Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef CONSTANTS_H
#define CONSTANTS_H
//Particles index
#define N 0
#define O 1
#define NG 2
//UI particle radii
#define radN 0.71f
#define radO 0.63f
#define radNG 0.58f
//the units are Ang.
#define reN 1.097f
#define reO 1.2075f
#define reNO 1.15f
//VDW parameters
#define sigNvdw 3.31f
#define sigOvdw 2.95f
#define reNvdw 3.72f
#define reOvdw 3.31f
#define reNOvdw 3.51f
//VDW parameters for Ne - Ne and Ne - N/O
#define sigNG 2.72f
#define sigNGN 3.015f
#define sigNGO 2.835f
//VDW parameters for Ne - Ne and Ne - N/O
#define epsNG 0.391e-4f
#define epsNGN 0.328e-4f
#define epsNGO 0.447e-4f
#define deN 941.4e-4f
#define deO 493.55309e-4f
#define deNO 626.734e-4f
// The units are 1/Ang
#define betaN 2.71009f
#define betaO 2.2478f
#define betaNO 2.24068f
// Masses: The units are gr/mol
#define mN 14.00674f
#define mO 15.9994f
#define mNG 20.1797f
// Cutoffs
#define CUTOFF_RIJ 15*sigNvdw
#define CUTOFF_RIJSQ 225*sigNvdw*sigNvdw
// Device Constants
#define GEAR1 0.15833333333333333333333333333333f
#define GEAR2 0.75f
#define GEAR3 0.5f
#define GEAR4 0.08333333333333333333333333333333f
#define S 2.0f
#define GM 0.3f
#define GMSQ 0.09f
#define ALFAV 3.0f
#define ALFAVSQ 9.0f
#define ALFA 2.0f
#define R0 1.3f
#define LAMDA3 1.33f
#define C 25.f
#define D 4.0417f
#define H 0.0f
#endif
|
vakuras/moleculardynamics
|
cpu/common/BondOrderFuncs.h
|
<gh_stars>0
///
/// CPU Device Bond Order Functions
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
///
/// Bond Order 1
///
void bondOrder1(real4 * posArray, real re, real rij, int NumberOfParticles, int nlargestsize, int nlistsize, int * list, int i, int j, real3 ij, real & bo, real3 & dbo, real rcutsq, real * xsi, real * xsj)
{
real drijx = (ij.x)/rij;
real drijy = (ij.y)/rij;
real drijz = (ij.z)/rij;
xsi[i*NumberOfParticles+j] = 0;
real dxsix = 0.0f;
real dxsiy = 0.0f;
real dxsiz = 0.0f;
xsj[i*NumberOfParticles+j] = 0;
real dxsjx = 0.0f;
real dxsjy = 0.0f;
real dxsjz = 0.0f;
real3 im;
real3 jm;
real rim;
real rjm;
for(int m=0; m<nlargestsize && list[nlistsize*i+m]!=-1; m++)
{
int mp = list[nlistsize*i+m];
int mtype = (int)posArray[mp].w;
if (mtype == NG)
continue;
if (mp==j)
continue;
im.x = posArray[i].x - posArray[mp].x;
im.y = posArray[i].y - posArray[mp].y;
im.z = posArray[i].z - posArray[mp].z;
rim = im.x*im.x + im.y*im.y + im.z*im.z;
if (rim>=rcutsq) //distance is too large... ignoring...
continue;
rim = sqrt(rim);
jm.x = posArray[j].x - posArray[mp].x;
jm.y = posArray[j].y - posArray[mp].y;
jm.z = posArray[j].z - posArray[mp].z;
rjm = sqrt(jm.x*jm.x + jm.y*jm.y + jm.z*jm.z);
real fci;
real dfci;
real fcj;
real dfcj;
cutoff(rim, fci, dfci);
cutoff(rjm, fcj, dfcj);
real drimx = (posArray[i].x - posArray[mp].x)/rim;
real drimy = (posArray[i].y - posArray[mp].y)/rim;
real drimz = (posArray[i].z - posArray[mp].z)/rim;
if (fci>0)
{
real icosthe = (rij*rij+rim*rim-rjm*rjm)/ (2.0f*rij*rim);
real igthe = 1.0f +C/D -C/(D+(H-icosthe)*(H-icosthe));
xsi[i*NumberOfParticles+j] += fci*igthe*exp(LAMDA3*(rij - re));
real dicosthex = ((2.0f*rij*drijx+2.0f*rim*drimx)*
2.0f*rij*rim - (2.0f*rim*drijx + 2.0f*rij*drimx)*
(rij*rij+rim*rim-rjm*rjm))/(4.0f*rij*rij*rim*rim);
real dicosthey = ((2.0f*rij*drijy+2.0f*rim*drimy)*
2.0f*rij*rim - (2.0f*rim*drijy + 2.0f*rij*drimy)*
(rij*rij+rim*rim-rjm*rjm))/(4.0f*rij*rij*rim*rim);
real dicosthez = ((2.0f*rij*drijz+2.0f*rim*drimz)*
2.0f*rij*rim - (2.0f*rim*drijz + 2.0f*rij*drimz)*
(rij*rij+rim*rim-rjm*rjm))/(4.0f*rij*rij*rim*rim);
real digthex = -C/((D+(H-icosthe)*(H-icosthe))*(D+(H-icosthe)*(H-icosthe)))* 2.0f*(H-icosthe)*dicosthex;
real digthey = -C/((D+(H-icosthe)*(H-icosthe))*(D+(H-icosthe)*(H-icosthe)))* 2.0f*(H-icosthe)*dicosthey;
real digthez = -C/((D+(H-icosthe)*(H-icosthe))*(D+(H-icosthe)*(H-icosthe)))* 2.0f*(H-icosthe)*dicosthez;
dxsix += (dfci*drimx*igthe*exp(LAMDA3*(rij - re)) + fci*digthex*exp(LAMDA3*(rij - re)) + fci*igthe*LAMDA3*exp(LAMDA3*(rij - re))*drijx);
dxsiy += (dfci*drimy*igthe*exp(LAMDA3*(rij - re)) + fci*digthey*exp(LAMDA3*(rij - re)) + fci*igthe*LAMDA3*exp(LAMDA3*(rij - re))*drijy);
dxsiz += (dfci*drimz*igthe*exp(LAMDA3*(rij - re)) + fci*digthez*exp(LAMDA3*(rij - re)) + fci*igthe*LAMDA3*exp(LAMDA3*(rij - re))*drijz);
}
if (fcj>0)
{
real jcosthe = (rij*rij+rjm*rjm-rim*rim)/ (2.0f*rij*rjm);
real jgthe = 1.0f +C/D -C/(D+(H-jcosthe)*(H-jcosthe));
xsj[i*NumberOfParticles+j] += fcj*jgthe*exp(LAMDA3*(rij - re));
real djcosthex = ((2.0f*rij*drijx-2.0f*rim*drimx)*
2.0f*rij*rjm -2.0f*rjm*drijx*
(rij*rij+rjm*rjm-rim*rim))/(4.0f*rij*rij*rjm*rjm);
real djcosthey = ((2.0f*rij*drijy-2.0f*rim*drimy)*
2.0f*rij*rjm -2.0f*rjm*drijy*
(rij*rij+rjm*rjm-rim*rim))/(4.0f*rij*rij*rjm*rjm);
real djcosthez = ((2.0f*rij*drijz-2.0f*rim*drimz)*
2.0f*rij*rjm -2.0f*rjm*drijz*
(rij*rij+rjm*rjm-rim*rim))/(4.0f*rij*rij*rjm*rjm);
real djgthex = -C/((D+(H-jcosthe)*(H-jcosthe))*(D+(H-jcosthe)*(H-jcosthe)))* 2.0f*(H-jcosthe)*djcosthex;
real djgthey = -C/((D+(H-jcosthe)*(H-jcosthe))*(D+(H-jcosthe)*(H-jcosthe)))* 2.0f*(H-jcosthe)*djcosthey;
real djgthez = -C/((D+(H-jcosthe)*(H-jcosthe))*(D+(H-jcosthe)*(H-jcosthe)))* 2.0f*(H-jcosthe)*djcosthez;
dxsjx += (fcj*(djgthex*exp(LAMDA3*(rij-re)) + LAMDA3*exp(LAMDA3*(rij-re))*drijx*jgthe));
dxsjy += (fcj*(djgthey*exp(LAMDA3*(rij-re)) + LAMDA3*exp(LAMDA3*(rij-re))*drijy*jgthe));
dxsjz += (fcj*(djgthez*exp(LAMDA3*(rij-re)) + LAMDA3*exp(LAMDA3*(rij-re))*drijz*jgthe));
}
}
real bij = 1.0f/(1.0f + xsi[i*NumberOfParticles+j]);
real dbijx = (1.0f/((1.0f + xsi[i*NumberOfParticles+j])*(1.0f + xsi[i*NumberOfParticles+j])))*dxsix;
real dbijy = (1.0f/((1.0f + xsi[i*NumberOfParticles+j])*(1.0f + xsi[i*NumberOfParticles+j])))*dxsiy;
real dbijz = (1.0f/((1.0f + xsi[i*NumberOfParticles+j])*(1.0f + xsi[i*NumberOfParticles+j])))*dxsiz;
real bji = 1.0f/(1.0f + xsj[i*NumberOfParticles+j]);
real dbjix = (1.0f/((1.0f + xsj[i*NumberOfParticles+j])*(1.0f + xsj[i*NumberOfParticles+j])))*dxsjx;
real dbjiy = (1.0f/((1.0f + xsj[i*NumberOfParticles+j])*(1.0f + xsj[i*NumberOfParticles+j])))*dxsjy;
real dbjiz = (1.0f/((1.0f + xsj[i*NumberOfParticles+j])*(1.0f + xsj[i*NumberOfParticles+j])))*dxsjz;
bo = 0.5f*(bij + bji);
dbo.x = 0.5f*(dbijx + dbjix);
dbo.y = 0.5f*(dbijy + dbjiy);
dbo.z = 0.5f*(dbijz + dbjiz);
}
///
/// Bond Order 2
///
void bondOrder2(real4 * posArray, real re, real rij, real rik, int NumberOfParticles, int nlargestsize, int nlistsize, int * list, int k, int i, int j, real3 & dbo, real rcutsq, real xsi, real xsj)
{
dbo.x = dbo.y = dbo.z = 0;
real3 jk;
real rjk;
jk.x = posArray[j].x - posArray[k].x;
jk.y = posArray[j].y - posArray[k].y;
jk.z = posArray[j].z - posArray[k].z;
rjk = sqrt(jk.x*jk.x + jk.y*jk.y + jk.z*jk.z);
real drjkx = (posArray[k].x - posArray[j].x)/rjk;
real drjky = (posArray[k].y - posArray[j].y)/rjk;
real drjkz = (posArray[k].z - posArray[j].z)/rjk;
real drikx = (posArray[k].x - posArray[i].x)/rik;
real driky = (posArray[k].y - posArray[i].y)/rik;
real drikz = (posArray[k].z - posArray[i].z)/rik;
real fci;
real dfci;
real fcj;
real dfcj;
cutoff(rik, fci, dfci);
cutoff(rjk, fcj, dfcj);
if (fci>0)
{
real icosthe = (rij*rij+rik*rik-rjk*rjk)/(2.0f*rij*rik);
real igthe = 1.0f +C/D -C/(D+(H-icosthe)*(H-icosthe));
real idcosthex = ((2.0f*rik*drikx - 2.0f*rjk*drjkx)*2.0f*rij*rik - (2.0f*rij*drikx)*
(rij*rij+rik*rik-rjk*rjk))/(4.0f*rij*rij*rik*rik);
real idcosthey = ((2.0f*rik*driky - 2.0f*rjk*drjky)*2.0f*rij*rik - (2.0f*rij*driky)*
(rij*rij+rik*rik-rjk*rjk))/(4.0f*rij*rij*rik*rik);
real idcosthez = ((2.0f*rik*drikz - 2.0f*rjk*drjkz)*2.0f*rij*rik - (2.0f*rij*drikz)*
(rij*rij+rik*rik-rjk*rjk))/(4.0f*rij*rij*rik*rik);
real idgthex = -C/((D+(H-icosthe)*(H-icosthe))*(D+(H-icosthe)*(H-icosthe)))*2.0f*(H-icosthe)*idcosthex;
real idgthey = -C/((D+(H-icosthe)*(H-icosthe))*(D+(H-icosthe)*(H-icosthe)))*2.0f*(H-icosthe)*idcosthey;
real idgthez = -C/((D+(H-icosthe)*(H-icosthe))*(D+(H-icosthe)*(H-icosthe)))*2.0f*(H-icosthe)*idcosthez;
real idxsix = dfci*drikx*igthe*exp(LAMDA3*(rij - re)) + fci*idgthex*exp(LAMDA3*(rij - re));
real idxsiy = dfci*driky*igthe*exp(LAMDA3*(rij - re)) + fci*idgthey*exp(LAMDA3*(rij - re));
real idxsiz = dfci*drikz*igthe*exp(LAMDA3*(rij - re)) + fci*idgthez*exp(LAMDA3*(rij - re));
real dbijx = (1.0f/((1.0f + xsi)*(1.0f + xsi)))*idxsix;
real dbijy = (1.0f/((1.0f + xsi)*(1.0f + xsi)))*idxsiy;
real dbijz = (1.0f/((1.0f + xsi)*(1.0f + xsi)))*idxsiz;
dbo.x += __fmul_rn(0.5f, dbijx);
dbo.y += __fmul_rn(0.5f, dbijy);
dbo.z += __fmul_rn(0.5f, dbijz);
}
if(fcj>0)
{
real jcosthe = (rij*rij+rjk*rjk-rik*rik)/(2.0f*rij*rjk);
real jgthe = 1.0f +C/D -C/(D+(H-jcosthe)*(H-jcosthe));
real jdcosthex = ((2.0f*rjk*drjkx - 2.0f*rik*drikx)*2.0f*rij*rjk - (2.0f*rij*drjkx)*
(rij*rij+rjk*rjk-rik*rik))/(4.0f*rij*rij*rjk*rjk);
real jdcosthey = ((2.0f*rjk*drjky - 2.0f*rik*driky)*2.0f*rij*rjk - (2.0f*rij*drjky)*
(rij*rij+rjk*rjk-rik*rik))/(4.0f*rij*rij*rjk*rjk);
real jdcosthez = ((2.0f*rjk*drjkz - 2.0f*rik*drikz)*2.0f*rij*rjk - (2.0f*rij*drjkz)*
(rij*rij+rjk*rjk-rik*rik))/(4.0f*rij*rij*rjk*rjk);
real jdgthex = -C/((D+(H-jcosthe)*(H-jcosthe))*(D+(H-jcosthe)*(H-jcosthe)))*2.0f*(H-jcosthe)*jdcosthex;
real jdgthey = -C/((D+(H-jcosthe)*(H-jcosthe))*(D+(H-jcosthe)*(H-jcosthe)))*2.0f*(H-jcosthe)*jdcosthey;
real jdgthez = -C/((D+(H-jcosthe)*(H-jcosthe))*(D+(H-jcosthe)*(H-jcosthe)))*2.0f*(H-jcosthe)*jdcosthez;
real jdxsix = dfcj*drjkx*jgthe*exp(LAMDA3*(rij - re)) + fcj*jdgthex*exp(LAMDA3*(rij - re));
real jdxsiy = dfcj*drjky*jgthe*exp(LAMDA3*(rij - re)) + fcj*jdgthey*exp(LAMDA3*(rij - re));
real jdxsiz = dfcj*drjkz*jgthe*exp(LAMDA3*(rij - re)) + fcj*jdgthez*exp(LAMDA3*(rij - re));
real dbjix = (1.0f/((1.0f + xsj)*(1.0f + xsj)))*jdxsix;
real dbjiy = (1.0f/((1.0f + xsj)*(1.0f + xsj)))*jdxsiy;
real dbjiz = (1.0f/((1.0f + xsj)*(1.0f + xsj)))*jdxsiz;
dbo.x += __fmul_rn(0.5f, dbjix);
dbo.y += __fmul_rn(0.5f, dbjiy);
dbo.z += __fmul_rn(0.5f, dbjiz);
}
}
///
/// Bond Order Forces
///
void bondForces(real3 & force, real4 * posArray, real rij, int NumberOfParticles, int i, int j, int itype, int jtype, real3 ij, int nlargestsize, int nlistsize, int * list, real rcutsq, real * xsi, real * xsj)
{
real va=0;
real dva=0;
real vr=0;
real dvr=0;
real vdw;
real dvdw;
real bo=0;
real3 dbo={0.0f, 0.0f, 0.0f};
real fcut, dfcut;
cutoff(rij/10, fcut, dfcut);
if (fcut > 0)
{
real de = getDE<real>(itype, jtype);
real re = getRE<real>(itype, jtype);
real beta = getbeta<real>(itype, jtype);
attractive(va, dva, rij, de, beta , re);
repulsive(vr, dvr, rij, de, beta, re);
bondOrder1(posArray, re, rij, NumberOfParticles, nlargestsize, nlistsize, list, i, j, ij, bo, dbo, rcutsq, xsi, xsj);
}
vanderWaals(vdw, dvdw, rij, getR0V<real>(itype, jtype));
real fij = dvr - bo*dva + dvdw;
real fxij = fij*(ij.x)/rij - dbo.x*va;
real fyij = fij*(ij.y)/rij - dbo.y*va;
real fzij = fij*(ij.z)/rij - dbo.z*va;
force.x += fxij;
force.y += fyij;
force.z += fzij;
}
///
/// Many Body Forces
///
void manyBodyForces(real4 * posArray, real3 * forceArray, int NumberOfParticles, int nlargestsize, int nlistsize, int * list, real rcutsq, bool ljexist)
{
real3 force;
real3 ij;
real3 ik;
real rij;
real * xsi;
real * xsj;
TC(xsi = new real[NumberOfParticles*NumberOfParticles]);
TC(xsj = new real[NumberOfParticles*NumberOfParticles]);
for(int i=0; i<NumberOfParticles; i++)
{
int type = (int)posArray[i].w;
force.x = force.y = force.z = 0.0;
for(int j=0; j<nlargestsize && list[nlistsize*i+j]!=-1; j++)
{
int jp = list[nlistsize*i+j];
ij.x = posArray[i].x - posArray[jp].x;
ij.y = posArray[i].y - posArray[jp].y;
ij.z = posArray[i].z - posArray[jp].z;
rij = ij.x*ij.x + ij.y*ij.y + ij.z*ij.z;
if (rij>=rcutsq || rij>CUTOFF_RIJSQ) //distance is too large... ignoring...
continue;
rij = sqrt(rij);
int jtype = (int)posArray[jp].w;
if (jtype != NG)
{
bondForces(force, posArray, rij, NumberOfParticles, i, jp, type, jtype, ij, nlargestsize, nlistsize, list, rcutsq, xsi, xsj);
}
}
if (ljexist)
{
forceArray[i].x += force.x;
forceArray[i].y += force.y;
forceArray[i].z += force.z;
}
else
{
forceArray[i].x = force.x;
forceArray[i].y = force.y;
forceArray[i].z = force.z;
}
}
for(int k=0; k<NumberOfParticles; k++)
{
for(int i=0; i<nlargestsize && list[nlistsize*k+i]!=-1; i++)
{
int ip = list[nlistsize*k+i];
int itype = (int)posArray[ip].w;
ik.x = posArray[k].x - posArray[ip].x;
ik.y = posArray[k].y - posArray[ip].y;
ik.z = posArray[k].z - posArray[ip].z;
real rik = ik.x*ik.x + ik.y*ik.y + ik.z*ik.z;
if (rik>=rcutsq)
continue;
rik = sqrt(rik);
for(int j=0; j<nlargestsize && list[nlistsize*k+j]!=-1; j++)
{
int jp = list[nlistsize*k+j];
int jtype = (int)posArray[jp].w;
if (ip == jp)
continue;
ij.x = posArray[ip].x - posArray[jp].x;
ij.y = posArray[ip].y - posArray[jp].y;
ij.z = posArray[ip].z - posArray[jp].z;
rij = ij.x*ij.x + ij.y*ij.y + ij.z*ij.z;
if (rij>=rcutsq || rij>CUTOFF_RIJSQ) //distance is too large... ignoring...
continue;
rij = sqrt(rij);
real de = getDE<real>(itype, jtype);
real re = getRE<real>(itype, jtype);
real beta = getbeta<real>(itype, jtype);
real va;
real dva;
real3 dbo;
attractive(va, dva, rij, de, beta, re);
bondOrder2(posArray, re, rij, rik, NumberOfParticles, nlargestsize, nlistsize, list, k, ip, jp, dbo, rcutsq, xsi[ip*NumberOfParticles+jp], xsj[ip*NumberOfParticles+jp]);
forceArray[k].x -= 0.5f*dbo.x*va;
forceArray[k].y -= 0.5f*dbo.y*va;
forceArray[k].z -= 0.5f*dbo.z*va;
}
}
}
delete [] xsi;
delete [] xsj;
}
|
vakuras/moleculardynamics
|
ui/ui/TitleBar.h
|
<filename>ui/ui/TitleBar.h
///
/// Title Bar definition.
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef TITLEBAR_H
#define TITLEBAR_H
#pragma once
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
namespace ui
{
public ref class TitleBar : public UserControl
{
public:
event EventHandler^ CloseClicked;
event EventHandler^ SaveClicked;
Void SetTitle(String ^ title);
Void AppendTitle(String ^ title);
Void SaveSetVisible(bool set);
TitleBar();
protected:
~TitleBar();
void InitializeComponent();
private:
Void TitleBar_Resize(Object^ sender, EventArgs^ e) ;
Void _picClose_MouseDown(Object^ sender, MouseEventArgs^ e);
Void _picClose_MouseUp(Object^ sender, MouseEventArgs^ e) ;
Void _picClose_MouseEnter(Object^ sender, EventArgs^ e);
Void _picClose_MouseLeave(Object^ sender, EventArgs^ e);
Void _picClose_Click(Object^ sender, EventArgs^ e);
Void _picSave_MouseDown(Object^ sender, MouseEventArgs^ e);
Void _picSave_MouseUp(Object^ sender, MouseEventArgs^ e) ;
Void _picSave_MouseEnter(Object^ sender, EventArgs^ e);
Void _picSave_MouseLeave(Object^ sender, EventArgs^ e);
Void _picSave_Click(Object^ sender, EventArgs^ e);
PictureBox^ _picClose;
PictureBox^ _picSave;
Label^ _lblTitle;
System::ComponentModel::ComponentResourceManager^ resources;
System::ComponentModel::Container ^components;
};
}
#endif
|
vakuras/moleculardynamics
|
common/NeighborList.h
|
///
/// Neighbor List Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef NEIGHBORLIST_HEADER
#define NEIGHBORLIST_HEADER
#include "Global.h"
#define H1 2971215073
#define H2 433494437
#define H3 1073807359
//list settings structure
struct listSettings
{
float maxnlmove; //lennard jones maximum neighbour list move
float maxnlmovesq; //lennard jones maximum neighbour list move squared
float rcut;
float rs;
float rcutsq; //lennard jones rcut squared
int nlistsize; //neightbour list size per particle
int nlargestsize; //neightbour largest list size
};
int * buildNeighborList(real4 * posArray, listSettings * listsettings, real boxSize, int buckets, int NumberOfParticles);
int computeBucket(int cx, int cy, int cz, int3 * bucketlist, int buckets, bool pop);
#endif
|
vakuras/moleculardynamics
|
common/Results.h
|
///
/// Results Header
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by <NAME>. 2009-2010.
///
#ifndef RESULTS_HEADER
#define RESULTS_HEADER
#include "Global.h"
//result structure
struct results
{
double time;
double temperature;
double e; //total energy
double ek; //kinetic energy
double eu; //potentional energy
double centerOfMassx; //center of mass
double centerOfMassy; //center of mass
double centerOfMassz; //center of mass
double momentumx; //momentum x
double momentumy; //momentum y
double momentumz; //momentum z
};
void pushAnim(vector<float*> & posVec, vector<float*> & velVec, real4* posArray, real3* velocityArray, int nop);
void flushVectors(vector<results> & resultVec, vector<float*> & posVec, vector<float*> & velVec);
void writeAnimationBinaryData(vector<float*> & posVec, vector<float*> & velVec, configuration * config, float vxcm);
void writeResults(vector<results> & resultVec, configuration * config, float elapsed, string tail, float vxcm);
string tailResults(real4 * posArray, int ManyBodyParticles);
#endif
|
omerlux/OS-Task1
|
xv6-public/myprog.c
|
<reponame>omerlux/OS-Task1
#include "types.h"
#include "stat.h"
#include "user.h"
//passing command line arguments
int main(int argc, char *argv[])
{
printf(1, "HelloXV6\n");
exit(0);
}
|
omerlux/OS-Task1
|
xv6-public/tee.c
|
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
//passing command line arguments
int main(int argc, char *argv[])
{
if(argc == 2){
char buf_read[512]; // creates a buffer
if (open(argv[1], 0)>=0) // a file already exists
unlink(argv[1]); // delete the file if exists...
int fd_txt1 = open(argv[1], O_WRONLY | O_CREATE); // create new fd if not exists, to write only
while(1){
int n = read(0, buf_read, sizeof(buf_read)); // return number of bytes
if(n==0)
break; // end of file
else if(n<0) { // error in read
printf(2, "read error\n");
break;
}
else if(n>= 2 && buf_read[n-2]==3)
break;// ctrl + c
else {//write to file and console
if (write(fd_txt1, buf_read, n) != n) { // wrriten bytes not equal to n = error!
printf(2, "write error\n");
break;
}
if (write(1, buf_read, n) != n) { // wrriten bytes not equal to n = error!
printf(2, "write to console error\n");
break;
}
}
}
close(fd_txt1); // closing file descriptor
}else if(argc == 3){
char buf_read[512]; // creates a buffer
int fd_txt1 = open(argv[1], O_RDONLY);
if (open(argv[2], 0)>=0) // a file already exists
unlink(argv[2]); // delete the file if exists...
int fd_txt2 = open(argv[2], O_WRONLY | O_CREATE); // create new fd if not exists, to write only
while(1){
int n = read(fd_txt1, buf_read, sizeof(buf_read)); // return number of bytes
if(n==0)
break; // end of file
else if(n<0) { // error in read
printf(2, "read error\n");
break;
}
else {//write to file and console
if (write(fd_txt2, buf_read, n) != n) { // wrriten bytes not equal to n = error!
printf(2, "write error\n");
break;
}
}
}
close(fd_txt1); // closing file descriptor
close(fd_txt2); // closing file descriptor
}else
printf(2, "cannot tee, given %d arguments\n", argc);
exit(0);
}
|
omerlux/OS-Task1
|
xv6-public/sh.c
|
<reponame>omerlux/OS-Task1<gh_stars>0
// Shell.
#include "types.h"
#include "user.h"
#include "fcntl.h"
// Parsed command representation
#define EXEC 1
#define REDIR 2
#define PIPE 3
#define LIST 4
#define BACK 5
#define MAXARGS 10
char env_path[10][100];
struct cmd {
int type;
};
struct execcmd {
int type;
char * argv[MAXARGS];
char * eargv[MAXARGS];
};
struct redircmd {
int type;
struct cmd * cmd;
char * file;
char * efile;
int mode;
int fd;
};
struct pipecmd {
int type;
struct cmd * left;
struct cmd * right;
};
struct listcmd {
int type;
struct cmd * left;
struct cmd * right;
};
struct backcmd {
int type;
struct cmd * cmd;
};
int fork1(void); // Fork but panics on failure.
void panic(char * );
struct cmd * parsecmd(char * );
// Execute cmd. Never returns.
void
runcmd(struct cmd * cmd) {
int p[2];
struct backcmd * bcmd;
struct execcmd * ecmd;
struct listcmd * lcmd;
struct pipecmd * pcmd;
struct redircmd * rcmd;
if (cmd == 0)
exit(0);
switch (cmd -> type) {
default:
panic("runcmd");
case EXEC:
ecmd = (struct execcmd * ) cmd;
if (ecmd -> argv[0] == 0)
exit(0);
exec(ecmd -> argv[0], ecmd -> argv);
// -- start edit 9/11 --
if(ecmd -> argv[0][0] != '/'){ // if we are NOT looking for absolute path then search path array
//printf(1, "We dont have absolute path... AND WE HOPE IT WILL RUN\n");
for(int i=0; i<10; i++){
int length = strlen(env_path[i]) + strlen(ecmd -> argv[0]);
char str[length + 1];
// store length of env_PATH in the length variable
length = 0;
while (env_path[i][length] != '\0') {
str[length] = env_path[i][length];
length ++;
}
str[length] = '/';
// concatenate argv[0] to str
for (int j = 0; ecmd -> argv[0][j] != '\0'; j++, length++) {
str[length] = ecmd -> argv[0][j];
}
// terminating the str string
str[length] = '\0';
exec(str, ecmd -> argv);
}
}
//else
//printf(1, "We did absolute path, BUT IT FAILED RUNNING...\n");
// -- end edit 9/11 --
printf(2, "exec %s failed\n", ecmd -> argv[0]);
break;
case REDIR:
rcmd = (struct redircmd * ) cmd;
close(rcmd -> fd);
if (open(rcmd -> file, rcmd -> mode) < 0) {
printf(2, "open %s failed\n", rcmd -> file);
exit(0);
}
runcmd(rcmd -> cmd);
break;
case LIST:
lcmd = (struct listcmd * ) cmd;
if (fork1() == 0)
runcmd(lcmd -> left);
wait(0);
runcmd(lcmd -> right);
break;
case PIPE:
pcmd = (struct pipecmd * ) cmd;
if (pipe(p) < 0)
panic("pipe");
if (fork1() == 0) {
close(1);
dup(p[1]);
close(p[0]);
close(p[1]);
runcmd(pcmd -> left);
}
if (fork1() == 0) {
close(0);
dup(p[0]);
close(p[0]);
close(p[1]);
runcmd(pcmd -> right);
}
close(p[0]);
close(p[1]);
wait(0);
wait(0);
break;
case BACK:
bcmd = (struct backcmd * ) cmd;
if (fork1() == 0)
runcmd(bcmd -> cmd);
break;
}
exit(0);
}
int
getcmd(char * buf, int nbuf) {
printf(2, "$ ");
memset(buf, 0, nbuf);
gets(buf, nbuf);
if (buf[0] == 0) // EOF
return -1;
return 0;
}
int
main(void) {
static char buf[100];
int fd;
// Ensure that three file descriptors are open.
while ((fd = open("console", O_RDWR)) >= 0) {
if (fd >= 3) {
close(fd);
break;
}
}
// Read and run input commands.
while (getcmd(buf, sizeof(buf)) >= 0) {
if (buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' ') {
// Chdir must be called by the parent, not the child.
buf[strlen(buf) - 1] = 0; // chop \n
if (chdir(buf + 3) < 0)
printf(2, "cannot cd %s\n", buf + 3);
continue;
}
// -- start edit 9/11 --
// set PATH /:/bin
if (buf[0] == 's' && buf[1] == 'e' && buf[2] == 't' && buf[3] == ' ' &&
buf[4] == 'P' && buf[5] == 'A' && buf[6] == 'T' && buf[7] == 'H' && buf[8] == ' ') {
// Set must be called by the parent, not the child.
buf[strlen(buf) - 1] = 0; // chop \n
char * paths_line = buf + 9; // now its only the paths
int paths_len = strlen(paths_line);
for (int i = 0; i < 10; i++) {
if (paths_len != 0) {
int s_end = 0;
while ((paths_line[s_end] != ':') & (strlen(paths_line) > s_end)) {
env_path[i][s_end] = paths_line[s_end];
s_end++;
}
if (env_path[i][s_end-1] == '/') {
env_path[i][s_end] = '\0';
}
else{ // if no '/' add it to the path
env_path[i][s_end] = '/';
env_path[i][s_end+1] = '\0';
}
paths_line = paths_line + s_end + 1; // it's a buffer - accumulate it by s_end+1
paths_len = paths_len - s_end;
// printf(1, "%d is: ", i);
// printf(1, "paths- '%s' ", paths_line);
// printf(1, "path is- '%s'\n", env_path[i]);
} else
memset(env_path[i], '\0', 100);
}
continue;
}
// -- end edit 9/11 --
if (fork1() == 0)
runcmd(parsecmd(buf));
wait(0);
}
exit(0);
}
void
panic(char * s) {
printf(2, "%s\n", s);
exit(0);
}
int
fork1(void) {
int pid;
pid = fork();
if (pid == -1)
panic("fork");
return pid;
}
//PAGEBREAK!
// Constructors
struct cmd *
execcmd(void) {
struct execcmd * cmd;
cmd = malloc(sizeof( * cmd));
memset(cmd, 0, sizeof( * cmd));
cmd -> type = EXEC;
return (struct cmd * ) cmd;
}
struct cmd *
redircmd(struct cmd * subcmd, char * file, char * efile, int mode, int fd) {
struct redircmd * cmd;
cmd = malloc(sizeof( * cmd));
memset(cmd, 0, sizeof( * cmd));
cmd -> type = REDIR;
cmd -> cmd = subcmd;
cmd -> file = file;
cmd -> efile = efile;
cmd -> mode = mode;
cmd -> fd = fd;
return (struct cmd * ) cmd;
}
struct cmd *
pipecmd(struct cmd * left, struct cmd * right) {
struct pipecmd * cmd;
cmd = malloc(sizeof( * cmd));
memset(cmd, 0, sizeof( * cmd));
cmd -> type = PIPE;
cmd -> left = left;
cmd -> right = right;
return (struct cmd * ) cmd;
}
struct cmd *
listcmd(struct cmd * left, struct cmd * right) {
struct listcmd * cmd;
cmd = malloc(sizeof( * cmd));
memset(cmd, 0, sizeof( * cmd));
cmd -> type = LIST;
cmd -> left = left;
cmd -> right = right;
return (struct cmd * ) cmd;
}
struct cmd *
backcmd(struct cmd * subcmd) {
struct backcmd * cmd;
cmd = malloc(sizeof( * cmd));
memset(cmd, 0, sizeof( * cmd));
cmd -> type = BACK;
cmd -> cmd = subcmd;
return (struct cmd * ) cmd;
}
//PAGEBREAK!
// Parsing
char whitespace[] = " \t\r\n\v";
char symbols[] = "<|>&;()";
int
gettoken(char ** ps, char * es, char ** q, char ** eq) {
char * s;
int ret;
s = * ps;
while (s < es && strchr(whitespace, * s))
s++;
if (q)
*
q = s;
ret = * s;
switch ( * s) {
case 0:
break;
case '|':
case '(':
case ')':
case ';':
case '&':
case '<':
s++;
break;
case '>':
s++;
if ( * s == '>') {
ret = '+';
s++;
}
break;
default:
ret = 'a';
while (s < es && !strchr(whitespace, * s) && !strchr(symbols, * s))
s++;
break;
}
if (eq)
*
eq = s;
while (s < es && strchr(whitespace, * s))
s++;
* ps = s;
return ret;
}
int
peek(char ** ps, char * es, char * toks) {
char * s;
s = * ps;
while (s < es && strchr(whitespace, * s))
s++;
* ps = s;
return *s && strchr(toks, * s);
}
struct cmd * parseline(char ** , char * );
struct cmd * parsepipe(char ** , char * );
struct cmd * parseexec(char ** , char * );
struct cmd * nulterminate(struct cmd * );
struct cmd *
parsecmd(char * s) {
char * es;
struct cmd * cmd;
es = s + strlen(s);
cmd = parseline( & s, es);
peek( & s, es, "");
if (s != es) {
printf(2, "leftovers: %s\n", s);
panic("syntax");
}
nulterminate(cmd);
return cmd;
}
struct cmd *
parseline(char ** ps, char * es) {
struct cmd * cmd;
cmd = parsepipe(ps, es);
while (peek(ps, es, "&")) {
gettoken(ps, es, 0, 0);
cmd = backcmd(cmd);
}
if (peek(ps, es, ";")) {
gettoken(ps, es, 0, 0);
cmd = listcmd(cmd, parseline(ps, es));
}
return cmd;
}
struct cmd *
parsepipe(char ** ps, char * es) {
struct cmd * cmd;
cmd = parseexec(ps, es);
if (peek(ps, es, "|")) {
gettoken(ps, es, 0, 0);
cmd = pipecmd(cmd, parsepipe(ps, es));
}
return cmd;
}
struct cmd *
parseredirs(struct cmd * cmd, char ** ps, char * es) {
int tok;
char * q, * eq;
while (peek(ps, es, "<>")) {
tok = gettoken(ps, es, 0, 0);
if (gettoken(ps, es, & q, & eq) != 'a')
panic("missing file for redirection");
switch (tok) {
case '<':
cmd = redircmd(cmd, q, eq, O_RDONLY, 0);
break;
case '>':
cmd = redircmd(cmd, q, eq, O_WRONLY | O_CREATE, 1);
break;
case '+': // >>
cmd = redircmd(cmd, q, eq, O_WRONLY | O_CREATE, 1);
break;
}
}
return cmd;
}
struct cmd *
parseblock(char ** ps, char * es) {
struct cmd * cmd;
if (!peek(ps, es, "("))
panic("parseblock");
gettoken(ps, es, 0, 0);
cmd = parseline(ps, es);
if (!peek(ps, es, ")"))
panic("syntax - missing )");
gettoken(ps, es, 0, 0);
cmd = parseredirs(cmd, ps, es);
return cmd;
}
struct cmd *
parseexec(char ** ps, char * es) {
char * q, * eq;
int tok, argc;
struct execcmd * cmd;
struct cmd * ret;
if (peek(ps, es, "("))
return parseblock(ps, es);
ret = execcmd();
cmd = (struct execcmd * ) ret;
argc = 0;
ret = parseredirs(ret, ps, es);
while (!peek(ps, es, "|)&;")) {
if ((tok = gettoken(ps, es, & q, & eq)) == 0)
break;
if (tok != 'a')
panic("syntax");
cmd -> argv[argc] = q;
cmd -> eargv[argc] = eq;
argc++;
if (argc >= MAXARGS)
panic("too many args");
ret = parseredirs(ret, ps, es);
}
cmd -> argv[argc] = 0;
cmd -> eargv[argc] = 0;
return ret;
}
// NUL-terminate all the counted strings.
struct cmd *
nulterminate(struct cmd * cmd) {
int i;
struct backcmd * bcmd;
struct execcmd * ecmd;
struct listcmd * lcmd;
struct pipecmd * pcmd;
struct redircmd * rcmd;
if (cmd == 0)
return 0;
switch (cmd -> type) {
case EXEC:
ecmd = (struct execcmd * ) cmd;
for (i = 0; ecmd -> argv[i]; i++)
*
ecmd -> eargv[i] = 0;
break;
case REDIR:
rcmd = (struct redircmd * ) cmd;
nulterminate(rcmd -> cmd);
* rcmd -> efile = 0;
break;
case PIPE:
pcmd = (struct pipecmd * ) cmd;
nulterminate(pcmd -> left);
nulterminate(pcmd -> right);
break;
case LIST:
lcmd = (struct listcmd * ) cmd;
nulterminate(lcmd -> left);
nulterminate(lcmd -> right);
break;
case BACK:
bcmd = (struct backcmd * ) cmd;
nulterminate(bcmd -> cmd);
break;
}
return cmd;
}
|
omerlux/OS-Task1
|
xv6-public/getpinfo.c
|
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
//passing command line arguments
int main(int argc, char *argv[])
{
getpinfo();
exit(0);
}
|
coin3d/simage
|
src/simage_tiff.c
|
/*
* Copyright (c) <NAME> & Gas Technologies
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* based on example code found in libtiff
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#ifdef HAVE_TIFFLIB
#include <simage_tiff.h>
#include <stdio.h>
#include <tiffio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#define ERR_NO_ERROR 0
#define ERR_OPEN 1
#define ERR_READ 2
#define ERR_MEM 3
#define ERR_UNSUPPORTED 4
#define ERR_TIFFLIB 5
#define ERR_OPEN_WRITE 6
#define ERR_WRITE 7
static int tifferror = ERR_NO_ERROR;
int
simage_tiff_error(char * buffer, int buflen)
{
switch (tifferror) {
case ERR_OPEN:
strncpy(buffer, "TIFF loader: Error opening file", buflen);
break;
case ERR_MEM:
strncpy(buffer, "TIFF loader: Out of memory error", buflen);
break;
case ERR_UNSUPPORTED:
strncpy(buffer, "TIFF loader: Unsupported image type", buflen);
break;
case ERR_TIFFLIB:
strncpy(buffer, "TIFF loader: Illegal tiff file", buflen);
break;
case ERR_OPEN_WRITE:
strncpy(buffer, "TIFF saver: Error opening file", buflen);
break;
case ERR_WRITE:
strncpy(buffer, "TIFF loader: Error writing file", buflen);
break;
}
return tifferror;
}
static void
tiff_error(const char* module, const char* fmt, va_list list)
{
/* FIXME: store error message ? */
}
static void
tiff_warn(const char * module, const char * fmt, va_list list)
{
/* FIXME: notify? */
}
static int
checkcmap(int n, uint16* r, uint16* g, uint16* b)
{
while (n-- > 0)
if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
return (16);
/* Assuming 8-bit colormap */
return (8);
}
static void
invert_row(unsigned char *ptr, unsigned char *data, int n, int invert)
{
while (n--) {
if (invert) *ptr++ = 255 - *data++;
else *ptr++ = *data++;
}
}
static void
remap_row(unsigned char *ptr, unsigned char *data, int n,
unsigned short *rmap, unsigned short *gmap, unsigned short *bmap,unsigned char *amap)
{
unsigned int ix;
while (n--) {
ix = *data++;
*ptr++ = (unsigned char) rmap[ix];
*ptr++ = (unsigned char) gmap[ix];
*ptr++ = (unsigned char) bmap[ix];
if (amap) *ptr++ = (unsigned char) amap[ix];
}
}
static void
copy_row(unsigned char *ptr, unsigned char *data, int n, int numcomponents)
{
memcpy(ptr, data, (size_t)n*numcomponents);
}
static void
interleave_row(unsigned char *ptr,
unsigned char *red,
unsigned char *blue,
unsigned char *green,
unsigned char *alpha,
int n)
{
while (n--) {
*ptr++ = *red++;
*ptr++ = *green++;
*ptr++ = *blue++;
if (alpha) *ptr++ = *alpha++;
}
}
static int
tiff_try_read_rgba(TIFF *in, int w, int h, int format,
unsigned char * buffer)
{
unsigned char * newbuffer = NULL;
if (format != 4) {
newbuffer = (unsigned char*) malloc((size_t)w*h*4);
}
else {
newbuffer = buffer;
}
if (!TIFFReadRGBAImage(in, w, h,
(unsigned int*) newbuffer, 1)) {
free(newbuffer);
return ERR_READ;
}
if (format != 4) {
unsigned char * src = newbuffer;
unsigned char * dst = buffer;
int i, n = w*h;
for (i = 0; i < n; i++) {
switch (format) {
case 1:
*dst++ = src[0];
break;
case 2:
*dst++ = src[0];
*dst++ = src[3];
break;
case 3:
*dst++ = src[0];
*dst++ = src[1];
*dst++ = src[2];
break;
default:
break;
}
src += 4;
}
free(newbuffer);
}
return ERR_NO_ERROR;
}
int
simage_tiff_identify(const char *ptr,
const unsigned char *header,
int headerlen)
{
static unsigned char tifcmp[] = {0x4d, 0x4d, 0x0, 0x2a};
static unsigned char tifcmp2[] = {0x49, 0x49, 0x2a, 0};
if (headerlen < 4) return 0;
if (memcmp((const void*)header, (const void*)tifcmp, 4) == 0) return 1;
if (memcmp((const void*)header, (const void*)tifcmp2, 4) == 0) return 1;
return 0;
}
/* useful defines (undef'ed below) */
#define CVT(x) (((x) * 255L) / ((1L<<16)-1))
#define pack(a,b) ((a)<<8 | (b))
unsigned char *
simage_tiff_load(const char *filename,
int *width_ret,
int *height_ret,
int *numComponents_ret)
{
TIFF *in;
uint16 samplesperpixel;
uint16 bitspersample;
uint16 photometric;
uint32 w, h;
uint16 config;
uint16* red;
uint16* green;
uint16* blue;
unsigned char *inbuf = NULL;
tsize_t rowsize;
uint32 row;
int format;
unsigned char *buffer;
int width;
int height;
unsigned char *currPtr;
TIFFSetErrorHandler(tiff_error);
TIFFSetWarningHandler(tiff_warn);
in = TIFFOpen(filename, "r");
if (in == NULL) {
tifferror = ERR_OPEN;
return NULL;
}
if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric) == 1) {
if (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_PALETTE &&
photometric != PHOTOMETRIC_MINISWHITE &&
photometric != PHOTOMETRIC_MINISBLACK) {
/*Bad photometric; can only handle Grayscale, RGB and Palette images :-( */
TIFFClose(in);
tifferror = ERR_UNSUPPORTED;
return NULL;
}
}
else {
tifferror = ERR_READ;
TIFFClose(in);
return NULL;
}
if (TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel) == 1) {
if (samplesperpixel < 1 || samplesperpixel > 4) {
/* Bad samples/pixel */
tifferror = ERR_UNSUPPORTED;
TIFFClose(in);
return NULL;
}
}
else {
tifferror = ERR_READ;
TIFFClose(in);
return NULL;
}
if (TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample) == 1) {
if (bitspersample != 8) {
/* can only handle 8-bit samples. */
TIFFClose(in);
tifferror = ERR_UNSUPPORTED;
return NULL;
}
}
else {
tifferror = ERR_READ;
TIFFClose(in);
return NULL;
}
if (TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w) != 1 ||
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h) != 1 ||
TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config) != 1) {
TIFFClose(in);
tifferror = ERR_READ;
return NULL;
}
if (photometric == PHOTOMETRIC_MINISWHITE ||
photometric == PHOTOMETRIC_MINISBLACK)
format = 1;
else {
if (photometric == PHOTOMETRIC_PALETTE) format = 3;
else format = samplesperpixel;
}
buffer = (unsigned char*)malloc((size_t)w*h*format);
if (!buffer) {
tifferror = ERR_MEM;
TIFFClose(in);
return NULL;
}
width = w;
height = h;
currPtr = buffer + (h-1)*w*format;
tifferror = ERR_NO_ERROR;
switch (pack(photometric, config)) {
case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_CONTIG):
case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_CONTIG):
case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_SEPARATE):
case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_SEPARATE):
inbuf = (unsigned char *)malloc(TIFFScanlineSize(in));
for (row = 0; row < h; row++) {
if (TIFFReadScanline(in, inbuf, row, 0) < 0) {
tifferror = ERR_READ;
break;
}
invert_row(currPtr, inbuf, w, photometric == PHOTOMETRIC_MINISWHITE);
currPtr -= format*w;
}
if (tifferror == ERR_READ) {
tifferror = tiff_try_read_rgba(in, w, h, format, buffer);
}
break;
case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG):
case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE):
if (TIFFGetField(in, TIFFTAG_COLORMAP, &red, &green, &blue) != 1)
tifferror = ERR_READ;
/* */
/* Convert 16-bit colormap to 8-bit (unless it looks */
/* like an old-style 8-bit colormap). */
/* */
if (!tifferror && checkcmap(1<<bitspersample, red, green, blue) == 16) {
int i;
for (i = (1<<bitspersample)-1; i >= 0; i--) {
red[i] = CVT(red[i]);
green[i] = CVT(green[i]);
blue[i] = CVT(blue[i]);
}
}
inbuf = (unsigned char *)malloc(TIFFScanlineSize(in));
for (row = 0; row < h; row++) {
if (TIFFReadScanline(in, inbuf, row, 0) < 0) {
tifferror = ERR_READ;
break;
}
remap_row(currPtr, inbuf, w, red, green, blue, NULL);
currPtr -= format*w;
}
if (tifferror == ERR_READ) {
tifferror = tiff_try_read_rgba(in, w, h, format, buffer);
}
break;
case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG):
inbuf = (unsigned char *)malloc(TIFFScanlineSize(in));
for (row = 0; row < h; row++) {
if (TIFFReadScanline(in, inbuf, row, 0) < 0) {
tifferror = ERR_READ;
break;
}
copy_row(currPtr, inbuf, w, format);
currPtr -= format*w;
}
if (tifferror == ERR_READ) {
tifferror = tiff_try_read_rgba(in, w, h, format, buffer);
}
break;
case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE):
rowsize = TIFFScanlineSize(in);
inbuf = (unsigned char *)malloc(format*rowsize);
for (row = 0; !tifferror && row < h; row++) {
int s;
for (s = 0; s < format; s++) {
if (TIFFReadScanline(in, (tdata_t)(inbuf+s*rowsize), (uint32)row, (tsample_t)s) < 0) {
tifferror = ERR_READ; break;
}
}
if (tifferror != ERR_READ) {
interleave_row(currPtr, inbuf, inbuf+rowsize, inbuf+2*rowsize,
format == 4 ? inbuf+3*rowsize : NULL, w);
currPtr -= format*w;
}
}
if (tifferror == ERR_READ) {
tifferror = tiff_try_read_rgba(in, w, h, format, buffer);
}
break;
default:
tifferror = ERR_UNSUPPORTED;
break;
}
if (inbuf) free(inbuf);
TIFFClose(in);
if (tifferror) {
if (buffer) free(buffer);
return NULL;
}
*width_ret = width;
*height_ret = height;
*numComponents_ret = format;
return buffer;
}
int
simage_tiff_save(const char *filename,
const unsigned char * bytes,
int width,
int height,
int numcomponents)
{
uint16 photometric;
TIFF * out;
int y, bytesperrow;
short config = PLANARCONFIG_CONTIG;
int16 compression = COMPRESSION_PACKBITS; /* RLE */
out = TIFFOpen(filename, "w");
if (out == NULL) {
tifferror = ERR_OPEN_WRITE;
return 0;
}
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, (uint32) width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, (uint32) height);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
if (numcomponents <= 2)
photometric = PHOTOMETRIC_MINISBLACK;
else
photometric = PHOTOMETRIC_RGB;
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, numcomponents);
if (numcomponents == 2 || numcomponents == 4) {
uint16 v[1];
v[0] = EXTRASAMPLE_UNASSALPHA;
TIFFSetField(out, TIFFTAG_EXTRASAMPLES, 1, v);
}
TIFFSetField(out, TIFFTAG_MINSAMPLEVALUE, (uint16) 0);
TIFFSetField(out, TIFFTAG_MAXSAMPLEVALUE, (uint16) 255);
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
/* force 1 row/strip for library limitation */
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, 1L);
TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, filename);
bytesperrow = width * numcomponents;
for (y = 0; y < height; y++) {
if (TIFFWriteScanline(out, (tdata_t) (bytes + bytesperrow * (height-y-1)), y, 0) < 0) {
TIFFClose(out);
tifferror = ERR_WRITE;
return 0;
}
}
TIFFClose(out);
return 1;
}
typedef struct {
TIFF * in;
uint16 samplesperpixel;
uint16 bitspersample;
uint16 photometric;
uint32 w, h;
uint16 config;
uint16 * red;
uint16 * green;
uint16 * blue;
int format;
int rowsize;
unsigned char * inbuf;
} simage_tiff_opendata;
void *
simage_tiff_open(const char * filename,
int * width,
int * height,
int * numcomponents)
{
TIFF * in;
simage_tiff_opendata * od;
tifferror = ERR_NO_ERROR;
TIFFSetErrorHandler(tiff_error);
TIFFSetWarningHandler(tiff_warn);
in = TIFFOpen(filename, "r");
if (in == NULL) {
tifferror = ERR_OPEN;
return NULL;
}
od = (simage_tiff_opendata*) malloc(sizeof(simage_tiff_opendata));
od->in = in;
/* random access of lines is not be supported for palette images */
if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &od->photometric) == 1) {
if (od->photometric != PHOTOMETRIC_RGB &&
/* od->photometric != PHOTOMETRIC_PALETTE && */
od->photometric != PHOTOMETRIC_MINISWHITE &&
od->photometric != PHOTOMETRIC_MINISBLACK) {
/* Bad photometric; can only handle Grayscale and RGB images */
TIFFClose(in);
tifferror = ERR_UNSUPPORTED;
free(od);
return NULL;
}
}
else {
tifferror = ERR_READ;
free(od);
TIFFClose(in);
return NULL;
}
if (TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &od->samplesperpixel) == 1) {
if (od->samplesperpixel < 1 || od->samplesperpixel > 4) {
/* Bad samples/pixel */
tifferror = ERR_UNSUPPORTED;
free(od);
TIFFClose(in);
return NULL;
}
}
else {
tifferror = ERR_READ;
free(od);
TIFFClose(in);
return NULL;
}
if (TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &od->bitspersample) == 1) {
if (od->bitspersample != 8) {
/* can only handle 8-bit samples. */
TIFFClose(in);
tifferror = ERR_UNSUPPORTED;
free(od);
return NULL;
}
}
else {
tifferror = ERR_READ;
TIFFClose(in);
free(od);
return NULL;
}
if (TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &od->w) != 1 ||
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &od->h) != 1 ||
TIFFGetField(in, TIFFTAG_PLANARCONFIG, &od->config) != 1) {
TIFFClose(in);
tifferror = ERR_READ;
free(od);
return NULL;
}
if (od->photometric == PHOTOMETRIC_MINISWHITE ||
od->photometric == PHOTOMETRIC_MINISBLACK)
od->format = 1;
else {
if (od->photometric == PHOTOMETRIC_PALETTE) od->format = 3;
else od->format = od->samplesperpixel;
}
switch (pack(od->photometric, od->config)) {
default:
break;
case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG):
case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE):
if (TIFFGetField(in, TIFFTAG_COLORMAP, &od->red, &od->green, &od->blue) != 1)
tifferror = ERR_READ;
/* */
/* Convert 16-bit colormap to 8-bit (unless it looks */
/* like an old-style 8-bit colormap). */
/* */
if (!tifferror && checkcmap(1<<od->bitspersample, od->red, od->green, od->blue) == 16) {
int i;
for (i = (1<<od->bitspersample)-1; i >= 0; i--) {
od->red[i] = CVT(od->red[i]);
od->green[i] = CVT(od->green[i]);
od->blue[i] = CVT(od->blue[i]);
}
}
}
od->rowsize = (int) TIFFScanlineSize(in);
od->inbuf = (unsigned char *) malloc(od->rowsize * 4); /* *4 to support all formats */
*width = od->w;
*height = od->h;
*numcomponents = od->format;
return (void*) od;
}
void
simage_tiff_close(void * opendata)
{
simage_tiff_opendata * od = (simage_tiff_opendata*) opendata;
TIFFClose(od->in);
free(od->inbuf);
free(od);
}
int
simage_tiff_read_line(void * opendata, int y, unsigned char * buf)
{
int s, row;
simage_tiff_opendata * od;
tifferror = ERR_NO_ERROR;
od = (simage_tiff_opendata*) opendata;
row = (od->h-1)-y;
switch (pack(od->photometric, od->config)) {
case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_CONTIG):
case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_CONTIG):
case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_SEPARATE):
case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_SEPARATE):
if (TIFFReadScanline(od->in, od->inbuf, row, 0) < 0) {
tifferror = ERR_READ;
break;
}
invert_row(buf, od->inbuf, od->w, od->photometric == PHOTOMETRIC_MINISWHITE);
break;
case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG):
case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE):
if (TIFFReadScanline(od->in, od->inbuf, row, 0) < 0) {
tifferror = ERR_READ;
break;
}
remap_row(buf, od->inbuf, od->w, od->red, od->green, od->blue, NULL);
break;
case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG):
if (TIFFReadScanline(od->in, od->inbuf, row, 0) < 0) {
tifferror = ERR_READ;
break;
}
copy_row(buf, od->inbuf, od->w, od->format);
break;
case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE):
for (s = 0; s < od->format; s++) {
if (TIFFReadScanline(od->in, (tdata_t)(od->inbuf+s*od->rowsize),
(uint32)row, (tsample_t)s) < 0) {
tifferror = ERR_READ; break;
}
}
if (!tifferror) {
interleave_row(buf, od->inbuf, od->inbuf+od->rowsize, od->inbuf + 2*od->rowsize,
od->format == 4 ? od->inbuf + 3*od->rowsize: NULL, od->w);
}
break;
default:
tifferror = ERR_UNSUPPORTED;
break;
}
return tifferror == ERR_NO_ERROR;
}
#undef CVT
#undef pack
#endif /* HAVE_TIFFLIB */
|
coin3d/simage
|
src/simage_rgb.c
|
/*
* Copyright (c) <NAME> & Gas Technologies
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* An SGI RGB loader. By <EMAIL>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#ifdef SIMAGE_RGB_SUPPORT
#include <simage_rgb.h>
#include <simage_private.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define ERR_NO_ERROR 0
#define ERR_OPEN 1
#define ERR_READ 2
#define ERR_MEM 3
#define ERR_SIZEZ 4
#define ERR_OPEN_WRITE 5
static int rgberror = ERR_NO_ERROR;
typedef struct {
FILE * in;
int w;
int h;
int nc;
int compressed;
unsigned int * rowseek;
int * rowlen;
unsigned char * rlebuf;
int rlebuflen;
unsigned char * tmpbuf[4];
} simage_rgb_opendata;
unsigned char *
simage_rgb_load(const char * filename,
int * width,
int * height,
int * numcomponents)
{
simage_rgb_opendata * od = (simage_rgb_opendata*)
simage_rgb_open(filename, width, height, numcomponents);
if (od) {
int i;
int bpr = *width * *numcomponents;
unsigned char * buf = (unsigned char *) malloc((size_t)bpr * *height);
for (i = 0; i < *height; i++) {
if (simage_rgb_read_line(od, i, buf+bpr*i) == 0) {
/* rgberror will be set by simage_rgb_read_line() */
free(buf);
simage_rgb_close(od);
return NULL;
}
}
simage_rgb_close(od);
return buf;
}
return NULL;
}
static int
write_short(FILE * fp, unsigned short val)
{
unsigned char tmp[2];
tmp[0] = (unsigned char)(val >> 8);
tmp[1] = (unsigned char)(val & 0xff);
return (int)fwrite(&tmp, 2, 1, fp);
}
int
simage_rgb_save(const char * filename,
const unsigned char * bytes,
int width,
int height,
int comp)
{
int x, y, c;
unsigned char * tmpbuf;
unsigned char buf[500];
FILE * fp = fopen(filename, "wb");
if (!fp) {
rgberror = ERR_OPEN_WRITE;
return 0;
}
write_short(fp, 0x01da); /* imagic */
write_short(fp, 0x0001); /* raw (no rle yet) */
if (comp == 1)
write_short(fp, 0x0002); /* 2 dimensions (heightmap) */
else
write_short(fp, 0x0003); /* 3 dimensions */
write_short(fp, (unsigned short) width);
write_short(fp, (unsigned short) height);
write_short(fp, (unsigned short) comp);
memset(buf, 0, 500);
buf[7] = 255; /* set maximum pixel value to 255 */
strcpy((char *)buf+8, "https://coin3d.github.io");
fwrite(buf, 1, 500, fp);
tmpbuf = (unsigned char *) malloc(width);
for (c = 0; c < comp; c++) {
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
tmpbuf[x] = bytes[x * comp + y * comp * width + c];
}
fwrite(tmpbuf, 1, width, fp);
}
}
free(tmpbuf);
fclose(fp);
return 1;
}
int
simage_rgb_identify(const char * filename,
const unsigned char * header,
int headerlen)
{
static unsigned char rgbcmp[] = {0x01, 0xda};
if (headerlen < 2) return 0;
if (memcmp((const void*)header,
(const void*)rgbcmp, 2) == 0) return 1;
return 0;
}
int
simage_rgb_error(char * buffer, int buflen)
{
switch (rgberror) {
case ERR_OPEN:
strncpy(buffer, "RGB loader: Error opening file", buflen);
break;
case ERR_READ:
strncpy(buffer, "RGB loader: Error reading file", buflen);
break;
case ERR_MEM:
strncpy(buffer, "RGB loader: Out of memory error", buflen);
break;
case ERR_SIZEZ:
strncpy(buffer, "RGB loader: Unsupported zsize", buflen);
break;
case ERR_OPEN_WRITE:
strncpy(buffer, "RGB loader: Error opening file for writing", buflen);
}
return rgberror;
}
static int
read_short(FILE * in, short * dst, int n, int swap)
{
int i;
unsigned char * ptr;
unsigned char tmp;
int num = (int)fread(dst, sizeof(short), n, in);
if (num == n && swap) {
ptr = (unsigned char *) dst;
for (i = 0; i < n; i++) {
tmp = ptr[0];
ptr[0] = ptr[1];
ptr[1] = tmp;
ptr += 2;
}
}
return num == n;
}
static int
read_ushort(FILE * in, unsigned short * dst, int n, int swap)
{
return read_short(in, (short*) dst, n, swap);
}
static int
read_int(FILE * in, int * dst, int n, int swap)
{
int i;
unsigned char tmp;
unsigned char * ptr;
int num = (int)fread(dst, sizeof(int), n, in);
if (num == n && swap) {
ptr = (unsigned char *) dst;
for (i = 0; i < n; i++) {
tmp = ptr[0];
ptr[0] = ptr[3];
ptr[3] = tmp;
tmp = ptr[1];
ptr[1] = ptr[2];
ptr[2] = tmp;
ptr += 4;
}
}
return num == n;
}
static int
read_uint(FILE * in, unsigned int * dst, int n, int swap)
{
return read_int(in, (int*)dst, n, swap);
}
void *
simage_rgb_open(const char * filename,
int * width,
int * height,
int * numcomponents)
{
int i;
int swap;
FILE * in;
unsigned short type;
unsigned short size[3];
simage_rgb_opendata * od;
union {
int data;
char bytedata[4];
} endiantest;
endiantest.data = 1;
/* need to swap shorts and integers on little endian systems */
swap = endiantest.bytedata[0] == 1;
in = fopen(filename, "rb");
if (!in) {
rgberror = ERR_OPEN;
return NULL;
}
/* skip imagic */
(void) fseek(in, 2, SEEK_SET);
if (!read_ushort(in, &type, 1, swap)) {
rgberror = ERR_READ;
fclose(in);
return NULL;
}
/* skip dim */
(void) fseek(in, 6, SEEK_SET);
if (!read_ushort(in, size, 3, swap)) {
rgberror = ERR_READ;
fclose(in);
return NULL;
}
od = (simage_rgb_opendata*) malloc(sizeof(simage_rgb_opendata));
memset(od, 0, sizeof(simage_rgb_opendata));
od->in = in;
od->w = (int) size[0];
od->h = (int) size[1];
od->nc = (int) size[2];
od->compressed = (type & 0xFF00) == 0x0100;
od->rlebuf = (unsigned char*) malloc(od->w * 2);
od->rlebuflen = od->w * 2;
for (i = 0; i < od->nc; i++) {
od->tmpbuf[i] = (unsigned char *) malloc(od->w);
}
if (od->compressed) {
/* create row lookup table */
int numlookup = od->h * od->nc;
od->rowseek = (unsigned int*) malloc(numlookup * 4);
od->rowlen = (int*) malloc(numlookup * 4);
(void) fseek(in, 512, SEEK_SET);
(void) read_uint(in, od->rowseek, numlookup, swap);
if (!read_int(in, od->rowlen, numlookup, swap)) {
rgberror = ERR_READ;
simage_rgb_close(od);
return NULL;
}
}
*width = od->w;
*height = od->h;
*numcomponents = od->nc;
return (void*) od;
}
void
simage_rgb_close(void * opendata)
{
int i;
simage_rgb_opendata * od =
(simage_rgb_opendata*) opendata;
fclose(od->in);
for (i = 0; i < od->nc; i++) {
free(od->tmpbuf[i]);
}
if (od->rowseek) free(od->rowseek);
if (od->rowlen) free(od->rowlen);
if (od->rlebuf) free(od->rlebuf);
free(od);
}
static int
read_rgb_row_component(simage_rgb_opendata * od, int y, int c)
{
if (od->compressed) {
unsigned char * src, * dst;
unsigned char * srcstop, * dststop;
unsigned char pixel;
int count;
int rowlen;
if (fseek(od->in, od->rowseek[y+c*od->h], SEEK_SET) != 0) {
rgberror = ERR_READ;
return 0;
}
rowlen = od->rowlen[y+c*od->h];
if (rowlen > od->rlebuflen) {
free(od->rlebuf);
od->rlebuflen = rowlen;
od->rlebuf = (unsigned char*) malloc(od->rlebuflen);
}
if (fread(od->rlebuf, 1, rowlen, od->in) != rowlen) {
rgberror = ERR_READ;
return 0;
}
src = od->rlebuf;
dst = od->tmpbuf[c];
srcstop = src + rowlen;
dststop = dst + od->w;
pixel = *src++;
count = (int)(pixel & 0x7F);
while (count) {
if (dst + count > dststop) { rgberror = ERR_READ; return 0; }
if (pixel & 0x80) {
if (src + count > srcstop) { rgberror = ERR_READ; return 0; }
while (count--) {
*dst++ = *src++;
}
}
else {
if (src >= srcstop) { rgberror = ERR_READ; return 0; }
pixel = *src++;
while (count--) {
*dst++ = pixel;
}
}
pixel = *src++;
count = (int)(pixel & 0x7F);
}
}
else {
if (fseek(od->in, 512+(y*od->w)+(c*od->w*od->h), SEEK_SET) != 0) {
rgberror = ERR_READ;
return 0;
}
if (fread(od->tmpbuf[c], 1, od->w, od->in) != od->w) {
rgberror = ERR_READ;
return 0;
}
}
return 1;
}
int
simage_rgb_read_line(void * opendata, int y, unsigned char * buf)
{
int i, c;
unsigned char * ptr;
simage_rgb_opendata * od =
(simage_rgb_opendata*) opendata;
/* read each component into tmpbufs */
for (c = 0; c < od->nc; c++) {
if (!read_rgb_row_component(od, y, c)) {
rgberror = ERR_READ;
return 0;
}
}
ptr = buf;
/* merge components into pixels */
for (i = 0; i < od->w; i++) {
for (c = 0; c < od->nc; c++) {
*ptr++ = od->tmpbuf[c][i];
}
}
return 1;
}
#endif /* SIMAGE_RGB_SUPPORT */
|
coin3d/simage
|
src/simage13.c
|
<filename>src/simage13.c
/*
* Copyright (c) <NAME> & Gas Technologies
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#include <simage.h>
#include <simage_private.h>
#include <string.h>
unsigned char * simage_resize3d(unsigned char *src,
int width, int height,
int nc, int layers,
int newwidth, int newheight,
int newlayers)
{
float sx, sy, sz, dx, dy, dz;
int src_bpr, dest_bpr, src_bpl, dest_bpl, xstop, ystop, zstop;
int x, y, z, offset, i;
unsigned char *dest =
(unsigned char*) malloc((size_t)newwidth*newheight*nc*newlayers);
dx = ((float)width)/((float)newwidth);
dy = ((float)height)/((float)newheight);
dz = ((float)layers)/((float)newlayers);
src_bpr = width * nc;
dest_bpr = newwidth * nc;
src_bpl = src_bpr * height;
dest_bpl = dest_bpr * newheight;
zstop = newlayers * dest_bpl;
ystop = dest_bpl;
xstop = dest_bpr;
sz = 0.0f;
for (z = 0; z < zstop; z += dest_bpl) {
sy = 0.0f;
for (y = 0; y < ystop; y += dest_bpr) {
sx = 0.0f;
for (x = 0; x < xstop; x += nc) {
offset = ((int)sz)*src_bpl + ((int)sy)*src_bpr + ((int)sx)*nc;
for (i = 0; i < nc; i++) dest[x+y+z+i] = src[offset+i];
sx += dx;
}
sy += dy;
}
sz += dz;
}
return dest;
}
|
coin3d/simage
|
src/resize.c
|
<reponame>coin3d/simage
/*
* Copyright (c) <NAME> & Gas Technologies
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Filtered Image Rescaling
*
* by <NAME>
*/
/*
* Slightly modified by pederb to be able to use it
* in simage.
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
/* Need to include this so the compiler knows that the simage_resize()
method should be defined with __declspec(dllexport) under
MSWindows. */
#include <simage.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif /* !M_PI */
typedef struct {
int xsize; /* horizontal size of the image in Pixels */
int ysize; /* vertical size of the image in Pixels */
int bpp; /* bytes per pixel */
unsigned char * data; /* pointer to first scanline of image */
int span; /* byte offset between two scanlines */
} Image;
static void
get_row(unsigned char * row, Image * image, int y)
{
assert(y >= 0);
assert(y < image->ysize);
memcpy(row,
image->data + (y * image->span),
(image->bpp * image->xsize));
}
static void
get_column(unsigned char * column, Image * image, int x)
{
int i, j, d, bpp, ysize;
unsigned char * p;
assert(x >= 0);
assert(x < image->xsize);
d = image->span;
bpp = image->bpp;
ysize = image->ysize;
for(i = 0, p = image->data + x * bpp; i < ysize; p += d, i++) {
for (j = 0; j < bpp; j++) {
*column++ = p[j];
}
}
}
static void
put_pixel(Image * image, int x, int y, float * data)
{
int i, bpp;
unsigned char * p;
float val;
assert(x >= 0);
assert(x < image->xsize);
assert(y >= 0);
assert(y < image->ysize);
bpp = image->bpp;
p = image->data + image->span * y + x * bpp;
for (i = 0; i < bpp; i++) {
val = data[i];
if (val < 0.0f) val = 0.0f;
else if (val > 255.0f) val = 255.0f;
*p++ = (unsigned char) val;
}
}
/*
* filter function definitions
*/
#define filter_support (1.0f)
static float
filter(float t)
{
/* f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1 */
if(t < 0.0f) t = -t;
if(t < 1.0f) return((2.0f * t - 3.0f) * t * t + 1.0f);
return(0.0f);
}
#define box_support (0.5f)
static float
box_filter(float t)
{
if((t > -0.5f) && (t <= 0.5f)) return(1.0f);
return(0.0f);
}
#define triangle_support (1.0f)
static float
triangle_filter(float t)
{
if(t < 0.0f) t = -t;
if(t < 1.0f) return(1.0f - t);
return(0.0f);
}
#define bell_support (1.5f)
static float
bell_filter(float t) /* box (*) box (*) box */
{
if(t < 0.0f) t = -t;
if(t < 0.5f) return(0.75f - (t * t));
if(t < 1.5f) {
t = (t - 1.5f);
return(0.5f * (t * t));
}
return(0.0f);
}
#define B_spline_support (2.0f)
static float
B_spline_filter(float t) /* box (*) box (*) box (*) box */
{
float tt;
if(t < 0.0f) t = -t;
if(t < 1.0f) {
tt = t * t;
return((.5f * tt * t) - tt + (2.0f / 3.0f));
} else if(t < 2.0f) {
t = 2.0f - t;
return((1.0f / 6.0f) * (t * t * t));
}
return(0.0f);
}
static float
sinc(float x)
{
x *= (float)M_PI;
if(x != 0.0f) return (float)(sin(x) / x);
return(1.0f);
}
#define Lanczos3_support (3.0f)
static float
Lanczos3_filter(float t)
{
if(t < 0.0f) t = -t;
if(t < 3.0f) return(sinc(t) * sinc(t/3.0f));
return(0.0f);
}
#define Mitchell_support (2.0)
#define B (1.0f / 3.0f)
#define C (1.0f / 3.0f)
static float
Mitchell_filter(float t)
{
float tt;
tt = t * t;
if(t < 0.0f) t = -t;
if(t < 1.0f) {
t = (((12.0f - 9.0f * B - 6.0f * C) * (t * tt))
+ ((-18.0f + 12.0f * B + 6.0f * C) * tt)
+ (6.0f - 2.0f * B));
return (t / 6.0f);
}
else if (t < 2.0f) {
t = (((-1.0f * B - 6.0f * C) * (t * tt))
+ ((6.0f * B + 30.0f * C) * tt)
+ ((-12.0f * B - 48.0f * C) * t)
+ (8.0f * B + 24.0f * C));
return (t / 6.0f);
}
return(0.0f);
}
/*
* image rescaling routine
*/
typedef struct {
int pixel;
float weight;
} CONTRIB;
typedef struct {
int n; /* number of contributors */
CONTRIB * p; /* pointer to list of contributions */
} CLIST;
static Image *
new_image(int xsize, int ysize, int bpp, unsigned char * data)
{
Image * img = (Image*) malloc(sizeof(Image));
img->xsize = xsize;
img->ysize = ysize;
img->bpp = bpp;
img->span = xsize * bpp;
img->data = data;
if (data == NULL) img->data = (unsigned char*) malloc((size_t)img->span*img->ysize);
return img;
}
static void
zoom(Image * dst, /* destination image structure */
Image * src, /* source image structure */
float (*filterf)(float), /* filter function */
float fwidth) /* filter width (support) */
{
CLIST * contrib;
Image * tmp; /* intermediate image */
float xscale, yscale; /* zoom scale factors */
int i, j, k, b; /* loop variables */
int n; /* pixel number */
int left, right; /* filter calculation variables */
float center; /* filter calculation variables */
float width, fscale, weight; /* filter calculation variables */
unsigned char * raster; /* a row or column of pixels */
float pixel[4]; /* one pixel */
int bpp;
unsigned char * dstptr;
int dstxsize, dstysize;
bpp = src->bpp;
dstxsize = dst->xsize;
dstysize = dst->ysize;
/* create intermediate image to hold horizontal zoom */
tmp = new_image(dstxsize, src->ysize, dst->bpp, NULL);
xscale = (float) dstxsize / (float) src->xsize;
yscale = (float) dstysize / (float) src->ysize;
/* pre-calculate filter contributions for a row */
contrib = (CLIST *)calloc(dstxsize, sizeof(CLIST));
if(xscale < 1.0f) {
width = fwidth / xscale;
fscale = 1.0f / xscale;
for(i = 0; i < dstxsize; i++) {
contrib[i].n = 0;
contrib[i].p = (CONTRIB *)calloc((int) (width * 2 + 1),
sizeof(CONTRIB));
center = (float) i / xscale;
left = (int) ceil(center - width);
right = (int) floor(center + width);
for(j = left; j <= right; j++) {
weight = center - (float) j;
weight = (*filterf)(weight / fscale) / fscale;
if(j < 0) {
n = -j;
}
else if(j >= src->xsize) {
n = (src->xsize - j) + src->xsize - 1;
}
else {
n = j;
}
k = contrib[i].n++;
contrib[i].p[k].pixel = n*bpp;
contrib[i].p[k].weight = weight;
}
}
}
else {
for(i = 0; i < dstxsize; i++) {
contrib[i].n = 0;
contrib[i].p = (CONTRIB *)calloc((int) (fwidth * 2 + 1),
sizeof(CONTRIB));
center = (float) i / xscale;
left = (int) ceil(center - fwidth);
right = (int) floor(center + fwidth);
for(j = left; j <= right; j++) {
weight = center - (float) j;
weight = (*filterf)(weight);
if(j < 0) {
n = -j;
}
else if(j >= src->xsize) {
n = (src->xsize - j) + src->xsize - 1;
}
else {
n = j;
}
k = contrib[i].n++;
contrib[i].p[k].pixel = n*bpp;
contrib[i].p[k].weight = weight;
}
}
}
/* apply filter to zoom horizontally from src to tmp */
raster = (unsigned char *)calloc(src->xsize, src->bpp);
dstptr = tmp->data;
for(k = 0; k < tmp->ysize; k++) {
get_row(raster, src, k);
for(i = 0; i < tmp->xsize; i++) {
for (b = 0; b < bpp; b++) pixel[b] = 0.0f;
for(j = 0; j < contrib[i].n; j++) {
for (b = 0; b < bpp; b++) {
pixel[b] += raster[contrib[i].p[j].pixel+b]
* contrib[i].p[j].weight;
}
}
#if 1 /* obsoleted 2001-11-18 pederb. Too slow */
put_pixel(tmp, i, k, pixel);
#else /* new code */
for (b = 0; b < bpp; b++) {
float val = pixel[b];
if (val < 0.0f) val = 0.0f;
else if (val > 255.0f) val = 255.0f;
*dstptr++ = (unsigned char ) val;
}
#endif /* new, faster code */
}
}
free(raster);
/* free the memory allocated for horizontal filter weights */
for(i = 0; i < tmp->xsize; i++) {
free(contrib[i].p);
}
free(contrib);
/* pre-calculate filter contributions for a column */
contrib = (CLIST *)calloc(dstysize, sizeof(CLIST));
if(yscale < 1.0f) {
width = fwidth / yscale;
fscale = 1.0f / yscale;
for(i = 0; i < dstysize; i++) {
contrib[i].n = 0;
contrib[i].p = (CONTRIB *)calloc((int) (width * 2 + 1),
sizeof(CONTRIB));
center = (float) i / yscale;
left = (int) ceil(center - width);
right = (int) floor(center + width);
for(j = left; j <= right; j++) {
weight = center - (float) j;
weight = (*filterf)(weight / fscale) / fscale;
if(j < 0) {
n = -j;
}
else if(j >= tmp->ysize) {
n = (tmp->ysize - j) + tmp->ysize - 1;
}
else {
n = j;
}
k = contrib[i].n++;
contrib[i].p[k].pixel = n*bpp;
contrib[i].p[k].weight = weight;
}
}
}
else {
for(i = 0; i < dstysize; i++) {
contrib[i].n = 0;
contrib[i].p = (CONTRIB *)calloc((int) (fwidth * 2 + 1),
sizeof(CONTRIB));
center = (float) i / yscale;
left = (int) ceil(center - fwidth);
right = (int) floor(center + fwidth);
for(j = left; j <= right; j++) {
weight = center - (float) j;
weight = (*filterf)(weight);
if(j < 0) {
n = -j;
}
else if(j >= tmp->ysize) {
n = (tmp->ysize - j) + tmp->ysize - 1;
}
else {
n = j;
}
k = contrib[i].n++;
contrib[i].p[k].pixel = n*bpp;
contrib[i].p[k].weight = weight;
}
}
}
/* apply filter to zoom vertically from tmp to dst */
raster = (unsigned char *) calloc(tmp->ysize, tmp->bpp);
for(k = 0; k < dstxsize; k++) {
get_column(raster, tmp, k);
dstptr = dst->data + k * bpp;
for(i = 0; i < dstysize; i++) {
for (b = 0; b < bpp; b++) pixel[b] = 0.0f;
for(j = 0; j < contrib[i].n; ++j) {
for (b = 0; b < bpp; b++) {
pixel[b] += raster[contrib[i].p[j].pixel+b]
* contrib[i].p[j].weight;
}
}
#if 1 /* obsoleted 2001-11-18 pederb. Too slow */
put_pixel(dst, k, i, pixel);
#else /* new code */
for (b = 0; b < bpp; b++) {
float val = pixel[b];
if (val < 0.0f) val = 0.0f;
else if (val > 255.0f) val = 255.0f;
dstptr[b] = (unsigned char) val;
}
#endif /* new, faster code */
dstptr += bpp * dstxsize;
}
}
free(raster);
/* free the memory allocated for vertical filter weights */
for(i = 0; i < dstysize; ++i) {
free(contrib[i].p);
}
free(contrib);
free(tmp->data);
free(tmp);
}
/*
* a pretty lame resize-function
*/
static unsigned char *
simage_resize_fast(unsigned char *src, int width,
int height, int num_comp,
int newwidth, int newheight)
{
float sx, sy, dx, dy;
int src_bpr, dest_bpr, xstop, ystop, x, y, offset, i;
unsigned char *dest =
(unsigned char*) malloc((size_t)newwidth*newheight*num_comp);
dx = ((float)width)/((float)newwidth);
dy = ((float)height)/((float)newheight);
src_bpr = width * num_comp;
dest_bpr = newwidth * num_comp;
sy = 0.0f;
ystop = newheight * dest_bpr;
xstop = newwidth * num_comp;
for (y = 0; y < ystop; y += dest_bpr) {
sx = 0.0f;
for (x = 0; x < xstop; x += num_comp) {
offset = ((int)sy)*src_bpr + ((int)sx)*num_comp;
for (i = 0; i < num_comp; i++) dest[x+y+i] = src[offset+i];
sx += dx;
}
sy += dy;
}
return dest;
}
// FIXME: pederb suspects that MSVC++ v6 mis-compiles some code in the
// resize functionality -- which again causes a crash whenever (?) a
// resize is attempted with a simage-library compiled in release mode.
// This sounds very nasty with regard to application programmers using
// Coin / simage, and should be investigated ASAP. 20010904 mortene.
// UPDATE: I haven't observed any crashes in the resize functionality
// for several years. That goes for debug builds as well as for
// release builds. Perhaps the bug has been fixed in the latest
// service pack, SP5 (which I'm using). 20031210 thammer.
// FIXME: methinks the type of the first argument should have been
// ``const unsigned char *''. Can't change it now, though, as it'd
// probably break ABI compatibility (?). Wait for simage2. 20010809 mortene.
unsigned char *
simage_resize(unsigned char * src, int width,
int height, int num_comp,
int newwidth, int newheight)
{
unsigned char * dstdata;
Image * srcimg, * dstimg;
#if 0 /* for comparing speed of resize functions */
return simage_resize_fast(src, width,
height, num_comp,
newwidth, newheight);
#endif /* testing only */
srcimg = new_image(width, height, num_comp, src);
dstimg = new_image(newwidth, newheight, num_comp, NULL);
/* Using the bell filter as default */
zoom(dstimg, srcimg, bell_filter, bell_support);
dstdata = dstimg->data;
free(srcimg);
free(dstimg);
return dstdata;
}
|
steven-michaud/SandboxMirror
|
mig/sm_reportServer.c
|
<gh_stars>10-100
/*
* IDENTIFICATION:
* stub generated Wed Sep 7 11:48:19 2016
* with a MiG generated by bootstrap_cmds-93
* OPTIONS:
* KernelUser
*/
/* Module sm_report */
#define __MIG_check__Request__sm_report_subsystem__ 1
#include <string.h>
#include <mach/ndr.h>
#include <mach/boolean.h>
#include <mach/kern_return.h>
#include <mach/notify.h>
#include <mach/mach_types.h>
#include <mach/message.h>
#include <mach/mig_errors.h>
#include <mach/port.h>
#include <mach/std_types.h>
#include <mach/mig.h>
#include <mach/mig.h>
#include <mach/mach_types.h>
#ifndef mig_internal
#define mig_internal static __inline__
#endif /* mig_internal */
#ifndef mig_external
#define mig_external
#endif /* mig_external */
#if !defined(__MigTypeCheck) && defined(TypeCheck)
#define __MigTypeCheck TypeCheck /* Legacy setting */
#endif /* !defined(__MigTypeCheck) */
#if !defined(__MigKernelSpecificCode) && defined(_MIG_KERNEL_SPECIFIC_CODE_)
#define __MigKernelSpecificCode _MIG_KERNEL_SPECIFIC_CODE_ /* Legacy setting */
#endif /* !defined(__MigKernelSpecificCode) */
#ifndef LimitCheck
#define LimitCheck 0
#endif /* LimitCheck */
#ifndef min
#define min(a,b) ( ((a) < (b))? (a): (b) )
#endif /* min */
#if !defined(_WALIGN_)
#define _WALIGN_(x) (((x) + 3) & ~3)
#endif /* !defined(_WALIGN_) */
#if !defined(_WALIGNSZ_)
#define _WALIGNSZ_(x) _WALIGN_(sizeof(x))
#endif /* !defined(_WALIGNSZ_) */
#ifndef UseStaticTemplates
#define UseStaticTemplates 0
#endif /* UseStaticTemplates */
#ifndef __DeclareRcvRpc
#define __DeclareRcvRpc(_NUM_, _NAME_)
#endif /* __DeclareRcvRpc */
#ifndef __BeforeRcvRpc
#define __BeforeRcvRpc(_NUM_, _NAME_)
#endif /* __BeforeRcvRpc */
#ifndef __AfterRcvRpc
#define __AfterRcvRpc(_NUM_, _NAME_)
#endif /* __AfterRcvRpc */
#ifndef __DeclareRcvSimple
#define __DeclareRcvSimple(_NUM_, _NAME_)
#endif /* __DeclareRcvSimple */
#ifndef __BeforeRcvSimple
#define __BeforeRcvSimple(_NUM_, _NAME_)
#endif /* __BeforeRcvSimple */
#ifndef __AfterRcvSimple
#define __AfterRcvSimple(_NUM_, _NAME_)
#endif /* __AfterRcvSimple */
#define novalue void
#define msgh_request_port msgh_local_port
#define MACH_MSGH_BITS_REQUEST(bits) MACH_MSGH_BITS_LOCAL(bits)
#define msgh_reply_port msgh_remote_port
#define MACH_MSGH_BITS_REPLY(bits) MACH_MSGH_BITS_REMOTE(bits)
#define MIG_RETURN_ERROR(X, code) {\
((mig_reply_error_t *)X)->RetCode = code;\
((mig_reply_error_t *)X)->NDR = NDR_record;\
return;\
}
/* typedefs for all requests */
#ifndef __Request__sm_report_subsystem__defined
#define __Request__sm_report_subsystem__defined
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
int32_t do_stacktrace;
int32_t pid;
uint64_t tid;
mach_msg_type_number_t log_fileOffset; /* MiG doesn't use it */
mach_msg_type_number_t log_fileCnt;
char log_file[1024];
mach_msg_type_number_t proc_pathOffset; /* MiG doesn't use it */
mach_msg_type_number_t proc_pathCnt;
char proc_path[1024];
mach_msg_type_number_t reportOffset; /* MiG doesn't use it */
mach_msg_type_number_t reportCnt;
char report[2048];
} __Request__sm_report_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#endif /* !__Request__sm_report_subsystem__defined */
/* typedefs for all replies */
#ifndef __Reply__sm_report_subsystem__defined
#define __Reply__sm_report_subsystem__defined
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
} __Reply__sm_report_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#endif /* !__Reply__sm_report_subsystem__defined */
/* union of all replies */
#ifndef __ReplyUnion__sm_report_subsystem__defined
#define __ReplyUnion__sm_report_subsystem__defined
union __ReplyUnion__sm_report_subsystem {
__Reply__sm_report_t Reply_sm_report;
};
#endif /* __RequestUnion__sm_report_subsystem__defined */
/* Forward Declarations */
mig_internal novalue _Xsm_report
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);
#if ( __MigTypeCheck )
#if __MIG_check__Request__sm_report_subsystem__
#if !defined(__MIG_check__Request__sm_report_t__defined)
#define __MIG_check__Request__sm_report_t__defined
mig_internal kern_return_t __MIG_check__Request__sm_report_t(__attribute__((__unused__)) __Request__sm_report_t *In0P, __attribute__((__unused__)) __Request__sm_report_t **In1PP, __attribute__((__unused__)) __Request__sm_report_t **In2PP)
{
typedef __Request__sm_report_t __Request;
__Request *In1P;
__Request *In2P;
#if __MigTypeCheck
unsigned int msgh_size;
#endif /* __MigTypeCheck */
unsigned int msgh_size_delta;
#if __MigTypeCheck
msgh_size = In0P->Head.msgh_size;
if (!(In0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
(In0P->msgh_body.msgh_descriptor_count != 1) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 4096)) || (msgh_size > (mach_msg_size_t)sizeof(__Request)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
#if __MigTypeCheck
if (In0P->task.type != MACH_MSG_PORT_DESCRIPTOR ||
In0P->task.disposition != 17)
return MIG_TYPE_ERROR;
#endif /* __MigTypeCheck */
#if defined(__NDR_convert__int_rep__Request__sm_report_t__log_fileCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__sm_report_t__log_fileCnt(&In0P->log_fileCnt, In0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__sm_report_t__log_fileCnt__defined */
msgh_size_delta = _WALIGN_(In0P->log_fileCnt);
#if __MigTypeCheck
if ( In0P->log_fileCnt > 1024 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 4096)) < In0P->log_fileCnt) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 4096) + _WALIGN_(In0P->log_fileCnt)))
return MIG_BAD_ARGUMENTS;
msgh_size -= msgh_size_delta;
#endif /* __MigTypeCheck */
*In1PP = In1P = (__Request *) ((pointer_t) In0P + msgh_size_delta - 1024);
#if defined(__NDR_convert__int_rep__Request__sm_report_t__proc_pathCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__sm_report_t__proc_pathCnt(&In1P->proc_pathCnt, In1P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__sm_report_t__proc_pathCnt__defined */
msgh_size_delta = _WALIGN_(In1P->proc_pathCnt);
#if __MigTypeCheck
if ( In1P->proc_pathCnt > 1024 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 4096)) < In1P->proc_pathCnt) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 4096) + _WALIGN_(In1P->proc_pathCnt)))
return MIG_BAD_ARGUMENTS;
msgh_size -= msgh_size_delta;
#endif /* __MigTypeCheck */
*In2PP = In2P = (__Request *) ((pointer_t) In1P + msgh_size_delta - 1024);
#if defined(__NDR_convert__int_rep__Request__sm_report_t__reportCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__sm_report_t__reportCnt(&In2P->reportCnt, In2P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__sm_report_t__reportCnt__defined */
#if __MigTypeCheck
if ( In2P->reportCnt > 2048 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 4096)) < In2P->reportCnt) ||
(msgh_size != (mach_msg_size_t)(sizeof(__Request) - 4096) + _WALIGN_(In2P->reportCnt)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
#if __MigTypeCheck
{
char * msg_limit = ((char *) In0P) + In0P->Head.msgh_size;
size_t memchr_limit;
memchr_limit = min((msg_limit - In0P->log_file), 1024);
if (( memchr(In0P->log_file, '\0', memchr_limit) == NULL ))
return MIG_BAD_ARGUMENTS; // string length exceeds buffer length!
memchr_limit = min((msg_limit - In1P->proc_path), 1024);
if (( memchr(In1P->proc_path, '\0', memchr_limit) == NULL ))
return MIG_BAD_ARGUMENTS; // string length exceeds buffer length!
memchr_limit = min((msg_limit - In2P->report), 2048);
if (( memchr(In2P->report, '\0', memchr_limit) == NULL ))
return MIG_BAD_ARGUMENTS; // string length exceeds buffer length!
}
#endif /* __MigTypeCheck */
return MACH_MSG_SUCCESS;
}
#endif /* !defined(__MIG_check__Request__sm_report_t__defined) */
#endif /* __MIG_check__Request__sm_report_subsystem__ */
#endif /* ( __MigTypeCheck ) */
/* Routine sm_report */
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
kern_return_t sm_report
(
mach_port_t server_port,
task_t task,
int32_t do_stacktrace,
int32_t pid,
uint64_t tid,
sm_filename_t log_file,
sm_path_t proc_path,
sm_report_t report
);
/* Routine sm_report */
mig_internal novalue _Xsm_report
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
int32_t do_stacktrace;
int32_t pid;
uint64_t tid;
mach_msg_type_number_t log_fileOffset; /* MiG doesn't use it */
mach_msg_type_number_t log_fileCnt;
char log_file[1024];
mach_msg_type_number_t proc_pathOffset; /* MiG doesn't use it */
mach_msg_type_number_t proc_pathCnt;
char proc_path[1024];
mach_msg_type_number_t reportOffset; /* MiG doesn't use it */
mach_msg_type_number_t reportCnt;
char report[2048];
mach_msg_trailer_t trailer;
} Request __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
typedef __Request__sm_report_t __Request;
typedef __Reply__sm_report_t Reply __attribute__((unused));
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
Request *In0P = (Request *) InHeadP;
Request *In1P;
Request *In2P;
Reply *OutP = (Reply *) OutHeadP;
#ifdef __MIG_check__Request__sm_report_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Request__sm_report_t__defined */
__DeclareRcvRpc(666, "sm_report")
__BeforeRcvRpc(666, "sm_report")
#if defined(__MIG_check__Request__sm_report_t__defined)
check_result = __MIG_check__Request__sm_report_t((__Request *)In0P, (__Request **)&In1P, (__Request **)&In2P);
if (check_result != MACH_MSG_SUCCESS)
{ MIG_RETURN_ERROR(OutP, check_result); }
#endif /* defined(__MIG_check__Request__sm_report_t__defined) */
OutP->RetCode = sm_report(In0P->Head.msgh_request_port, In0P->task.name, In0P->do_stacktrace, In0P->pid, In0P->tid, In0P->log_file, In1P->proc_path, In2P->report);
OutP->NDR = NDR_record;
__AfterRcvRpc(666, "sm_report")
}
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
boolean_t sm_report_server(
mach_msg_header_t *InHeadP,
mach_msg_header_t *OutHeadP);
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
mig_routine_t sm_report_server_routine(
mach_msg_header_t *InHeadP);
/* Description of this subsystem, for use in direct RPC */
const struct sm_report_subsystem {
mig_server_routine_t server; /* Server routine */
mach_msg_id_t start; /* Min routine number */
mach_msg_id_t end; /* Max routine number + 1 */
unsigned int maxsize; /* Max msg size */
vm_address_t reserved; /* Reserved */
struct routine_descriptor /*Array of routine descriptors */
routine[1];
} sm_report_subsystem = {
sm_report_server_routine,
666,
667,
(mach_msg_size_t)sizeof(union __ReplyUnion__sm_report_subsystem),
(vm_address_t)0,
{
{ (mig_impl_routine_t) 0,
(mig_stub_routine_t) _Xsm_report, 9, 0, (routine_arg_descriptor_t)0, (mach_msg_size_t)sizeof(__Reply__sm_report_t)},
}
};
mig_external boolean_t sm_report_server
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
register mig_routine_t routine;
OutHeadP->msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REPLY(InHeadP->msgh_bits), 0);
OutHeadP->msgh_remote_port = InHeadP->msgh_reply_port;
/* Minimal size: routine() will update it if different */
OutHeadP->msgh_size = (mach_msg_size_t)sizeof(mig_reply_error_t);
OutHeadP->msgh_local_port = MACH_PORT_NULL;
OutHeadP->msgh_id = InHeadP->msgh_id + 100;
if ((InHeadP->msgh_id > 666) || (InHeadP->msgh_id < 666) ||
((routine = sm_report_subsystem.routine[InHeadP->msgh_id - 666].stub_routine) == 0)) {
((mig_reply_error_t *)OutHeadP)->NDR = NDR_record;
((mig_reply_error_t *)OutHeadP)->RetCode = MIG_BAD_ID;
return FALSE;
}
(*routine) (InHeadP, OutHeadP);
return TRUE;
}
mig_external mig_routine_t sm_report_server_routine
(mach_msg_header_t *InHeadP)
{
register int msgh_id;
msgh_id = InHeadP->msgh_id - 666;
if ((msgh_id > 0) || (msgh_id < 0))
return 0;
return sm_report_subsystem.routine[msgh_id].stub_routine;
}
|
steven-michaud/SandboxMirror
|
mig/sm_report.h
|
#ifndef _sm_report_user_
#define _sm_report_user_
/* Module sm_report */
#include <string.h>
#include <mach/ndr.h>
#include <mach/boolean.h>
#include <mach/kern_return.h>
#include <mach/notify.h>
#include <mach/mach_types.h>
#include <mach/message.h>
#include <mach/mig_errors.h>
#include <mach/port.h>
#if (__MigKernelSpecificCode) || (_MIG_KERNEL_SPECIFIC_CODE_)
#include <kern/ipc_mig.h>
#endif /* __MigKernelSpecificCode */
#ifdef AUTOTEST
#ifndef FUNCTION_PTR_T
#define FUNCTION_PTR_T
typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t);
typedef struct {
char *name;
function_ptr_t function;
} function_table_entry;
typedef function_table_entry *function_table_t;
#endif /* FUNCTION_PTR_T */
#endif /* AUTOTEST */
#ifndef sm_report_MSG_COUNT
#define sm_report_MSG_COUNT 1
#endif /* sm_report_MSG_COUNT */
#include <mach/std_types.h>
#include <mach/mig.h>
#include <mach/mig.h>
#include <mach/mach_types.h>
#ifdef __BeforeMigUserHeader
__BeforeMigUserHeader
#endif /* __BeforeMigUserHeader */
#include <sys/cdefs.h>
__BEGIN_DECLS
/* Routine sm_report */
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
kern_return_t sm_report
(
mach_port_t server_port,
task_t task,
int32_t do_stacktrace,
int32_t pid,
uint64_t tid,
sm_filename_t log_file,
sm_path_t proc_path,
sm_report_t report
);
__END_DECLS
/********************** Caution **************************/
/* The following data types should be used to calculate */
/* maximum message sizes only. The actual message may be */
/* smaller, and the position of the arguments within the */
/* message layout may vary from what is presented here. */
/* For example, if any of the arguments are variable- */
/* sized, and less than the maximum is sent, the data */
/* will be packed tight in the actual message to reduce */
/* the presence of holes. */
/********************** Caution **************************/
/* typedefs for all requests */
#ifndef __Request__sm_report_subsystem__defined
#define __Request__sm_report_subsystem__defined
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
int32_t do_stacktrace;
int32_t pid;
uint64_t tid;
mach_msg_type_number_t log_fileOffset; /* MiG doesn't use it */
mach_msg_type_number_t log_fileCnt;
char log_file[1024];
mach_msg_type_number_t proc_pathOffset; /* MiG doesn't use it */
mach_msg_type_number_t proc_pathCnt;
char proc_path[1024];
mach_msg_type_number_t reportOffset; /* MiG doesn't use it */
mach_msg_type_number_t reportCnt;
char report[2048];
} __Request__sm_report_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#endif /* !__Request__sm_report_subsystem__defined */
/* union of all requests */
#ifndef __RequestUnion__sm_report_subsystem__defined
#define __RequestUnion__sm_report_subsystem__defined
union __RequestUnion__sm_report_subsystem {
__Request__sm_report_t Request_sm_report;
};
#endif /* !__RequestUnion__sm_report_subsystem__defined */
/* typedefs for all replies */
#ifndef __Reply__sm_report_subsystem__defined
#define __Reply__sm_report_subsystem__defined
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
} __Reply__sm_report_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#endif /* !__Reply__sm_report_subsystem__defined */
/* union of all replies */
#ifndef __ReplyUnion__sm_report_subsystem__defined
#define __ReplyUnion__sm_report_subsystem__defined
union __ReplyUnion__sm_report_subsystem {
__Reply__sm_report_t Reply_sm_report;
};
#endif /* !__RequestUnion__sm_report_subsystem__defined */
#ifndef subsystem_to_name_map_sm_report
#define subsystem_to_name_map_sm_report \
{ "sm_report", 666 }
#endif
#ifdef __AfterMigUserHeader
__AfterMigUserHeader
#endif /* __AfterMigUserHeader */
#endif /* _sm_report_user_ */
|
steven-michaud/SandboxMirror
|
mig/sm_reportUser.c
|
<filename>mig/sm_reportUser.c
/*
* IDENTIFICATION:
* stub generated Wed Sep 7 11:48:19 2016
* with a MiG generated by bootstrap_cmds-93
* OPTIONS:
* KernelUser
*/
#define __MIG_check__Reply__sm_report_subsystem__ 1
#include "sm_report.h"
#ifndef mig_internal
#define mig_internal static __inline__
#endif /* mig_internal */
#ifndef mig_external
#define mig_external
#endif /* mig_external */
#if !defined(__MigTypeCheck) && defined(TypeCheck)
#define __MigTypeCheck TypeCheck /* Legacy setting */
#endif /* !defined(__MigTypeCheck) */
#if !defined(__MigKernelSpecificCode) && defined(_MIG_KERNEL_SPECIFIC_CODE_)
#define __MigKernelSpecificCode _MIG_KERNEL_SPECIFIC_CODE_ /* Legacy setting */
#endif /* !defined(__MigKernelSpecificCode) */
#ifndef LimitCheck
#define LimitCheck 0
#endif /* LimitCheck */
#ifndef min
#define min(a,b) ( ((a) < (b))? (a): (b) )
#endif /* min */
#if !defined(_WALIGN_)
#define _WALIGN_(x) (((x) + 3) & ~3)
#endif /* !defined(_WALIGN_) */
#if !defined(_WALIGNSZ_)
#define _WALIGNSZ_(x) _WALIGN_(sizeof(x))
#endif /* !defined(_WALIGNSZ_) */
#ifndef UseStaticTemplates
#define UseStaticTemplates 0
#endif /* UseStaticTemplates */
#ifndef __MachMsgErrorWithTimeout
#define __MachMsgErrorWithTimeout(_R_) { \
switch (_R_) { \
case MACH_SEND_INVALID_DATA: \
case MACH_SEND_INVALID_DEST: \
case MACH_SEND_INVALID_HEADER: \
mig_put_reply_port(InP->Head.msgh_reply_port); \
break; \
case MACH_SEND_TIMED_OUT: \
case MACH_RCV_TIMED_OUT: \
default: \
mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
} \
}
#endif /* __MachMsgErrorWithTimeout */
#ifndef __MachMsgErrorWithoutTimeout
#define __MachMsgErrorWithoutTimeout(_R_) { \
switch (_R_) { \
case MACH_SEND_INVALID_DATA: \
case MACH_SEND_INVALID_DEST: \
case MACH_SEND_INVALID_HEADER: \
mig_put_reply_port(InP->Head.msgh_reply_port); \
break; \
default: \
mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
} \
}
#endif /* __MachMsgErrorWithoutTimeout */
#ifndef __DeclareSendRpc
#define __DeclareSendRpc(_NUM_, _NAME_)
#endif /* __DeclareSendRpc */
#ifndef __BeforeSendRpc
#define __BeforeSendRpc(_NUM_, _NAME_)
#endif /* __BeforeSendRpc */
#ifndef __AfterSendRpc
#define __AfterSendRpc(_NUM_, _NAME_)
#endif /* __AfterSendRpc */
#ifndef __DeclareSendSimple
#define __DeclareSendSimple(_NUM_, _NAME_)
#endif /* __DeclareSendSimple */
#ifndef __BeforeSendSimple
#define __BeforeSendSimple(_NUM_, _NAME_)
#endif /* __BeforeSendSimple */
#ifndef __AfterSendSimple
#define __AfterSendSimple(_NUM_, _NAME_)
#endif /* __AfterSendSimple */
#define msgh_request_port msgh_remote_port
#define msgh_reply_port msgh_local_port
#if ( __MigTypeCheck )
#if __MIG_check__Reply__sm_report_subsystem__
#if !defined(__MIG_check__Reply__sm_report_t__defined)
#define __MIG_check__Reply__sm_report_t__defined
mig_internal kern_return_t __MIG_check__Reply__sm_report_t(__Reply__sm_report_t *Out0P)
{
typedef __Reply__sm_report_t __Reply __attribute__((unused));
if (Out0P->Head.msgh_id != 766) {
if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE)
{ return MIG_SERVER_DIED; }
else
{ return MIG_REPLY_MISMATCH; }
}
#if __MigTypeCheck
if ((Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
(Out0P->Head.msgh_size != (mach_msg_size_t)sizeof(__Reply)))
{ return MIG_TYPE_ERROR ; }
#endif /* __MigTypeCheck */
{
return Out0P->RetCode;
}
}
#endif /* !defined(__MIG_check__Reply__sm_report_t__defined) */
#endif /* __MIG_check__Reply__sm_report_subsystem__ */
#endif /* ( __MigTypeCheck ) */
/* Routine sm_report */
mig_external kern_return_t sm_report
(
mach_port_t server_port,
task_t task,
int32_t do_stacktrace,
int32_t pid,
uint64_t tid,
sm_filename_t log_file,
sm_path_t proc_path,
sm_report_t report
)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
int32_t do_stacktrace;
int32_t pid;
uint64_t tid;
mach_msg_type_number_t log_fileOffset; /* MiG doesn't use it */
mach_msg_type_number_t log_fileCnt;
char log_file[1024];
mach_msg_type_number_t proc_pathOffset; /* MiG doesn't use it */
mach_msg_type_number_t proc_pathCnt;
char proc_path[1024];
mach_msg_type_number_t reportOffset; /* MiG doesn't use it */
mach_msg_type_number_t reportCnt;
char report[2048];
} Request __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
mach_msg_trailer_t trailer;
} Reply __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
} __Reply __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
union {
Request In;
Reply Out;
} Mess;
Request *InP = &Mess.In;
Reply *Out0P = &Mess.Out;
mach_msg_return_t msg_result;
unsigned int msgh_size;
unsigned int msgh_size_delta;
#ifdef __MIG_check__Reply__sm_report_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Reply__sm_report_t__defined */
__DeclareSendRpc(666, "sm_report")
#if UseStaticTemplates
const static mach_msg_port_descriptor_t taskTemplate = {
/* name = */ MACH_PORT_NULL,
/* pad1 = */ 0,
/* pad2 = */ 0,
/* disp = */ 19,
/* type = */ MACH_MSG_PORT_DESCRIPTOR,
};
#endif /* UseStaticTemplates */
InP->msgh_body.msgh_descriptor_count = 1;
#if UseStaticTemplates
InP->task = taskTemplate;
InP->task.name = task;
#else /* UseStaticTemplates */
InP->task.name = task;
InP->task.disposition = 19;
InP->task.type = MACH_MSG_PORT_DESCRIPTOR;
#endif /* UseStaticTemplates */
InP->NDR = NDR_record;
InP->do_stacktrace = do_stacktrace;
InP->pid = pid;
InP->tid = tid;
InP->log_fileCnt = mig_strncpy(InP->log_file, log_file, 1024);
msgh_size_delta = _WALIGN_(InP->log_fileCnt);
msgh_size = (mach_msg_size_t)(sizeof(Request) - 4096) + msgh_size_delta;
InP = (Request *) ((pointer_t) InP + msgh_size_delta - 1024);
InP->proc_pathCnt = mig_strncpy(InP->proc_path, proc_path, 1024);
msgh_size_delta = _WALIGN_(InP->proc_pathCnt);
msgh_size += msgh_size_delta;
InP = (Request *) ((pointer_t) InP + msgh_size_delta - 1024);
InP->reportCnt = mig_strncpy(InP->report, report, 2048);
msgh_size += _WALIGN_(InP->reportCnt);
InP = &Mess.In;
InP->Head.msgh_bits = MACH_MSGH_BITS_COMPLEX|
MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE);
/* msgh_size passed as argument */
InP->Head.msgh_request_port = server_port;
InP->Head.msgh_reply_port = mig_get_reply_port();
InP->Head.msgh_id = 666;
__BeforeSendRpc(666, "sm_report")
#if (__MigKernelSpecificCode) || (_MIG_KERNELSPECIFIC_CODE_)
msg_result = mach_msg_rpc_from_kernel(&InP->Head, msgh_size, (mach_msg_size_t)sizeof(Reply));
#else
msg_result = mach_msg(&InP->Head, MACH_SEND_MSG|MACH_RCV_MSG|MACH_MSG_OPTION_NONE, msgh_size, (mach_msg_size_t)sizeof(Reply), InP->Head.msgh_reply_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
#endif /* __MigKernelSpecificCode */
__AfterSendRpc(666, "sm_report")
if (msg_result != MACH_MSG_SUCCESS) {
__MachMsgErrorWithoutTimeout(msg_result);
{ return msg_result; }
}
#if defined(__MIG_check__Reply__sm_report_t__defined)
check_result = __MIG_check__Reply__sm_report_t((__Reply__sm_report_t *)Out0P);
if (check_result != MACH_MSG_SUCCESS)
{ return check_result; }
#endif /* defined(__MIG_check__Reply__sm_report_t__defined) */
return KERN_SUCCESS;
}
|
erneson/watersheds
|
watershed_FBC.c
|
<filename>watershed_FBC.c<gh_stars>1-10
// gcc -O3 -o watershed watershed.c
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <string.h>
#include <stdbool.h>
struct NEIGHBORHOOD
{
int64_t NNZV; // Compressed Row "Binary" Storage (CRBS)
int64_t *IV; // Compressed Row "Binary" Storage (CRBS)
int32_t *JV; // Compressed Row "Binary" Storage (CRBS)
};
struct LATTICE
{
int32_t lx; // Lattice size on X dimension
int32_t ly; // Lattice size on Y dimension
int32_t n; // Total number of sites
float *h; // Heights
struct NEIGHBORHOOD *nei; // Lattice neighboorhood
};
struct LIST
{
int32_t n; // Length
int32_t m; // Size
int32_t *key; // Keys
};
struct HEAP
{
int32_t n; // Length
int32_t m; // Size
float *key; // Keys
int32_t *item; // Positions
};
struct SYSTEM
{
struct LATTICE *L; // Lattice
int32_t *sigma; // Basins
struct LIST *sink; // Sinks
struct LIST *stalker; // Stalkers
int32_t *check; // Check
struct LIST *burner; // Burners
int32_t *status; // Status
struct HEAP *H; // Binary Heap
};
void input(char name[100],struct SYSTEM *S);
void set_neighbors(struct SYSTEM *S);
void coastline(char hcutoff[100],struct SYSTEM *S);
void drainage_basin(struct SYSTEM *S);
void invasion_percolation(struct SYSTEM *S,int32_t k);
void output(char name[100],char hcutoff[100],struct SYSTEM *S);
int32_t parent(int32_t i);
int32_t left(int32_t i);
int32_t right(int32_t i);
void min_heap_insert(struct HEAP *A,float key,int32_t item);
void heap_decrease_key(struct HEAP *A,int32_t i,float key,int32_t item);
void heap_extract_min(struct HEAP *A,float *key,int32_t *item);
void min_heapify(struct HEAP *A,int32_t i);
void set_free(struct SYSTEM *S);
int32_t main(int32_t argc,char *argv[])
{
char name[100];
char hcutoff[100];
struct SYSTEM *S;
strcpy(name,argv[1]);
strcpy(hcutoff,argv[2]);
S=(struct SYSTEM *)malloc(sizeof(struct SYSTEM));
input(name,S);
coastline(hcutoff,S);
drainage_basin(S);https://www.globo.com/
output(name,hcutoff,S);
set_free(S);
return(0);
}
void input(char name[100],struct SYSTEM *S)
{
char filename[400];
FILE *f;
int32_t lx;
int32_t ly;
int32_t i,j,k;
float height;
int32_t t;
strcpy(filename,name);
strcat(filename,".dat");
f=fopen(filename,"r");
fscanf(f,"%d %d\n",&lx,&ly);
S->L=(struct LATTICE *)malloc(sizeof(struct LATTICE));
S->L->lx=lx;
S->L->ly=ly;
S->L->n=S->L->lx*S->L->ly;
S->L->h=(float *)malloc(S->L->n*sizeof(float));
set_neighbors(S); // Neighborhood
for(t=0;t<S->L->n;t++)
{
fscanf(f,"%d %d %f\n",&i,&j,&height);
k=i+j*S->L->lx;
S->L->h[k]=height;
}
fclose(f);
}
void set_neighbors(struct SYSTEM *S)
{
int32_t i,j,k;
int64_t t;
/*FBC*/
S->L->nei=(struct NEIGHBORHOOD *)malloc(sizeof(struct NEIGHBORHOOD));
S->L->nei->NNZV=4*(int64_t)S->L->lx*(int64_t)S->L->ly-2*(int64_t)S->L->lx-2*(int64_t)S->L->ly;
S->L->nei->IV=(int64_t *)malloc((S->L->n+1)*sizeof(int64_t));
S->L->nei->JV=(int32_t *)malloc(S->L->nei->NNZV*sizeof(int32_t));
/*FBC*/
/*FBC*/
t=0;
S->L->nei->IV[0]=t;
for(k=0;k<S->L->n;k++)
{
i=k%S->L->lx;
j=k/S->L->lx;
if(j==0)
{
if(i==0)
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k+1;
t=t+1;
S->L->nei->JV[t]=k+S->L->lx;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
else
{
if(i==S->L->lx-1)
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-1;
t=t+1;
S->L->nei->JV[t]=k+S->L->lx;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
else
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-1;
t=t+1;
S->L->nei->JV[t]=k+1;
t=t+1;
S->L->nei->JV[t]=k+S->L->lx;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
}
}
else
{
if(j<S->L->ly-1) //k<=(S->L->ly-1)*S->L->lx-1
{
if(i==0)
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-S->L->lx;
t=t+1;
S->L->nei->JV[t]=k+1;
t=t+1;
S->L->nei->JV[t]=k+S->L->lx;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
else
{
if(i==S->L->lx-1)
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-S->L->lx;
t=t+1;
S->L->nei->JV[t]=k-1;
t=t+1;
S->L->nei->JV[t]=k+S->L->lx;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
else
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-S->L->lx;
t=t+1;
S->L->nei->JV[t]=k-1;
t=t+1;
S->L->nei->JV[t]=k+1;
t=t+1;
S->L->nei->JV[t]=k+S->L->lx;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
}
}
else
{
if(i==0)
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-S->L->lx;
t=t+1;
S->L->nei->JV[t]=k+1;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
else
{
if(i==S->L->lx-1)
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-S->L->lx;
t=t+1;
S->L->nei->JV[t]=k-1;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
else
{
/*VON NEUMMAN*/
S->L->nei->JV[t]=k-S->L->lx;
t=t+1;
S->L->nei->JV[t]=k-1;
t=t+1;
S->L->nei->JV[t]=k+1;
t=t+1;
S->L->nei->IV[k+1]=t;
/*VON NEUMMAN*/
}
}
}
}
}
/*FBC*/
}
void coastline(char hcutoff[100],struct SYSTEM *S)
{
int32_t k;
int64_t r;
int32_t s;
S->sigma=(int32_t *)malloc(S->L->n*sizeof(int32_t));
S->sink=(struct LIST *)malloc(sizeof(struct LIST));
S->sink->n=S->L->n;
S->sink->m=0;
S->sink->key=(int32_t *)malloc(S->sink->n*sizeof(int32_t));
for(k=0;k<S->L->n;k++)
{
if(S->L->h[k]>atof(hcutoff))
{
S->sigma[k]=-1;
for(r=S->L->nei->IV[k];r<S->L->nei->IV[k+1];r++) // from IA[i] to IA[i+1]-1
{
s=S->L->nei->JV[r];
if(S->L->h[s]<=atof(hcutoff))
{
S->sink->key[S->sink->m]=k;
S->sink->m++;
break;
}
}
}
else
{
S->sigma[k]=-2;
}
}
}
void drainage_basin(struct SYSTEM *S)
{
int32_t q;
int32_t i,j,k;
int64_t r,u;
int32_t s,t;
int32_t v;
S->stalker=(struct LIST *)malloc(sizeof(struct LIST));
S->stalker->n=S->L->n;
S->stalker->m=0;
S->stalker->key=(int32_t *)malloc(S->stalker->n*sizeof(int32_t));
S->check=(int32_t *)malloc(S->L->n*sizeof(int32_t));
S->burner=(struct LIST *)malloc(sizeof(struct LIST));
S->burner->n=S->L->n;
S->burner->m=0;
S->burner->key=(int32_t *)malloc(S->burner->n*sizeof(int32_t));
S->status=(int32_t *)malloc(S->L->n*sizeof(int32_t));
S->H=(struct HEAP *)malloc(sizeof(struct HEAP));
S->H->n=S->L->n;
//S->H->m=0;
S->H->key=(float *)malloc(S->H->n*sizeof(float));
S->H->item=(int32_t *)malloc(S->H->n*sizeof(int32_t));
for(i=0;i<S->L->n;i++)
{
S->check[i]=-2;
}
for(i=0;i<S->L->n;i++)
{
if(S->sigma[i]==-2)
{
S->status[i]=-2;
}
else
{
S->status[i]=-1;
}
}
for(i=0;i<S->sink->m;i++)
{
k=S->sink->key[i];
invasion_percolation(S,k); // S->sigma[k]=k
for(j=0;j<S->stalker->m;j++)
{
t=S->stalker->key[j];
S->check[t]=-2;
}
S->stalker->m=0; // Restarting
S->stalker->key[S->stalker->m]=k;
S->stalker->m++;
S->check[k]=1;
q=0;
while(q<S->stalker->m)
{
t=S->stalker->key[q];
for(r=S->L->nei->IV[t];r<S->L->nei->IV[t+1];r++) // from IA[i] to IA[i+1]-1
{
s=S->L->nei->JV[r];
if(S->sigma[s]>=-1)
{
invasion_percolation(S,s);
for(u=S->L->nei->IV[s];u<S->L->nei->IV[s+1];u++) // from IA[i] to IA[i+1]-1
{
v=S->L->nei->JV[u];
if(S->sigma[v]>=-1)
{
invasion_percolation(S,v);
if(S->sigma[s]==S->sigma[k])
{
if(S->sigma[v]!=S->sigma[k])
{
if(S->check[s]==-2)
{
S->stalker->key[S->stalker->m]=s;
S->stalker->m++;
S->check[s]=1;
}
}
}
else
{
if(S->sigma[v]==S->sigma[k])
{
if(S->check[v]==-2)
{
S->stalker->key[S->stalker->m]=v;
S->stalker->m++;
S->check[v]=1;
}
}
}
}
}
}
}
q++;
}
}
}
void invasion_percolation(struct SYSTEM *S,int32_t k)
{
bool stop;
float key;
int32_t item;
int32_t i;
int64_t r;
int32_t s,t;
int32_t w;
if(S->sigma[k]==-1)
{
for(t=0;t<S->burner->m;t++)
{
i=S->burner->key[t];
S->status[i]=-1;
}
S->burner->m=0; // Restarting
S->H->m=0; // Restarting
S->burner->key[S->burner->m]=k;
S->burner->m++;
S->status[k]=1;
min_heap_insert(S->H,S->L->h[k],k);
stop=false;
while(S->H->m>0 && stop==false)
{
heap_extract_min(S->H,&key,&item);
t=item;
S->status[t]=2;
for(r=S->L->nei->IV[t];r<S->L->nei->IV[t+1];r++) // from IA[i] to IA[i+1]-1
{
s=S->L->nei->JV[r];
if(S->status[s]==-2)
{
w=t;
stop=true;
break;
}
}
if(stop==false)
{
for(r=S->L->nei->IV[t];r<S->L->nei->IV[t+1];r++) // from IA[i] to IA[i+1]-1
{
s=S->L->nei->JV[r];
if(S->status[s]==-1)
{
S->burner->key[S->burner->m]=s;
S->burner->m++;
S->status[s]=1;
min_heap_insert(S->H,S->L->h[s],s);
}
}
}
}
if(stop==true)
{
S->sigma[k]=w;
}
}
}
void output(char name[100],char hcutoff[100],struct SYSTEM *S)
{
FILE *f;
char filename[400];
int32_t i,j,k;
strcpy(filename,"sigma_");
strcat(filename,name);
strcat(filename,"_h"); // hcutoff
strcat(filename,hcutoff); // hcutoff
strcat(filename,".dat");
f=fopen(filename,"w");
fprintf(f,"%d %d\n",S->L->lx,S->L->ly);
for(k=0;k<S->L->n;k++)
{
i=k%S->L->lx;
j=k/S->L->lx;
fprintf(f,"%d %d %d\n",i,j,S->sigma[k]);
}
fclose(f);
}
int32_t parent(int32_t i)
{
return (i-1)/2;
}
int32_t left(int32_t i)
{
return 2*i+1;
}
int32_t right(int32_t i)
{
return 2*i+2;
}
void min_heap_insert(struct HEAP *A,float key,int32_t item)
{
A->m++;
A->key[A->m-1]=FLT_MAX;
heap_decrease_key(A,A->m-1,key,item);
}
void heap_decrease_key(struct HEAP *A, int32_t i, float key,int32_t item)
{
int32_t p;
float aux_key;
int32_t aux_item;
if(key>A->key[i])
{
printf("New key is larger than current key\n");
exit(0);
}
A->key[i]=key;
A->item[i]=item;
p=parent(i);
while(i>0 && A->key[p]>A->key[i])
{
aux_key=A->key[i];
A->key[i]=A->key[p];
A->key[p]=aux_key;
aux_item=A->item[i];
A->item[i]=A->item[p];
A->item[p]=aux_item;
i=p;
p=parent(i);
}
}
void heap_extract_min(struct HEAP *A, float *key, int32_t *item)
{
if(A->m<1)
{
printf("Heap underflow\n");
exit(0);
}
*key=A->key[0];
*item=A->item[0];
A->key[0]=A->key[A->m-1];
A->item[0]=A->item[A->m-1];
A->m--;
min_heapify(A,0);
}
void min_heapify(struct HEAP *A,int32_t i)
{
int32_t l;
int32_t r;
int32_t smallest;
float aux_key;
int32_t aux_item;
l=left(i);
r=right(i);
if(l<A->m && A->key[l]<A->key[i])
{
smallest=l;
}
else
{
smallest=i;
}
if(r<A->m && A->key[r]<A->key[smallest])
{
smallest=r;
}
if(smallest!=i)
{
aux_key=A->key[i];
A->key[i]=A->key[smallest];
A->key[smallest]=aux_key;
aux_item=A->item[i];
A->item[i]=A->item[smallest];
A->item[smallest]=aux_item;
min_heapify(A,smallest);
}
}
void set_free(struct SYSTEM *S)
{
free(S->H->item);
free(S->H->key);
free(S->H);
free(S->status);
free(S->burner->key);
free(S->burner);
free(S->check);
free(S->stalker->key);
free(S->stalker);
free(S->sink->key);
free(S->sink);
free(S->sigma);
free(S->L->nei->JV);
free(S->L->nei->IV);
free(S->L->nei);
free(S->L->h);
free(S->L);
free(S);
}
|
oliverkurth/pmd
|
privsep/netmgmtrpcapi.c
|
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
unsigned32
netmgr_privsep_rpc_get_version(
handle_t hBinding,
wstring_t* ppwszVersion
)
{
uint32_t dwError = 0;
const char* pszVersion = NULL;
wstring_t pwszVersion = NULL;
if(!hBinding || !ppwszVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
pszVersion = PACKAGE_VERSION;
if(IsNullOrEmptyString(pszVersion))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDRpcServerAllocateWFromA(pszVersion, &pwszVersion);
BAIL_ON_PMD_ERROR(dwError);
*ppwszVersion = pwszVersion;
cleanup:
return dwError;
error:
if(ppwszVersion)
{
*ppwszVersion = NULL;
}
PMD_SAFE_FREE_MEMORY(pwszVersion);
goto cleanup;
}
/*
* Interface configuration APIs
*/
unsigned32
netmgr_privsep_rpc_set_mac_addr(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszMacAddress
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
char *pszMacAddr = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pwszMacAddress)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
if (pwszMacAddress)
{
dwError = PMDAllocateStringAFromW(pwszMacAddress, &pszMacAddr);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_set_link_mac_addr(pszIfName, pszMacAddr);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszMacAddr);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_mac_addr(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t *ppwszMacAddress
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
char *pszMacAddr = NULL;
wstring_t pwszMacAddress = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !ppwszMacAddress)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_link_mac_addr(pszIfName, &pszMacAddr);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(pszMacAddr, &pwszMacAddress);
BAIL_ON_PMD_ERROR(dwError);
*ppwszMacAddress = pwszMacAddress;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
if (pszMacAddr != NULL)
{
free(pszMacAddr);
}
return dwError;
error:
if (ppwszMacAddress)
{
ppwszMacAddress = NULL;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_link_mode(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_LINK_MODE linkMode
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_set_link_mode(pszIfName, linkMode);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_link_mode(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_LINK_MODE *pLinkMode
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
NET_LINK_MODE linkMode;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pLinkMode)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_link_mode(pszIfName, &linkMode);
BAIL_ON_PMD_ERROR(dwError);
*pLinkMode = linkMode;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (pLinkMode)
{
*pLinkMode = RPC_LINK_MODE_UNKNOWN;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_link_mtu(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 mtu
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_set_link_mtu(pszIfName, mtu);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_link_mtu(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 *pMtu
)
{
uint32_t dwError = 0, mtu;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pMtu)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_link_mtu(pszIfName, &mtu);
BAIL_ON_PMD_ERROR(dwError);
*pMtu = mtu;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (pMtu)
{
*pMtu = 0;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_link_state(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_LINK_STATE linkState
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_set_link_state(pszIfName, linkState);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_link_state(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_LINK_STATE *pLinkState
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
NET_LINK_STATE linkState;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pLinkState)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_link_state(pszIfName, &linkState);
BAIL_ON_PMD_ERROR(dwError);
*pLinkState = linkState;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (pLinkState)
{
*pLinkState = RPC_LINK_STATE_UNKNOWN;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_ifup(
handle_t hBinding,
wstring_t pwszInterfaceName
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_ifup(pszIfName);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_ifdown(
handle_t hBinding,
wstring_t pwszInterfaceName
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_ifdown(pszIfName);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_link_info(
handle_t hBinding,
wstring_t pwszInterfaceName,
PNET_RPC_LINK_INFO_ARRAY *ppLinkInfoArray
)
{
uint32_t dwError = 0, dwCount = 0, i = 0;
char *pszIfName = NULL;
NET_LINK_INFO *pLinkInfo = NULL, *cur;
PNET_RPC_LINK_INFO_ARRAY pLinkInfoArray = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppLinkInfoArray)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_link_info(pszIfName, &pLinkInfo);
BAIL_ON_PMD_ERROR(dwError);
for (cur = pLinkInfo; cur; cur = cur->pNext, dwCount++);
dwError = PMDRpcServerAllocateMemory(sizeof(NET_RPC_LINK_INFO_ARRAY),
(void **)&pLinkInfoArray);
BAIL_ON_PMD_ERROR(dwError);
pLinkInfoArray->dwCount = dwCount;
if (dwCount)
{
dwError = PMDRpcServerAllocateMemory(
dwCount * sizeof(NET_RPC_LINK_INFO),
(void**)&pLinkInfoArray->pRpcLinkInfo);
BAIL_ON_PMD_ERROR(dwError);
for (cur = pLinkInfo; cur; cur = cur->pNext, i++)
{
dwError = PMDAllocateStringWFromA(cur->pszInterfaceName,
&pLinkInfoArray->pRpcLinkInfo[i].pwszInterfaceName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringWFromA(cur->pszMacAddress,
&pLinkInfoArray->pRpcLinkInfo[i].pwszMacAddress);
BAIL_ON_PMD_ERROR(dwError);
pLinkInfoArray->pRpcLinkInfo[i].mtu = cur->mtu;
pLinkInfoArray->pRpcLinkInfo[i].mode =
(NET_RPC_LINK_MODE)cur->mode;
pLinkInfoArray->pRpcLinkInfo[i].state =
(NET_RPC_LINK_STATE)cur->state;
}
}
*ppLinkInfoArray = pLinkInfoArray;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
nm_free_link_info(pLinkInfo);
return dwError;
error:
if (ppLinkInfoArray)
{
*ppLinkInfoArray = NULL;
}
if (pLinkInfoArray && pLinkInfoArray->pRpcLinkInfo)
{
for (i = 0; i < dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(
pLinkInfoArray->pRpcLinkInfo[i].pwszInterfaceName);
PMD_SAFE_FREE_MEMORY(
pLinkInfoArray->pRpcLinkInfo[i].pwszMacAddress);
}
PMD_SAFE_FREE_MEMORY(pLinkInfoArray->pRpcLinkInfo);
}
PMD_SAFE_FREE_MEMORY(pLinkInfoArray);
goto cleanup;
}
/*
* IP Address configuration APIs
*/
unsigned32
netmgr_privsep_rpc_set_ipv4_addr_gateway(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_IPV4_ADDR_MODE mode,
wstring_t pwszIPv4AddrPrefix,
wstring_t pwszIPv4Gateway
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
char *pszIPv4AddrPrefix = NULL;
char *pszIPv4Gateway = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
if (pwszIPv4AddrPrefix)
{
dwError = PMDAllocateStringAFromW(pwszIPv4AddrPrefix,
&pszIPv4AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszIPv4Gateway)
{
dwError = PMDAllocateStringAFromW(pwszIPv4Gateway, &pszIPv4Gateway);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_set_ipv4_addr_gateway(pszIfName,
mode,
pszIPv4AddrPrefix,
pszIPv4Gateway);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszIPv4AddrPrefix);
PMD_SAFE_FREE_MEMORY(pszIPv4Gateway);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_ipv4_addr_gateway(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_IPV4_ADDR_MODE *pMode,
wstring_t *ppwszIPv4AddrPrefix,
wstring_t *ppwszIPv4Gateway
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
NET_IPV4_ADDR_MODE mode;
char *pszIPv4AddrPrefix = NULL, *pszIPv4Gateway = NULL;
wstring_t pwszIPv4AddrPrefix = NULL, pwszIPv4Gateway = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pMode || !ppwszIPv4AddrPrefix ||
!ppwszIPv4Gateway)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_get_ipv4_addr_gateway(pszIfName,
&mode,
&pszIPv4AddrPrefix,
&pszIPv4Gateway);
BAIL_ON_PMD_ERROR(dwError);
if (pszIPv4AddrPrefix)
{
dwError = PMDRpcServerAllocateWFromA(pszIPv4AddrPrefix,
&pwszIPv4AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
}
if (pszIPv4Gateway)
{
dwError = PMDRpcServerAllocateWFromA(pszIPv4Gateway, &pwszIPv4Gateway);
BAIL_ON_PMD_ERROR(dwError);
}
*pMode = mode;
*ppwszIPv4AddrPrefix = pwszIPv4AddrPrefix;
*ppwszIPv4Gateway = pwszIPv4Gateway;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
free(pszIPv4AddrPrefix);
free(pszIPv4Gateway);
return dwError;
error:
if (pMode)
{
*pMode = RPC_IPV4_ADDR_MODE_NONE;
}
if (ppwszIPv4AddrPrefix)
{
*ppwszIPv4AddrPrefix = NULL;
}
if (ppwszIPv4Gateway)
{
*ppwszIPv4Gateway = NULL;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_add_static_ipv6_addr(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszIPv6AddrPrefix
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
char *pszIPv6AddrPrefix = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pwszIPv6AddrPrefix)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pwszIPv6AddrPrefix, &pszIPv6AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_add_static_ipv6_addr(pszIfName, pszIPv6AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszIPv6AddrPrefix);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_delete_static_ipv6_addr(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszIPv6AddrPrefix
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
char *pszIPv6AddrPrefix = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pwszIPv6AddrPrefix)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pwszIPv6AddrPrefix, &pszIPv6AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_delete_static_ipv6_addr(pszIfName, pszIPv6AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszIPv6AddrPrefix);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_ipv6_addr_mode(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 enableDhcp,
unsigned32 enableAutoconf
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_set_ipv6_addr_mode(pszIfName, enableDhcp, enableAutoconf);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_ipv6_addr_mode(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 *pDhcpEnabled,
unsigned32 *pAutoconfEnabled
)
{
uint32_t dwError = 0, dhcpEnabled, autoconfEnabled;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_get_ipv6_addr_mode(pszIfName, &dhcpEnabled, &autoconfEnabled);
BAIL_ON_PMD_ERROR(dwError);
if (pDhcpEnabled)
{
*pDhcpEnabled = dhcpEnabled;
}
if (pAutoconfEnabled)
{
*pAutoconfEnabled = autoconfEnabled;
}
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (pDhcpEnabled)
{
*pDhcpEnabled = 0;
}
if (pAutoconfEnabled)
{
*pAutoconfEnabled = 0;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_ipv6_gateway(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszIPv6Gateway
)
{
uint32_t dwError = 0;
char *pszIfName = NULL, *pszIPv6Gateway = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
if (pwszIPv6Gateway)
{
dwError = PMDAllocateStringAFromW(pwszIPv6Gateway, &pszIPv6Gateway);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_set_ipv6_gateway(pszIfName, pszIPv6Gateway);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszIPv6Gateway);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_ipv6_gateway(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t *ppwszIPv6Gateway
)
{
uint32_t dwError = 0;
char *pszIfName = NULL, *pszIPv6Gateway = NULL;
wstring_t pwszIPv6Gateway = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !ppwszIPv6Gateway)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_get_ipv6_gateway(pszIfName, &pszIPv6Gateway);
BAIL_ON_PMD_ERROR(dwError);
if (pszIPv6Gateway)
{
dwError = PMDAllocateStringWFromA(pszIPv6Gateway, &pwszIPv6Gateway);
BAIL_ON_PMD_ERROR(dwError);
}
*ppwszIPv6Gateway = pwszIPv6Gateway;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
free(pszIPv6Gateway);
return dwError;
error:
if (ppwszIPv6Gateway)
{
*ppwszIPv6Gateway = NULL;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_ip_addr(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 addrTypes,
NET_RPC_IP_ADDR_ARRAY **ppIpAddrArray
)
{
uint32_t dwError = 0;
size_t i, dwCount = 0;
char *pszIfName = NULL;
NET_IP_ADDR **ppIpAddrList = NULL;
NET_RPC_IP_ADDR_ARRAY *pIpAddrArray = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppIpAddrArray)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_ip_addr(pszIfName, addrTypes, &dwCount, &ppIpAddrList);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateMemory(sizeof(NET_RPC_IP_ADDR_ARRAY),
(void **)&pIpAddrArray);
BAIL_ON_PMD_ERROR(dwError);
pIpAddrArray->dwCount = dwCount;
if (dwCount)
{
dwError = PMDRpcServerAllocateMemory(dwCount * sizeof(NET_RPC_IP_ADDR),
(void**)&pIpAddrArray->pRpcIpAddr);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < dwCount; i++)
{
dwError = PMDAllocateStringWFromA(ppIpAddrList[i]->pszInterfaceName,
&pIpAddrArray->pRpcIpAddr[i].pwszInterfaceName);
BAIL_ON_PMD_ERROR(dwError);
pIpAddrArray->pRpcIpAddr[i].type = (NET_RPC_ADDR_TYPE)
ppIpAddrList[i]->type;
dwError = PMDAllocateStringWFromA(ppIpAddrList[i]->pszIPAddrPrefix,
&pIpAddrArray->pRpcIpAddr[i].pwszIPAddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
}
}
*ppIpAddrArray = pIpAddrArray;
cleanup:
for (i = 0; i < dwCount; i++)
{
free(ppIpAddrList[i]->pszInterfaceName);
free(ppIpAddrList[i]->pszIPAddrPrefix);
free(ppIpAddrList[i]);
}
free(ppIpAddrList);
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (ppIpAddrArray)
{
*ppIpAddrArray = NULL;
}
if (pIpAddrArray && pIpAddrArray->pRpcIpAddr)
{
for (i = 0; i < pIpAddrArray->dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(
pIpAddrArray->pRpcIpAddr[i].pwszInterfaceName);
PMD_SAFE_FREE_MEMORY(
pIpAddrArray->pRpcIpAddr[i].pwszIPAddrPrefix);
}
PMD_SAFE_FREE_MEMORY(pIpAddrArray->pRpcIpAddr);
}
PMD_SAFE_FREE_MEMORY(pIpAddrArray);
goto cleanup;
}
/*
* Route configuration APIs
*/
unsigned32
netmgr_privsep_rpc_add_static_ip_route(
handle_t hBinding,
NET_RPC_IP_ROUTE *pIpRoute
)
{
uint32_t dwError = 0;
NET_IP_ROUTE ipRoute = {0};
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pIpRoute)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pIpRoute->pwszInterfaceName,
&ipRoute.pszInterfaceName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pIpRoute->pwszDestNetwork,
&ipRoute.pszDestNetwork);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pIpRoute->pwszGateway,
&ipRoute.pszGateway);
BAIL_ON_PMD_ERROR(dwError);
if (pIpRoute->pwszSourceNetwork)
{
dwError = PMDAllocateStringAFromW(pIpRoute->pwszSourceNetwork,
&ipRoute.pszSourceNetwork);
BAIL_ON_PMD_ERROR(dwError);
}
ipRoute.scope = (NET_ROUTE_SCOPE)pIpRoute->scope;
ipRoute.metric = pIpRoute->dwMetric;
ipRoute.table = pIpRoute->dwTableId;
dwError = nm_add_static_ip_route(&ipRoute);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(ipRoute.pszInterfaceName);
PMD_SAFE_FREE_MEMORY(ipRoute.pszDestNetwork);
PMD_SAFE_FREE_MEMORY(ipRoute.pszSourceNetwork);
PMD_SAFE_FREE_MEMORY(ipRoute.pszGateway);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_delete_static_ip_route(
handle_t hBinding,
NET_RPC_IP_ROUTE *pIpRoute
)
{
uint32_t dwError = 0;
NET_IP_ROUTE ipRoute = {0};
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pIpRoute)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pIpRoute->pwszInterfaceName,
&ipRoute.pszInterfaceName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pIpRoute->pwszDestNetwork,
&ipRoute.pszDestNetwork);
BAIL_ON_PMD_ERROR(dwError);
if (pIpRoute->pwszGateway)
{
dwError = PMDAllocateStringAFromW(pIpRoute->pwszGateway,
&ipRoute.pszGateway);
BAIL_ON_PMD_ERROR(dwError);
}
if (pIpRoute->pwszSourceNetwork)
{
dwError = PMDAllocateStringAFromW(pIpRoute->pwszSourceNetwork,
&ipRoute.pszSourceNetwork);
BAIL_ON_PMD_ERROR(dwError);
}
ipRoute.scope = (NET_ROUTE_SCOPE)pIpRoute->scope;
ipRoute.metric = pIpRoute->dwMetric;
ipRoute.table = pIpRoute->dwTableId;
dwError = nm_delete_static_ip_route(&ipRoute);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(ipRoute.pszInterfaceName);
PMD_SAFE_FREE_MEMORY(ipRoute.pszDestNetwork);
PMD_SAFE_FREE_MEMORY(ipRoute.pszSourceNetwork);
PMD_SAFE_FREE_MEMORY(ipRoute.pszGateway);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_static_ip_routes(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_IP_ROUTE_ARRAY **ppIpRouteArray
)
{
uint32_t dwError = 0;
size_t i, dwCount = 0;
char *pszIfName = NULL;
NET_IP_ROUTE **ppRoutesList = NULL;
NET_RPC_IP_ROUTE_ARRAY *pIpRouteArray = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppIpRouteArray)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_static_ip_routes(pszIfName, &dwCount, &ppRoutesList);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateMemory(sizeof(NET_RPC_IP_ROUTE_ARRAY),
(void **)&pIpRouteArray);
BAIL_ON_PMD_ERROR(dwError);
pIpRouteArray->dwCount = dwCount;
if (dwCount)
{
dwError = PMDRpcServerAllocateMemory(
dwCount * sizeof(NET_RPC_IP_ROUTE),
(void**)&pIpRouteArray->pRpcIpRoute);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < dwCount; i++)
{
dwError = PMDAllocateStringWFromA(ppRoutesList[i]->pszInterfaceName,
&pIpRouteArray->pRpcIpRoute[i].pwszInterfaceName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringWFromA(ppRoutesList[i]->pszDestNetwork,
&pIpRouteArray->pRpcIpRoute[i].pwszDestNetwork);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringWFromA(ppRoutesList[i]->pszGateway,
&pIpRouteArray->pRpcIpRoute[i].pwszGateway);
BAIL_ON_PMD_ERROR(dwError);
if (ppRoutesList[i]->pszSourceNetwork)
{
dwError = PMDAllocateStringWFromA(
ppRoutesList[i]->pszSourceNetwork,
&pIpRouteArray->pRpcIpRoute[i].pwszSourceNetwork);
BAIL_ON_PMD_ERROR(dwError);
}
pIpRouteArray->pRpcIpRoute[i].scope = (NET_RPC_ROUTE_SCOPE)
ppRoutesList[i]->scope;
pIpRouteArray->pRpcIpRoute[i].dwMetric = ppRoutesList[i]->metric;
pIpRouteArray->pRpcIpRoute[i].dwTableId = ppRoutesList[i]->table;
}
}
*ppIpRouteArray = pIpRouteArray;
cleanup:
for (i = 0; i < dwCount; i++)
{
free(ppRoutesList[i]->pszInterfaceName);
free(ppRoutesList[i]->pszDestNetwork);
free(ppRoutesList[i]->pszSourceNetwork);
free(ppRoutesList[i]->pszGateway);
free(ppRoutesList[i]);
}
free(ppRoutesList);
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (ppIpRouteArray)
{
*ppIpRouteArray = NULL;
}
if (pIpRouteArray && pIpRouteArray->pRpcIpRoute)
{
for (i = 0; i < pIpRouteArray->dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(
pIpRouteArray->pRpcIpRoute[i].pwszInterfaceName);
PMD_SAFE_FREE_MEMORY(
pIpRouteArray->pRpcIpRoute[i].pwszDestNetwork);
PMD_SAFE_FREE_MEMORY(
pIpRouteArray->pRpcIpRoute[i].pwszSourceNetwork);
PMD_SAFE_FREE_MEMORY(
pIpRouteArray->pRpcIpRoute[i].pwszGateway);
}
PMD_SAFE_FREE_MEMORY(pIpRouteArray->pRpcIpRoute);
}
PMD_SAFE_FREE_MEMORY(pIpRouteArray);
goto cleanup;
}
/*
* DNS configuration APIs
*/
unsigned32
netmgr_privsep_rpc_add_dns_server(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszDnsServer
)
{
uint32_t i, dwError = 0;
char *pszIfName = NULL;
char *pszDnsServer = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszDnsServer)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszDnsServer, &pszDnsServer);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_add_dns_server(pszIfName, pszDnsServer);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszDnsServer);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_delete_dns_server(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszDnsServer
)
{
uint32_t i, dwError = 0;
char *pszIfName = NULL;
char *pszDnsServer = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszDnsServer)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszDnsServer, &pszDnsServer);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_delete_dns_server(pszIfName, pszDnsServer);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszDnsServer);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_dns_servers(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_DNS_MODE dwMode,
PPMD_WSTRING_ARRAY pwszDnsServers
)
{
uint32_t i, dwError = 0;
char *pszIfName = NULL;
char **ppszDnsServers = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszDnsServers)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszDnsServers->dwCount)
{
dwError = PMDAllocateMemory(sizeof(char *) * pwszDnsServers->dwCount,
(void **)&ppszDnsServers);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < pwszDnsServers->dwCount; ++i)
{
dwError = PMDAllocateStringAFromW(pwszDnsServers->ppwszStrings[i],
&ppszDnsServers[i]);
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = nm_set_dns_servers(pszIfName,
dwMode,
pwszDnsServers->dwCount,
(const char **)ppszDnsServers);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
if ((pwszDnsServers != NULL) && (ppszDnsServers != NULL))
{
for (i = 0; i < pwszDnsServers->dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(ppszDnsServers[i]);
}
PMD_SAFE_FREE_MEMORY(ppszDnsServers);
}
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_dns_servers(
handle_t hBinding,
wstring_t pwszInterfaceName,
NET_RPC_DNS_MODE *pdwMode,
PPMD_WSTRING_ARRAY *ppwszDnsServers
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
NET_DNS_MODE mode;
size_t i, bytes = 0, count = 0;
char **ppszDnsServers = NULL, *pszDnsServers = NULL;
PPMD_WSTRING_ARRAY pwszDnsServers = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pdwMode || !ppwszDnsServers)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_dns_servers(pszIfName,
&mode,
&count,
&ppszDnsServers);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateMemory(sizeof(PMD_WSTRING_ARRAY),
(void **)&pwszDnsServers);
BAIL_ON_PMD_ERROR(dwError);
if (count > 0)
{
dwError = PMDRpcServerAllocateMemory(sizeof(wstring_t) * count,
(void **)&pwszDnsServers->ppwszStrings);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < count; i++)
{
dwError = PMDRpcServerAllocateWFromA(ppszDnsServers[i],
&pwszDnsServers->ppwszStrings[i]);
BAIL_ON_PMD_ERROR(dwError);
}
pwszDnsServers->dwCount = count;
}
*pdwMode = mode;
*ppwszDnsServers = pwszDnsServers;
cleanup:
PMDFreeStringArrayWithCount(ppszDnsServers, count);
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (pdwMode)
{
*pdwMode = RPC_DNS_MODE_INVALID;
}
if (ppwszDnsServers)
{
*ppwszDnsServers = NULL;
}
if (pwszDnsServers != NULL)
{
for (i = 0; i < pwszDnsServers->dwCount; i++)
{
PMDRpcServerFreeMemory(pwszDnsServers->ppwszStrings[i]);
}
PMDRpcServerFreeMemory(pwszDnsServers->ppwszStrings);
PMDRpcServerFreeMemory(pwszDnsServers);
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_add_dns_domain(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszDnsDomain
)
{
uint32_t i, dwError = 0;
char *pszIfName = NULL;
char *pszDnsDomain = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszDnsDomain)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszDnsDomain, &pszDnsDomain);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_add_dns_domain(pszIfName,
pszDnsDomain);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_delete_dns_domain(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszDnsDomain
)
{
uint32_t i, dwError = 0;
char *pszIfName = NULL;
char *pszDnsDomain = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszDnsDomain)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszDnsDomain, &pszDnsDomain);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_delete_dns_domain(pszIfName, pszDnsDomain);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_dns_domains(
handle_t hBinding,
wstring_t pwszInterfaceName,
PPMD_WSTRING_ARRAY pwszDnsDomains
)
{
uint32_t i, dwError = 0;
char *pszIfName = NULL;
char **ppszDnsDomains = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszDnsDomains)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszDnsDomains->dwCount)
{
dwError = PMDAllocateMemory(sizeof(char *) * pwszDnsDomains->dwCount,
(void **)&ppszDnsDomains);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < pwszDnsDomains->dwCount; ++i)
{
dwError = PMDAllocateStringAFromW(pwszDnsDomains->ppwszStrings[i],
&ppszDnsDomains[i]);
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = nm_set_dns_domains(pszIfName,
pwszDnsDomains->dwCount,
(const char **)ppszDnsDomains);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
if ((pwszDnsDomains != NULL) && (ppszDnsDomains != NULL))
{
for (i = 0; i < pwszDnsDomains->dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(ppszDnsDomains[i]);
}
PMD_SAFE_FREE_MEMORY(ppszDnsDomains);
}
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_dns_domains(
handle_t hBinding,
wstring_t pwszInterfaceName,
PPMD_WSTRING_ARRAY *ppwszDnsDomains
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
size_t i, bytes = 0, count = 0;
char **ppszDnsDomains = NULL;
PPMD_WSTRING_ARRAY pwszDnsDomains = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppwszDnsDomains)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_dns_domains(pszIfName, &count, &ppszDnsDomains);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateMemory(sizeof(PMD_WSTRING_ARRAY),
(void **)&pwszDnsDomains);
BAIL_ON_PMD_ERROR(dwError);
if (count > 0)
{
dwError = PMDRpcServerAllocateMemory(sizeof(wstring_t) * count,
(void **)&pwszDnsDomains->ppwszStrings);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < count; i++)
{
dwError = PMDRpcServerAllocateWFromA(ppszDnsDomains[i],
&pwszDnsDomains->ppwszStrings[i]);
BAIL_ON_PMD_ERROR(dwError);
}
pwszDnsDomains->dwCount = count;
}
*ppwszDnsDomains = pwszDnsDomains;
cleanup:
for (i = 0; i < count; i++)
{
free(ppszDnsDomains[i]);
}
free(ppszDnsDomains);
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (ppwszDnsDomains)
{
*ppwszDnsDomains = NULL;
}
if (pwszDnsDomains != NULL)
{
for (i = 0; i < pwszDnsDomains->dwCount; i++)
{
PMDRpcServerFreeMemory(pwszDnsDomains->ppwszStrings[i]);
}
PMDRpcServerFreeMemory(pwszDnsDomains->ppwszStrings);
PMDRpcServerFreeMemory(pwszDnsDomains);
}
goto cleanup;
}
/*
* DHCP options, DUID, IAID configuration APIs
*/
unsigned32
netmgr_privsep_rpc_set_iaid(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 dwIaid
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_set_iaid(pszIfName, (uint32_t)dwIaid);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_iaid(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 *pdwIaid
)
{
uint32_t dwError = 0, iaid = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName || !pdwIaid)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_get_iaid(pszIfName, &iaid);
BAIL_ON_PMD_ERROR(dwError);
*pdwIaid = (unsigned32)iaid;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
if (pdwIaid)
{
*pdwIaid = 0;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_duid(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t pwszDuid
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
char *pszDuid = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszDuid)
{
dwError = PMDAllocateStringAFromW(pwszDuid, &pszDuid);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_set_duid(pszIfName, pszDuid);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
PMD_SAFE_FREE_MEMORY(pszDuid);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_duid(
handle_t hBinding,
wstring_t pwszInterfaceName,
wstring_t *ppwszDuid
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
char *pszDuid = NULL;
wstring_t pwszDuid = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppwszDuid)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszInterfaceName)
{
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_duid(pszIfName, &pszDuid);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(pszDuid, &pwszDuid);
BAIL_ON_PMD_ERROR(dwError);
*ppwszDuid = pwszDuid;
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
if (pszDuid != NULL)
{
free(pszDuid);
}
return dwError;
error:
if (ppwszDuid)
{
ppwszDuid = NULL;
}
goto cleanup;
}
uint32_t
netmgr_privsep_rpc_set_ntp_servers(
handle_t hBinding,
PPMD_WSTRING_ARRAY pwszNtpServers
)
{
uint32_t dwError = 0;
char **ppszNtpServers = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszNtpServers)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszNtpServers->dwCount)
{
size_t i = 0;
dwError = PMDAllocateMemory(
sizeof(char *) * pwszNtpServers->dwCount + 1,
(void **)&ppszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < pwszNtpServers->dwCount; ++i)
{
dwError = PMDAllocateStringAFromW(pwszNtpServers->ppwszStrings[i],
&ppszNtpServers[i]);
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = nm_set_ntp_servers(pwszNtpServers->dwCount,
(const char **)ppszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArray(ppszNtpServers);
return dwError;
error:
goto cleanup;
}
uint32_t
netmgr_privsep_rpc_add_ntp_servers(
handle_t hBinding,
PPMD_WSTRING_ARRAY pwszNtpServers
)
{
uint32_t dwError = 0;
char **ppszNtpServers = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszNtpServers)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszNtpServers->dwCount)
{
size_t i = 0;
dwError = PMDAllocateMemory(
sizeof(char *) * pwszNtpServers->dwCount + 1,
(void **)&ppszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < pwszNtpServers->dwCount; ++i)
{
dwError = PMDAllocateStringAFromW(pwszNtpServers->ppwszStrings[i],
&ppszNtpServers[i]);
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = nm_add_ntp_servers(pwszNtpServers->dwCount,
(const char **)ppszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArray(ppszNtpServers);
return dwError;
error:
goto cleanup;
}
uint32_t
netmgr_privsep_rpc_delete_ntp_servers(
handle_t hBinding,
PPMD_WSTRING_ARRAY pwszNtpServers
)
{
uint32_t dwError = 0;
char **ppszNtpServers = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszNtpServers)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pwszNtpServers->dwCount)
{
size_t i = 0;
dwError = PMDAllocateMemory(
sizeof(char *) * pwszNtpServers->dwCount + 1,
(void **)&ppszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < pwszNtpServers->dwCount; ++i)
{
dwError = PMDAllocateStringAFromW(pwszNtpServers->ppwszStrings[i],
&ppszNtpServers[i]);
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = nm_delete_ntp_servers(pwszNtpServers->dwCount,
(const char **)ppszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArray(ppszNtpServers);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_ntp_servers(
handle_t hBinding,
PPMD_WSTRING_ARRAY *ppwszNtpServers
)
{
uint32_t dwError = 0;
size_t nCount = 0;
char **ppszNtpServers = NULL;
PPMD_WSTRING_ARRAY pwszNtpServers = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppwszNtpServers)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_ntp_servers(&nCount, &ppszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateMemory(sizeof(PMD_WSTRING_ARRAY),
(void **)&pwszNtpServers);
BAIL_ON_PMD_ERROR(dwError);
if (nCount > 0)
{
int i = 0;
dwError = PMDRpcServerAllocateMemory(
sizeof(wstring_t) * nCount,
(void **)&pwszNtpServers->ppwszStrings);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < nCount; i++)
{
dwError = PMDRpcServerAllocateWFromA(
ppszNtpServers[i],
&pwszNtpServers->ppwszStrings[i]);
BAIL_ON_PMD_ERROR(dwError);
}
pwszNtpServers->dwCount = nCount;
}
*ppwszNtpServers = pwszNtpServers;
cleanup:
PMDFreeStringArrayWithCount(ppszNtpServers, nCount);
return dwError;
error:
if (ppwszNtpServers)
{
*ppwszNtpServers = NULL;
}
if (pwszNtpServers != NULL)
{
int i = 0;
for (i = 0; i < pwszNtpServers->dwCount; i++)
{
PMDRpcServerFreeMemory(pwszNtpServers->ppwszStrings[i]);
}
PMDRpcServerFreeMemory(pwszNtpServers->ppwszStrings);
PMDRpcServerFreeMemory(pwszNtpServers);
}
goto cleanup;
}
/*
* Misc APIs
*/
unsigned32
netmgr_privsep_rpc_set_hostname(
handle_t hBinding,
wstring_t pwszHostname
)
{
uint32_t dwError = 0;
char *pszHostname = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszHostname)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszHostname, &pszHostname);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_set_hostname(pszHostname);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszHostname);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_hostname(
handle_t hBinding,
wstring_t *ppwszHostname
)
{
uint32_t dwError = 0;
char *pszHostname = NULL;
wstring_t pwszHostname = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppwszHostname)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_get_hostname(&pszHostname);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(pszHostname, &pwszHostname);
BAIL_ON_PMD_ERROR(dwError);
*ppwszHostname = pwszHostname;
cleanup:
if (pszHostname != NULL)
{
free(pszHostname);
}
return dwError;
error:
if (ppwszHostname)
{
ppwszHostname = NULL;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_wait_for_link_up(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 dwTimeout
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_wait_for_link_up(pszIfName, (uint32_t)dwTimeout);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_wait_for_ip(
handle_t hBinding,
wstring_t pwszInterfaceName,
unsigned32 dwTimeout,
NET_RPC_ADDR_TYPE dwAddrTypes
)
{
uint32_t dwError = 0;
char *pszIfName = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszInterfaceName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszInterfaceName, &pszIfName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_wait_for_ip(pszIfName,
(uint32_t)dwTimeout,
(NET_ADDR_TYPE)dwAddrTypes);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszIfName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_error_info(
handle_t hBinding,
unsigned32 nmErrCode,
wstring_t *ppwszErrInfo
)
{
uint32_t dwError = 0;
const char *pszErrInfo = NULL;
wstring_t pwszErrInfo = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!ppwszErrInfo)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszErrInfo = nm_get_error_info(nmErrCode);
if (pszErrInfo == NULL)
{
dwError = ERROR_PMD_NO_DATA;
}
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(pszErrInfo, &pwszErrInfo);
BAIL_ON_PMD_ERROR(dwError);
*ppwszErrInfo = pwszErrInfo;
cleanup:
return dwError;
error:
if (ppwszErrInfo)
{
ppwszErrInfo = NULL;
}
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_set_network_param(
handle_t hBinding,
wstring_t pwszObjectName,
wstring_t pwszParamName,
wstring_t pwszParamValue
)
{
uint32_t dwError = 0;
char *pszObjectName = NULL, *pszParamName = NULL, *pszParamValue = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszObjectName || !pwszParamName)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszObjectName, &pszObjectName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pwszParamName, &pszParamName);
BAIL_ON_PMD_ERROR(dwError);
if (pwszParamValue)
{
dwError = PMDAllocateStringAFromW(pwszParamValue, &pszParamValue);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = nm_set_network_param(pszObjectName, pszParamName, pszParamValue);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMD_SAFE_FREE_MEMORY(pszParamValue);
PMD_SAFE_FREE_MEMORY(pszParamName);
PMD_SAFE_FREE_MEMORY(pszObjectName);
return dwError;
error:
goto cleanup;
}
unsigned32
netmgr_privsep_rpc_get_network_param(
handle_t hBinding,
wstring_t pwszObjectName,
wstring_t pwszParamName,
wstring_t *ppwszParamValue
)
{
uint32_t dwError = 0;
char *pszObjectName = NULL, *pszParamName = NULL, *pszParamValue = NULL;
wstring_t pwszParamValue = NULL;
dwError = check_connection_integrity(hBinding);
BAIL_ON_PMD_ERROR(dwError);
if (!pwszObjectName || !pwszParamName || !ppwszParamValue)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszObjectName, &pszObjectName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pwszParamName, &pszParamName);
BAIL_ON_PMD_ERROR(dwError);
dwError = nm_get_network_param(pszObjectName, pszParamName, &pszParamValue);
BAIL_ON_PMD_ERROR(dwError);
if (pszParamValue)
{
dwError = PMDAllocateStringWFromA(pszParamValue, &pwszParamValue);
BAIL_ON_PMD_ERROR(dwError);
}
*ppwszParamValue = pwszParamValue;
cleanup:
if (pszParamValue != NULL)
{
free(pszParamValue);
}
PMD_SAFE_FREE_MEMORY(pszParamName);
PMD_SAFE_FREE_MEMORY(pszObjectName);
return dwError;
error:
if (ppwszParamValue)
{
ppwszParamValue = NULL;
}
goto cleanup;
}
|
oliverkurth/pmd
|
server/rolemgmt/rolemgmt_restapi.c
|
<reponame>oliverkurth/pmd
/*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
REST_MODULE _rolemgmt_rest_module[] =
{
{
"/v1/rolemgmt/version",
{
rolemgmt_rest_get_version,
NULL,
NULL,
NULL
}
},
{
"/v1/rolemgmt/role/version",
{
rolemgmt_rest_get_roleversion,
NULL,
NULL,
NULL
}
},
{
"/v1/rolemgmt/roles",
{
rolemgmt_rest_get_roles,
NULL,
NULL,
NULL
}
},
{
"/v1/rolemgmt/role/status",
{
rolemgmt_rest_get_status,
NULL,
NULL,
NULL
}
},
{
"/v1/rolemgmt/role/logs",
{
rolemgmt_rest_get_logs,
NULL,
NULL,
NULL
}
},
{
"/v1/rolemgmt/role/alter",
{
NULL,
rolemgmt_rest_alter_put,
NULL,
rolemgmt_rest_alter_delete,
rolemgmt_rest_alter_patch
}
},
{0}
};
uint32_t
rolemgmt_rest_get_registration(
PREST_MODULE *ppRestModule
)
{
uint32_t dwError = 0;
if(!ppRestModule)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
*ppRestModule = _rolemgmt_rest_module;
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
rolemgmt_rest_get_version(
void *pInputJson,
void **ppszOutputJson
)
{
uint32_t dwError = 0;
char *pszVersion = NULL;
char *pszOutputJson = NULL;
PKEYVALUE pKeyValue = NULL;
if(!ppszOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pmd_rolemgmt_get_version(&pszVersion);
BAIL_ON_PMD_ERROR(dwError);
dwError = make_keyvalue("version", pszVersion, &pKeyValue);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_string(pKeyValue, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppszOutputJson = pszOutputJson;
cleanup:
PMD_SAFE_FREE_MEMORY(pszVersion);
if(pKeyValue)
{
free_keyvalue(pKeyValue);
}
return dwError;
error:
if(ppszOutputJson)
{
*ppszOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
rolemgmt_rest_get_roleversion(
void *pInputJson,
void **ppszOutputJson
)
{
uint32_t dwError = 0;
char *pszName = NULL;
char *pszVersion = NULL;
char *pszOutputJson = NULL;
PKEYVALUE pKeyValue = NULL;
const char *pszInputJson = pInputJson;
json_t *pJson = NULL;
if(!pszInputJson || !ppszOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pmd_rolemgmt_get_version(&pszVersion);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_object_from_string(pszInputJson, &pJson);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "name", &pszName);
dwError = pmd_rolemgmt_role_version(pszName, &pszVersion);
BAIL_ON_PMD_ERROR(dwError);
dwError = make_keyvalue("version", pszVersion, &pKeyValue);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_string(pKeyValue, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppszOutputJson = pszOutputJson;
cleanup:
PMD_SAFE_FREE_MEMORY(pszVersion);
if(pKeyValue)
{
free_keyvalue(pKeyValue);
}
return dwError;
error:
if(ppszOutputJson)
{
*ppszOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
get_tasklogs_json(
int nCount,
PPMD_PLUGIN_TASK_LOG pTaskLogs,
char **ppszJson
)
{
uint32_t dwError = 0;
char *pszJson = NULL;
json_t *pRoot = NULL;
int i = 0;
if(!pTaskLogs || !ppszJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pRoot = json_array();
if(!pRoot)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(; pTaskLogs && i < nCount; pTaskLogs = pTaskLogs->pNext, ++i)
{
json_t *pLogObj = json_object();
json_object_set_new(pLogObj, "log", json_string(pTaskLogs->pszLog));
json_array_append_new(pRoot, pLogObj);
}
pszJson = json_dumps(pRoot, 0);
*ppszJson = pszJson;
cleanup:
if(pRoot)
{
json_decref(pRoot);
}
return dwError;
error:
if(ppszJson)
{
*ppszJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszJson);
goto cleanup;
}
uint32_t
get_roles_json_string(
PPMD_ROLEMGMT_ROLE pRoles,
char **ppszJson
)
{
uint32_t dwError = 0;
char *pszJson = NULL;
json_t *pRoot = NULL;
PPMD_ROLEMGMT_ROLE pRole = NULL;
if(!pRoles || !ppszJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pRoot = json_array();
if(!pRoot)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(pRole = pRoles; pRole; pRole = pRole->pNext)
{
json_t *pRoleObj = json_object();
json_object_set_new(pRoleObj, "id", json_string(pRole->pszId));
json_object_set_new(pRoleObj, "name", json_string(pRole->pszName));
json_object_set_new(pRoleObj, "baseurl", json_string(pRole->pszDescription));
json_array_append_new(pRoot, pRoleObj);
}
pszJson = json_dumps(pRoot, 0);
*ppszJson = pszJson;
cleanup:
if(pRoot)
{
json_decref(pRoot);
}
return dwError;
error:
if(ppszJson)
{
*ppszJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszJson);
goto cleanup;
}
uint32_t
rolemgmt_rest_get_roles(
void *pInputJson,
void **ppszOutputJson
)
{
uint32_t dwError = 0;
char *pszOutputJson = NULL;
int nLocked = 0;
PPMD_ROLEMGMT_ROLE pRoles = NULL;
if(!ppszOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pthread_mutex_lock(&gRoleMgmtEnv.mutexEnv);
nLocked = 1;
pRoles = gRoleMgmtEnv.pRoles;
if(!pRoles)
{
dwError = ERROR_PMD_NO_DATA;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = get_roles_json_string(pRoles, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppszOutputJson = pszOutputJson;
cleanup:
if(nLocked)
{
pthread_mutex_unlock(&gRoleMgmtEnv.mutexEnv);
}
return dwError;
error:
if(ppszOutputJson)
{
*ppszOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
rolemgmt_rest_get_status(
void *pInputJson,
void **ppszOutputJson
)
{
uint32_t dwError = 0;
char *pszName = NULL;
char *pszTaskUUID = NULL;
char *pszOutputJson = NULL;
char *pszStatus = NULL;
json_t *pJson = NULL;
PMD_ROLE_STATUS nStatus = ROLE_STATUS_NONE;
PKEYVALUE pKeyValue = NULL;
char *pszInputJson = pInputJson;
if(IsNullOrEmptyString(pszInputJson) || !ppszOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = get_json_object_from_string(pszInputJson, &pJson);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "name", &pszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "taskid", &pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_get_status(pszName, pszTaskUUID, &nStatus);
BAIL_ON_PMD_ERROR(dwError);
dwError = make_keyvalue("status", pszStatus, &pKeyValue);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_string(pKeyValue, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppszOutputJson = pszOutputJson;
cleanup:
PMD_SAFE_FREE_MEMORY(pszName);
PMD_SAFE_FREE_MEMORY(pszTaskUUID);
PMD_SAFE_FREE_MEMORY(pszStatus);
free_keyvalue(pKeyValue);
return dwError;
error:
if(ppszOutputJson)
{
*ppszOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
rolemgmt_rest_get_logs(
void *pInputJson,
void **ppszOutputJson
)
{
uint32_t dwError = 0;
char *pszTaskUUID = NULL;
char *pszOutputJson = NULL;
char *pszStartAt = NULL;
char *pszCount = NULL;
char *pszStatus = NULL;
json_t *pJson = NULL;
char *pszInputJson = pInputJson;
int nStartAt = 0;
int nCount = 0;
PPMD_PLUGIN_TASK_LOG pTaskLogs = NULL;
if(IsNullOrEmptyString(pszInputJson) || !ppszOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = get_json_object_from_string(pszInputJson, &pJson);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "taskid", &pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "startat", &pszStartAt);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "count", &pszCount);
BAIL_ON_PMD_ERROR(dwError);
nStartAt = atoi(pszStartAt);
nCount = atoi(pszCount);
dwError = pmd_rolemgmt_get_logs(
pszTaskUUID,
nStartAt,
nCount,
&pTaskLogs);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_tasklogs_json(nCount, pTaskLogs, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppszOutputJson = pszOutputJson;
cleanup:
PMD_SAFE_FREE_MEMORY(pszTaskUUID);
PMD_SAFE_FREE_MEMORY(pszStartAt);
PMD_SAFE_FREE_MEMORY(pszCount);
return dwError;
error:
if(ppszOutputJson)
{
*ppszOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
rolemgmt_rest_do_alter(
PMD_ROLE_OPERATION nOperation,
void *pInputJson,
void **ppszOutputJson
)
{
uint32_t dwError = 0;
char *pszTaskUUID = NULL;
char *pszOutputJson = NULL;
char *pszConfig = NULL;
char *pszName = NULL;
json_t *pJson = NULL;
char *pszInputJson = pInputJson;
PKEYVALUE pKeyValue = NULL;
if(IsNullOrEmptyString(pszInputJson) || !ppszOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = get_json_object_from_string(pszInputJson, &pJson);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "name", &pszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "config", &pszConfig);
if(nOperation != ROLE_OPERATION_ENABLE && !pszConfig)
{
dwError = PMDAllocateString("{}", &pszConfig);
}
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_role_alter(
pszName,
nOperation,
pszConfig,
&pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
dwError = make_keyvalue("taskid", pszTaskUUID, &pKeyValue);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_string(pKeyValue, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppszOutputJson = pszOutputJson;
cleanup:
free_keyvalue(pKeyValue);
PMD_SAFE_FREE_MEMORY(pszName);
PMD_SAFE_FREE_MEMORY(pszConfig);
PMD_SAFE_FREE_MEMORY(pszTaskUUID);
return dwError;
error:
if(ppszOutputJson)
{
*ppszOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
rolemgmt_rest_alter_put(
void *pInputJson,
void **ppszOutputJson
)
{
return rolemgmt_rest_do_alter(
ROLE_OPERATION_ENABLE,
pInputJson,
ppszOutputJson);
}
uint32_t
rolemgmt_rest_alter_delete(
void *pInputJson,
void **ppszOutputJson
)
{
return rolemgmt_rest_do_alter(
ROLE_OPERATION_REMOVE,
pInputJson,
ppszOutputJson);
}
uint32_t
rolemgmt_rest_alter_patch(
void *pInputJson,
void **ppszOutputJson
)
{
return rolemgmt_rest_do_alter(
ROLE_OPERATION_UPDATE,
pInputJson,
ppszOutputJson);
}
|
oliverkurth/pmd
|
server/security/apisecurity.c
|
<filename>server/security/apisecurity.c
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
uint32_t
init_security_config(
const char *pszApiSecurityConf,
PPMD_SECURITY_CONTEXT *ppContext
)
{
uint32_t dwError = 0;
PCONF_DATA pData = NULL;
PPMD_SECURITY_CONTEXT pContext = NULL;
if(IsNullOrEmptyString(pszApiSecurityConf) || !ppContext)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(sizeof(PMD_SECURITY_CONTEXT),
(void **)&pContext);
BAIL_ON_PMD_ERROR(dwError);
dwError = read_config_file(pszApiSecurityConf,
MAX_API_SECURITY_LINE_LENGTH,
&pData);
BAIL_ON_PMD_ERROR(dwError);
dwError = init_module_security(pData, &pContext->pModuleSecurity);
BAIL_ON_PMD_ERROR(dwError);
*ppContext = pContext;
cleanup:
free_config_data(pData);
return dwError;
error:
if(ppContext)
{
*ppContext = NULL;
}
free_security_context(pContext);
goto cleanup;
}
uint32_t
save_security_config(
const char *pszApiSecurityConf,
PPMD_SECURITY_CONTEXT *ppContext
)
{
uint32_t dwError = 0;
if(IsNullOrEmptyString(pszApiSecurityConf))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
init_module_security(
PCONF_DATA pData,
PPMD_MODULE_SECURITY *ppModuleSecurity
)
{
uint32_t dwError = 0;
PPMD_MODULE_SECURITY pModuleSecurity = NULL;
PPMD_MODULE_SECURITY pModuleTemp = NULL;
PCONF_SECTION pSection = NULL;
if(!pData || !ppModuleSecurity)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(pSection = pData->pSections; pSection; pSection = pSection->pNext)
{
PKEYVALUE pKeyValue = NULL;
dwError = PMDAllocateMemory(sizeof(PMD_MODULE_SECURITY),
(void **)&pModuleTemp);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateString(pSection->pszName,
&pModuleTemp->pszName);
BAIL_ON_PMD_ERROR(dwError);
for(pKeyValue = pSection->pKeyValues;
pKeyValue;
pKeyValue = pKeyValue->pNext)
{
PPMD_API_SECURITY pApiSecurity = NULL;
dwError = PMDAllocateMemory(sizeof(PMD_API_SECURITY),
(void **)&pModuleTemp->pApiSecurity);
BAIL_ON_PMD_ERROR(dwError);
pApiSecurity = pModuleTemp->pApiSecurity;
dwError = PMDAllocateString(pKeyValue->pszKey,
&pApiSecurity->pszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateString(pKeyValue->pszValue,
&pApiSecurity->pszSDDL);
BAIL_ON_PMD_ERROR(dwError);
}
pModuleTemp->pNext = pModuleSecurity;
pModuleSecurity = pModuleTemp;
pModuleTemp = NULL;
}
*ppModuleSecurity = pModuleSecurity;
cleanup:
return dwError;
error:
if(ppModuleSecurity)
{
*ppModuleSecurity = NULL;
}
free_module_security(pModuleTemp);
free_module_security(pModuleSecurity);
goto cleanup;
}
uint32_t
init_security_context(
PPMD_SECURITY_CONTEXT pContext
)
{
uint32_t dwError = 0;
PLW_MAP_SECURITY_CONTEXT pSecContext = NULL;
if(!pContext)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(pContext->pSecContext)
{
dwError = EALREADY;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = LwMapSecurityInitialize();
BAIL_ON_PMD_ERROR(dwError);
dwError = LwMapSecurityCreateContext(&pSecContext);
BAIL_ON_PMD_ERROR(dwError);
pContext->pSecContext = pSecContext;
cleanup:
return dwError;
error:
if(dwError == EALREADY)
{
dwError = 0;
}
if(pSecContext)
{
LwMapSecurityFreeContext(&pSecContext);
}
goto cleanup;
}
uint32_t
absolute_from_relative_sd(
PSECURITY_DESCRIPTOR_RELATIVE pRelative,
PSECURITY_DESCRIPTOR_ABSOLUTE *ppAbsolute
)
{
uint32_t dwError = 0;
PSECURITY_DESCRIPTOR_ABSOLUTE pAbsolute = NULL;
PSID pOwnerSid = NULL;
PSID pGroupSid = NULL;
PACL pDacl = NULL;
PACL pSacl = NULL;
uint32_t nAbsSize = 0;
uint32_t nOwnerSize = 0;
uint32_t nGroupSize = 0;
uint32_t nDaclSize = 0;
uint32_t nSaclSize = 0;
dwError = RtlSelfRelativeToAbsoluteSD(
pRelative,
pAbsolute,
&nAbsSize,
pDacl,
&nDaclSize,
pSacl,
&nSaclSize,
pOwnerSid,
&nOwnerSize,
pGroupSid,
&nGroupSize);
if (dwError != STATUS_BUFFER_TOO_SMALL)
{
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(
SECURITY_DESCRIPTOR_ABSOLUTE_MIN_SIZE,
(void **)&pAbsolute);
BAIL_ON_PMD_ERROR(dwError);
dwError = RtlCreateSecurityDescriptorAbsolute(
pAbsolute,
SECURITY_DESCRIPTOR_REVISION);
BAIL_ON_PMD_ERROR(dwError);
if (nDaclSize)
{
dwError = PMDAllocateMemory(nDaclSize, (void **)&pDacl);
BAIL_ON_PMD_ERROR(dwError);
}
if (nSaclSize)
{
dwError = PMDAllocateMemory(nSaclSize, (void **)&pSacl);
BAIL_ON_PMD_ERROR(dwError);
}
if (nOwnerSize)
{
dwError = PMDAllocateMemory(nOwnerSize, (void **)&pOwnerSid);
BAIL_ON_PMD_ERROR(dwError);
}
if (nGroupSize)
{
dwError = PMDAllocateMemory(nGroupSize, (void **)&pGroupSid);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = RtlSelfRelativeToAbsoluteSD(
pRelative,
pAbsolute,
&nAbsSize,
pDacl,
&nDaclSize,
pSacl,
&nSaclSize,
pOwnerSid,
&nOwnerSize,
pGroupSid,
&nGroupSize);
BAIL_ON_PMD_ERROR(dwError);
*ppAbsolute = pAbsolute;
cleanup:
return dwError;
error:
PMD_SAFE_FREE_MEMORY(pOwnerSid);
PMD_SAFE_FREE_MEMORY(pGroupSid);
PMD_SAFE_FREE_MEMORY(pDacl);
PMD_SAFE_FREE_MEMORY(pSacl);
PMD_SAFE_FREE_MEMORY(pAbsolute);
goto cleanup;
}
uint32_t
sddl_to_sec_abs(
const char *pszSDDL,
PSECURITY_DESCRIPTOR_ABSOLUTE *ppSecAbs
)
{
uint32_t dwError = 0;
NTSTATUS ntStatus = STATUS_SUCCESS;
uint32_t dwSize = 0;
PSECURITY_DESCRIPTOR_ABSOLUTE pSecAbs = NULL;
PSECURITY_DESCRIPTOR_RELATIVE pSecRel = NULL;
if(IsNullOrEmptyString(pszSDDL) || !ppSecAbs)
{
ntStatus = STATUS_INVALID_PARAMETER;
BAIL_ON_NT_STATUS(ntStatus);
}
ntStatus = RtlAllocateSecurityDescriptorFromSddlCString(
&pSecRel,
&dwSize,
pszSDDL,
SDDL_REVISION_1);
if (ntStatus == STATUS_BUFFER_TOO_SMALL)
{
ntStatus = STATUS_SUCCESS;
}
BAIL_ON_NT_STATUS(ntStatus);
dwError = PMDAllocateMemory(dwSize, (void **)&pSecAbs);
BAIL_ON_PMD_ERROR(dwError);
ntStatus = RtlAllocateSecurityDescriptorFromSddlCString(
&pSecRel,
&dwSize,
pszSDDL,
SDDL_REVISION_1);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = absolute_from_relative_sd(pSecRel, &pSecAbs);
BAIL_ON_NT_STATUS(ntStatus);
*ppSecAbs = pSecAbs;
cleanup:
return dwError;
error:
if(ppSecAbs)
{
*ppSecAbs = NULL;
}
PMD_SAFE_FREE_MEMORY(pSecAbs);
goto cleanup;
}
uint32_t
init_security_abs(
PPMD_SECURITY_CONTEXT pContext,
PPMD_API_SECURITY pApiSecurity
)
{
uint32_t dwError = 0;
if(!pContext || !pApiSecurity)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(!pContext->pSecContext)
{
dwError = init_security_context(pContext);
BAIL_ON_PMD_ERROR(dwError);
}
if(!pApiSecurity->pSecAbs)
{
dwError = sddl_to_sec_abs(pApiSecurity->pszSDDL,
&pApiSecurity->pSecAbs);
BAIL_ON_PMD_ERROR(dwError);
}
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
find_module_api(
PPMD_SECURITY_CONTEXT pContext,
const char *pszModule,
const char *pszApiName,
PPMD_API_SECURITY *ppApiSecurity
)
{
uint32_t dwError = 0;
PPMD_MODULE_SECURITY pModule = NULL;
PPMD_API_SECURITY pApiSecurity = NULL;
if(!pContext ||
!pContext->pModuleSecurity ||
IsNullOrEmptyString(pszModule) ||
IsNullOrEmptyString(pszApiName) ||
!ppApiSecurity)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pModule = pContext->pModuleSecurity;
for(; pModule; pModule = pModule->pNext)
{
if(!strcmp(pModule->pszName, pszModule))
{
pApiSecurity = pModule->pApiSecurity;
break;
}
}
if(!pApiSecurity)
{
dwError = ENOENT;
BAIL_ON_PMD_ERROR(dwError);
}
for(; pApiSecurity; pApiSecurity = pApiSecurity->pNext)
{
if(!strcmp(pApiSecurity->pszName, pszApiName))
{
break;
}
}
if(!pApiSecurity)
{
dwError = ENOENT;
BAIL_ON_PMD_ERROR(dwError);
}
*ppApiSecurity = pApiSecurity;
cleanup:
return dwError;
error:
if(ppApiSecurity)
{
*ppApiSecurity = NULL;
}
goto cleanup;
}
uint32_t
check_access_uid_gid(
PPMD_SECURITY_CONTEXT pContext,
uid_t uid,
gid_t gid,
const char *pszModule,
const char *pszApiName
)
{
uint32_t dwError = 0;
NTSTATUS status = STATUS_SUCCESS;
PPMD_API_SECURITY pApiSecurity = NULL;
PACCESS_TOKEN pToken = NULL;
ACCESS_MASK AccessDesired = FILE_GENERIC_READ;
ACCESS_MASK AccessMask = 0;
GENERIC_MAPPING stMapping =
{
.GenericRead = FILE_GENERIC_READ,
.GenericWrite = FILE_GENERIC_WRITE,
.GenericExecute = FILE_GENERIC_EXECUTE,
.GenericAll = FILE_ALL_ACCESS
};
if(!pContext ||
IsNullOrEmptyString(pszModule) ||
IsNullOrEmptyString(pszApiName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = find_module_api(pContext, pszModule, pszApiName, &pApiSecurity);
BAIL_ON_PMD_ERROR(dwError);
if(!pApiSecurity->pSecAbs)
{
dwError = init_security_abs(pContext, pApiSecurity);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = LwMapSecurityCreateAccessTokenFromUidGid(
pContext->pSecContext,
&pToken,
uid,
gid);
BAIL_ON_PMD_ERROR(dwError);
if(!RtlAccessCheck(pApiSecurity->pSecAbs,
pToken,
AccessDesired,
0,
&stMapping,
&AccessMask,
&status))
{
fprintf(stderr,
"API Access denied. User: %d, Group: %d, Module: %s Api: %s",
uid,
gid,
pszModule,
pszApiName);
dwError = ERROR_PMD_ACCESS_DENIED;
BAIL_ON_PMD_ERROR(dwError);
}
cleanup:
return dwError;
error:
goto cleanup;
}
void
free_api_security(
PPMD_API_SECURITY pApiSecurity
)
{
if(!pApiSecurity)
{
return;
}
while(pApiSecurity)
{
PPMD_API_SECURITY pTemp = pApiSecurity->pNext;
PMD_SAFE_FREE_MEMORY(pApiSecurity->pszName);
PMD_SAFE_FREE_MEMORY(pApiSecurity->pszSDDL);
PMD_SAFE_FREE_MEMORY(pApiSecurity);
pApiSecurity = pTemp;
}
}
void
free_module_security(
PPMD_MODULE_SECURITY pModuleSecurity
)
{
if(!pModuleSecurity)
{
return;
}
while(pModuleSecurity)
{
PPMD_MODULE_SECURITY pTemp = pModuleSecurity->pNext;
free_api_security(pModuleSecurity->pApiSecurity);
PMD_SAFE_FREE_MEMORY(pModuleSecurity->pszName);
PMD_SAFE_FREE_MEMORY(pModuleSecurity);
pModuleSecurity = pTemp;
}
}
void
free_security_context(
PPMD_SECURITY_CONTEXT pContext
)
{
if(!pContext)
{
return;
}
free_module_security(pContext->pModuleSecurity);
PMD_SAFE_FREE_MEMORY(pContext);
}
|
oliverkurth/pmd
|
server/rolemgmt/rolemgmt_rpcapi.c
|
/*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
unsigned32
rolemgmt_rpc_version(
handle_t hBinding,
wstring_t* ppwszVersion
)
{
uint32_t dwError = 0;
char* pszVersion = NULL;
wstring_t pwszVersion = NULL;
if(!hBinding || !ppwszVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pmd_rolemgmt_get_version(&pszVersion);
BAIL_ON_PMD_ERROR(dwError);
if(IsNullOrEmptyString(pszVersion))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDRpcServerAllocateWFromA(pszVersion, &pwszVersion);
BAIL_ON_PMD_ERROR(dwError);
*ppwszVersion = pwszVersion;
cleanup:
PMD_SAFE_FREE_MEMORY(pszVersion);
return dwError;
error:
if(ppwszVersion)
{
*ppwszVersion = NULL;
}
PMD_SAFE_FREE_MEMORY(pwszVersion);
goto cleanup;
}
unsigned32
rolemgmt_rpc_get_roles(
handle_t hBinding,
PPMD_RPC_ROLEMGMT_ROLE_ARRAY *ppRpcRoleArray
)
{
uint32_t dwError = 0;
PPMD_ROLEMGMT_ROLE pRoleMgmtRole = NULL;
PPMD_ROLEMGMT_ROLE pRole = NULL;
PPMD_RPC_ROLEMGMT_ROLE_ARRAY pRpcRoleArray = NULL;
PPMD_RPC_ROLEMGMT_ROLE pRpcRoles = NULL;
uint32_t dwCount = 0;
int i = 0;
int nLocked = 0;
if(!hBinding || !ppRpcRoleArray)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pthread_mutex_lock(&gRoleMgmtEnv.mutexEnv);
nLocked = 1;
pRoleMgmtRole = gRoleMgmtEnv.pRoles;
if(!pRoleMgmtRole)
{
dwError = ERROR_PMD_NO_DATA;
BAIL_ON_PMD_ERROR(dwError);
}
for(pRole = pRoleMgmtRole; pRole; pRole = pRole->pNext)
{
++dwCount;
}
dwError = PMDRpcServerAllocateMemory(
sizeof(PMD_RPC_ROLEMGMT_ROLE_ARRAY),
(void **)&pRpcRoleArray);
BAIL_ON_PMD_ERROR(dwError);
pRpcRoleArray->dwCount = dwCount;
dwError = PMDRpcServerAllocateMemory(
sizeof(PMD_RPC_ROLEMGMT_ROLE) * dwCount,
(void **)&pRpcRoles);
BAIL_ON_PMD_ERROR(dwError);
for(i = 0, pRole = pRoleMgmtRole; pRole; pRole = pRole->pNext, ++i)
{
dwError = PMDRpcServerAllocateWFromA(
pRole->pszId,
&pRpcRoles[i].pwszId);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(
pRole->pszName,
&pRpcRoles[i].pwszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(
pRole->pszDescription,
&pRpcRoles[i].pwszDescription);
BAIL_ON_PMD_ERROR(dwError);
}
pRpcRoleArray->pRoles = pRpcRoles;
*ppRpcRoleArray = pRpcRoleArray;
cleanup:
if(nLocked)
{
pthread_mutex_unlock(&gRoleMgmtEnv.mutexEnv);
}
return dwError;
error:
if(ppRpcRoleArray)
{
*ppRpcRoleArray = NULL;
}
PMDRpcServerFreeMemory(pRpcRoleArray);
goto cleanup;
}
unsigned32
rolemgmt_rpc_role_version(
handle_t hBinding,
wstring_t pwszName,
wstring_t* ppwszVersion
)
{
uint32_t dwError = 0;
char* pszVersion = NULL;
char* pszName = NULL;
wstring_t pwszVersion = NULL;
if(!hBinding || !pwszName || !ppwszVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszName, &pszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_role_version(pszName, &pszVersion);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(pszVersion, &pwszVersion);
BAIL_ON_PMD_ERROR(dwError);
*ppwszVersion = pwszVersion;
cleanup:
PMD_SAFE_FREE_MEMORY(pszName);
return dwError;
error:
if(ppwszVersion)
{
*ppwszVersion = NULL;
}
PMD_SAFE_FREE_MEMORY(pwszVersion);
goto cleanup;
}
unsigned32
rolemgmt_rpc_role_get_prereqs(
handle_t hBinding,
wstring_t pwszName,
RPC_ROLE_OPERATION nOperation,
PPMD_RPC_ROLEMGMT_PREREQ_ARRAY *ppPrereqArray
)
{
uint32_t dwError = 0;
uint32_t dwPrereqCount = 0;
char *pszName = NULL;
PPMD_ROLE_PREREQ pPrereqs = NULL;
PPMD_RPC_ROLEMGMT_PREREQ_ARRAY pPrereqArray = NULL;
if(!hBinding || !pwszName || !ppPrereqArray)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszName, &pszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_role_get_prereqs(
pszName,
nOperation,
&pPrereqs,
&dwPrereqCount);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateMemory(
sizeof(PMD_RPC_ROLEMGMT_PREREQ_ARRAY),
(void **)&pPrereqArray);
BAIL_ON_PMD_ERROR(dwError);
pPrereqArray->dwCount = dwPrereqCount;
if(dwPrereqCount > 0)
{
uint32_t i = 0;
dwError = PMDRpcServerAllocateMemory(
sizeof(PMD_RPC_ROLEMGMT_PREREQ) * dwPrereqCount,
(void **)&pPrereqArray->pPrereqs);
BAIL_ON_PMD_ERROR(dwError);
for(i = 0; i < dwPrereqCount; ++i)
{
dwError = PMDRpcServerAllocateWFromA(
pPrereqs[i].pszName,
&pPrereqArray->pPrereqs[i].pwszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(
pPrereqs[i].pszDescription,
&pPrereqArray->pPrereqs[i].pwszDescription);
BAIL_ON_PMD_ERROR(dwError);
}
}
*ppPrereqArray = pPrereqArray;
cleanup:
PMD_SAFE_FREE_MEMORY(pszName);
return dwError;
error:
if(ppPrereqArray)
{
*ppPrereqArray = NULL;
}
rolemgmt_rpc_role_free_prereq_array(pPrereqArray);
goto cleanup;
}
unsigned32
rolemgmt_rpc_role_get_status(
handle_t hBinding,
wstring_t pwszName,
wstring_t pwszTaskUUID,
RPC_ROLE_STATUS *pnStatus
)
{
uint32_t dwError = 0;
PMD_ROLE_STATUS nStatus = RPC_ROLE_STATUS_NONE;
char *pszName = NULL;
char *pszTaskUUID = NULL;
if(!hBinding || !pwszName || !pwszTaskUUID || !pnStatus)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszName, &pszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pwszTaskUUID, &pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_get_status(pszName, pszTaskUUID, &nStatus);
BAIL_ON_PMD_ERROR(dwError);
*pnStatus = nStatus;
cleanup:
return dwError;
error:
if(pnStatus)
{
*pnStatus = RPC_ROLE_STATUS_NONE;
}
goto cleanup;
}
unsigned32
rolemgmt_rpc_role_alter(
handle_t hBinding,
wstring_t pwszName,
RPC_ROLE_OPERATION nOperation,
wstring_t pwszConfigJson,
wstring_t* ppwszTaskUUID
)
{
uint32_t dwError = 0;
char *pszName = NULL;
char *pszConfigJson = NULL;
wstring_t pwszTaskUUID = NULL;
char *pszTaskUUID = NULL;
if(!hBinding || !pwszName || !pwszConfigJson || !ppwszTaskUUID)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszName, &pszName);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pwszConfigJson, &pszConfigJson);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_role_alter(
pszName,
nOperation,
pszConfigJson,
&pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcServerAllocateWFromA(pszTaskUUID, &pwszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
*ppwszTaskUUID = pwszTaskUUID;
cleanup:
PMD_SAFE_FREE_MEMORY(pszName);
return dwError;
error:
if(ppwszTaskUUID)
{
*ppwszTaskUUID = NULL;
}
if(pwszTaskUUID)
{
PMDRpcServerFreeMemory(pwszTaskUUID);
}
goto cleanup;
}
unsigned32
rolemgmt_rpc_role_get_log(
handle_t hBinding,
wstring_t pwszTaskUUID,
unsigned32 nOffset,
unsigned32 nEntriesToFetch,
PPMD_RPC_ROLEMGMT_TASK_LOG_ARRAY *ppTaskLogArray
)
{
uint32_t dwError = 0;
char *pszTaskUUID = NULL;
PPMD_RPC_ROLEMGMT_TASK_LOG_ARRAY pTaskLogArray = NULL;
PPMD_PLUGIN_TASK_LOG pTaskLogs = NULL;
PPMD_PLUGIN_TASK_LOG pTemp = NULL;
uint32_t i = 0;
if(!hBinding || !pwszTaskUUID || !ppTaskLogArray)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(nEntriesToFetch == 0)
{
dwError = ERROR_PMD_NOTHING_TO_DO;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringAFromW(pwszTaskUUID, &pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_get_logs(pszTaskUUID,
nOffset,
nEntriesToFetch,
&pTaskLogs);
if (dwError != ERROR_PMD_ROLE_TASK_NO_LOGS)
{
BAIL_ON_PMD_ERROR(dwError);
}
else
{
dwError = 0;
}
for(pTemp = pTaskLogs, i = 0;
pTemp && i < nEntriesToFetch;
pTemp = pTemp->pNext, ++i);
if (i > 0)
{
dwError = PMDRpcServerAllocateMemory(
sizeof(PMD_RPC_ROLEMGMT_TASK_LOG_ARRAY),
(void **)&pTaskLogArray);
BAIL_ON_PMD_ERROR(dwError);
pTaskLogArray->dwCount = i;
dwError = PMDRpcServerAllocateMemory(
sizeof(PMD_RPC_ROLEMGMT_TASK_LOG) * i,
(void **)&pTaskLogArray->pTaskLogs);
BAIL_ON_PMD_ERROR(dwError);
for(i = 0, pTemp = pTaskLogs; i < pTaskLogArray->dwCount; ++i)
{
dwError = PMDRpcServerAllocateWFromA(
pTemp->pszLog,
&pTaskLogArray->pTaskLogs[i].pwszLog);
BAIL_ON_PMD_ERROR(dwError);
}
}
*ppTaskLogArray = pTaskLogArray;
cleanup:
return dwError;
error:
if(ppTaskLogArray)
{
*ppTaskLogArray = NULL;
}
rolemgmt_rpc_role_free_task_log_array(pTaskLogArray);
goto cleanup;
}
void
rolemgmt_rpc_role_free_task_log_array(
PPMD_RPC_ROLEMGMT_TASK_LOG_ARRAY pTaskLogArray
)
{
uint32_t i = 0;
if(!pTaskLogArray)
{
return;
}
for(i = 0; i < pTaskLogArray->dwCount; ++i)
{
PPMD_RPC_ROLEMGMT_TASK_LOG pTaskLog = &pTaskLogArray->pTaskLogs[i];
PMD_RPCSRV_SAFE_FREE_MEMORY(pTaskLog->pwszLog);
}
PMD_RPCSRV_SAFE_FREE_MEMORY(pTaskLogArray->pTaskLogs);
PMDRpcServerFreeMemory(pTaskLogArray);
}
void
rolemgmt_rpc_role_free_prereq_array(
PPMD_RPC_ROLEMGMT_PREREQ_ARRAY pPrereqArray
)
{
uint32_t i = 0;
if(!pPrereqArray)
{
return;
}
for(i = 0; i < pPrereqArray->dwCount; ++i)
{
PPMD_RPC_ROLEMGMT_PREREQ pPrereq = &pPrereqArray->pPrereqs[i];
PMD_RPCSRV_SAFE_FREE_MEMORY(pPrereq->pwszName);
PMD_RPCSRV_SAFE_FREE_MEMORY(pPrereq->pwszDescription);
}
PMD_RPCSRV_SAFE_FREE_MEMORY(pPrereqArray->pPrereqs);
PMDRpcServerFreeMemory(pPrereqArray);
}
|
oliverkurth/pmd
|
python/utils.c
|
/*
* Copyright © 2016-2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
static const char *szLinkStateString[] =
{
"down",
"up",
"unknown"
};
static const char *szLinkModeString[] =
{
"auto",
"manual",
"unknown"
};
const char *
py_link_state_to_string(
NET_LINK_STATE state
)
{
if (state > LINK_STATE_UNKNOWN)
{
state = LINK_STATE_UNKNOWN;
}
return szLinkStateString[state];
}
const char *
py_link_mode_to_string(
NET_LINK_MODE mode
)
{
if (mode > LINK_MODE_UNKNOWN)
{
mode = LINK_MODE_UNKNOWN;
}
return szLinkModeString[mode];
}
uint32_t
py_list_as_string_list(
PyObject *pyList,
char ***pppszStrings,
size_t *pnCount
)
{
uint32_t dwError = 0;
char **ppszStrings = NULL;
size_t i = 0;
size_t nCount = 0;
if(!pyList || !pppszStrings)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
nCount = PyList_Size(pyList);
if(nCount == 0)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(sizeof(char *) * (nCount + 1),
(void **)&ppszStrings);
BAIL_ON_PMD_ERROR(dwError);
for(i = 0; i < nCount; ++i)
{
PyObject *pyItem = NULL;
PyObject *pyString = NULL;
pyItem = PyList_GetItem(pyList, i);
dwError = py_string_as_string(pyItem, &pyString);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateString(PyBytes_AsString(pyString),
&ppszStrings[i]);
BAIL_ON_PMD_ERROR(dwError);
}
*pppszStrings = ppszStrings;
*pnCount = nCount;
cleanup:
return dwError;
error:
if(pppszStrings)
{
*pppszStrings = NULL;
}
if(pnCount)
{
*pnCount = 0;
}
PMDFreeStringArray(ppszStrings);
goto cleanup;
}
uint32_t
py_string_as_string(
PyObject *pyObj,
PyObject **ppString
)
{
uint32_t dwError = 0;
PyObject *pString = NULL;
if(!pyObj || !ppString)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(PyBytes_Check(pyObj))
{
Py_XINCREF(pyObj);
pString = pyObj;
}
else if(PyUnicode_Check(pyObj))
{
pString = PyUnicode_AsUTF8String(pyObj);
}
if(!pString)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
*ppString = pString;
cleanup:
return dwError;
error:
goto cleanup;
}
void
raise_exception(
uint32_t dwErrorCode
)
{
uint32_t dwError = 0;
char *pszError = NULL;
char *pszMessage = NULL;
dwError = PMDGetErrorString(dwErrorCode, &pszError);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringPrintf(&pszMessage,
"Error = %d: %s",
dwErrorCode,
pszError);
BAIL_ON_PMD_ERROR(dwError);
PyErr_SetString(PyExc_Exception, pszMessage);
cleanup:
PMD_SAFE_FREE_MEMORY(pszMessage);
PMD_SAFE_FREE_MEMORY(pszError);
return;
error:
goto cleanup;
}
char *
string_from_py_string(
PyObject *pyString
)
{
char *pszResult = PyBytes_AsString(pyString);
if(!pszResult || !*pszResult)
{
pszResult = NULL;
}
return pszResult;
}
|
oliverkurth/pmd
|
tools/cli/pkgmgmt/pkg_main.c
|
<filename>tools/cli/pkgmgmt/pkg_main.c
/*
* Copyright © 2016-2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
uint32_t
pkg_main(
int argc,
char* const* argv,
PPMD_CMD_ARGS pMainArgs)
{
uint32_t dwError = 0;
PTDNF_CMD_ARGS pCmdArgs = NULL;
TDNF_CLI_CMD_MAP arCmdMap[] =
{
{"check-update", TDNFCliCheckUpdateCommand},
{"clean", TDNFCliCleanCommand},
{"count", TDNFCliCountCommand},
{"distro-sync", TDNFCliDistroSyncCommand},
{"downgrade", TDNFCliDowngradeCommand},
{"erase", TDNFCliEraseCommand},
{"help", TDNFCliHelpCommand},
{"info", TDNFCliInfoCommand},
{"install", TDNFCliInstallCommand},
{"list", TDNFCliListCommand},
{"makecache", TDNFCliMakeCacheCommand},
{"provides", TDNFCliProvidesCommand},
{"whatprovides", TDNFCliProvidesCommand},
{"reinstall", TDNFCliReinstallCommand},
{"remove", TDNFCliEraseCommand},
{"repolist", TDNFCliRepoListCommand},
{"search", TDNFCliSearchCommand},
{"update", TDNFCliUpgradeCommand},
{"update-to", TDNFCliUpgradeCommand},
{"upgrade", TDNFCliUpgradeCommand},
{"upgrade-to", TDNFCliUpgradeCommand},
{"updateinfo", TDNFCliUpdateInfoCommand},
{"version", pkg_show_version_cmd},
};
int nCommandCount = sizeof(arCmdMap)/sizeof(TDNF_CLI_CMD_MAP);
const char* pszCmd = NULL;
int nFound = 0;
PMD_PKG_CLI_CONTEXT stCliContext = {0};
TDNF_CLI_CONTEXT stContext = {0};
stContext.pUserData = &stCliContext;
stContext.pFnCount = pkg_invoke_count;
stContext.pFnAlter = pkg_invoke_alter;
stContext.pFnInfo = pkg_invoke_info;
stContext.pFnList = pkg_invoke_list;
stContext.pFnRepoList = pkg_invoke_repolist;
stContext.pFnResolve = pkg_invoke_resolve;
stContext.pFnUpdateInfo = pkg_invoke_updateinfo;
stContext.pFnUpdateInfoSummary = pkg_invoke_updateinfo_summary;
dwError = pkg_parse_args(argc, argv, &pCmdArgs);
BAIL_ON_CLI_ERROR(dwError);
if(pCmdArgs->nShowHelp)
{
show_help();
}
else if(pCmdArgs->nCmdCount > 0)
{
pszCmd = pCmdArgs->ppszCmds[0];
while(nCommandCount > 0)
{
--nCommandCount;
if(!strcmp(pszCmd, arCmdMap[nCommandCount].pszCmdName))
{
nFound = 1;
dwError = rpc_open(
"pkg",
pMainArgs->pszServer,
pMainArgs->pszUser,
pMainArgs->pszDomain,
pMainArgs->pszPass,
pMainArgs->pszSpn,
&stCliContext.hPMD);
BAIL_ON_CLI_ERROR(dwError);
stContext.hTdnf = stCliContext.hPMD;
dwError = pkg_open_handle(stCliContext.hPMD,
pCmdArgs,
&stCliContext.hPkgHandle);
BAIL_ON_CLI_ERROR(dwError);
dwError = arCmdMap[nCommandCount].pFnCmd(&stContext, pCmdArgs);
BAIL_ON_CLI_ERROR(dwError);
break;
}
};
if(!nFound)
{
dwError = ERROR_PMD_FAIL;
show_no_such_cmd(pszCmd);
BAIL_ON_CLI_ERROR(dwError);
}
}
else
{
pkg_show_help();
}
cleanup:
if(stCliContext.hPMD && stCliContext.hPkgHandle)
{
pkg_close_handle(stCliContext.hPMD, stCliContext.hPkgHandle);
}
rpc_free_handle(stCliContext.hPMD);
if(pCmdArgs)
{
pkg_free_cmd_args(pCmdArgs);
}
return dwError;
error:
pkg_print_error(stCliContext.hPMD, dwError);
if (dwError == ERROR_TDNF_CLI_NOTHING_TO_DO)
{
// Nothing to do should not return an error code
dwError = 0;
}
goto cleanup;
}
uint32_t
pkg_invoke_alter(
PTDNF_CLI_CONTEXT pContext,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO pSolvedPkgInfo
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_alter(pLocalContext->hPMD,
pLocalContext->hPkgHandle,
nAlterType,
pSolvedPkgInfo);
}
uint32_t
pkg_invoke_check_update(
PTDNF_CLI_CONTEXT pContext,
char** ppszPackageArgs,
PTDNF_PKG_INFO *ppPkgInfo,
uint32_t *pdwCount
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return 0;
}
uint32_t
pkg_invoke_count(
PTDNF_CLI_CONTEXT pContext,
uint32_t *pdwCount
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_count(pLocalContext->hPMD, pLocalContext->hPkgHandle, pdwCount);
}
uint32_t
pkg_invoke_info(
PTDNF_CLI_CONTEXT pContext,
PTDNF_LIST_ARGS pInfoArgs,
PTDNF_PKG_INFO *ppPkgInfo,
uint32_t *pdwCount
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_list(pLocalContext->hPMD,
pLocalContext->hPkgHandle,
pInfoArgs->nScope,
pInfoArgs->ppszPackageNameSpecs,
ppPkgInfo,
pdwCount);
}
uint32_t
pkg_invoke_list(
PTDNF_CLI_CONTEXT pContext,
PTDNF_LIST_ARGS pInfoArgs,
PTDNF_PKG_INFO *ppPkgInfo,
uint32_t *pdwCount
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_list(pLocalContext->hPMD,
pLocalContext->hPkgHandle,
pInfoArgs->nScope,
pInfoArgs->ppszPackageNameSpecs,
ppPkgInfo,
pdwCount);
}
uint32_t
pkg_invoke_repolist(
PTDNF_CLI_CONTEXT pContext,
TDNF_REPOLISTFILTER nFilter,
PTDNF_REPO_DATA *ppRepos
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_repolist(pLocalContext->hPMD,
pLocalContext->hPkgHandle,
nFilter,
ppRepos);
}
uint32_t
pkg_invoke_resolve(
PTDNF_CLI_CONTEXT pContext,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO *ppSolvedPkgInfo
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_resolve(pLocalContext->hPMD,
pLocalContext->hPkgHandle,
nAlterType,
ppSolvedPkgInfo);
}
uint32_t
pkg_invoke_updateinfo(
PTDNF_CLI_CONTEXT pContext,
PTDNF_UPDATEINFO_ARGS pInfoArgs,
PTDNF_UPDATEINFO *ppUpdateInfo
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_updateinfo(
pLocalContext->hPMD,
pLocalContext->hPkgHandle,
pInfoArgs->ppszPackageNameSpecs,
ppUpdateInfo);
}
uint32_t
pkg_invoke_updateinfo_summary(
PTDNF_CLI_CONTEXT pContext,
TDNF_AVAIL nAvail,
PTDNF_UPDATEINFO_ARGS pInfoArgs,
PTDNF_UPDATEINFO_SUMMARY *ppSummary
)
{
PPMD_PKG_CLI_CONTEXT pLocalContext = pContext->pUserData;
return pkg_updateinfo_summary(
pLocalContext->hPMD,
pLocalContext->hPkgHandle,
nAvail,
pInfoArgs->ppszPackageNameSpecs,
ppSummary);
}
uint32_t
pkg_show_version_cmd(
PTDNF_CLI_CONTEXT pContext,
PTDNF_CMD_ARGS pCmdArgs
)
{
uint32_t dwError = 0;
char *pszVersion = NULL;
if(!pContext || !pContext->hTdnf || !pCmdArgs)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = pkg_version(pContext->hTdnf, &pszVersion);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "Version: %s\n", pszVersion);
cleanup:
PMD_SAFE_FREE_MEMORY(pszVersion);
return dwError;
error:
goto cleanup;
}
uint32_t
pkg_print_error(
PPMDHANDLE hPMD,
uint32_t dwErrorCode
)
{
uint32_t dwError = 0;
char* pszError = NULL;
if(dwErrorCode >= ERROR_TDNF_CLI_BASE && dwErrorCode < ERROR_PKG_BASE_BEGIN)
{
dwError = TDNFCliGetErrorString(dwErrorCode, &pszError);
BAIL_ON_CLI_ERROR(dwError);
}
else if(hPMD && dwErrorCode >= ERROR_PKG_BASE_BEGIN && dwErrorCode <= ERROR_PKG_BASE_END)
{
dwError = pkg_get_error_string(hPMD, dwErrorCode, &pszError);
BAIL_ON_CLI_ERROR(dwError);
}
if(dwErrorCode != ERROR_PMD_FAIL)
{
printf("Error(%d) : %s\n", dwErrorCode, pszError);
}
cleanup:
PMD_CLI_SAFE_FREE_MEMORY(pszError);
return dwError;
error:
printf(
"Retrieving error string for %d failed with %d\n",
dwErrorCode,
dwError);
goto cleanup;
}
uint32_t
get_error_string(
uint32_t dwErrorCode,
char** ppszError
)
{
uint32_t dwError = 0;
char* pszError = NULL;
int i = 0;
int nCount = 0;
PMD_ERROR_DESC arErrorDesc[] = PMD_CLI_ERROR_TABLE;
nCount = sizeof(arErrorDesc)/sizeof(arErrorDesc[0]);
for(i = 0; i < nCount; i++)
{
if (dwErrorCode == arErrorDesc[i].nCode)
{
dwError = PMDAllocateString(arErrorDesc[i].pszDesc, &pszError);
BAIL_ON_CLI_ERROR(dwError);
break;
}
}
*ppszError = pszError;
cleanup:
return dwError;
error:
PMD_CLI_SAFE_FREE_MEMORY(pszError);
goto cleanup;
}
|
oliverkurth/pmd
|
idl/fwmgmtrpctypes.h
|
<reponame>oliverkurth/pmd<filename>idl/fwmgmtrpctypes.h
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#ifndef __FIREWALL_RPC_TYPES_H__
#define __FIREWALL_RPC_TYPES_H__
#ifdef __cplusplus
extern "C" {
#endif
#if (!defined NO_LIKEWISE && !defined _WIN32)
#include <lw/types.h>
#endif
#ifdef _DCE_IDL_
cpp_quote("#include <fwmgmtrpctypes.h>")
cpp_quote("#if 0")
#endif
typedef struct _PMD_RPC_FIREWALL_RULE_
{
wstring_t pwszRule;
}PMD_RPC_FIREWALL_RULE, *PPMD_RPC_FIREWALL_RULE;
typedef struct _PMD_RPC_FIREWALL_RULE_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_FIREWALL_RULE pRules;
}PMD_RPC_FIREWALL_RULE_ARRAY, *PPMD_RPC_FIREWALL_RULE_ARRAY;
typedef struct _PMD_RPC_FIREWALL_CMD_
{
wstring_t pwszRawCmd;
}PMD_RPC_FIREWALL_CMD, *PPMD_RPC_FIREWALL_CMD;
typedef struct _PMD_RPC_FIREWALL_CMD_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_FIREWALL_CMD pCmds;
}PMD_RPC_FIREWALL_CMD_ARRAY, *PPMD_RPC_FIREWALL_CMD_ARRAY;
typedef struct _PMD_RPC_FIREWALL_TABLE_
{
wstring_t pwszName;
PPMD_RPC_FIREWALL_CMD_ARRAY pCmds;
}PMD_RPC_FIREWALL_TABLE, *PPMD_RPC_FIREWALL_TABLE;
typedef struct _PMD_RPC_FIREWALL_TABLE_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_FIREWALL_TABLE pTables;
}PMD_RPC_FIREWALL_TABLE_ARRAY, *PPMD_RPC_FIREWALL_TABLE_ARRAY;
#ifdef _DCE_IDL_
cpp_quote("#endif")
#endif
#ifdef __cplusplus
}
#endif
#endif /* __FIREWALL_RPC_TYPES_H__ */
|
oliverkurth/pmd
|
tools/cli/pkgmgmt/prototypes.h
|
<gh_stars>1-10
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#pragma once
//pkg_main.c
uint32_t
pkg_exec_cmd(
int argc,
char* const* argv,
PTDNF_CMD_ARGS pCmdArgs);
uint32_t
pkg_invoke_alter(
PTDNF_CLI_CONTEXT pContext,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO pSolvedPkgInfo
);
uint32_t
pkg_invoke_count(
PTDNF_CLI_CONTEXT pContext,
uint32_t *pdwCount
);
uint32_t
pkg_invoke_info(
PTDNF_CLI_CONTEXT pContext,
PTDNF_LIST_ARGS pInfoArgs,
PTDNF_PKG_INFO *ppPkgInfo,
uint32_t *pdwCount
);
uint32_t
pkg_invoke_list(
PTDNF_CLI_CONTEXT pContext,
PTDNF_LIST_ARGS pListArgs,
PTDNF_PKG_INFO *ppPkgInfo,
uint32_t *pdwCount
);
uint32_t
pkg_invoke_repolist(
PTDNF_CLI_CONTEXT pContext,
TDNF_REPOLISTFILTER nFilter,
PTDNF_REPO_DATA *ppRepos
);
uint32_t
pkg_invoke_resolve(
PTDNF_CLI_CONTEXT pContext,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO *ppSolvedPkgInfo
);
uint32_t
pkg_invoke_updateinfo(
PTDNF_CLI_CONTEXT pContext,
PTDNF_UPDATEINFO_ARGS pInfoArgs,
PTDNF_UPDATEINFO *ppUpdateInfo
);
uint32_t
pkg_invoke_updateinfo_summary(
PTDNF_CLI_CONTEXT pContext,
TDNF_AVAIL nAvail,
PTDNF_UPDATEINFO_ARGS pInfoArgs,
PTDNF_UPDATEINFO_SUMMARY *ppSummary
);
uint32_t
pkg_count_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_info_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_list_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_repolist_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_updateinfo_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_downgrade_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_distro_sync_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_erase_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_install_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_reinstall_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_update_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_alter_cmd(
PPMDHANDLE hPMD,
PTDNF_CMD_ARGS pCmdArgs,
TDNF_ALTERTYPE nType
);
uint32_t
pkg_serverinfo_cmd(
PTDNF_CLI_CONTEXT pContext,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_ostree_sync_cmd(
PTDNF_CLI_CONTEXT pContext,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_show_version_cmd(
PTDNF_CLI_CONTEXT pContext,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_print_error(
PPMDHANDLE hPMD,
uint32_t dwErrorCode
);
//pkg_parseargs.c
uint32_t
pkg_parse_args(
int argc,
char* const* argv,
PTDNF_CMD_ARGS* ppCmdArgs
);
uint32_t
pkg_parse_option(
const char* pszName,
const char* pszArg,
PTDNF_CMD_ARGS pCmdArgs
);
uint32_t
pkg_copy_options(
PTDNF_CMD_ARGS pOptionArgs,
PTDNF_CMD_ARGS pArgs
);
uint32_t
pkg_handle_options_error(
const char* pszName,
const char* pszArg,
struct option* pstOptions
);
uint32_t
pkg_parse_info_args(
PTDNF_CMD_ARGS pCmdArgs,
PTDNF_LIST_ARGS* ppListArgs
);
void
pkg_free_cmd_args(
PTDNF_CMD_ARGS pCmdArgs
);
//parselistargs.c
uint32_t
pkg_parse_scope(
const char* pszScope,
TDNF_SCOPE* pnScope
);
uint32_t
pkg_parse_list_args(
PTDNF_CMD_ARGS pCmdArgs,
PTDNF_LIST_ARGS* ppListArgs
);
uint32_t
pkg_parse_info_args(
PTDNF_CMD_ARGS pCmdArgs,
PTDNF_LIST_ARGS* ppListArgs
);
void
pkg_free_list_args(
PTDNF_LIST_ARGS pListArgs
);
//parserepolistargs.c
uint32_t
pkg_parse_filter(
const char* pszRepolistFilter,
TDNF_REPOLISTFILTER* pnFilter
);
uint32_t
pkg_parse_repolist_args(
PTDNF_CMD_ARGS pCmdArgs,
TDNF_REPOLISTFILTER* pnFilter
);
//help.c
void
pkg_show_help(
);
|
oliverkurth/pmd
|
idl/rpmostreerpctypes.h
|
/*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#ifndef __RPMOSTREE_RPC_TYPES_H__
#define __RPMOSTREE_RPC_TYPES_H__
#ifdef __cplusplus
extern "C" {
#endif
#if (!defined NO_LIKEWISE && !defined _WIN32)
#include <lw/types.h>
#endif
#ifdef _DCE_IDL_
cpp_quote("#include <rpmostreerpctypes.h>")
cpp_quote("#if 0")
#endif
typedef struct _PMD_RPMOSTREE_SERVER_INFO_
{
unsigned32 dwServerType;
wstring_t pwszServerUrl;
wstring_t pwszCurrentHash;
}PMD_RPMOSTREE_SERVER_INFO, *PPMD_RPMOSTREE_SERVER_INFO;
typedef struct _PMD_RPMOSTREE_CLIENT_INFO_
{
unsigned32 dwServerType;
wstring_t pwszComposeServer;
wstring_t pwszCurrentHash;
wstring_t pwszLastSyncDate;
}PMD_RPMOSTREE_CLIENT_INFO, *PPMD_RPMOSTREE_CLIENT_INFO;
#ifdef _DCE_IDL_
cpp_quote("#endif")
#endif
#ifdef __cplusplus
}
#endif
#endif /* __RPMOSTREE_RPC_TYPES_H__ */
|
oliverkurth/pmd
|
client/pkgmgmt_api.c
|
<gh_stars>0
/*
* Copyright © 2016-2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
uint32_t
pkg_open_handle(
PPMDHANDLE hHandle,
PTDNF_CMD_ARGS pArgs,
PPKGHANDLE *phPkgHandle
)
{
uint32_t dwError = 0;
pkg_handle_t hPkgHandle = NULL;
PTDNF_RPC_CMD_ARGS pRpcArgs = NULL;
dwError = pkg_get_rpc_cmd_args(pArgs, &pRpcArgs);
BAIL_ON_PMD_ERROR(dwError);
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_open_handle(
hHandle->hRpc,
pRpcArgs,
&hPkgHandle), dwError);
}
else
{
DO_RPC(pkg_rpc_open_handle(
hHandle->hRpc,
pRpcArgs,
&hPkgHandle), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
*phPkgHandle = hPkgHandle;
cleanup:
free_pkg_rpc_cmd_args(pRpcArgs);
return dwError;
error:
if(phPkgHandle)
{
*phPkgHandle = NULL;
}
goto cleanup;
}
uint32_t
pkg_close_handle(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle
)
{
uint32_t dwError = 0;
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_close_handle(
hHandle->hRpc,
hPkgHandle), dwError);
BAIL_ON_PMD_ERROR(dwError);
}
else
{
DO_RPC(pkg_rpc_close_handle(
hHandle->hRpc,
hPkgHandle), dwError);
BAIL_ON_PMD_ERROR(dwError);
}
error:
return dwError;
}
uint32_t
pkg_list_w(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_SCOPE nScope,
PPMD_WSTRING_ARRAY pPkgNameSpecs,
PTDNF_RPC_PKGINFO_ARRAY* ppRpcInfo
)
{
uint32_t dwError = 0;
if(!hHandle || !hPkgHandle || !pPkgNameSpecs || !ppRpcInfo)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_list(hHandle->hRpc,
hPkgHandle,
nScope,
pPkgNameSpecs,
ppRpcInfo), dwError);
}
else
{
DO_RPC(pkg_rpc_list(hHandle->hRpc,
hPkgHandle,
nScope,
pPkgNameSpecs,
ppRpcInfo), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_list(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_SCOPE nScope,
char **ppszPkgNameSpecs,
PTDNF_PKG_INFO *ppPkgInfo,
uint32_t *pdwCount
)
{
uint32_t dwError = 0;
uint32_t dwCount = 0;
uint32_t dwIndex = 0;
PTDNF_RPC_PKGINFO_ARRAY pRpcInfo = NULL;
PTDNF_PKG_INFO pPkgInfo = NULL;
PPMD_WSTRING_ARRAY pPkgNameSpecs = NULL;
char **ppszNameSpecsTemp = NULL;
if(!ppPkgInfo || !ppszPkgNameSpecs || !pdwCount)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
ppszNameSpecsTemp = ppszPkgNameSpecs;
dwError = PMDAllocateMemory(sizeof(PMD_WSTRING_ARRAY),
(void **)&pPkgNameSpecs);
BAIL_ON_PMD_ERROR(dwError);
while(*ppszNameSpecsTemp)
{
pPkgNameSpecs->dwCount++;
ppszNameSpecsTemp++;
}
if(pPkgNameSpecs->dwCount > 0)
{
int i = 0;
dwError = PMDAllocateMemory(sizeof(wstring_t) * pPkgNameSpecs->dwCount,
(void **)&pPkgNameSpecs->ppwszStrings);
BAIL_ON_PMD_ERROR(dwError);
for(i = 0; i < pPkgNameSpecs->dwCount; ++i)
{
dwError = PMDAllocateStringWFromA(ppszPkgNameSpecs[i],
&pPkgNameSpecs->ppwszStrings[i]);
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = pkg_list_w(hHandle, hPkgHandle, nScope, pPkgNameSpecs, &pRpcInfo);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcClientConvertPkgInfo(pRpcInfo, &pPkgInfo);
BAIL_ON_PMD_ERROR(dwError);
*ppPkgInfo = pPkgInfo;
*pdwCount = pRpcInfo->dwCount;
cleanup:
if(pPkgNameSpecs)
{
pmd_free_wstring_array(pPkgNameSpecs);
}
if(pRpcInfo)
{
PMDRpcClientFreePkgInfoArray(pRpcInfo);
}
return dwError;
error:
if(ppPkgInfo)
{
*ppPkgInfo = NULL;
}
if(pdwCount)
{
*pdwCount = 0;
}
goto cleanup;
}
uint32_t
pkg_count(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
uint32_t* pdwCount
)
{
uint32_t dwError = 0;
uint32_t dwCount = 0;
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_count(hHandle->hRpc, hPkgHandle, &dwCount),
dwError);
}
else
{
DO_RPC(pkg_rpc_count(hHandle->hRpc, hPkgHandle, &dwCount), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
*pdwCount = dwCount;
cleanup:
return dwError;
error:
if(pdwCount)
{
*pdwCount = 0;
}
goto cleanup;
}
uint32_t
pkg_repolist_w(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_REPOLISTFILTER nRepoListFilter,
PTDNF_RPC_REPODATA_ARRAY *ppRpcRepoDataArray
)
{
uint32_t dwError = 0;
if(!hHandle || !hPkgHandle || !ppRpcRepoDataArray)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_repolist(hHandle->hRpc,
hPkgHandle,
nRepoListFilter,
ppRpcRepoDataArray), dwError);
}
else
{
DO_RPC(pkg_rpc_repolist(hHandle->hRpc,
hPkgHandle,
nRepoListFilter,
ppRpcRepoDataArray), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_repolist(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_REPOLISTFILTER nRepoListFilter,
PTDNF_REPO_DATA *ppRepoData
)
{
uint32_t dwError = 0;
uint32_t dwCount = 0;
int i = 0;
PTDNF_RPC_REPODATA_ARRAY pRpcRepoDataArray = NULL;
PTDNF_RPC_REPODATA pRpcRepoData = NULL;
PTDNF_REPO_DATA pRepoData = NULL;
PTDNF_REPO_DATA pRepoTemp = NULL;
if(!hHandle || !hPkgHandle || !ppRepoData)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_repolist_w(
hHandle,
hPkgHandle,
nRepoListFilter,
&pRpcRepoDataArray);
BAIL_ON_PMD_ERROR(dwError);
if(!pRpcRepoDataArray || !pRpcRepoDataArray->dwCount)
{
dwError = ERROR_PMD_NO_DATA;
BAIL_ON_PMD_ERROR(dwError);
}
dwCount = pRpcRepoDataArray->dwCount;
pRpcRepoData = pRpcRepoDataArray->pRepoData;
for(i = dwCount-1; i >= 0; --i)
{
dwError = PMDAllocateMemory(sizeof(TDNF_REPO_DATA),
(void**)&pRepoTemp);
BAIL_ON_PMD_ERROR(dwError);
pRepoTemp->nEnabled = pRpcRepoData[i].nEnabled;
dwError = PMDAllocateStringAFromW(pRpcRepoData[i].pwszId,
&pRepoTemp->pszId);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(pRpcRepoData[i].pwszName,
&pRepoTemp->pszName);
BAIL_ON_PMD_ERROR(dwError);
pRepoTemp->pNext = pRepoData;
pRepoData = pRepoTemp;
pRepoTemp = NULL;
}
*ppRepoData = pRepoData;
cleanup:
if(pRpcRepoDataArray)
{
PMDRpcClientFreeRepoDataArray(pRpcRepoDataArray);
}
return dwError;
error:
if(ppRepoData)
{
*ppRepoData = NULL;
}
pkg_free_repos(pRepoTemp);
pkg_free_repos(pRepoData);
goto cleanup;
}
uint32_t
pkg_updateinfo_w(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
PTDNF_RPC_UPDATEINFO_SUMMARY_ARRAY *ppRpcSummary
)
{
uint32_t dwError = 0;
if(!hHandle || !hPkgHandle || !ppRpcSummary)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_updateinfo_summary(hHandle->hRpc,
hPkgHandle,
ppRpcSummary), dwError);
}
else
{
DO_RPC(pkg_rpc_updateinfo_summary(hHandle->hRpc,
hPkgHandle,
ppRpcSummary), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_updateinfo(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
char **ppszPackageNameSpecs,
PTDNF_UPDATEINFO *ppUpdateInfo
)
{
uint32_t dwError = 0;
uint32_t dwIndex = 0;
PTDNF_UPDATEINFO pUpdateInfo = NULL;
PTDNF_RPC_UPDATEINFO_SUMMARY_ARRAY pRpcSummary = NULL;
if(!hHandle || !ppUpdateInfo)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_updateinfo_w(hHandle, hPkgHandle, &pRpcSummary);
BAIL_ON_PMD_ERROR(dwError);
if(!pRpcSummary || !pRpcSummary->dwCount)
{
dwError = ERROR_PMD_NO_DATA;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(
sizeof(TDNF_UPDATEINFO) * pRpcSummary->dwCount,
(void**)&pUpdateInfo);
BAIL_ON_PMD_ERROR(dwError);
*ppUpdateInfo = pUpdateInfo;
cleanup:
return dwError;
error:
if(ppUpdateInfo)
{
*ppUpdateInfo = NULL;
}
goto cleanup;
}
uint32_t
pkg_updateinfo_summary_w(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_AVAIL nAvail,
PTDNF_RPC_UPDATEINFO_SUMMARY_ARRAY *ppRpcSummary
)
{
uint32_t dwError = 0;
if(!hHandle || !hPkgHandle || !ppRpcSummary)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_updateinfo_summary(hHandle->hRpc,
hPkgHandle,
ppRpcSummary), dwError);
}
else
{
DO_RPC(pkg_rpc_updateinfo_summary(hHandle->hRpc,
hPkgHandle,
ppRpcSummary), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_updateinfo_summary(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_AVAIL nAvail,
char **ppszPackageNameSpecs,
PTDNF_UPDATEINFO_SUMMARY *ppSummary
)
{
uint32_t dwError = 0;
uint32_t dwIndex = 0;
PTDNF_UPDATEINFO_SUMMARY pSummary = NULL;
PTDNF_RPC_UPDATEINFO_SUMMARY_ARRAY pRpcSummary = NULL;
if(!hHandle || !ppSummary)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_updateinfo_summary_w(
hHandle,
hPkgHandle,
nAvail,
&pRpcSummary);
BAIL_ON_PMD_ERROR(dwError);
if(!pRpcSummary || !pRpcSummary->dwCount)
{
dwError = ERROR_PMD_NO_DATA;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(
sizeof(TDNF_UPDATEINFO_SUMMARY) * pRpcSummary->dwCount,
(void**)&pSummary);
BAIL_ON_PMD_ERROR(dwError);
for(dwIndex = 0; dwIndex < pRpcSummary->dwCount; ++dwIndex)
{
pSummary[dwIndex].nType =
pRpcSummary->pRpcUpdateInfoSummaries[dwIndex].nType;
pSummary[dwIndex].nCount =
pRpcSummary->pRpcUpdateInfoSummaries[dwIndex].nCount;
}
*ppSummary = pSummary;
cleanup:
return dwError;
error:
if(ppSummary)
{
*ppSummary = NULL;
}
pkg_free_updateinfo_summary(pSummary);
goto cleanup;
}
uint32_t
pkg_resolve_w(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_ALTERTYPE nAlterType,
PTDNF_RPC_SOLVED_PKG_INFO *ppRpcSolvedInfo
)
{
uint32_t dwError = 0;
if(!hHandle || !hPkgHandle || !ppRpcSolvedInfo)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_resolve(hHandle->hRpc,
hPkgHandle,
nAlterType,
ppRpcSolvedInfo), dwError);
}
else
{
DO_RPC(pkg_rpc_resolve(hHandle->hRpc,
hPkgHandle,
nAlterType,
ppRpcSolvedInfo), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_resolve(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO *ppSolvedInfo
)
{
uint32_t dwError = 0;
PTDNF_RPC_SOLVED_PKG_INFO pRpcSolvedInfo = NULL;
PTDNF_SOLVED_PKG_INFO pSolvedInfo = NULL;
if(!hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_resolve_w(
hHandle,
hPkgHandle,
nAlterType,
&pRpcSolvedInfo);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDRpcClientConvertSolvedPkgInfo(pRpcSolvedInfo, &pSolvedInfo);
BAIL_ON_PMD_ERROR(dwError);
*ppSolvedInfo = pSolvedInfo;
cleanup:
return dwError;
error:
if(ppSolvedInfo)
{
*ppSolvedInfo = NULL;
}
pkg_free_solvedinfo(pSolvedInfo);
goto cleanup;
}
uint32_t
pkg_alter_w(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_ALTERTYPE nAlterType
)
{
uint32_t dwError = 0;
if(!hHandle || !hPkgHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_alter(hHandle->hRpc, hPkgHandle, nAlterType),
dwError);
}
else
{
DO_RPC(pkg_rpc_alter(hHandle->hRpc, hPkgHandle, nAlterType), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_alter(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO pSolvedPkgInfo
)
{
uint32_t dwError = 0;
if(!hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_alter_w(
hHandle,
hPkgHandle,
nAlterType);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
pkg_version_w(
PPMDHANDLE hHandle,
wstring_t *ppwszVersion
)
{
uint32_t dwError = 0;
if(!hHandle || !ppwszVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_version(hHandle->hRpc, ppwszVersion), dwError);
}
else
{
DO_RPC(pkg_rpc_version(hHandle->hRpc, ppwszVersion), dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_version(
PPMDHANDLE hHandle,
char **ppszVersion
)
{
uint32_t dwError = 0;
wstring_t pwszVersion = NULL;
char *pszVersion = NULL;
if(!hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_version_w(hHandle, &pwszVersion);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(
pwszVersion,
&pszVersion);
BAIL_ON_PMD_ERROR(dwError);
*ppszVersion = pszVersion;
cleanup:
PMDRpcClientFreeStringW(pwszVersion);
return dwError;
error:
if(ppszVersion)
{
*ppszVersion = NULL;
}
PMD_SAFE_FREE_MEMORY(pszVersion);
goto cleanup;
}
uint32_t
pmd_server_type(
PPMDHANDLE hHandle,
uint32_t* pdwServerType
)
{
uint32_t dwError = 0;
uint32_t dwServerType = 0;
if(!hHandle || !pdwServerType)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
DO_RPC(pmd_rpc_server_type(hHandle->hRpc, &dwServerType), dwError);
BAIL_ON_PMD_ERROR(dwError);
*pdwServerType = dwServerType;
cleanup:
return dwError;
error:
if(pdwServerType)
{
*pdwServerType = 0;
}
goto cleanup;
}
void
pkg_free_repos(
PTDNF_REPO_DATA pRepos
)
{
PTDNF_REPO_DATA pRepo = NULL;
while(pRepos)
{
pRepo = pRepos;
PMD_SAFE_FREE_MEMORY(pRepo->pszId);
PMD_SAFE_FREE_MEMORY(pRepo->pszName);
PMD_SAFE_FREE_MEMORY(pRepo->pszBaseUrl);
PMD_SAFE_FREE_MEMORY(pRepo->pszMetaLink);
PMD_SAFE_FREE_MEMORY(pRepo->pszUrlGPGKey);
pRepos = pRepo->pNext;
PMD_SAFE_FREE_MEMORY(pRepo);
}
}
void
pkg_free_package_info(
PTDNF_PKG_INFO pPkgInfo
)
{
if(!pPkgInfo)
{
return;
}
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszName);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszRepoName);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszVersion);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszArch);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszSummary);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszURL);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszLicense);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszDescription);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszFormattedSize);
PMD_SAFE_FREE_MEMORY(pPkgInfo->pszRelease);
}
void
pkg_free_package_info_list(
PTDNF_PKG_INFO pPkgInfo
)
{
PTDNF_PKG_INFO pTemp = NULL;
if(!pPkgInfo)
{
return;
}
while(pPkgInfo)
{
pTemp = pPkgInfo->pNext;
pkg_free_package_info(pPkgInfo);
PMD_SAFE_FREE_MEMORY(pPkgInfo);
pPkgInfo = pTemp;
}
}
void
pkg_free_package_info_array(
PTDNF_PKG_INFO pPkgInfo,
uint32_t dwLength
)
{
uint32_t i = 0;
if(pPkgInfo && dwLength > 0)
{
for(i = 0; i < dwLength; ++i)
{
pkg_free_package_info(&pPkgInfo[i]);
}
}
PMD_SAFE_FREE_MEMORY(pPkgInfo);
}
uint32_t
pkg_get_error_string_w(
PPMDHANDLE hHandle,
uint32_t dwErrorCode,
wstring_t *ppwszError
)
{
uint32_t dwError = 0;
if(!hHandle || !ppwszError)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(hHandle->nPrivSep)
{
DO_RPC(pkg_privsep_rpc_get_error_string(
hHandle->hRpc, dwErrorCode, ppwszError),
dwError);
}
else
{
DO_RPC(pkg_rpc_get_error_string(
hHandle->hRpc, dwErrorCode, ppwszError),
dwError);
}
BAIL_ON_PMD_ERROR(dwError);
error:
return dwError;
}
uint32_t
pkg_get_error_string(
PPMDHANDLE hHandle,
uint32_t dwErrorCode,
char** ppszError
)
{
uint32_t dwError = 0;
wstring_t pwszError = NULL;
char *pszError = NULL;
if(!hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_get_error_string_w(
hHandle,
dwErrorCode,
&pwszError);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringAFromW(
pwszError,
&pszError);
BAIL_ON_PMD_ERROR(dwError);
*ppszError = pszError;
cleanup:
PMDRpcClientFreeStringW(pwszError);
return dwError;
error:
if(ppszError)
{
*ppszError = NULL;
}
PMD_SAFE_FREE_MEMORY(pszError);
goto cleanup;
}
void
pmd_free_wstring_array(
PPMD_WSTRING_ARRAY pArray
)
{
if(!pArray)
{
return;
}
while(pArray->dwCount)
{
PMDFreeMemory(pArray->ppwszStrings[--pArray->dwCount]);
}
PMD_SAFE_FREE_MEMORY(pArray->ppwszStrings);
PMDFreeMemory(pArray);
}
void
pkg_free_updateinfo_summary(
PTDNF_UPDATEINFO_SUMMARY pSummary
)
{
if(pSummary)
{
PMD_SAFE_FREE_MEMORY(pSummary);
}
}
void
pkg_free_solvedinfo(
PTDNF_SOLVED_PKG_INFO pSolvedInfo
)
{
if(pSolvedInfo)
{
pkg_free_package_info_list(pSolvedInfo->pPkgsExisting);
pkg_free_package_info_list(pSolvedInfo->pPkgsToInstall);
pkg_free_package_info_list(pSolvedInfo->pPkgsToUpgrade);
pkg_free_package_info_list(pSolvedInfo->pPkgsToDowngrade);
pkg_free_package_info_list(pSolvedInfo->pPkgsNotAvailable);
pkg_free_package_info_list(pSolvedInfo->pPkgsToRemove);
pkg_free_package_info_list(pSolvedInfo->pPkgsToReinstall);
PMDFreeStringArray(pSolvedInfo->ppszPkgsNotResolved);
PMD_SAFE_FREE_MEMORY(pSolvedInfo);
}
}
|
oliverkurth/pmd
|
tools/cli/netmgmt/net_main.c
|
<filename>tools/cli/netmgmt/net_main.c
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
uint32_t
netmgr_print_error(
PPMDHANDLE hPMD,
uint32_t dwErrorCode
);
static const char *
link_state_to_string(
NET_LINK_STATE state
)
{
switch (state)
{
case RPC_LINK_DOWN:
return "down";
case RPC_LINK_UP:
return "up";
default:
return "unknown";
}
}
static const char *
link_mode_to_string(
NET_RPC_LINK_MODE mode
)
{
switch (mode)
{
case RPC_LINK_AUTO:
return "auto";
case RPC_LINK_MANUAL:
return "manual";
default:
return "unknown";
}
}
const char *
ip_addr_type_to_string(
NET_ADDR_TYPE addrType
)
{
switch (addrType)
{
case STATIC_IPV4:
return "IPv4 static";
case STATIC_IPV6:
return "IPv6 static";
case DHCP_IPV4:
return "IPv4 dhcp";
case DHCP_IPV6:
return "IPv6 dhcp";
case AUTO_IPV6:
return "IPv6 autoconf";
case LINK_LOCAL_IPV6:
return "IPv6 link-local";
default:
break;
}
return "Unknown addrtype";
}
static uint32_t
cmd_link_info(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0, mtu = 0;
char *pszIfname = NULL, *pszLinkMode = NULL, *pszLinkState = NULL;
char *pszMacAddr = NULL, *pszMtu = NULL, *pszEnd = NULL;
NET_LINK_MODE linkMode = LINK_MODE_UNKNOWN;
NET_LINK_INFO *pLinkInfo = NULL, *cur = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
switch (pCmd->op)
{
case OP_SET:
dwError = netmgrcli_find_cmdopt(pCmd, "interface", &pszIfname);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgrcli_find_cmdopt(pCmd, "macaddr", &pszMacAddr);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if (pszMacAddr != NULL)
{
dwError = netmgr_client_set_mac_addr(hPMD,
pszIfname,
pszMacAddr);
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "mode", &pszLinkMode);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if (pszLinkMode != NULL)
{
if (!strcmp(pszLinkMode, "manual"))
{
linkMode = LINK_MANUAL;
}
else if (!strcmp(pszLinkMode, "auto"))
{
linkMode = LINK_AUTO;
}
dwError = netmgr_client_set_link_mode(hPMD,
pszIfname,
linkMode);
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "mtu", &pszMtu);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if (pszMtu != NULL)
{
mtu = (uint32_t)strtoul(pszMtu, &pszEnd, 10);
dwError = netmgr_client_set_link_mtu(hPMD, pszIfname, mtu);
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "state", &pszLinkState);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if (pszLinkState != NULL)
{
if (!strcmp(pszLinkState, "up"))
{
dwError = netmgr_client_ifup(hPMD, pszIfname);
}
else if (!strcmp(pszLinkState, "down"))
{
dwError = netmgr_client_ifdown(hPMD, pszIfname);
}
BAIL_ON_CLI_ERROR(dwError);
}
break;
case OP_GET:
dwError = netmgrcli_find_cmdopt(pCmd, "interface", &pszIfname);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_get_link_info(hPMD,
pszIfname,
&pLinkInfo);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "%-10s\t%-17s\t%-10s\t%-10s\t%-10s\n", "Name",
"MacAddress", "Mode", "MTU", "State");
for (cur = pLinkInfo; cur; cur = cur->pNext)
{
fprintf(stdout, "%-10s\t", cur->pszInterfaceName);
fprintf(stdout, "%-17s\t", cur->pszMacAddress);
fprintf(stdout, "%-10s\t", link_mode_to_string(cur->mode));
fprintf(stdout, "%-10u\t", cur->mtu);
fprintf(stdout, "%-25s\n", link_state_to_string(cur->state));
}
break;
default:
dwError = EINVAL;
}
BAIL_ON_CLI_ERROR(dwError);
cleanup:
for (cur = pLinkInfo; cur; cur = pLinkInfo)
{
pLinkInfo = cur->pNext;
free(cur->pszMacAddress);
free(cur->pszInterfaceName);
free(cur);
}
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_ip4_address(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0;
NET_IPV4_ADDR_MODE ip4Mode;
char *pszIfName = NULL, *pszMode = NULL;
char *pszIpAddr = NULL, *pszGateway = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "interface", &pszIfName);
if (pCmd->op == OP_SET)
{
dwError = netmgrcli_find_cmdopt(pCmd, "mode", &pszMode);
BAIL_ON_CLI_ERROR(dwError);
if (!strcmp(pszMode, "dhcp"))
{
ip4Mode = IPV4_ADDR_MODE_DHCP;
}
else if (!strcmp(pszMode, "static"))
{
ip4Mode = IPV4_ADDR_MODE_STATIC;
}
else if (!strcmp(pszMode, "none"))
{
ip4Mode = IPV4_ADDR_MODE_NONE;
}
else
{
dwError = EINVAL;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "address", &pszIpAddr);
netmgrcli_find_cmdopt(pCmd, "gateway", &pszGateway);
dwError = netmgr_client_set_ipv4_addr_gateway(hPMD,
pszIfName,
ip4Mode,
pszIpAddr,
pszGateway);
pszIpAddr = NULL;
pszGateway = NULL;
BAIL_ON_CLI_ERROR(dwError);
}
if (pCmd->op == OP_GET)
{
dwError = netmgr_client_get_ipv4_addr_gateway(hPMD,
pszIfName,
&ip4Mode,
&pszIpAddr,
&pszGateway);
BAIL_ON_CLI_ERROR(dwError);
if (ip4Mode == IPV4_ADDR_MODE_NONE)
{
fprintf(stdout, "IPv4 Address Mode: none\n");
}
else if (ip4Mode == IPV4_ADDR_MODE_DHCP)
{
fprintf(stdout, "IPv4 Address Mode: dhcp\n");
}
else
{
fprintf(stdout, "IPv4 Address Mode: static\n");
}
if (pszIpAddr != NULL)
{
fprintf(stdout, "IPv4 Address=%s\n", pszIpAddr);
}
if (pszGateway != NULL)
{
fprintf(stdout, "IPv4 Gateway=%s\n", pszGateway);
}
}
cleanup:
/* Free allocated memory */
PMD_CLI_SAFE_FREE_MEMORY(pszIpAddr);
PMD_CLI_SAFE_FREE_MEMORY(pszGateway);
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_ip6_address(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0, dhcp = 0, autoconf = 0;
char *pszIfName = NULL, *pszDhcp = NULL, *pszAutoconf = NULL;
char *a1, *a2, *pszIpAddrList = NULL, *pszGateway = NULL;
NET_IP_ADDR **ppIpAddrList = NULL;
size_t i, count = 0;
CMD_OP addrOp = OP_MAX;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "interface", &pszIfName);
switch (pCmd->op)
{
case OP_ADD:
case OP_DEL:
dwError = netmgrcli_find_cmdopt(pCmd, "addrlist", &pszIpAddrList);
if (dwError != ENOENT)
{
BAIL_ON_CLI_ERROR(dwError);
}
if (pszIpAddrList != NULL)
{
a2 = pszIpAddrList;
do {
a1 = strsep(&a2, ",");
if (strlen(a1) == 0)
{
continue;
}
if (pCmd->op == OP_ADD)
{
dwError = netmgr_client_add_static_ipv6_addr(
hPMD,
pszIfName,
a1);
}
else
{
dwError = netmgr_client_delete_static_ipv6_addr(
hPMD,
pszIfName,
a1);
}
BAIL_ON_CLI_ERROR(dwError);
} while (a2 != NULL);
}
dwError = netmgrcli_find_cmdopt(pCmd, "gateway", &pszGateway);
if (dwError != ENOENT)
{
BAIL_ON_CLI_ERROR(dwError);
}
if (pszGateway)
{
if (pCmd->op == OP_ADD)
{
dwError = netmgr_client_set_ipv6_gateway(hPMD,
pszIfName,
pszGateway);
}
else
{
dwError = netmgr_client_set_ipv6_gateway(hPMD,
pszIfName,
NULL);
}
BAIL_ON_CLI_ERROR(dwError);
}
/* fall through */
case OP_SET:
dwError = netmgrcli_find_cmdopt(pCmd, "dhcp", &pszDhcp);
if (dwError != ENOENT)
{
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "autoconf", &pszAutoconf);
if (dwError != ENOENT)
{
BAIL_ON_CLI_ERROR(dwError);
}
if (pszDhcp != NULL)
{
if (!strcmp(pszDhcp, "1"))
{
dhcp = 1;
}
}
if (pszAutoconf != NULL)
{
if (!strcmp(pszAutoconf, "1"))
{
autoconf = 1;
}
}
dwError = netmgr_client_set_ipv6_addr_mode(hPMD,
pszIfName,
dhcp,
autoconf);
BAIL_ON_CLI_ERROR(dwError);
break;
case OP_GET:
dwError = netmgr_client_get_ipv6_addr_mode(hPMD,
pszIfName,
&dhcp,
&autoconf);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_get_ip_addr(
hPMD,
pszIfName,
STATIC_IPV6 | AUTO_IPV6 | DHCP_IPV6,
&count,
&ppIpAddrList);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_get_ipv6_gateway(hPMD,
pszIfName,
&pszGateway);
if (dwError == ENOENT)
{
dwError = 0;
}
if (dhcp)
{
fprintf(stdout, "DHCP IPv6 enabled\n");
}
if (autoconf)
{
fprintf(stdout, "Autoconf IPv6 enabled\n");
}
for (i = 0; i < count; i++)
{
fprintf(stdout, "%s Address=%s\n",
ip_addr_type_to_string(ppIpAddrList[i]->type),
ppIpAddrList[i]->pszIPAddrPrefix);
}
if (pszGateway)
{
fprintf(stdout, "IPv6 Gateway=%s", pszGateway);
}
fprintf(stdout, "\n");
break;
default:
dwError = EINVAL;
}
cleanup:
/* Free allocated memory */
for (i = 0; i < count; i++)
{
PMD_CLI_SAFE_FREE_MEMORY(ppIpAddrList[i]->pszInterfaceName);
PMD_CLI_SAFE_FREE_MEMORY(ppIpAddrList[i]->pszIPAddrPrefix);
PMD_CLI_SAFE_FREE_MEMORY(ppIpAddrList[i]);
}
PMD_CLI_SAFE_FREE_MEMORY(ppIpAddrList);
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_ip_route(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0;
size_t i, dwCount = 0;
char *pszMetric = NULL, *pszScope = NULL;
NET_IP_ROUTE ipRoute = {0}, **ppRoutesList = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "interface", &ipRoute.pszInterfaceName);
switch (pCmd->op)
{
case OP_ADD:
netmgrcli_find_cmdopt(pCmd, "gateway", &ipRoute.pszGateway);
dwError = netmgrcli_find_cmdopt(pCmd, "metric", &pszMetric);
if (dwError == ENOENT)
{
dwError = 0;
ipRoute.metric = 1024;
}
else
{
sscanf(pszMetric, "%u", &ipRoute.metric);
}
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgrcli_find_cmdopt(pCmd, "scope", &pszScope);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
/* fall through */
case OP_DEL:
netmgrcli_find_cmdopt(pCmd, "destination", &ipRoute.pszDestNetwork);
if (pCmd->op == OP_ADD)
{
dwError = netmgr_client_add_static_ip_route(hPMD, &ipRoute);
}
else
{
dwError = netmgr_client_delete_static_ip_route(hPMD, &ipRoute);
}
BAIL_ON_CLI_ERROR(dwError);
break;
case OP_GET:
dwError = netmgr_client_get_static_ip_routes(
hPMD,
ipRoute.pszInterfaceName,
&dwCount,
&ppRoutesList);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "Static IP Routes:\n");
for (i = 0; i < dwCount; i++)
{
fprintf(stdout, "Route #%zu\n", i+1);
fprintf(stdout, " Dest=%s\n", ppRoutesList[i]->pszDestNetwork);
fprintf(stdout, " Gateway=%s\n", ppRoutesList[i]->pszGateway);
fprintf(stdout, " Scope=%u\n", ppRoutesList[i]->scope);
fprintf(stdout, " Metric=%u\n", ppRoutesList[i]->metric);
}
fprintf(stdout, "\n");
break;
default:
dwError = ERROR_PMD_INVALID_PARAMETER;
}
BAIL_ON_CLI_ERROR(dwError);
cleanup:
for (i = 0; i < dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(ppRoutesList[i]->pszInterfaceName);
PMD_SAFE_FREE_MEMORY(ppRoutesList[i]->pszDestNetwork);
PMD_SAFE_FREE_MEMORY(ppRoutesList[i]->pszSourceNetwork);
PMD_SAFE_FREE_MEMORY(ppRoutesList[i]->pszGateway);
PMD_SAFE_FREE_MEMORY(ppRoutesList[i]);
}
PMD_SAFE_FREE_MEMORY(ppRoutesList);
return dwError;
error:
goto cleanup;
}
static unsigned32
netmgr_parse_comma_sep_tokens(
char *pszCommaSepTokens,
uint32_t *add_servers,
size_t *dwCount,
char ***ppszCommaSepTokenList
)
{
uint32_t i = 0, add_flag = 0, count = 0, dwError = 0;
char *pszTokens = NULL, *s1, *s2, **ppszTokensList = NULL;
if (!dwCount || !ppszCommaSepTokenList || !add_servers)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateString(pszCommaSepTokens, &pszTokens);
BAIL_ON_PMD_ERROR(dwError);
if (strlen(pszTokens) > 0)
{
s2 = pszTokens;
do {
s1 = strsep(&s2, ",");
if (strlen(s1) > 0)
{
count++;
}
} while (s2 != NULL);
}
if (count == 0)
{
goto done;
}
dwError = PMDAllocateMemory((count * sizeof(char *)),
(void **)&ppszTokensList);
BAIL_ON_PMD_ERROR(dwError);
strcpy(pszTokens, pszCommaSepTokens);
s2 = pszTokens;
do {
s1 = strsep(&s2, ",");
if (strlen(s1) > 0)
{
if ((i == 0) && !strcmp(s1,"+"))
{
add_flag = 1;
count -= 1;
continue;
}
dwError = PMDAllocateString(s1, &(ppszTokensList[i++]));
BAIL_ON_PMD_ERROR(dwError);
}
} while (s2 != NULL);
done:
*add_servers = add_flag;
*dwCount = count;
*ppszCommaSepTokenList = ppszTokensList;
cleanup:
PMD_SAFE_FREE_MEMORY(pszTokens);
return dwError;
error:
if (add_servers)
{
*add_servers = 0;
}
if (dwCount)
{
*dwCount = 0;
}
if (ppszCommaSepTokenList)
{
*ppszCommaSepTokenList = NULL;
}
for (i = 0; i < count; i++)
{
PMD_SAFE_FREE_MEMORY(ppszTokensList[i]);
}
PMD_SAFE_FREE_MEMORY(ppszTokensList);
goto cleanup;
}
static uint32_t
cmd_dns_servers(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0, add = 0;
size_t dwCount = 0, i = 0;
NET_DNS_MODE dnsMode = DNS_MODE_INVALID;
char *pszIfname = NULL, *pszMode = NULL;
char *pszDnsServers = NULL, *pszNoRestart = NULL;
char *s1, *s2, *pszServers = NULL, **ppszDnsServersList = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "interface", &pszIfname);
switch (pCmd->op)
{
case OP_SET:
dwError = netmgrcli_find_cmdopt(pCmd, "mode", &pszMode);
BAIL_ON_CLI_ERROR(dwError);
if (!strcmp(pszMode, "dhcp"))
{
dnsMode = DHCP_DNS;
}
else if (!strcmp(pszMode, "static"))
{
dnsMode = STATIC_DNS;
}
/* fall through */
case OP_ADD:
case OP_DEL:
dwError = netmgrcli_find_cmdopt(pCmd, "servers", &pszDnsServers);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if (pszDnsServers != NULL)
{
dwError = PMDAllocateString(pszDnsServers, &pszServers);
BAIL_ON_CLI_ERROR(dwError);
if (strlen(pszServers) > 0)
{
s2 = pszServers;
do {
s1 = strsep(&s2, ",");
if (strlen(s1) > 0)
{
dwCount++;
}
} while (s2 != NULL);
}
}
if (!dwCount && (pCmd->op != OP_SET))
{
dwError = EDOM;
BAIL_ON_CLI_ERROR(dwError);
}
if (dwCount > 0)
{
dwError = PMDAllocateMemory(
(dwCount * sizeof(char*)),
(void **)&ppszDnsServersList);
BAIL_ON_CLI_ERROR(dwError);
strcpy(pszServers, pszDnsServers);
s2 = pszServers;
do {
s1 = strsep(&s2, ",");
if (strlen(s1) > 0)
{
dwError = PMDAllocateString(
s1,
&(ppszDnsServersList[i++]));
BAIL_ON_CLI_ERROR(dwError);
}
} while (s2 != NULL);
}
dwError = netmgrcli_find_cmdopt(pCmd, "norestart", &pszNoRestart);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if ((pszNoRestart != NULL) && !strcmp(pszNoRestart, "true"))
{
//TODO: Handle norestart
}
if (pCmd->op == OP_SET)
{
dwError = netmgr_client_set_dns_servers(
hPMD,
pszIfname,
dnsMode,
dwCount,
ppszDnsServersList);
}
else if (pCmd->op == OP_ADD)
{
dwError = netmgr_client_add_dns_server(
hPMD,
pszIfname,
ppszDnsServersList[0]);
}
else if (pCmd->op == OP_DEL)
{
dwError = netmgr_client_delete_dns_server(
hPMD,
pszIfname,
ppszDnsServersList[0]);
}
break;
case OP_GET:
dwError = netmgr_client_get_dns_servers(
hPMD,
pszIfname,
&dnsMode,
&dwCount,
&ppszDnsServersList);
BAIL_ON_CLI_ERROR(dwError);
if (dnsMode == STATIC_DNS)
{
fprintf(stdout, "DNSMode=static\n");
}
else
{
fprintf(stdout, "DNSMode=dhcp\n");
}
fprintf(stdout, "DNSServers=");
for (i = 0; i < dwCount; i++)
{
fprintf(stdout, "%s ", ppszDnsServersList[i]);
}
fprintf(stdout, "\n");
break;
default:
dwError = EINVAL;
}
BAIL_ON_CLI_ERROR(dwError);
cleanup:
/* Free allocated memory */
for (i = 0; i < dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(ppszDnsServersList[i]);
}
PMD_SAFE_FREE_MEMORY(ppszDnsServersList);
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_dns_domains(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0, add = 0;
size_t dwCount = 0, i = 0;
char *pszDnsDomains = NULL, **ppszDnsDomains = NULL;
char *pszDomains = NULL, *pszIfname = NULL, *pszNoRestart = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "interface", &pszIfname);
switch (pCmd->op)
{
case OP_SET:
case OP_ADD:
case OP_DEL:
dwError = netmgrcli_find_cmdopt(pCmd, "domains", &pszDnsDomains);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_parse_comma_sep_tokens(
pszDnsDomains,
&add,
&dwCount,
&ppszDnsDomains);
BAIL_ON_PMD_ERROR(dwError);
if (!dwCount && (pCmd->op != OP_SET))
{
dwError = EDOM;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "norestart", &pszNoRestart);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if ((pszNoRestart != NULL) && !strcmp(pszNoRestart, "true"))
{
//TODO: Handle
}
if (pCmd->op == OP_SET)
{
dwError = netmgr_client_set_dns_domains(
hPMD,
pszIfname,
dwCount,
ppszDnsDomains);
}
else if (pCmd->op == OP_ADD)
{
dwError = netmgr_client_add_dns_domain(
hPMD,
pszIfname,
ppszDnsDomains[0]);
}
else if (pCmd->op == OP_DEL)
{
dwError = netmgr_client_delete_dns_domain(
hPMD,
pszIfname,
ppszDnsDomains[0]);
BAIL_ON_CLI_ERROR(dwError);
}
BAIL_ON_CLI_ERROR(dwError);
break;
case OP_GET:
dwError = netmgr_client_get_dns_domains(
hPMD,
pszIfname,
&dwCount,
&ppszDnsDomains);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "Domains=");
for (i = 0; i < dwCount; i++)
{
fprintf(stdout, "%s ", ppszDnsDomains[i]);
}
fprintf(stdout, "\n");
break;
default:
dwError = EINVAL;
}
cleanup:
/* Free allocated memory */
for (i = 0; i < dwCount; i++)
{
PMD_SAFE_FREE_MEMORY(ppszDnsDomains[i]);
}
PMD_SAFE_FREE_MEMORY(ppszDnsDomains);
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_if_iaid(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0, dwIaid;
char *pszIaid = NULL, *pszIfname = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "interface", &pszIfname);
BAIL_ON_CLI_ERROR(dwError);
if (pCmd->op == OP_SET)
{
dwError = netmgrcli_find_cmdopt(pCmd, "iaid", &pszIaid);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_set_iaid(hPMD, pszIfname, atoi(pszIaid));
BAIL_ON_CLI_ERROR(dwError);
}
if (pCmd->op == OP_GET)
{
dwError = netmgr_client_get_iaid(hPMD, pszIfname, &dwIaid);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "IAID=%u\n", dwIaid);
}
cleanup:
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_dhcp_duid(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0;
char *pszDuid = NULL, *pszIfName = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "interface", &pszIfName);
if (pCmd->op == OP_SET)
{
dwError = netmgrcli_find_cmdopt(pCmd, "duid", &pszDuid);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_set_duid(hPMD, pszIfName, pszDuid);
pszDuid = NULL;
BAIL_ON_CLI_ERROR(dwError);
}
if (pCmd->op == OP_GET)
{
dwError = netmgr_client_get_duid(hPMD, pszIfName, &pszDuid);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "DUID=%s\n", pszDuid);
}
cleanup:
/* Free allocated memory */
PMD_CLI_SAFE_FREE_MEMORY(pszDuid);
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_ntp_servers(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd
)
{
uint32_t dwError = 0;
char **ppszServers = NULL;
size_t nServers = 0;
uint32_t dummy = 0;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
if (pCmd->op == OP_SET || pCmd->op == OP_ADD || pCmd->op == OP_DEL)
{
char *pszServersCmdLine = NULL;
dwError = netmgrcli_find_cmdopt(pCmd, "servers", &pszServersCmdLine);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_parse_comma_sep_tokens(
pszServersCmdLine,
&dummy,
&nServers,
&ppszServers);
BAIL_ON_PMD_ERROR(dwError);
switch(pCmd->op)
{
case OP_SET:
dwError = netmgr_client_set_ntp_servers(
hPMD,
nServers,
ppszServers);
BAIL_ON_CLI_ERROR(dwError);
break;
case OP_ADD:
dwError = netmgr_client_add_ntp_servers(
hPMD,
nServers,
(const char **)ppszServers);
BAIL_ON_CLI_ERROR(dwError);
break;
case OP_DEL:
dwError = netmgr_client_delete_ntp_servers(
hPMD,
nServers,
(const char **)ppszServers);
BAIL_ON_CLI_ERROR(dwError);
break;
default:
break;
}
}
else if (pCmd->op == OP_GET)
{
int i = 0;
dwError = netmgr_client_get_ntp_servers(hPMD, &nServers, &ppszServers);
BAIL_ON_CLI_ERROR(dwError);
for(i = 0; i < nServers; ++i)
{
fprintf(stdout,
"%s%s",
ppszServers[i],
(i+1) < nServers ? "," : "");
}
fprintf(stdout, "\n");
}
cleanup:
/* Free allocated memory */
PMDFreeStringArrayWithCount(ppszServers, nServers);
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_hostname(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0;
char *pszHostname = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
if (pCmd->op == OP_SET)
{
dwError = netmgrcli_find_cmdopt(pCmd, "hostname", &pszHostname);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_set_hostname(hPMD, pszHostname);
pszHostname = NULL;
BAIL_ON_CLI_ERROR(dwError);
}
if (pCmd->op == OP_GET)
{
dwError = netmgr_client_get_hostname(hPMD, &pszHostname);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "Hostname: %s\n", pszHostname);
}
cleanup:
/* Free allocated memory */
PMD_CLI_SAFE_FREE_MEMORY(pszHostname);
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_wait_for_link(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0;
long int ltimeout = 0;
char *pszIfname = NULL, *pszTimeOut = NULL, *pszEnd = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "interface", &pszIfname);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgrcli_find_cmdopt(pCmd, "timeout", &pszTimeOut);
BAIL_ON_CLI_ERROR(dwError);
if ((ltimeout = strtol(pszTimeOut, &pszEnd, 10)) < 0)
{
dwError= ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgr_client_wait_for_link_up(hPMD,
pszIfname,
(uint32_t)ltimeout);
BAIL_ON_CLI_ERROR(dwError);
cleanup:
return dwError;
error:
goto cleanup;
}
typedef struct _NM_CLI_ADDR_STR_TYPE
{
char *pszIpAddrType;
NET_ADDR_TYPE ipAddrType;
} NM_CLI_ADDR_STR_TYPE, *PNM_CLI_ADDR_STR_TYPE;
NM_CLI_ADDR_STR_TYPE addrStrToTypeMap[] =
{
{ "ipv4", NET_ADDR_IPV4 },
{ "ipv6", NET_ADDR_IPV6 },
{ "static_ipv4", STATIC_IPV4 },
{ "static_ipv6", STATIC_IPV6 },
{ "dhcp_ipv4", DHCP_IPV4 },
{ "dhcp_ipv6", DHCP_IPV6 },
{ "auto_ipv6", AUTO_IPV6 },
{ "link_local_ipv6", LINK_LOCAL_IPV6 },
};
static uint32_t
get_ip_addrtype(
const char *pszAddrType,
NET_ADDR_TYPE *pIpAddrType)
{
uint32_t dwError = 0;
NET_ADDR_TYPE addrType = 0;
size_t i = 0, addrTypeCount = 0;
if (IsNullOrEmptyString(pszAddrType) || !pIpAddrType)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
addrTypeCount = sizeof(addrStrToTypeMap)/sizeof(NM_CLI_ADDR_STR_TYPE);
for (i = 0; i < addrTypeCount; i++)
{
if (!strcmp(pszAddrType, addrStrToTypeMap[i].pszIpAddrType))
{
addrType = addrStrToTypeMap[i].ipAddrType;
break;
}
}
if (!addrType)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
*pIpAddrType = addrType;
cleanup:
return dwError;
error:
if (pIpAddrType)
{
*pIpAddrType = 0;
}
goto cleanup;
}
static uint32_t
cmd_wait_for_ip(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0, dummy = 0;
long int ltimeout = 0;
char *pszIfname = NULL, *pszTimeOut = NULL, *pszEnd = NULL;
char *pszAddrTypes = NULL;
char **ppszIpAddrTypeList = NULL;
size_t i = 0, ipAddrTypeCount = 0;
NET_ADDR_TYPE ipAddrTypes = 0, addrType = 0;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "interface", &pszIfname);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgrcli_find_cmdopt(pCmd, "timeout", &pszTimeOut);
BAIL_ON_CLI_ERROR(dwError);
if ((ltimeout = strtol(pszTimeOut, &pszEnd, 10)) < 0)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "addrtype", &pszAddrTypes);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_parse_comma_sep_tokens(pszAddrTypes,
&dummy,
&ipAddrTypeCount,
&ppszIpAddrTypeList);
BAIL_ON_PMD_ERROR(dwError);
for (i = 0; i < ipAddrTypeCount; i++)
{
addrType = 0;
dwError = get_ip_addrtype(ppszIpAddrTypeList[i], &addrType);
BAIL_ON_PMD_ERROR(dwError);
ipAddrTypes |= addrType;
}
dwError = netmgr_client_wait_for_ip(hPMD,
pszIfname,
(uint32_t)ltimeout,
ipAddrTypes);
BAIL_ON_CLI_ERROR(dwError);
cleanup:
/* Free allocated memory */
for (i = 0; i < ipAddrTypeCount; i++)
{
PMD_SAFE_FREE_MEMORY(ppszIpAddrTypeList[i]);
}
PMD_SAFE_FREE_MEMORY(ppszIpAddrTypeList);
return dwError;
error:
goto cleanup;;
}
static uint32_t
cmd_err_info(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0, dwErrCode = 0;
char *pszErrCode = NULL, *pszEnd = NULL, *pszErrInfo = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgrcli_find_cmdopt(pCmd, "errcode", &pszErrCode);
BAIL_ON_CLI_ERROR(dwError);
dwErrCode = strtol(pszErrCode, &pszEnd, 10);
dwError = errno;
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_get_error_info(hPMD, dwErrCode, &pszErrInfo);
BAIL_ON_PMD_ERROR(dwError);
if (pszErrInfo == NULL)
{
dwError = ENOENT;
BAIL_ON_PMD_ERROR(dwError);
}
fprintf(stdout, "ErrorInfo: %s\n", pszErrInfo);
cleanup:
return dwError;
error:
goto cleanup;
}
static uint32_t
cmd_net_info(
PPMDHANDLE hPMD,
PNETMGR_CMD pCmd)
{
uint32_t dwError = 0;
char *pszObjectName = NULL, *pszParamName = NULL, *pszParamValue = NULL;
if(!hPMD || !pCmd)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
netmgrcli_find_cmdopt(pCmd, "objectname", &pszObjectName);
switch (pCmd->op)
{
case OP_SET:
dwError = netmgrcli_find_cmdopt(pCmd, "paramname", &pszParamName);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgrcli_find_cmdopt(pCmd, "paramvalue", &pszParamValue);
if (dwError == ENOENT)
{
dwError = 0;
}
BAIL_ON_CLI_ERROR(dwError);
if (pszParamName != NULL)
{
dwError = netmgr_client_set_network_param(hPMD,
pszObjectName,
pszParamName,
pszParamValue);
pszParamValue = NULL;
BAIL_ON_CLI_ERROR(dwError);
}
break;
case OP_GET:
dwError = netmgrcli_find_cmdopt(pCmd, "paramname", &pszParamName);
BAIL_ON_CLI_ERROR(dwError);
dwError = netmgr_client_get_network_param(hPMD,
pszObjectName,
pszParamName,
&pszParamValue);
BAIL_ON_CLI_ERROR(dwError);
fprintf(stdout, "ParamName: %s, ParamValue: %s\n", pszParamName,
pszParamValue);
break;
default:
dwError = EINVAL;
}
BAIL_ON_CLI_ERROR(dwError);
cleanup:
PMD_CLI_SAFE_FREE_MEMORY(pszParamValue);
return dwError;
error:
goto cleanup;
}
typedef struct _NETMGR_CLI_HANDLER
{
CMD_ID id;
uint32_t (*pFnCmd)(PPMDHANDLE, PNETMGR_CMD);
} NETMGR_CLI_HANDLER, *PNETMGR_CLI_HANDLER;
NETMGR_CLI_HANDLER cmdHandler[] =
{
{ CMD_LINK_INFO, cmd_link_info },
{ CMD_IP4_ADDRESS, cmd_ip4_address },
{ CMD_IP6_ADDRESS, cmd_ip6_address },
{ CMD_IP_ROUTE, cmd_ip_route },
{ CMD_DNS_SERVERS, cmd_dns_servers },
{ CMD_DNS_DOMAINS, cmd_dns_domains },
{ CMD_DHCP_DUID, cmd_dhcp_duid },
{ CMD_IF_IAID, cmd_if_iaid },
{ CMD_NTP_SERVERS, cmd_ntp_servers },
{ CMD_HOSTNAME, cmd_hostname },
{ CMD_WAIT_FOR_LINK, cmd_wait_for_link },
{ CMD_WAIT_FOR_IP, cmd_wait_for_ip },
{ CMD_ERR_INFO, cmd_err_info },
{ CMD_NET_INFO, cmd_net_info },
};
uint32_t
netmgr_main(
int argc,
char* const* argv,
PPMD_CMD_ARGS pMainArgs)
{
uint32_t dwError = 0;
size_t i, cmdCount = sizeof(cmdHandler)/sizeof(NETMGR_CLI_HANDLER);
PPMDHANDLE hPMD = NULL;
PNETMGR_CMD pCmd = NULL;
char *arg1;
arg1 = (char *)argv[1];
if (argc > 2)
{
strcpy(arg1, argv[2]);
}
dwError = netmgrcli_parse_cmdline(argc, (char **)argv, &pCmd);
BAIL_ON_CLI_ERROR(dwError);
for (i = 0; i < cmdCount; i++)
{
if (pCmd->id == cmdHandler[i].id)
{
dwError = rpc_open(
"net",
pMainArgs->pszServer,
pMainArgs->pszUser,
pMainArgs->pszDomain,
pMainArgs->pszPass,
pMainArgs->pszSpn,
&hPMD);
BAIL_ON_CLI_ERROR(dwError);
dwError = cmdHandler[i].pFnCmd(hPMD, pCmd);
BAIL_ON_CLI_ERROR(dwError);
break;
}
}
cleanup:
rpc_free_handle(hPMD);
if(pCmd)
{
netmgrcli_free_cmd(pCmd);
}
return dwError;
error:
if(netmgr_print_error(hPMD, dwError) == 0)
{
dwError = ERROR_PMD_FAIL;//already handled
}
goto cleanup;
}
uint32_t
netmgr_print_error(
PPMDHANDLE hPMD,
uint32_t dwErrorCode
)
{
uint32_t dwError = 0;
char* pszError = NULL;
if(dwErrorCode >= ERROR_PMD_NET_BASE)
{
if(!hPMD)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_CLI_ERROR(dwError);
}
dwError = netmgr_client_get_error_info(hPMD, dwErrorCode, &pszError);
BAIL_ON_CLI_ERROR(dwError);
}
else
{
dwError = dwErrorCode;
goto cleanup;//let the super main handle
}
printf("Error(%d) : %s\n", dwErrorCode, pszError);
cleanup:
PMD_CLI_SAFE_FREE_MEMORY(pszError);
return dwError;
error:
printf(
"Retrieving error string for %d failed with %d\n",
dwErrorCode,
dwError);
goto cleanup;
}
|
oliverkurth/pmd
|
python/netmgmt_py.c
|
<filename>python/netmgmt_py.c
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
static char net__doc__[] = "";
static void
net_dealloc(PY_NET *self)
{
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
net_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
uint32_t dwError = 0;
PPY_NET self = NULL;
self = (PPY_NET)type->tp_alloc(type, 0);
if (self != NULL)
{
if (!(self->server = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
cleanup:
return (PyObject *)self;
error:
Py_DECREF(self);
self = NULL;
goto cleanup;
}
static int
net_init(PY_NET *self, PyObject *args, PyObject *kwds)
{
uint32_t dwError = 0;
PyObject *server = NULL;
PyObject *tmp = NULL;
static char *kwlist[] = {"server"};
if (! PyArg_ParseTuple(args, "|S", &server))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (server)
{
tmp = self->server;
Py_INCREF(server);
self->server = server;
Py_XDECREF(tmp);
}
cleanup:
return dwError > 0 ? -1 : 0;
error:
goto cleanup;
}
static void
raise_javelin_exception(
PPY_NET self,
uint32_t dwPmdErrCode
)
{
uint32_t dwError = 0;
char szErrMsg[MAX_LINE_LENGTH];
// TODO: Improve this - get PMD err string
sprintf(szErrMsg, "javelin error code=%u", dwPmdErrCode);
PyErr_SetString(PyExc_Exception, szErrMsg);
return;
}
static void
raise_netmgr_exception(
PPY_NET self,
uint32_t dwNmErrCode
)
{
uint32_t dwError = 0;
char *pszErrInfo = NULL;
char szErrMsg[MAX_LINE_LENGTH];
if ((dwNmErrCode > NM_BASE_ERROR) && (dwNmErrCode < NM_MAX_ERROR))
{
dwError = netmgr_client_get_error_info(self->hHandle,
dwNmErrCode,
&pszErrInfo);
BAIL_ON_PMD_ERROR(dwError);
sprintf(szErrMsg,
"netmgr error code=%u msg=%s",
dwNmErrCode,
pszErrInfo);
PyErr_SetString(PyExc_Exception, szErrMsg);
}
else
{
raise_javelin_exception(self, dwNmErrCode);
}
cleanup:
PMDFreeMemory(pszErrInfo);
return;
error:
sprintf(szErrMsg,
"javelin error code=%u raising netmgr exception for code=%u",
dwError,
dwNmErrCode);
PyErr_SetString(PyExc_Exception, szErrMsg);
goto cleanup;
}
static PyObject *
set_link_iaid(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
uint32_t dwIaid = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", "iaid", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"sI",
kwlist,
&pszInterfaceName,
&dwIaid))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_iaid(self->hHandle, pszInterfaceName, dwIaid);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_link_iaid(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
uint32_t dwIaid = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg, kwds, "s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_iaid(self->hHandle, pszInterfaceName, &dwIaid);
BAIL_ON_PMD_ERROR(dwError);
pyRes = Py_BuildValue("i", dwIaid);
cleanup:
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_dhcp_duid(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszDuid = NULL;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"duid", "ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s|s",
kwlist,
&pszDuid,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_duid(self->hHandle, pszInterfaceName, pszDuid);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_dhcp_duid(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszDuid = NULL;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if(!PyArg_ParseTupleAndKeywords(arg, kwds, "|s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_duid(self->hHandle, pszInterfaceName, &pszDuid);
BAIL_ON_PMD_ERROR(dwError);
pyRes = Py_BuildValue("s", pszDuid);
cleanup:
PMDFreeMemory(pszDuid);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_link_macaddr(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
char *pszMacAddr = NULL;
static char *kwlist[] = {"ifname", "macaddr", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"sz",
kwlist,
&pszInterfaceName,
&pszMacAddr))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_mac_addr(self->hHandle,
pszInterfaceName,
pszMacAddr);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_link_macaddr(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszMacAddr = NULL;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg, kwds, "s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_mac_addr(self->hHandle, pszInterfaceName, &pszMacAddr);
BAIL_ON_PMD_ERROR(dwError);
pyRes = Py_BuildValue("s", pszMacAddr);
cleanup:
PMDFreeMemory(pszMacAddr);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_link_mtu(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, mtu = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", "mtu", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"sI",
kwlist,
&pszInterfaceName,
&mtu))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_link_mtu(self->hHandle, pszInterfaceName, mtu);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_link_mtu(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
uint32_t mtu;
char *pszInterfaceName = NULL, *pszErr = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg, kwds, "s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_link_mtu(self->hHandle, pszInterfaceName, &mtu);
BAIL_ON_PMD_ERROR(dwError);
pyRes = Py_BuildValue("i", mtu);
cleanup:
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_link_mode(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
int link_mode = LINK_MODE_UNKNOWN;
char *pszLinkMode = NULL;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", "link_mode", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss",
kwlist,
&pszInterfaceName,
&pszLinkMode))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!strcmp(pszLinkMode, "manual"))
{
link_mode = LINK_MANUAL;
}
else if (!strcmp(pszLinkMode, "auto"))
{
link_mode = LINK_AUTO;
}
else
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_link_mode(self->hHandle,
pszInterfaceName,
link_mode);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_link_mode(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
NET_LINK_MODE mode;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg, kwds, "s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_link_mode(self->hHandle, pszInterfaceName, &mode);
BAIL_ON_PMD_ERROR(dwError);
pyRes = Py_BuildValue("s", py_link_mode_to_string(mode));
cleanup:
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_link_state(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
int link_state = LINK_STATE_UNKNOWN;
char *pszInterfaceName = NULL;
char *pszLinkState = NULL;
static char *kwlist[] = {"ifname", "link_state", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss",
kwlist,
&pszInterfaceName,
&pszLinkState))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!strcmp(pszLinkState, "up"))
{
link_state = LINK_UP;
}
else if (!strcmp(pszLinkState, "down"))
{
link_state = LINK_DOWN;
}
else
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_link_state(self->hHandle,
pszInterfaceName,
link_state);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_link_state(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
NET_LINK_STATE state;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg, kwds, "s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_link_state(self->hHandle, pszInterfaceName, &state);
BAIL_ON_PMD_ERROR(dwError);
pyRes = Py_BuildValue("s", py_link_state_to_string(state));
cleanup:
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_link_up(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s",
kwlist,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_ifup(self->hHandle, pszInterfaceName);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_link_down(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s",
kwlist,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_ifdown(self->hHandle, pszInterfaceName);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_ipv4_addr_gateway(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
int ip4Mode = IPV4_ADDR_MODE_MAX;
char *pszMode = NULL;
char *pszIPv4AddrPrefix = NULL;
char *pszIPv4Gateway = NULL;
static char *kwlist[] = {"ifname",
"addr_mode",
"addr_prefix",
"gateway",
NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss|s|s",
kwlist,
&pszInterfaceName,
&pszMode,
&pszIPv4AddrPrefix,
&pszIPv4Gateway))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!strcmp(pszMode, "dhcp"))
{
ip4Mode = IPV4_ADDR_MODE_DHCP;
}
else if (!strcmp(pszMode, "static"))
{
ip4Mode = IPV4_ADDR_MODE_STATIC;
}
else if (!strcmp(pszMode, "none"))
{
ip4Mode = IPV4_ADDR_MODE_NONE;
}
else
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_ipv4_addr_gateway(self->hHandle,
pszInterfaceName,
ip4Mode,
pszIPv4AddrPrefix,
pszIPv4Gateway);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_ipv4_addr_gateway(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
NET_IPV4_ADDR_MODE addrMode = IPV4_ADDR_MODE_NONE;
char *pszIPv4AddrPrefix = NULL;
char *pszIPv4Gateway = NULL;
char *pszAddrMode = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg, kwds, "s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_ipv4_addr_gateway(self->hHandle,
pszInterfaceName,
&addrMode,
&pszIPv4AddrPrefix,
&pszIPv4Gateway);
BAIL_ON_PMD_ERROR(dwError);
if (addrMode == IPV4_ADDR_MODE_NONE)
{
pszAddrMode = "none";
}
else if (addrMode == IPV4_ADDR_MODE_DHCP)
{
pszAddrMode = "dhcp";
}
else
{
pszAddrMode = "static";
}
pyRes = PyTuple_New(3);
PyTuple_SetItem(pyRes, 0, Py_BuildValue("s", pszAddrMode));
PyTuple_SetItem(pyRes, 1, Py_BuildValue("s", pszIPv4AddrPrefix));
PyTuple_SetItem(pyRes, 2, Py_BuildValue("s", pszIPv4Gateway));
cleanup:
PMDFreeMemory(pszIPv4AddrPrefix);
PMDFreeMemory(pszIPv4Gateway);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
add_static_ipv6_addr(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
char *pszIPv6AddrPrefix = NULL;
static char *kwlist[] = {"ifname", "addr_prefix", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss",
kwlist,
&pszInterfaceName,
&pszIPv6AddrPrefix))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_add_static_ipv6_addr(self->hHandle,
pszInterfaceName,
pszIPv6AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
delete_static_ipv6_addr(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
char *pszIPv6AddrPrefix = NULL;
static char *kwlist[] = {"ifname", "addr_prefix", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss",
kwlist,
&pszInterfaceName,
&pszIPv6AddrPrefix))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_delete_static_ipv6_addr(self->hHandle,
pszInterfaceName,
pszIPv6AddrPrefix);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_ipv6_addr(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t j, count = 0;
uint32_t addrTypes = DHCP_IPV6 | AUTO_IPV6 | STATIC_IPV6;
char *pszInterfaceName = NULL;
char *pszType = NULL;
NET_IP_ADDR **ppipaddrList = NULL;
static char *kwlist[] = {"ifname", "type", NULL};
PyObject *pyRes = Py_None;
PyObject *pPyIpv6AddrList = PyList_New(0);
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s|s",
kwlist,
&pszInterfaceName,
&pszType))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pszType != NULL)
{
addrTypes = 0;
if (strcasestr(pszType, "dhcp"))
{
addrTypes |= DHCP_IPV6;
}
if (strcasestr(pszType, "static"))
{
addrTypes |= STATIC_IPV6;
}
if (strcasestr(pszType, "autoconf"))
{
addrTypes |= AUTO_IPV6;
}
if (strcasestr(pszType, "linklocal"))
{
addrTypes |= LINK_LOCAL_IPV6;
}
}
dwError = netmgr_client_get_ip_addr(self->hHandle,
pszInterfaceName,
addrTypes,
&count,
&ppipaddrList);
if (dwError == NM_ERR_VALUE_NOT_FOUND)
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
for (j = 0; j < count; j++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppipaddrList[j]->pszIPAddrPrefix);
if (PyList_Append(pPyIpv6AddrList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
pyRes = pPyIpv6AddrList;
cleanup:
if (ppipaddrList)
{
for (j = 0; j < count; j++)
{
PMDFreeMemory(ppipaddrList[j]->pszInterfaceName);
PMDFreeMemory(ppipaddrList[j]->pszIPAddrPrefix);
PMDFreeMemory(ppipaddrList[j]);
}
PMDFreeMemory(ppipaddrList);
}
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_ipv6_addr_mode(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
uint32_t enableDhcp = 0;
uint32_t enableAutoconf = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname",
"enable_dhcp",
"enable_autoconf",
NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"sii",
kwlist,
&pszInterfaceName,
&enableDhcp,
&enableAutoconf))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_ipv6_addr_mode(self->hHandle,
pszInterfaceName,
enableDhcp,
enableAutoconf);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_ipv6_addr_mode(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
uint32_t enableDhcp = 0;
uint32_t enableAutoconf = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg, kwds, "s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_ipv6_addr_mode(self->hHandle,
pszInterfaceName,
&enableDhcp,
&enableAutoconf);
BAIL_ON_PMD_ERROR(dwError);
pyRes = PyTuple_New(2);
PyTuple_SetItem(pyRes, 0, Py_BuildValue("i", enableDhcp));
PyTuple_SetItem(pyRes, 1, Py_BuildValue("i", enableAutoconf));
cleanup:
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_ipv6_gateway(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
char *pszIPv6Gateway = NULL;
static char *kwlist[] = {"ifname", "gateway", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"sz",
kwlist,
&pszInterfaceName,
&pszIPv6Gateway))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_ipv6_gateway(self->hHandle,
pszInterfaceName,
pszIPv6Gateway);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_ipv6_gateway(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
char *pszIPv6Gateway = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s",
kwlist,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_ipv6_gateway(self->hHandle,
pszInterfaceName,
&pszIPv6Gateway);
BAIL_ON_PMD_ERROR(dwError);
pyRes = Py_BuildValue("s", pszIPv6Gateway);
cleanup:
PMDFreeMemory(pszIPv6Gateway);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
add_dns_server(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char *pszInterfaceName = NULL;
char *pszServer = NULL;
static char *kwlist[] = {"server", "ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s|s",
kwlist,
&pszServer,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_add_dns_server(self->hHandle,
pszInterfaceName,
pszServer);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
delete_dns_server(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char *pszInterfaceName = NULL;
char *pszServer = NULL;
static char *kwlist[] = {"server", "ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s|s",
kwlist,
&pszServer,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_delete_dns_server(self->hHandle,
pszInterfaceName,
pszServer);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_dns_servers(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
int dnsMode = DNS_MODE_MAX;
char *pszMode = NULL;
char *pszInterfaceName = NULL;
char **ppszServersList = NULL;
PyObject *pServerList = Py_None;
static char *kwlist[] = {"dns_mode", "servers", "ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s|O|s",
kwlist,
&pszMode,
&pServerList,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!strcmp(pszMode, "dhcp"))
{
dnsMode = DHCP_DNS;
}
else if (!strcmp(pszMode, "static"))
{
dnsMode = STATIC_DNS;
}
else
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if ((pServerList != Py_None) && (PyList_Size(pServerList) > 0))
{
dwError = py_list_as_string_list(pServerList,
&ppszServersList,
&count);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_dns_servers(self->hHandle,
pszInterfaceName,
dnsMode,
count,
ppszServersList);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArrayWithCount(ppszServersList, count);
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_dns_servers(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
NET_DNS_MODE dnsMode = DNS_MODE_INVALID;
char *pszInterfaceName = NULL;
char *pszDnsMode = NULL;
char **ppszDnsServers = NULL;
PyObject *pPyDnsServersList = Py_None;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if(!PyArg_ParseTupleAndKeywords(arg, kwds, "|s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_dns_servers(self->hHandle,
pszInterfaceName,
&dnsMode,
&count,
&ppszDnsServers);
BAIL_ON_PMD_ERROR(dwError);
pPyDnsServersList = PyList_New(0);
for (i = 0; i < count; i++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszDnsServers[i]);
if (PyList_Append(pPyDnsServersList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
if (dnsMode == DNS_MODE_INVALID)
{
pszDnsMode = "invalid";
}
else if (dnsMode == STATIC_DNS)
{
pszDnsMode = "static";
}
else
{
pszDnsMode = "dhcp";
}
pyRes = PyTuple_New(2);
PyTuple_SetItem(pyRes, 0, Py_BuildValue("s", pszDnsMode));
PyTuple_SetItem(pyRes, 1, pPyDnsServersList);
cleanup:
PMDFreeStringArrayWithCount(ppszDnsServers, count);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_dns_domains(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char *pszInterfaceName = NULL;
char **ppszDomainsList = NULL;
PyObject *pDomainList = Py_None;
static char *kwlist[] = {"domains", "ifname", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"O|s",
kwlist,
&pDomainList,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if ((pDomainList != Py_None) && (PyList_Size(pDomainList) > 0))
{
dwError = py_list_as_string_list(pDomainList,
&ppszDomainsList,
&count);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_dns_domains(self->hHandle,
pszInterfaceName,
count,
ppszDomainsList);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArrayWithCount(ppszDomainsList, count);
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_dns_domains(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char *pszInterfaceName = NULL;
char **ppszDnsDomains = NULL;
PyObject *pPyDnsDomainsList = Py_None;
static char *kwlist[] = {"ifname", NULL};
PyObject *pyRes = Py_None;
if(!PyArg_ParseTupleAndKeywords(arg, kwds, "|s", kwlist, &pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_dns_domains(self->hHandle,
pszInterfaceName,
&count,
&ppszDnsDomains);
if (dwError == NM_ERR_VALUE_NOT_FOUND)
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
pPyDnsDomainsList = PyList_New(0);
for (i = 0; i < count; i++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszDnsDomains[i]);
if (PyList_Append(pPyDnsDomainsList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
pyRes = pPyDnsDomainsList;
cleanup:
PMDFreeStringArrayWithCount(ppszDnsDomains, count);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_ntp_servers(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char *pszInterfaceName = NULL;
char **ppszNtpServersList = NULL;
PyObject *pNtpServerList = Py_None;
static char *kwlist[] = {"ntpservers", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"O",
kwlist,
&pNtpServerList))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = py_list_as_string_list(pNtpServerList,
&ppszNtpServersList,
&count);
BAIL_ON_PMD_ERROR(dwError);
dwError = netmgr_client_set_ntp_servers(self->hHandle,
count,
ppszNtpServersList);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArrayWithCount(ppszNtpServersList, count);
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
add_ntp_servers(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char *pszInterfaceName = NULL;
char **ppszNtpServersList = NULL;
PyObject *pNtpServerList = Py_None;
static char *kwlist[] = {"ntpservers", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"O",
kwlist,
&pNtpServerList))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = py_list_as_string_list(pNtpServerList,
&ppszNtpServersList,
&count);
BAIL_ON_PMD_ERROR(dwError);
dwError = netmgr_client_add_ntp_servers(self->hHandle,
count,
(const char **)ppszNtpServersList);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArrayWithCount(ppszNtpServersList, count);
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
delete_ntp_servers(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char *pszInterfaceName = NULL;
char **ppszNtpServersList = NULL;
PyObject *pNtpServerList = Py_None;
static char *kwlist[] = {"ntpservers", NULL};
PyObject *pyRes = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"O",
kwlist,
&pNtpServerList))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = py_list_as_string_list(pNtpServerList,
&ppszNtpServersList,
&count);
BAIL_ON_PMD_ERROR(dwError);
dwError = netmgr_client_delete_ntp_servers(self->hHandle,
count,
(const char **)ppszNtpServersList);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArrayWithCount(ppszNtpServersList, count);
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_ntp_servers(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
size_t i = 0, count = 0;
char **ppszNtpServers = NULL;
PyObject *pPyNtpServersList = Py_None;
PyObject *pyRes = Py_None;
dwError = netmgr_client_get_ntp_servers(self->hHandle,
&count,
&ppszNtpServers);
if (dwError == NM_ERR_VALUE_NOT_FOUND)
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
pPyNtpServersList = PyList_New(0);
for (i = 0; i < count; i++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszNtpServers[i]);
if (PyList_Append(pPyNtpServersList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
pyRes = pPyNtpServersList;
cleanup:
PMDFreeStringArrayWithCount(ppszNtpServers, count);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
add_static_ip_route(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, metric = 0, table = 0;
char *pszInterfaceName = NULL;
char *pszDestNetwork = NULL;
char *pszSourceNetwork = NULL;
char *pszGateway = NULL;
NET_ROUTE_SCOPE scope = GLOBAL_ROUTE;
NET_IP_ROUTE pIpRoute = {0};
PyObject *pyRes = Py_None;
static char *kwlist[] = {"ifname",
"destination",
"gateway",
"metric",
"source",
"scope",
"table",
NULL};
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"sss|i|s|i|i",
kwlist,
&pszInterfaceName,
&pszDestNetwork,
&pszGateway,
&metric,
&pszSourceNetwork,
&scope,
&table))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pIpRoute.pszInterfaceName = pszInterfaceName;
pIpRoute.pszDestNetwork = pszDestNetwork;
pIpRoute.pszGateway = pszGateway;
pIpRoute.metric = metric;
pIpRoute.pszSourceNetwork = pszSourceNetwork;
pIpRoute.scope = scope;
pIpRoute.table = table;
dwError = netmgr_client_add_static_ip_route(self->hHandle, &pIpRoute);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
delete_static_ip_route(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, metric = 0, table = 0;
char *pszInterfaceName = NULL;
char *pszDestNetwork = NULL;
char *pszSourceNetwork = NULL;
char *pszGateway = NULL;
NET_ROUTE_SCOPE scope = GLOBAL_ROUTE;
NET_IP_ROUTE pIpRoute = {0};
PyObject *pyRes = Py_None;
static char *kwlist[] = {"ifname",
"destination",
"gateway",
"metric",
"source",
"scope",
"table",
NULL};
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss|s|i|s|i|i",
kwlist,
&pszInterfaceName,
&pszDestNetwork,
&pszGateway,
&metric,
&pszSourceNetwork,
&scope,
&table))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pIpRoute.pszInterfaceName = pszInterfaceName;
pIpRoute.pszDestNetwork = pszDestNetwork;
pIpRoute.pszSourceNetwork = pszSourceNetwork;
pIpRoute.pszGateway = pszGateway;
pIpRoute.scope = scope;
pIpRoute.metric = metric;
pIpRoute.table = table;
dwError = netmgr_client_delete_static_ip_route(self->hHandle, &pIpRoute);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pyRes = Py_BuildValue("i", dwError);
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static uint32_t
fill_route_info(
PPY_NET self,
NET_IP_ROUTE *pNetRouteInfo,
PPY_IP_ROUTE *ppPyIpRoute
)
{
uint32_t dwError = 0;
PyTypeObject *retType = &routeType;
PPY_IP_ROUTE pPyRouteObject = NULL;
if (!pNetRouteInfo|| !ppPyIpRoute)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pPyRouteObject = (PPY_IP_ROUTE)retType->tp_alloc(retType, 0);
if (!pPyRouteObject)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
pPyRouteObject->pRouteDestNetwork = Py_BuildValue("s",
pNetRouteInfo->pszDestNetwork);
pPyRouteObject->pRouteSourceNetwork = Py_BuildValue("s",
pNetRouteInfo->pszSourceNetwork);
pPyRouteObject->pRouteGateway = Py_BuildValue("s",
pNetRouteInfo->pszGateway);
pPyRouteObject->scope = pNetRouteInfo->scope;
pPyRouteObject->metric = pNetRouteInfo->metric;
pPyRouteObject->table = pNetRouteInfo->table;
*ppPyIpRoute = pPyRouteObject;
cleanup:
return dwError;
error:
Py_XDECREF((PyObject *)pPyRouteObject);
goto cleanup;
}
static uint32_t
fill_link_info(
PPY_NET self,
NET_LINK_INFO *pNetLinkInfo,
PPY_LINK *pppyLinkObject
)
{
uint32_t dwError = 0, linkMtu = 0, ndhcpEnabled = 0, nautoconfEnabled = 0;
uint32_t dwIaid = 0;
size_t countDnsServers = 0, countDnsDomains = 0, countRoutes = 0;
size_t countIpv6List = 0;
size_t i = 0, j = 0;
NET_LINK_MODE linkMode = LINK_MODE_UNKNOWN;
NET_LINK_STATE linkState = LINK_STATE_UNKNOWN;
NET_DNS_MODE dnsMode = DNS_MODE_INVALID;
NET_IPV4_ADDR_MODE addrMode = IPV4_ADDR_MODE_NONE;
char *pszDuid = 0, *pszIfName = NULL, *pszAddrMode = NULL;
char *pszMacAddress = NULL, *pszIpv4Addr =NULL, *pszDnsMode = NULL;
char *pszIpv4Gateway = NULL, *pszIpv6Gateway = NULL;
char **ppszDnsServers = NULL, **ppszDnsDomains = NULL;
PyTypeObject *retType = &linkType;
PPY_LINK pPyLinkObject = NULL;
NET_IP_ROUTE **ppRouteList = NULL;
NET_IP_ADDR **ppipaddrList = NULL;
PyObject *pPyDnsServersList = PyList_New(0);
PyObject *pPyDnsDomainsList = PyList_New(0);
PyObject *pPyIpv6AddrList = PyList_New(0);
PyObject *pyIpRoutesList = PyList_New(0);
if (!pNetLinkInfo || !pppyLinkObject)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pPyLinkObject = (PPY_LINK)retType->tp_alloc(retType, 0);
if (!pPyLinkObject)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
pszIfName = pNetLinkInfo->pszInterfaceName;
pszMacAddress = pNetLinkInfo->pszMacAddress;
linkMode = pNetLinkInfo->mode;
linkMtu = pNetLinkInfo->mtu;
linkState = pNetLinkInfo->state;
dwError = netmgr_client_get_duid(self->hHandle, pszIfName, &pszDuid);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
dwError = netmgr_client_get_ipv4_addr_gateway(self->hHandle,
pszIfName,
&addrMode,
&pszIpv4Addr,
&pszIpv4Gateway);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
if (addrMode == IPV4_ADDR_MODE_NONE)
{
pszAddrMode = "none";
}
else if (addrMode == IPV4_ADDR_MODE_DHCP)
{
pszAddrMode = "dhcp";
}
else
{
pszAddrMode = "static";
}
dwError = netmgr_client_get_ipv6_addr_mode(self->hHandle,
pszIfName,
&ndhcpEnabled,
&nautoconfEnabled);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
dwError = netmgr_client_get_ipv6_gateway(self->hHandle,
pszIfName,
&pszIpv6Gateway);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
dwError = netmgr_client_get_dns_servers(self->hHandle,
pszIfName,
&dnsMode,
&countDnsServers,
&ppszDnsServers);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
if (dnsMode == DNS_MODE_INVALID)
{
pszDnsMode = "invalid";
}
else if (dnsMode == STATIC_DNS)
{
pszDnsMode = "static";
}
else
{
pszDnsMode = "dhcp";
}
for (j = 0; j < countDnsServers; j++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszDnsServers[j]);
if (PyList_Append(pPyDnsServersList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_get_dns_domains(self->hHandle,
pszIfName,
&countDnsDomains,
&ppszDnsDomains);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
for (j = 0; j < countDnsDomains; j++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszDnsDomains[j]);
if (PyList_Append(pPyDnsDomainsList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_get_ip_addr(self->hHandle,
pszIfName,
DHCP_IPV6 | AUTO_IPV6 | STATIC_IPV6,
&countIpv6List,
&ppipaddrList);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
for (j = 0; j < countIpv6List; j++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppipaddrList[j]->pszIPAddrPrefix);
if (PyList_Append(pPyIpv6AddrList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_get_static_ip_routes(self->hHandle,
pszIfName,
&countRoutes,
&ppRouteList);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
for (j = 0; j < countRoutes; j++)
{
PPY_IP_ROUTE ipRoute = NULL;
dwError = fill_route_info(self, ppRouteList[j], &ipRoute);
BAIL_ON_PMD_ERROR(dwError);
if (PyList_Append(pyIpRoutesList, (PyObject *)ipRoute) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_get_iaid(self->hHandle,
pszIfName,
&dwIaid);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
pPyLinkObject->pInterface_name = Py_BuildValue("s", pszIfName);
pPyLinkObject->pDuid = Py_BuildValue("s", pszDuid);
pPyLinkObject->pIaid = Py_BuildValue("i", dwIaid);
pPyLinkObject->pMacAddress = Py_BuildValue("s", pszMacAddress);
pPyLinkObject->pLinkMode = Py_BuildValue("s",
py_link_mode_to_string(linkMode));
pPyLinkObject->link_mtu = linkMtu;
pPyLinkObject->pLinkState = Py_BuildValue("s",
py_link_state_to_string(linkState));
pPyLinkObject->pIpv4AddrMode = Py_BuildValue("s", pszAddrMode);
pPyLinkObject->pIpv4_addr = Py_BuildValue("s", pszIpv4Addr);
pPyLinkObject->pIpv4_gateway = Py_BuildValue("s", pszIpv4Gateway);
pPyLinkObject->ipv6_dhcp_enabled = ndhcpEnabled ? Py_True : Py_False;
pPyLinkObject->ipv6_autoconf_enabled = nautoconfEnabled ? Py_True :
Py_False;
pPyLinkObject->pIpv6_gateway = Py_BuildValue("s", pszIpv6Gateway);
pPyLinkObject->pIpv6_addr_list = (PyObject *)pPyIpv6AddrList;
pPyLinkObject->pDnsMode = Py_BuildValue("s", pszDnsMode);
pPyLinkObject->pServersList = (PyObject *)pPyDnsServersList;
pPyLinkObject->pDomainsList = (PyObject *)pPyDnsDomainsList;
pPyLinkObject->pIP_Route_Info = (PyObject *)pyIpRoutesList;
*pppyLinkObject = pPyLinkObject;
cleanup:
PMDFreeMemory(pszDuid);
PMDFreeMemory(pszIpv4Addr);
PMDFreeMemory(pszIpv4Gateway);
PMDFreeMemory(pszIpv6Gateway);
PMDFreeStringArrayWithCount(ppszDnsServers, countDnsServers);
PMDFreeStringArrayWithCount(ppszDnsDomains, countDnsDomains);
if (ppRouteList)
{
for (j= 0; j < countRoutes; j++)
{
PMDFreeMemory(ppRouteList[j]->pszInterfaceName);
PMDFreeMemory(ppRouteList[j]->pszDestNetwork);
PMDFreeMemory(ppRouteList[j]->pszSourceNetwork);
PMDFreeMemory(ppRouteList[j]->pszGateway);
PMDFreeMemory(ppRouteList[j]);
}
PMDFreeMemory(ppRouteList);
}
if (ppipaddrList)
{
for (j = 0; j < countIpv6List; j++)
{
PMDFreeMemory(ppipaddrList[j]->pszInterfaceName);
PMDFreeMemory(ppipaddrList[j]->pszIPAddrPrefix);
PMDFreeMemory(ppipaddrList[j]);
}
PMDFreeMemory(ppipaddrList);
}
return dwError;
error:
Py_XDECREF((PyObject *)pPyLinkObject);
goto cleanup;
}
static PyObject *
get_link_info(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
static char *kwlist[] = {"ifname", NULL};
PyObject *pPyLinkDict = Py_None;
NET_LINK_INFO *pLinkInfo = NULL, *pCur = NULL;
PyObject *pyRes = Py_None;
if(!PyArg_ParseTupleAndKeywords(arg,
kwds,
"|s",
kwlist,
&pszInterfaceName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_link_info(self->hHandle,
pszInterfaceName,
&pLinkInfo);
BAIL_ON_PMD_ERROR(dwError);
pPyLinkDict = PyDict_New();
for (pCur = pLinkInfo; pCur; pCur = pCur->pNext)
{
PPY_LINK pPyLinkObject = NULL;
dwError = fill_link_info(self, pCur, &pPyLinkObject);
BAIL_ON_PMD_ERROR(dwError);
if (PyDict_SetItem(pPyLinkDict, pPyLinkObject->pInterface_name,
(PyObject *)pPyLinkObject) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
pyRes = pPyLinkDict;
cleanup:
while (pLinkInfo)
{
pCur = pLinkInfo;
pLinkInfo = pLinkInfo->pNext;
PMDFreeMemory(pCur->pszInterfaceName);
PMDFreeMemory(pCur->pszMacAddress);
PMDFreeMemory(pCur);
}
return pyRes;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_system_network_info(
PPY_NET self,
PyObject *arg
)
{
uint32_t dwError = 0;
size_t j = 0;
size_t countDnsServers = 0, countDnsDomains = 0, countNtpServers = 0;
NET_DNS_MODE dnsMode = DNS_MODE_INVALID;
PPY_SYSTEM pPySystemObject = NULL;
char *pszDuid = 0, *pszDnsMode = NULL;
char **ppszDnsServers = NULL, **ppszDnsDomains = NULL;
char **ppszNtpServers = NULL;
PyTypeObject *retType = &systemType;
PyObject *pPySystemInfoList = Py_None;
PyObject *pPyDnsServersList = Py_None;
PyObject *pPyDnsDomainsList = Py_None;
PyObject *pPyNtpServersList = Py_None;
PyObject *pyRes = Py_None;
pPySystemObject = (PPY_SYSTEM)retType->tp_alloc(retType, 0);
if (!pPySystemObject)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_dns_servers(self->hHandle,
NULL,
&dnsMode,
&countDnsServers,
&ppszDnsServers);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
if (dnsMode == DNS_MODE_INVALID)
{
pszDnsMode = "invalid";
}
else if (dnsMode == STATIC_DNS)
{
pszDnsMode = "static";
}
else
{
pszDnsMode = "dhcp";
}
pPySystemInfoList = PyList_New(0);
pPyDnsServersList = PyList_New(0);
for (j = 0; j < countDnsServers; j++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszDnsServers[j]);
if (PyList_Append(pPyDnsServersList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_get_dns_domains(self->hHandle,
NULL,
&countDnsDomains,
&ppszDnsDomains);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
pPyDnsDomainsList = PyList_New(0);
for (j = 0; j < countDnsDomains; j++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszDnsDomains[j]);
if (PyList_Append(pPyDnsDomainsList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_get_ntp_servers(self->hHandle,
&countNtpServers,
&ppszNtpServers);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
pPyNtpServersList = PyList_New(0);
for (j = 0; j < countNtpServers; j++)
{
PyObject *ptoAppend = Py_BuildValue("s", ppszNtpServers[j]);
if (PyList_Append(pPyNtpServersList, ptoAppend) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_get_duid(self->hHandle, NULL, &pszDuid);
if ((dwError == NM_ERR_VALUE_NOT_FOUND) || (dwError == ENOENT))
{
dwError = 0;
}
BAIL_ON_PMD_ERROR(dwError);
pPySystemObject->pDnsMode = Py_BuildValue("s", pszDnsMode);
pPySystemObject->pServersList = (PyObject *)pPyDnsServersList;
pPySystemObject->pDomainsList = (PyObject *)pPyDnsDomainsList;
pPySystemObject->pNtpServersList = (PyObject *)pPyNtpServersList;
pPySystemObject->pDuid = Py_BuildValue("s", pszDuid);
if (PyList_Append(pPySystemInfoList, (PyObject *)pPySystemObject) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
pyRes = pPySystemInfoList;
cleanup:
PMDFreeMemory(pszDuid);
PMDFreeStringArrayWithCount(ppszDnsServers, countDnsServers);
PMDFreeStringArrayWithCount(ppszDnsDomains, countDnsDomains);
PMDFreeStringArrayWithCount(ppszNtpServers, countNtpServers);
return pyRes;
error:
Py_XDECREF(pPySystemObject);
pPyDnsServersList = Py_None;
pPyDnsDomainsList = Py_None;
pPySystemInfoList = Py_None;
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
net_py_getfirewall(
PPY_NET self,
void *closure)
{
return NULL;
#if 0
uint32_t dwError = 0;
PyTypeObject *retType = &firewallType;
PPY_NM_FIREWALL pyFirewall = NULL;
if(!self->firewall)
{
self->firewall = retType->tp_alloc(retType, 0);
if(!self->firewall)
{
dwError = ENOMEM;
BAIL_ON_PMD_ERROR(dwError);
}
}
pyFirewall = (PPY_NM_FIREWALL)self->firewall;
pyFirewall->pNet = (PyObject *)self;
cleanup:
return self->firewall;
error:
self->firewall = Py_None;
goto cleanup;
#endif
}
static PyObject *
wait_for_link_up(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszInterfaceName = NULL;
uint32_t dwTimeout = 0;
static char *kwlist[] = {"ifname", "timeout", NULL};
PyObject *pResult = Py_None;
NET_LINK_INFO *pLinkInfo = NULL, *pCur = NULL;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"si",
kwlist,
&pszInterfaceName,
&dwTimeout))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_wait_for_link_up(self->hHandle,
pszInterfaceName,
dwTimeout);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pResult = Py_BuildValue("i", dwError);
return pResult;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
typedef struct _NM_CLI_ADDR_STR_TYPE
{
char *pszIpAddrType;
NET_ADDR_TYPE ipAddrType;
} NM_CLI_ADDR_STR_TYPE, *PNM_CLI_ADDR_STR_TYPE;
NM_CLI_ADDR_STR_TYPE addrStrToTypeMap[] =
{
{ "ipv4", NET_ADDR_IPV4 },
{ "ipv6", NET_ADDR_IPV6 },
{ "static_ipv4", STATIC_IPV4 },
{ "static_ipv6", STATIC_IPV6 },
{ "dhcp_ipv4", DHCP_IPV4 },
{ "dhcp_ipv6", DHCP_IPV6 },
{ "auto_ipv6", AUTO_IPV6 },
{ "link_local_ipv6", LINK_LOCAL_IPV6 },
};
static PyObject *
wait_for_ip(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, dwTimeout = 0;
size_t i = 0, j = 0, count = 0, addrTypeCount = 0;
char *pszInterfaceName = NULL;
char *s1 = NULL, *s2 = NULL;
char **ppszAddrTypeList = NULL;
NET_ADDR_TYPE dwAddrTypes = 0;
PyObject *pPyResult = Py_None;
PyObject *pszAddrTypes = Py_None;
static char *kwlist[] = {"ifname", "timeout", "addrtype", NULL};
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"sdO",
kwlist,
&pszInterfaceName,
&dwTimeout,
&pszAddrTypes))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = py_list_as_string_list(pszAddrTypes,
&ppszAddrTypeList,
&count);
BAIL_ON_PMD_ERROR(dwError);
addrTypeCount = sizeof(addrStrToTypeMap)/sizeof(NM_CLI_ADDR_STR_TYPE);
for (i = 0; i < count; i++)
{
for (j = 0; j < addrTypeCount; j++)
{
if (!strcmp(ppszAddrTypeList[i], addrStrToTypeMap[j].pszIpAddrType))
{
dwAddrTypes |= addrStrToTypeMap[j].ipAddrType;
break;
}
}
if (j == addrTypeCount)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
}
dwError = netmgr_client_wait_for_ip(self->hHandle,
pszInterfaceName,
dwTimeout,
dwAddrTypes);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeStringArrayWithCount(ppszAddrTypeList, count);
pPyResult = Py_BuildValue("i", dwError);
return pPyResult;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_err_info(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, error = 0;
static char *kwlist[] = {"error", NULL};
char *pszErrorInfo = NULL;
PyObject *pPyResult = Py_None;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"l",
kwlist,
&error))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_error_info(self->hHandle,
error,
&pszErrorInfo);
BAIL_ON_PMD_ERROR(dwError);
pPyResult = Py_BuildValue("s", pszErrorInfo);
cleanup:
PMDFreeMemory(pszErrorInfo);
return pPyResult;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_hostname(
PPY_NET self,
PyObject *arg
)
{
uint32_t dwError = 0, error = 0;
PyObject *pPyResult = Py_None;
char *pszHostname = NULL;
dwError = netmgr_client_get_hostname(self->hHandle,
&pszHostname);
BAIL_ON_PMD_ERROR(dwError);
pPyResult = Py_BuildValue("s", pszHostname);
cleanup:
PMDFreeMemory(pszHostname);
return pPyResult;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_hostname(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, error = 0;
static char *kwlist[] = {"hostname", NULL};
char *pszErrorInfo = NULL;
PyObject *pPyResult = Py_None;
char *pszHostname = NULL;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"s",
kwlist,
&pszHostname))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_hostname(self->hHandle,
pszHostname);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
PMDFreeMemory(pszErrorInfo);
pPyResult = Py_BuildValue("i", dwError);
return pPyResult;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
get_network_param(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, error = 0;
static char *kwlist[] = {"object", "paramname", NULL};
PyObject *pPyResult = Py_None;
char *pszObjectName = NULL, *pszParamName = NULL, *pszParamValue = NULL;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss",
kwlist,
&pszObjectName,
&pszParamName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_get_network_param(self->hHandle,
pszObjectName,
pszParamName,
&pszParamValue);
BAIL_ON_PMD_ERROR(dwError);
pPyResult = Py_BuildValue("s", pszParamValue);
cleanup:
PMDFreeMemory(pszParamValue);
return pPyResult;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyObject *
set_network_param(
PPY_NET self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0, error = 0;
static char *kwlist[] = {"object", "paramname", "paramvalue", NULL};
PyObject *pPyResult = Py_None;
char *pszObjectName = NULL, *pszParamName = NULL, *pszParamValue = NULL;
if (!PyArg_ParseTupleAndKeywords(arg,
kwds,
"ss|z",
kwlist,
&pszObjectName,
&pszParamName,
&pszParamValue))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = netmgr_client_set_network_param(self->hHandle,
pszObjectName,
pszParamName,
pszParamValue);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
pPyResult = Py_BuildValue("i", dwError);
return pPyResult;
error:
raise_netmgr_exception(self, dwError);
goto cleanup;
}
static PyMethodDef net_methods[] =
{
{"set_dhcp_duid", (PyCFunction)set_dhcp_duid, METH_VARARGS|METH_KEYWORDS,
"net.set_dhcp_duid(duid = \"11:22:33:44:55:66:77:20\", ifname = interfacename) \n\
set dhcp duid (interface optional). returns 0 if successful, exception on failure.\n"},
{"get_dhcp_duid", (PyCFunction)get_dhcp_duid, METH_VARARGS|METH_KEYWORDS,
"net.get_dhcp_duid(ifname = interface)\n\
get dhcp duid (interface optional). returns DUID if successful, exception on failure.\n"},
{"set_link_iaid", (PyCFunction)set_link_iaid, METH_VARARGS|METH_KEYWORDS,
"net.set_link_iaid(ifname = interfacename, iaid = 1234) \n\
set interface iaid. returns 0 if successful, exception on failure.\n"},
{"get_link_iaid", (PyCFunction)get_link_iaid, METH_VARARGS|METH_KEYWORDS,
"net.get_link_iaid(ifname = interface)\n\
get interface iaid. returns IAID if successful, exception on failure.\n"},
{"set_link_macaddr", (PyCFunction)set_link_macaddr,
METH_VARARGS|METH_KEYWORDS,
"net.set_link_macaddr(ifname = interfacename, macaddr = \"10:20:30:40:50:60\") \n\
sets macaddress. returns 0 if successful, exception on failure.\n"},
{"get_link_macaddr", (PyCFunction)get_link_macaddr,
METH_VARARGS|METH_KEYWORDS,
"net.get_link_macaddr(ifname = interfacename\") \n\
gets macaddress. returns MAC address if successful, exception on failure.\n"},
{"set_link_mtu", (PyCFunction)set_link_mtu, METH_VARARGS|METH_KEYWORDS,
"net.set_link_mtu(ifname = interfacename, mtu = 1500) \n\
sets mtu of interface. returns 0 if successful, exception on failure.\n"},
{"get_link_mtu", (PyCFunction)get_link_mtu,
METH_VARARGS|METH_KEYWORDS,
"net.get_link_mtu(ifname = interfacename\") \n\
gets link mtu. returns link MTU if successful, exception on failure.\n"},
{"set_link_mode", (PyCFunction)set_link_mode, METH_VARARGS|METH_KEYWORDS,
"net.set_link_mode(ifname = interfacename, "
"link_mode = [aut0, manual])\n\
sets mode of interface. returns 0 if successful, exception on failure.\n"},
{"get_link_mode", (PyCFunction)get_link_mode,
METH_VARARGS|METH_KEYWORDS,
"net.get_link_mode(ifname = interfacename\") \n\
gets link mode. returns link mode if successful, exception on failure.\n"},
{"set_link_state", (PyCFunction)set_link_state, METH_VARARGS|METH_KEYWORDS,
"net.set_link_state(ifname = interfacename, "
"link_state = [down, up]) \n\
sets state of interface. returns 0 if successful, exception on failure.\n"},
{"get_link_state", (PyCFunction)get_link_state,
METH_VARARGS|METH_KEYWORDS,
"net.get_link_state(ifname = interfacename\") \n\
gets link state. returns link state if successful, exception on failure.\n"},
{"set_link_up", (PyCFunction)set_link_up, METH_VARARGS|METH_KEYWORDS,
"net.set_link_up(ifname = interfacename) \n\
brings interface up. returns 0 if successful, exception on failure.\n"},
{"set_link_down", (PyCFunction)set_link_down, METH_VARARGS|METH_KEYWORDS,
"net.set_link_down(ifname = interfacename) \n\
brings interface down. returns 0 if successful, exception on failure.\n"},
{"set_ipv4_addr_gateway", (PyCFunction)set_ipv4_addr_gateway,
METH_VARARGS|METH_KEYWORDS,
"net.set_ipv4_addr_gateway(ifname = interfacename, addr_mode = [dhcp, static, none], "
"addr_prefix = ipv4addressprefix, gateway = ipv4gateway) \n\
set ipv4 address with prefix and gateway for the interface."
"returns 0 if successful, exception on failure.\n"},
{"get_ipv4_addr_gateway", (PyCFunction)get_ipv4_addr_gateway,
METH_VARARGS|METH_KEYWORDS,
"net.get_ipv4_addr_gateway(ifname = interfacename) \n\
get ipv4 address with prefix and gateway for the interface."
"returns IPv4 addr & gateway if successful, exception on failure.\n"},
{"add_static_ipv6_addr", (PyCFunction)add_static_ipv6_addr,
METH_VARARGS|METH_KEYWORDS,
"net.add_static_ipv6_addr(ifname = interfacename, "
"addr_prefix = ipv6addressprefix) \n\
adds static ipv6 address for the interface. returns 0 if successful, exception on failure.\n"},
{"del_static_ipv6_addr", (PyCFunction)delete_static_ipv6_addr,
METH_VARARGS|METH_KEYWORDS,
"net.del_static_ipv6_addr(ifname = interfacename, "
"addr_prefix = ipv6addressprefix) \n\
delete static ipv6 address assigned to the interface. returns 0 if"
" successful, exception on failure.\n"},
{"get_ipv6_addr", (PyCFunction)get_ipv6_addr,
METH_VARARGS|METH_KEYWORDS,
"net.get_ipv6_addr(ifname = interfacename) \n\
get the list of IPv6 addresses for the interface. "
"returns IPv6 address list if successful, exception on failure.\n"},
{"set_ipv6_addr_mode", (PyCFunction)set_ipv6_addr_mode,
METH_VARARGS|METH_KEYWORDS,
"net.set_ipv6_addr_mode(ifname = interfacename, "
"enable_dhcp = [True, False], enable_autoconf = [True, False]) \n\
enable dhcp and autoconf for the ipv6 address. "
"returns 0 if successful, exception on failure.\n"},
{"get_ipv6_addr_mode", (PyCFunction)get_ipv6_addr_mode,
METH_VARARGS|METH_KEYWORDS,
"net.get_ipv6_addr_mode(ifname = interfacename) \n\
returns if dhcpv6, autoconfv6 are enabled or disabled. "
"returns dhcpv6 & autoconf settings if successful, exception on failure.\n"},
{"set_ipv6_gateway", (PyCFunction)set_ipv6_gateway,
METH_VARARGS|METH_KEYWORDS,
"net.set_ipv6_gateway(ifname = interfacename, gateway = ipv6gateway) \n\
set the IPv6 gateway for the interface. "
"returns 0 if successful, exception on failure.\n"},
{"get_ipv6_gateway", (PyCFunction)get_ipv6_gateway,
METH_VARARGS|METH_KEYWORDS,
"net.get_ipv6_gateway(ifname = interfacename) \n\
get the IPv6 gateway for the interface. "
"returns IPv6 gateway if successful, exception on failure.\n"},
{"add_dns_server", (PyCFunction)add_dns_server,
METH_VARARGS|METH_KEYWORDS,
"net.add_dns_server(server = \"10.20.30.40\", ifname = interfacename) \n\
add dns server. returns 0 if successful, exception on failure.\n"},
{"delete_dns_server", (PyCFunction)delete_dns_server,
METH_VARARGS|METH_KEYWORDS,
"net.delete_dns_servers(server = \"10.20.30.40\", ifname = interfacename) \n\
delete dns server. returns 0 if successful, exception on failure.\n"},
{"set_dns_servers", (PyCFunction)set_dns_servers,
METH_VARARGS|METH_KEYWORDS,
"net.set_dns_servers(dns_mode = [dhcp, static], "
"servers = [\"10.20.30.40\",\"172.16.17.32\"], ifname = interfacename) \n\
set dns servers and the mode. returns 0 if successful, exception on failure.\n"},
{"get_dns_servers", (PyCFunction)get_dns_servers,
METH_VARARGS|METH_KEYWORDS,
"net.get_dns_servers(ifname = interfacename) \n\
get dns servers and the mode. returns dns servers, mode if successful, exception on failure.\n"},
{"set_dns_domains", (PyCFunction)set_dns_domains,
METH_VARARGS|METH_KEYWORDS,
"net.set_dns_domains(domains = [\"abcd.com\"], ifname = interfacename) \n\
set dns domains. returns 0 if successful, exception on failure.\n"},
{"get_dns_domains", (PyCFunction)get_dns_domains,
METH_VARARGS|METH_KEYWORDS,
"net.get_dns_domains(ifname = interfacename) \n\
get dns domains. returns dns domains if successful, exception on failure.\n"},
{"set_ntp_servers", (PyCFunction)set_ntp_servers,
METH_VARARGS|METH_KEYWORDS,
"net.set_ntp_servers(ntpservers = [\"20.20.20.20\", \"172.16.58.3\"]) \n\
set ntp servers. returns 0 if successful, exception on failure.\n"},
{"add_ntp_servers", (PyCFunction)add_ntp_servers,
METH_VARARGS|METH_KEYWORDS,
"net.add_ntp_servers(ntpservers = [\"20.20.20.20\", \"172.16.58.3\"]) \n\
adds ntp servers. returns 0 if successful, exception on failure.\n"},
{"del_ntp_servers", (PyCFunction)delete_ntp_servers,
METH_VARARGS|METH_KEYWORDS,
"net.del_ntp_servers(ntpservers = [\"20.20.20.20\", \"172.16.58.3\"]) \n\
deletes ntp servers. returns 0 if successful, exception on failure.\n"},
{"get_ntp_servers", (PyCFunction)get_ntp_servers,
METH_VARARGS|METH_KEYWORDS,
"net.get_ntp_servers() \n\
get ntp servers. returns NTP servers list if successful, exception on failure.\n"},
{"add_static_ip_route", (PyCFunction)add_static_ip_route,
METH_VARARGS|METH_KEYWORDS,
"net.add_static_ip_route(ifname = interfacename, "
"destination = destination network, "
"source = source network, gateway = gateway_address, "
"scope = 1, metric = 10, table = 0) \n\
adds a static route to the interface. returns 0 if successful, exception on failure.\n"},
{"delete_static_ip_route", (PyCFunction)delete_static_ip_route,
METH_VARARGS|METH_KEYWORDS,
"net.delete_static_ip_route(ifname = interfacename, "
"destination = destination network, source = source network, "
"gateway = gateway, scope = 0, metric = 1, table = 100) \n\
deletes a static route to the interface. returns 0 if successful, exception on failure.\n"},
{"get_link_info", (PyCFunction)get_link_info, METH_VARARGS|METH_KEYWORDS,
"net.get_link_info(ifname = interfacename)\n\
get link info per interface or all interface.\n"},
{"get_system_network_info", (PyCFunction)get_system_network_info,
METH_NOARGS, "net.get_system_network_info()\n\
get network info common to the entire system.\n"},
{"wait_for_link_up", (PyCFunction)wait_for_link_up,
METH_VARARGS|METH_KEYWORDS, "net.wait_for_link_up(ifname = interfacename, "
"timeout = timeout)\n\
wait for link up.\n"},
{"wait_for_ip", (PyCFunction)wait_for_ip,
METH_VARARGS|METH_KEYWORDS, "net.wait_for_ip(ifname = interfacename, "
"timeout = timeout, addrtypes = [ipv4, ipv6, static_ipv4, static_ipv6, "
"dhcp_ipv4, dhcp_ipv6, auto_ipv6, link_local_ipv6])\n\
wait for ip.\n"},
{"get_err_info", (PyCFunction)get_err_info,
METH_VARARGS|METH_KEYWORDS, "net.get_err_info(error = <errno> )\n\
returns a string describing the errorcode passed in argument.\n"},
{"get_hostname", (PyCFunction)get_hostname,
METH_NOARGS, "net.get_hostname()\n\
returns hostname.\n"},
{"set_hostname", (PyCFunction)set_hostname,
METH_VARARGS|METH_KEYWORDS, "net.set_hostname(hostname=hostname)\n\
sets hostname.\n"},
{"get_network_param", (PyCFunction)get_network_param,
METH_VARARGS|METH_KEYWORDS, "net.get_network_param(object = IfName or "
"Filename, paramname = SectionName_KeyName)\n\
gets network config parameter.\n"},
{"set_network_param", (PyCFunction)set_network_param,
METH_VARARGS|METH_KEYWORDS, "net.set_network_param(object = IfName or "
"Filename, paramname = SectionName_KeyName, paramvalue = KeyValue)\n\
sets network config parameter.\n"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static PyMemberDef net_members[] =
{
{"server", T_OBJECT_EX, offsetof(PY_NET, server), 0,
"server details"},
{NULL} /* Sentinel */
};
static PyGetSetDef net_getset[] = {
{"firewall",
(getter)net_py_getfirewall, (setter)NULL,
"get firewall object",
NULL},
{NULL} /* Sentinel */
};
PyTypeObject netType = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"server.net", /*tp_name*/
sizeof(PY_NET), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)net_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
net__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
net_methods, /* tp_methods */
net_members, /* tp_members */
net_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)net_init, /* tp_init */
0, /* tp_alloc */
net_new, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
|
oliverkurth/pmd
|
python/rolemgmt_py.c
|
<reponame>oliverkurth/pmd
/*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
static char rolemgmt__doc__[] = "";
static void
rolemgmt_dealloc(
PY_ROLEMGMT *self
)
{
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
rolemgmt_new(
PyTypeObject *type,
PyObject *args,
PyObject *kwds
)
{
PPY_ROLEMGMT self = NULL;
self = (PPY_ROLEMGMT)type->tp_alloc(type, 0);
if (self != NULL)
{
}
return (PyObject *)self;
}
static int
rolemgmt_init(
PY_ROLEMGMT *self,
PyObject *args,
PyObject *kwds
)
{
PyObject *pRoles = NULL;
if (! PyArg_ParseTuple(args, "O", &pRoles))
{
return -1;
}
return 0;
}
PyObject*
rolemgmt_py_get_version(
PPY_ROLEMGMT self,
void *closure)
{
uint32_t dwError = 0;
char *pszVersion = NULL;
PyObject *pyVersion = Py_None;
dwError = rolemgmt_get_version(self->hHandle, &pszVersion);
BAIL_ON_PMD_ERROR(dwError);
pyVersion = PyBytes_FromString(pszVersion);
if(!pyVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
cleanup:
PMD_SAFE_FREE_MEMORY(pszVersion);
return pyVersion;
error:
pyVersion = NULL;
raise_exception(dwError);
goto cleanup;
}
PyObject*
rolemgmt_py_get_roles(
PPY_ROLEMGMT self,
void *closure)
{
uint32_t dwError = 0;
size_t nCount = 0;
size_t i = 0;
PPMD_ROLEMGMT_ROLE pRoles = NULL;
PPMD_ROLEMGMT_ROLE pRole = NULL;
PyObject *pPyRolesDict = Py_None;
if(!self || !self->hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pPyRolesDict = PyDict_New();
dwError = rolemgmt_get_roles(self->hHandle, &pRoles);
BAIL_ON_PMD_ERROR(dwError);
for(pRole = pRoles; pRole; pRole = pRole->pNext)
{
PyObject *pPyRoleDict = Py_None;
PyObject *pPyRoleId = PyBytes_FromString(pRole->pszId);
dwError = rolemgmt_role_py_make(pRole, &pPyRoleDict);
BAIL_ON_PMD_ERROR(dwError);
if(PyDict_SetItem(pPyRolesDict, pPyRoleId, pPyRoleDict) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
cleanup:
rolemgmt_free_roles(pRoles);
return pPyRolesDict;
error:
pPyRolesDict = NULL;
raise_exception(dwError);
goto cleanup;
}
PyObject *
rolemgmt_py_role_version(
PPY_ROLEMGMT self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszRoleName = NULL;
char *pszRoleVersion = NULL;
static char *kwlist[] = {"name", NULL};
PyObject *pyRoleVersion = Py_None;
if(!self || !self->hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!PyArg_ParseTupleAndKeywords(
arg, kwds, "s", kwlist,
&pszRoleName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = rolemgmt_get_role_version(
self->hHandle,
pszRoleName,
&pszRoleVersion);
BAIL_ON_PMD_ERROR(dwError);
pyRoleVersion = PyBytes_FromString(pszRoleVersion);
if(!pyRoleVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
cleanup:
return pyRoleVersion;
error:
pyRoleVersion = NULL;
raise_exception(dwError);
goto cleanup;
}
PyObject *
rolemgmt_py_prereqs(
PPY_ROLEMGMT self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszRoleName = NULL;
PPMD_ROLE_PREREQ pPrereqs = NULL;
uint32_t i = 0;
uint32_t dwPrereqCount = 0;
PMD_ROLE_OPERATION nOperation = ROLE_OPERATION_NONE;
static char *kwlist[] = {"name", NULL};
PPY_ROLEMGMT_PREREQ pPyPrereq = NULL;
PyObject *pyPrereqList = NULL;
if(!self || !self->hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!PyArg_ParseTupleAndKeywords(
arg, kwds, "s", kwlist,
&pszRoleName))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = rolemgmt_get_prereqs(
self->hHandle,
pszRoleName,
nOperation,
&pPrereqs,
&dwPrereqCount);
BAIL_ON_PMD_ERROR(dwError);
pyPrereqList = PyList_New(0);
for(i = 0; i < dwPrereqCount; ++i)
{
dwError = rolemgmt_prereq_py_make(
&pPrereqs[i],
&pPyPrereq);
BAIL_ON_PMD_ERROR(dwError);
if(PyList_Append(pyPrereqList, (PyObject *)pPyPrereq) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
cleanup:
return pyPrereqList;
error:
pyPrereqList = NULL;
raise_exception(dwError);
goto cleanup;
}
PyObject *
rolemgmt_py_task_status(
PPY_ROLEMGMT self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszRoleName = NULL;
char *pszTaskUUID = NULL;
static char *kwlist[] = {"name", "taskid", NULL};
PyObject *pyTaskStatus = Py_None;
PMD_ROLE_STATUS nStatus = ROLE_STATUS_NONE;
if(!self || !self->hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!PyArg_ParseTupleAndKeywords(
arg, kwds, "ss", kwlist,
&pszRoleName, &pszTaskUUID))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = rolemgmt_get_status(
self->hHandle,
pszRoleName,
pszTaskUUID,
&nStatus);
BAIL_ON_PMD_ERROR(dwError);
pyTaskStatus = Py_BuildValue("i", nStatus);
cleanup:
return pyTaskStatus;
error:
pyTaskStatus = NULL;
raise_exception(dwError);
goto cleanup;
}
PyObject *
rolemgmt_py_alter(
PPY_ROLEMGMT self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
char *pszRoleName = NULL;
char *pszConfig = NULL;
PMD_ROLE_OPERATION nOperation = ROLE_OPERATION_NONE;
char *pszTaskUUID = NULL;
PyObject *pyTaskID = NULL;
static char *kwlist[] = {"name", "operation", "config", NULL};
if(!self || !self->hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!PyArg_ParseTupleAndKeywords(
arg, kwds, "sIs", kwlist,
&pszRoleName, &nOperation, &pszConfig))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(nOperation <= ROLE_OPERATION_NONE || nOperation >= ROLE_OPERATION_MAX)
{
dwError = ERROR_PMD_ROLE_BAD_OPERATION;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = rolemgmt_alter(
self->hHandle,
pszRoleName,
nOperation,
pszConfig,
&pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
pyTaskID = PyBytes_FromString(pszTaskUUID);
cleanup:
return pyTaskID;
error:
pyTaskID = NULL;
raise_exception(dwError);
goto cleanup;
}
PyObject *
rolemgmt_py_logs(
PPY_ROLEMGMT self,
PyObject *arg,
PyObject *kwds
)
{
uint32_t dwError = 0;
uint32_t i = 0;
char *pszTaskUUID = NULL;
int nStartAt = 0;
int nNumLogs = 0;
PPMD_ROLEMGMT_TASK_LOG pTaskLogs = NULL;
uint32_t dwLogCount = 0;
PyObject *pyTaskLogList = NULL;
PPY_ROLEMGMT_LOG_ENTRY pPyLogEntry = NULL;
static char *kwlist[] = {"taskid", "startat", "numlogs", NULL};
if(!self || !self->hHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (!PyArg_ParseTupleAndKeywords(
arg, kwds, "sII", kwlist,
&pszTaskUUID, &nStartAt, &nNumLogs))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = rolemgmt_get_log(
self->hHandle,
pszTaskUUID,
nStartAt,
nNumLogs,
&pTaskLogs,
&dwLogCount);
BAIL_ON_PMD_ERROR(dwError);
pyTaskLogList = PyList_New(0);
for(i = 0; i < dwLogCount; ++i)
{
printf("i = %d\n", i);
dwError = rolemgmt_logentry_py_make(
&pTaskLogs[i],
&pPyLogEntry);
BAIL_ON_PMD_ERROR(dwError);
printf("i = %d\n", i);
if(PyList_Append(pyTaskLogList, (PyObject *)pPyLogEntry) == -1)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
cleanup:
return pyTaskLogList;
error:
pyTaskLogList = NULL;
raise_exception(dwError);
goto cleanup;
}
static PyGetSetDef rolemgmt_getset[] = {
{"version",
(getter)rolemgmt_py_get_version, (setter)NULL,
"get rolemgmt version",
NULL},
{"roles",
(getter)rolemgmt_py_get_roles, (setter)NULL,
"get all registered roles",
NULL},
{NULL} /* Sentinel */
};
static PyMethodDef rolemgmt_methods[] =
{
{"role_version", (PyCFunction)rolemgmt_py_role_version, METH_VARARGS|METH_KEYWORDS,
"rolemgmt.role_version(name=<role name>) \n\
returns the version of a role by making a query to the plugin.\n\
returns version if successful.\n"},
{"prereqs", (PyCFunction)rolemgmt_py_prereqs, METH_VARARGS|METH_KEYWORDS,
"rolemgmt.prereqs(name=<role name>) \n\
returns the prereqs of a role by making a query to the plugin.\n\
returns list of prereqs if successful.\n"},
{"status", (PyCFunction)rolemgmt_py_task_status, METH_VARARGS|METH_KEYWORDS,
"rolemgmt.status(name=<role name>, taskid=<task uuid>) \n\
returns the status a role's task at the server.\n\
returns status of role's task if successful.\n"},
{"alter", (PyCFunction)rolemgmt_py_alter, METH_VARARGS|METH_KEYWORDS,
"rolemgmt.alter(name=<role name>,operation=<operation>,config=<config json>) \n\
run the alter operation of a role at the server.\n\
return new task id if successful.\n"},
{"logs", (PyCFunction)rolemgmt_py_logs, METH_VARARGS|METH_KEYWORDS,
"rolemgmt.logs(taskid=<task uuid>,startat=<start at>,count=<number of entries to fetch>) \n\
returns logs from an index for a task running at the server.\n\
return logs if successful.\n"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static PyMemberDef rolemgmt_members[] =
{
{NULL} /* Sentinel */
};
PyTypeObject rolemgmtType = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"server.rolemgmt", /*tp_name*/
sizeof(PY_ROLEMGMT), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)rolemgmt_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
rolemgmt__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
rolemgmt_methods, /* tp_methods */
rolemgmt_members, /* tp_members */
rolemgmt_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)rolemgmt_init, /* tp_init */
0, /* tp_alloc */
rolemgmt_new, /* tp_new */
0, /* tp_free */
0 /* tp_is_gc */
};
|
oliverkurth/pmd
|
common/strings.c
|
/*
* Copyright © 2016-2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
uint32_t
PMDSafeAllocateString(
const char *pszSrc,
char **ppszDest
)
{
if(!pszSrc && ppszDest)
{
*ppszDest = NULL;
return 0;
}
return PMDAllocateString(pszSrc, ppszDest);
}
uint32_t
PMDGetStringLengthW(
const wstring_t pwszStr,
size_t* pLength
)
{
ULONG dwError = 0;
if (!pwszStr || !pLength)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
}
else
{
*pLength = LwRtlWC16StringNumChars(pwszStr);
}
return dwError;
}
uint32_t
PMDAllocateStringWFromA(
const char* pszSrc,
wstring_t* ppwszDst
)
{
uint32_t dwError = 0;
if (!pszSrc || !ppwszDst)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
}
else
{
dwError = LwNtStatusToWin32Error(
LwRtlWC16StringAllocateFromCString(ppwszDst, pszSrc));
}
return dwError;
}
uint32_t
PMDAllocateStringAFromW(
const wstring_t pwszSrc,
char** ppszDst
)
{
uint32_t dwError = 0;
if (!pwszSrc || !ppszDst)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
}
else
{
dwError = LwNtStatusToWin32Error(
LwRtlCStringAllocateFromWC16String(ppszDst, pwszSrc));
}
return dwError;
}
uint32_t
PMDAllocateString(
const char* pszSrc,
char** ppszDest
)
{
uint32_t dwError = 0;
char* pszDest = NULL;
if (!pszSrc || !ppszDest)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszDest = strdup(pszSrc);
*ppszDest = pszDest;
cleanup:
return dwError;
error:
if(ppszDest)
{
*ppszDest = NULL;
}
goto cleanup;
}
void
PMDFreeStringArrayWithCount(
char **ppszArray,
int nCount
)
{
char** ppszTemp = NULL;
if(ppszArray)
{
while(nCount)
{
PMDFreeMemory(ppszArray[--nCount]);
}
PMDFreeMemory(ppszArray);
}
}
void
PMDFreeStringArray(
char** ppszArray
)
{
char** ppszTemp = NULL;
if(ppszArray)
{
ppszTemp = ppszArray;
while(ppszTemp && *ppszTemp)
{
PMDFreeMemory(*ppszTemp);
++ppszTemp;
}
PMDFreeMemory(ppszArray);
}
}
uint32_t
PMDAllocateStringPrintf(
char** ppszDst,
const char* pszFmt,
...
)
{
uint32_t dwError = 0;
size_t nSize = 0;
char* pszDst = NULL;
char chDstTest = '\0';
va_list argList;
if(!ppszDst || !pszFmt)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
//Find size
va_start(argList, pszFmt);
nSize = vsnprintf(&chDstTest, 1, pszFmt, argList);
va_end(argList);
if(nSize <= 0)
{
dwError = errno;
BAIL_ON_PMD_ERROR(dwError);
}
nSize = nSize + 1;
dwError = PMDAllocateMemory(nSize, (void**)&pszDst);
BAIL_ON_PMD_ERROR(dwError);
va_start(argList, pszFmt);
nSize = vsnprintf(pszDst, nSize, pszFmt, argList);
va_end(argList);
if(nSize <= 0)
{
dwError = errno;
BAIL_ON_PMD_ERROR(dwError);
}
*ppszDst = pszDst;
cleanup:
return dwError;
error:
if(ppszDst)
{
*ppszDst = NULL;
}
PMD_SAFE_FREE_MEMORY(pszDst);
goto cleanup;
}
int32_t
PMDStringCompareA(
const char* pszStr1,
const char* pszStr2,
uint32_t bIsCaseSensitive
)
{
return LwRtlCStringCompare(pszStr1, pszStr2, bIsCaseSensitive);
}
uint32_t
find_in_array(
char **ppszArray,
int nCount,
const char *pszStrToFind
)
{
uint32_t dwError = 0;
if(!ppszArray || nCount <= 0 || IsNullOrEmptyString(pszStrToFind))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = ENOENT;
while(nCount > 0)
{
if(!strcmp(pszStrToFind, ppszArray[--nCount]))
{
dwError = 0;
break;
}
}
cleanup:
return dwError;
error:
goto cleanup;
}
|
oliverkurth/pmd
|
idl/rolemgmtrpctypes.h
|
/*
* Copyright © 2016-2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#ifndef __ROLEMGMT_RPC_TYPES_H__
#define __ROLEMGMT_RPC_TYPES_H__
#ifdef __cplusplus
extern "C" {
#endif
#if (!defined NO_LIKEWISE && !defined _WIN32)
#include <lw/types.h>
#endif
#ifdef _DCE_IDL_
cpp_quote("#include <rolemgmtrpctypes.h>")
cpp_quote("#if 0")
#endif
typedef enum
{
RPC_ROLE_STATE_IDLE,
RPC_ROLE_STATE_ALTER,
RPC_ROLE_STATE_PREREQ
}RPC_ROLE_STATE;
typedef enum
{
RPC_ROLE_OPERATION_NONE,
RPC_ROLE_OPERATION_ENABLE,
RPC_ROLE_OPERATION_UPDATE,
RPC_ROLE_OPERATION_REMOVE
}RPC_ROLE_OPERATION;
typedef enum
{
RPC_ROLE_STATUS_NONE,
RPC_ROLE_STATUS_SUCCESS,
RPC_ROLE_STATUS_FAILURE,
RPC_ROLE_STATUS_NOT_STARTED,
RPC_ROLE_STATUS_IN_PROGRESS
}RPC_ROLE_STATUS;
typedef struct _PMD_RPC_ROLEMGMT_ROLE_
{
wstring_t pwszId;
wstring_t pwszName;
wstring_t pwszDisplayName;
wstring_t pwszDescription;
}PMD_RPC_ROLEMGMT_ROLE, *PPMD_RPC_ROLEMGMT_ROLE;
typedef struct _PMD_RPC_ROLEMGMT_ROLE_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_ROLEMGMT_ROLE pRoles;
}PMD_RPC_ROLEMGMT_ROLE_ARRAY, *PPMD_RPC_ROLEMGMT_ROLE_ARRAY;
typedef struct _PMD_RPC_ROLEMGMT_PREREQ_
{
wstring_t pwszName;
wstring_t pwszDescription;
}PMD_RPC_ROLEMGMT_PREREQ, *PPMD_RPC_ROLEMGMT_PREREQ;
typedef struct _PMD_RPC_ROLEMGMT_STATUS_
{
RPC_ROLE_STATE nState;
unsigned32 nSecondsElapsed;
unsigned32 nPercentCompleted;
wstring_t pwszStatus;
}PMD_RPC_ROLEMGMT_STATUS, *PPMD_RPC_ROLEMGMT_STATUS;
typedef struct _PMD_RPC_ROLEMGMT_PREREQ_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_ROLEMGMT_PREREQ pPrereqs;
}PMD_RPC_ROLEMGMT_PREREQ_ARRAY, *PPMD_RPC_ROLEMGMT_PREREQ_ARRAY;
typedef struct _PMD_RPC_ROLEMGMT_TASK_LOG_
{
unsigned long int tStamp;
wstring_t pwszLog;
}PMD_RPC_ROLEMGMT_TASK_LOG, *PPMD_RPC_ROLEMGMT_TASK_LOG;
typedef struct _PMD_RPC_ROLEMGMT_TASK_LOG_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_ROLEMGMT_TASK_LOG pTaskLogs;
}PMD_RPC_ROLEMGMT_TASK_LOG_ARRAY, *PPMD_RPC_ROLEMGMT_TASK_LOG_ARRAY;
#ifdef _DCE_IDL_
cpp_quote("#endif")
#endif
#ifdef __cplusplus
}
#endif
#endif /* __ROLEMGMT_RPC_TYPES_H__ */
|
oliverkurth/pmd
|
include/pmd_netmgr.h
|
<reponame>oliverkurth/pmd
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "pmdtypes.h"
#include "pmderror.h"
uint32_t
netmgr_client_set_mac_addr(
PPMDHANDLE hHandle,
const char *pszIfname,
const char *pszMacAddress
);
uint32_t
netmgr_client_get_mac_addr(
PPMDHANDLE hHandle,
const char *pszIfname,
char **ppszMacAddress
);
uint32_t
netmgr_client_set_link_mode(
PPMDHANDLE hHandle,
const char *pszIfname,
NET_LINK_MODE linkMode
);
uint32_t
netmgr_client_get_link_mode(
PPMDHANDLE hHandle,
const char *pszIfname,
NET_LINK_MODE *pLinkMode
);
uint32_t
netmgr_client_set_link_mtu(
PPMDHANDLE hHandle,
const char *pszIfname,
uint32_t mtu
);
uint32_t
netmgr_client_get_link_mtu(
PPMDHANDLE hHandle,
const char *pszIfname,
uint32_t *pMtu
);
uint32_t
netmgr_client_set_link_state(
PPMDHANDLE hHandle,
const char *pszIfname,
NET_LINK_STATE linkState
);
uint32_t
netmgr_client_get_link_state(
PPMDHANDLE hHandle,
const char *pszIfname,
NET_LINK_STATE *pLinkState
);
uint32_t
netmgr_client_ifup(
PPMDHANDLE hHandle,
const char *pszIfname
);
uint32_t
netmgr_client_ifdown(
PPMDHANDLE hHandle,
const char *pszIfname
);
uint32_t
netmgr_client_get_link_info(
PPMDHANDLE hHandle,
const char *pszIfname,
NET_LINK_INFO **ppLinkInfo
);
uint32_t
netmgr_client_set_ipv4_addr_gateway(
PPMDHANDLE hHandle,
char *pszIfname,
NET_IPV4_ADDR_MODE mode,
char *pszIPv4AddrPrefix,
char *pszIPv4Gateway
);
uint32_t
netmgr_client_get_ipv4_addr_gateway(
PPMDHANDLE hHandle,
char *pszIfname,
NET_IPV4_ADDR_MODE *pMode,
char **ppszIPv4AddrPrefix,
char **ppszIPv4Gateway
);
uint32_t
netmgr_client_add_static_ipv6_addr(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszIPv6AddrPrefix
);
uint32_t
netmgr_client_delete_static_ipv6_addr(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszIPv6AddrPrefix
);
uint32_t
netmgr_client_set_ipv6_addr_mode(
PPMDHANDLE hHandle,
char *pszIfname,
uint32_t enableDhcp,
uint32_t enableAutoconf
);
uint32_t
netmgr_client_get_ipv6_addr_mode(
PPMDHANDLE hHandle,
char *pszIfname,
uint32_t *pDhcpEnabled,
uint32_t *pAutoconfEnabled
);
uint32_t
netmgr_client_set_ipv6_gateway(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszIPv6Gateway
);
uint32_t
netmgr_client_get_ipv6_gateway(
PPMDHANDLE hHandle,
char *pszIfname,
char **ppszIPv6Gateway
);
uint32_t
netmgr_client_get_ip_addr(
PPMDHANDLE hHandle,
char *pszIfname,
uint32_t addrTypes,
size_t *pCount,
NET_IP_ADDR ***pppIpAddrList
);
uint32_t
netmgr_client_add_static_ip_route(
PPMDHANDLE hHandle,
NET_IP_ROUTE *pRoute
);
uint32_t
netmgr_client_delete_static_ip_route(
PPMDHANDLE hHandle,
NET_IP_ROUTE *pRoute
);
uint32_t
netmgr_client_get_static_ip_routes(
PPMDHANDLE hHandle,
char *pszIfname,
size_t *pCount,
NET_IP_ROUTE ***pppRouteList
);
uint32_t
netmgr_client_add_dns_server(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszDnsServer
);
uint32_t
netmgr_client_delete_dns_server(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszDnsServer
);
uint32_t
netmgr_client_set_dns_servers(
PPMDHANDLE hHandle,
char *pszIfname,
NET_DNS_MODE mode,
size_t count,
char **ppszDnsServers
);
uint32_t
netmgr_client_get_dns_servers(
PPMDHANDLE hHandle,
char *pszIfname,
NET_DNS_MODE *pMode,
size_t *pCount,
char ***pppszDnsServers
);
uint32_t
netmgr_client_add_dns_domain(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszDnsDomain
);
uint32_t
netmgr_client_delete_dns_domain(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszDnsDomain
);
uint32_t
netmgr_client_set_dns_domains(
PPMDHANDLE hHandle,
char *pszIfname,
size_t count,
char **ppszDnsDomains
);
uint32_t
netmgr_client_get_dns_domains(
PPMDHANDLE hHandle,
char *pszIfname,
size_t *pCount,
char ***pppszDnsDomains
);
uint32_t
netmgr_client_get_iaid(
PPMDHANDLE hHandle,
char *pszIfname,
uint32_t *pdwIaid
);
uint32_t
netmgr_client_set_iaid(
PPMDHANDLE hHandle,
char *pszIfname,
uint32_t dwIaid
);
uint32_t
netmgr_client_get_duid(
PPMDHANDLE hHandle,
char *pszIfname,
char **ppszDuid
);
uint32_t
netmgr_client_set_duid(
PPMDHANDLE hHandle,
char *pszIfname,
char *pszDuid
);
//ntpd related
uint32_t
netmgr_client_set_ntp_servers(
PPMDHANDLE hHandle,
size_t nCount,
char **ppszNtpServers);
uint32_t
netmgr_client_add_ntp_servers(
PPMDHANDLE hHandle,
size_t nCount,
const char **ppszNtpServers);
uint32_t
netmgr_client_delete_ntp_servers(
PPMDHANDLE hHandle,
size_t nCount,
const char **ppszNtpServers);
uint32_t
netmgr_client_get_ntp_servers(
PPMDHANDLE hHandle,
size_t *pnCount,
char ***pppszNtpServers);
uint32_t
netmgr_client_set_hostname(
PPMDHANDLE hHandle,
const char *pszHostname);
uint32_t
netmgr_client_get_hostname(
PPMDHANDLE hHandle,
char **ppszHostname);
uint32_t
netmgr_client_wait_for_link_up(
PPMDHANDLE hHandle,
const char *pszInterfaceName,
uint32_t dwTimeout);
uint32_t
netmgr_client_wait_for_ip(
PPMDHANDLE hHandle,
const char *pszInterfaceName,
uint32_t dwTimeout,
NET_ADDR_TYPE dwAddrTypes);
uint32_t
netmgr_client_get_error_info(
PPMDHANDLE hHandle,
uint32_t nmErrCode,
char **ppszErrInfo);
uint32_t
netmgr_client_set_network_param(
PPMDHANDLE hHandle,
const char *pszObjectName,
const char *pszParamName,
const char *pszParamValue);
uint32_t
netmgr_client_get_network_param(
PPMDHANDLE hHandle,
const char *pszObjectName,
const char *pszParamName,
char **ppszParamValue);
#ifdef __cplusplus
}
#endif
|
oliverkurth/pmd
|
server/rolemgmt/rolemgmt_api.c
|
/*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
uint32_t
pmd_rolemgmt_get_version(
char **ppszVersion
)
{
uint32_t dwError = 0;
char *pszVersion = NULL;
if(!ppszVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateString(PMD_ROLEMGMT_VERSION, &pszVersion);
BAIL_ON_PMD_ERROR(dwError);
*ppszVersion = pszVersion;
cleanup:
return dwError;
error:
if(ppszVersion)
{
*ppszVersion = NULL;
}
goto cleanup;
}
uint32_t
pmd_rolemgmt_load(
)
{
uint32_t dwError = 0;
int nLocked = 0, nPrefix = 0;
PPMD_ROLEMGMT_ROLE pRoles = NULL;
PPMD_ROLEMGMT_ROLE pRole = NULL;
PPMD_PLUGIN_CONTEXT pContexts = NULL;
PPMD_PLUGIN_CONTEXT pContext = NULL;
char pszResolvedPath[PATH_MAX];
pthread_mutex_lock(&gRoleMgmtEnv.mutexEnv);
nLocked = 1;
if(gRoleMgmtEnv.pRoles)
{
goto cleanup;
}
dwError = rolemgmt_load_roles(
PMD_ROLES_DIR,
PMD_ROLE_PLUGINS_DIR,
&pRoles);
BAIL_ON_PMD_ERROR(dwError);
for(pRole = pRoles; pRole; pRole = pRole->pNext)
{
dwError = PMDAllocateMemory(sizeof(PMD_PLUGIN_CONTEXT), (void **)&pContext);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateString(pRole->pszId, &pContext->pszPluginId);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringPrintf(
&pContext->pszPluginPath,
"%s/%s",
PMD_ROLE_PLUGINS_DIR,
pRole->pszPlugin);
BAIL_ON_PMD_ERROR(dwError);
if(NULL == realpath(pContext->pszPluginPath, pszResolvedPath))
{
dwError = errno;
BAIL_ON_PMD_SYSTEM_ERROR(dwError);
}
BAIL_ON_PMD_ERROR(dwError);
dwError = isStringPrefix(pszResolvedPath,
PMD_ROLE_PLUGINS_DIR,
&nPrefix);
BAIL_ON_PMD_ERROR(dwError);
if(!nPrefix)
{
dwError = ERROR_PMD_ROLE_PATH_MISMATCH;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(sizeof(PMD_PLUGIN_MODULE),
(void **)&pContext->pModule);
BAIL_ON_PMD_ERROR(dwError);
pContext->pNext = pContexts;
pContexts = pContext;
pContext = NULL;
}
gRoleMgmtEnv.pRoles = pRoles;
gRoleMgmtEnv.pContexts = pContexts;
cleanup:
if(nLocked)
{
pthread_mutex_unlock(&gRoleMgmtEnv.mutexEnv);
}
return dwError;
error:
if(dwError == ERROR_PMD_NO_DATA)//no role files. don't fail.
{
dwError = 0;
}
gRoleMgmtEnv.pRoles = NULL;
gRoleMgmtEnv.pContexts = NULL;
rolemgmt_free_roles(pRoles);
rolemgmt_free_context(pContext);
rolemgmt_free_contexts(pContexts);
goto cleanup;
}
void
pmd_rolemgmt_unload(
)
{
pthread_mutex_lock(&gRoleMgmtEnv.mutexEnv);
rolemgmt_free_roles(gRoleMgmtEnv.pRoles);
gRoleMgmtEnv.pRoles = NULL;
rolemgmt_free_contexts(gRoleMgmtEnv.pContexts);
gRoleMgmtEnv.pContexts = NULL;
pthread_mutex_unlock(&gRoleMgmtEnv.mutexEnv);
}
uint32_t
pmd_load_plugin(
const char *pszPluginPath,
const PPMD_PLUGIN_MODULE pModule
)
{
uint32_t dwError = 0;
int nLocked = 0;
PMD_PLUGIN_MODULE stModule = {0};
if(IsNullOrEmptyString(pszPluginPath) || !pModule)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(pModule->pHandle)
{
goto cleanup;
}
if(pModule->nDisabled)
{
dwError = ERROR_PMD_ROLE_PLUGIN_DISABLED;
BAIL_ON_PMD_ERROR(dwError);
}
pthread_mutex_lock(&pModule->mutexModule);
nLocked = 1;
//clear error
dlerror();
stModule.pHandle = dlopen (pszPluginPath, RTLD_NOW);
if(!stModule.pHandle)
{
dwError = ERROR_PMD_LIBACC;
BAIL_ON_PMD_ERROR(dwError);
}
stModule.pFnLoad = dlsym(stModule.pHandle,
PMD_ROLEPLUGIN_LOAD_INTERFACE);
if(!stModule.pFnLoad)
{
dwError = ERROR_PMD_ROLE_UNMAPPED_LOAD;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = stModule.pFnLoad(&stModule.pInterface);
BAIL_ON_PMD_ERROR(dwError);
if(!stModule.pInterface)
{
dwError = ERROR_PMD_ROLE_PLUGIN_BAD;
BAIL_ON_PMD_ERROR(dwError);
}
//unload can be null.
stModule.pFnUnload = dlsym(stModule.pHandle,
PMD_ROLEPLUGIN_UNLOAD_INTERFACE);
pModule->pHandle = stModule.pHandle;
pModule->pFnLoad = stModule.pFnLoad;
pModule->pFnUnload = stModule.pFnUnload;
pModule->pInterface = stModule.pInterface;
cleanup:
if(nLocked)
{
pthread_mutex_unlock(&pModule->mutexModule);
}
return dwError;
error:
fprintf(stderr, "Error: %d, dlerror: %s", dwError, dlerror());
if(pModule)
{
pModule->nDisabled = 1;
}
if(stModule.pHandle)
{
dlclose(stModule.pHandle);
}
goto cleanup;
}
uint32_t
pmd_rolemgmt_get_role_plugin(
const char *pszName,
PPMD_PLUGIN_MODULE *ppModule
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_CONTEXT pContext = NULL;
PPMD_PLUGIN_MODULE pModule = NULL;
if(IsNullOrEmptyString(pszName) || !ppModule)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(pContext = gRoleMgmtEnv.pContexts; pContext; pContext = pContext->pNext)
{
if(!strcasecmp(pContext->pszPluginId, pszName))
{
break;
}
}
if(!pContext || !pContext->pModule)
{
dwError = ERROR_PMD_ROLES_NO_SUCH_ROLE;
BAIL_ON_PMD_ERROR(dwError);
}
pModule = pContext->pModule;
if(!pModule->pHandle)
{
if(IsNullOrEmptyString(pContext->pszPluginPath))
{
dwError = ERROR_PMD_ROLES_PLUGIN_NOT_SET;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pmd_load_plugin(pContext->pszPluginPath, pModule);
BAIL_ON_PMD_ERROR(dwError);
}
*ppModule = pModule;
cleanup:
return dwError;
error:
if(ppModule)
{
*ppModule = NULL;
}
goto cleanup;
}
uint32_t
pmd_rolemgmt_role_version(
const char *pszName,
char **ppszVersion
)
{
uint32_t dwError = 0;
char *pszVersion = NULL;
char *pszPlugin = NULL;
PPMD_PLUGIN_MODULE pModule = NULL;
if(IsNullOrEmptyString(pszName) || !ppszVersion)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pmd_rolemgmt_get_role_plugin(pszName, &pModule);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_plugin_get_version(pModule, &pszVersion);
BAIL_ON_PMD_ERROR(dwError);
*ppszVersion = pszVersion;
cleanup:
return dwError;
error:
if(ppszVersion)
{
*ppszVersion = NULL;
}
PMD_SAFE_FREE_MEMORY(pszVersion);
goto cleanup;
}
uint32_t
pmd_rolemgmt_role_get_prereqs(
const char *pszName,
PMD_ROLE_OPERATION nOperation,
PPMD_ROLE_PREREQ *ppPreReqs,
uint32_t *pdwPreReqCount
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_MODULE pModule = NULL;
PPMD_ROLE_PREREQ pPreReqs = NULL;
uint32_t dwPreReqCount = 0;
PPMD_ROLE_HANDLE pRoleHandle = NULL;
if(!ppPreReqs || !pdwPreReqCount)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pmd_rolemgmt_get_role_plugin(pszName, &pModule);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_plugin_open(pModule, &pRoleHandle);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_plugin_get_prereqs(
pModule,
nOperation,
pRoleHandle,
&pPreReqs,
&dwPreReqCount);
BAIL_ON_PMD_ERROR(dwError);
*ppPreReqs = pPreReqs;
*pdwPreReqCount = dwPreReqCount;
cleanup:
if(pRoleHandle)
{
pmd_rolemgmt_plugin_close(pModule, pRoleHandle);
}
return dwError;
error:
if(ppPreReqs)
{
*ppPreReqs = NULL;
}
if(pdwPreReqCount)
{
*pdwPreReqCount = 0;
}
goto cleanup;
}
uint32_t
rolemgmt_task_progress_cb(
const char *pszTaskUUID,
const char *pszProgress
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_TASK pTask = NULL;
PPMD_PLUGIN_TASK_LOG pLog = NULL;
if(IsNullOrEmptyString(pszTaskUUID) || IsNullOrEmptyString(pszProgress))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
fprintf(stdout, "Task(%s): %s\n", pszTaskUUID, pszProgress);
dwError = rolemgmt_find_task_by_id(pszTaskUUID, &pTask);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateMemory(sizeof(PMD_PLUGIN_TASK_LOG), (void **)&pLog);
BAIL_ON_PMD_ERROR(dwError);
pLog->tStamp = time(NULL);
dwError = PMDAllocateString(pszProgress, &pLog->pszLog);
BAIL_ON_PMD_ERROR(dwError);
if(!pTask->pLogData)
{
pTask->pLogData = pLog;
}
else
{
PPMD_PLUGIN_TASK_LOG pTemp = pTask->pLogData;
while(pTemp->pNext) pTemp = pTemp->pNext;
pTemp->pNext = pLog;
}
cleanup:
return dwError;
error:
fprintf(stderr, "Callback from plugin caused an error: %d\n", dwError);
rolemgmt_free_plugin_task_logs(pLog);
goto cleanup;
}
uint32_t
pmd_rolemgmt_role_create_task(
PPMD_PLUGIN_MODULE pModule,
PMD_ROLE_OPERATION nOperation,
const char *pszConfigJson,
PPMD_PLUGIN_TASK *ppTask
)
{
uint32_t dwError = 0;
int nLocked = 0;
PPMD_PLUGIN_TASK pTask = NULL;
uuid_t uuidTask = {0};
if(!pModule || IsNullOrEmptyString(pszConfigJson) || !ppTask)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(pModule->pCurrentTask)
{
dwError = ERROR_PMD_ROLE_PLUGIN_HAS_TASKS;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(sizeof(PMD_PLUGIN_TASK), (void **)&pTask);
BAIL_ON_PMD_ERROR(dwError);
pTask->tStart = time(NULL);
pTask->pFnProgressCallback = rolemgmt_task_progress_cb;
pTask->nOperation = nOperation;
dwError = PMDAllocateString(pszConfigJson, &pTask->pszConfigJson);
BAIL_ON_PMD_ERROR(dwError);
//make uuid for this task
uuid_generate(uuidTask);
dwError = PMDAllocateMemory(sizeof(char) * UUID_STR_LEN,
(void **)&pTask->pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
dwError = pmd_rolemgmt_plugin_open(pModule, &pTask->pRoleHandle);
BAIL_ON_PMD_ERROR(dwError);
uuid_unparse(uuidTask, pTask->pszTaskUUID);
pModule->pCurrentTask = pTask;
*ppTask = pTask;
cleanup:
return dwError;
error:
if(ppTask)
{
*ppTask = 0;
}
rolemgmt_free_plugin_module_task(pModule);
goto cleanup;
}
uint32_t
rolemgmt_archive_current_task(
PPMD_PLUGIN_MODULE pModule
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_TASK pTask = NULL;
if(!pModule || !pModule->pCurrentTask)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pTask = pModule->pCurrentTask;
pModule->pCurrentTask = NULL;
pTask->pNext = pModule->pTaskHistory;
pModule->pTaskHistory = pTask;
fprintf(stdout, "Archiving task %s\n", pTask->pszTaskUUID);
error:
return dwError;
}
void *
pmd_rolemgmt_task_thread(
void *pThreadInfo
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_TASK_THREAD_INFO pTaskThreadInfo = pThreadInfo;
if(!pTaskThreadInfo ||
!pTaskThreadInfo->pModule ||
!pTaskThreadInfo->pTask)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pTaskThreadInfo->pTask->nStatus = ROLE_STATUS_IN_PROGRESS;
dwError = pmd_rolemgmt_plugin_alter(
pTaskThreadInfo->pModule,
pTaskThreadInfo->pTask);
BAIL_ON_PMD_ERROR(dwError);
pTaskThreadInfo->pTask->nStatus = ROLE_STATUS_SUCCESS;
cleanup:
if(pTaskThreadInfo)
{
rolemgmt_archive_current_task(pTaskThreadInfo->pModule);
PMDFreeMemory(pTaskThreadInfo);
}
return NULL;
error:
if(pTaskThreadInfo)
{
pTaskThreadInfo->pTask->nStatus = ROLE_STATUS_FAILURE;
pTaskThreadInfo->pTask->dwError = dwError;
}
goto cleanup;
}
uint32_t
pmd_rolemgmt_role_alter(
const char *pszName,
PMD_ROLE_OPERATION nOperation,
const char *pszConfigJson,
char **ppszTaskUUID
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_MODULE pModule = NULL;
PPMD_PLUGIN_TASK pTask = NULL;
char *pszTaskUUID = NULL;
int nLocked = 0;
PPMD_PLUGIN_TASK_THREAD_INFO pTaskThreadInfo = NULL;
if(IsNullOrEmptyString(pszName) ||
IsNullOrEmptyString(pszConfigJson) ||
!ppszTaskUUID)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pmd_rolemgmt_get_role_plugin(pszName, &pModule);
BAIL_ON_PMD_ERROR(dwError);
pthread_mutex_lock(&pModule->mutexTasks);
nLocked = 1;
dwError = pmd_rolemgmt_role_create_task(
pModule,
nOperation,
pszConfigJson,
&pTask);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateMemory(sizeof(PMD_PLUGIN_TASK_THREAD_INFO),
(void **)&pTaskThreadInfo);
BAIL_ON_PMD_ERROR(dwError);
pTaskThreadInfo->pModule = pModule;
pTaskThreadInfo->pTask = pTask;
dwError = pthread_create(&pTask->nThreadID,
NULL,
&pmd_rolemgmt_task_thread,
pTaskThreadInfo);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateString(pTask->pszTaskUUID, &pszTaskUUID);
BAIL_ON_PMD_ERROR(dwError);
*ppszTaskUUID = pszTaskUUID;
cleanup:
if(nLocked && pModule)
{
pthread_mutex_unlock(&pModule->mutexTasks);
}
return dwError;
error:
if(ppszTaskUUID)
{
*ppszTaskUUID = NULL;
}
PMD_SAFE_FREE_MEMORY(pszTaskUUID);
//TODO: safely remove this task
//pmd_rolemgmt_role_remove_task(pTask);
goto cleanup;
}
uint32_t
rolemgmt_find_archived_task_by_id(
const char *pszTaskUUID,
PPMD_PLUGIN_TASK *ppTask
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_TASK pTask = NULL;
PPMD_PLUGIN_CONTEXT pContext = NULL;
if(IsNullOrEmptyString(pszTaskUUID) || !ppTask)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(pContext = gRoleMgmtEnv.pContexts; pContext; pContext = pContext->pNext)
{
PPMD_PLUGIN_TASK pCurrentTask = NULL;
if(!pContext->pModule || !pContext->pModule->pTaskHistory)
{
continue;
}
pCurrentTask = pContext->pModule->pTaskHistory;
while(pCurrentTask != NULL)
{
if(!strcasecmp(pCurrentTask->pszTaskUUID, pszTaskUUID))
{
pTask = pCurrentTask;
break;
}
pCurrentTask = pCurrentTask->pNext;
}
}
if(!pTask)
{
dwError = ERROR_PMD_ROLE_TASK_NO_LOGS;
BAIL_ON_PMD_ERROR(dwError);
}
*ppTask = pTask;
cleanup:
return dwError;
error:
if(ppTask)
{
*ppTask = NULL;
}
goto cleanup;
}
uint32_t
rolemgmt_find_task_by_id(
const char *pszTaskUUID,
PPMD_PLUGIN_TASK *ppTask
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_TASK pTask = NULL;
PPMD_PLUGIN_CONTEXT pContext = NULL;
if(IsNullOrEmptyString(pszTaskUUID) || !ppTask)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(pContext = gRoleMgmtEnv.pContexts; pContext; pContext = pContext->pNext)
{
PPMD_PLUGIN_TASK pCurrentTask = NULL;
if(!pContext->pModule || !pContext->pModule->pCurrentTask)
{
continue;
}
pCurrentTask = pContext->pModule->pCurrentTask;
if(!strcasecmp(pCurrentTask->pszTaskUUID, pszTaskUUID))
{
pTask = pContext->pModule->pCurrentTask;
break;
}
}
if(!pTask)
{
dwError = ERROR_PMD_ROLE_TASK_NOT_FOUND;
BAIL_ON_PMD_ERROR(dwError);
}
*ppTask = pTask;
cleanup:
return dwError;
error:
if(ppTask)
{
*ppTask = NULL;
}
goto cleanup;
}
uint32_t
pmd_rolemgmt_get_status(
const char *pszName,
const char *pszTaskUUID,
PMD_ROLE_STATUS *pnStatus
)
{
uint32_t dwError = 0;
PPMD_PLUGIN_TASK pTask = NULL;
if(IsNullOrEmptyString(pszName) ||
IsNullOrEmptyString(pszTaskUUID) ||
!pnStatus)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = rolemgmt_find_task_by_id(pszTaskUUID, &pTask);
if (dwError != ERROR_PMD_ROLE_TASK_NOT_FOUND)
{
BAIL_ON_PMD_ERROR(dwError);
}
else
{
dwError = rolemgmt_find_archived_task_by_id(pszTaskUUID, &pTask);
BAIL_ON_PMD_ERROR(dwError);
}
*pnStatus = pTask->nStatus;
cleanup:
return dwError;
error:
if(pnStatus)
{
*pnStatus = ROLE_STATUS_NONE;
}
goto cleanup;
}
uint32_t
pmd_rolemgmt_get_logs(
const char *pszTaskUUID,
uint32_t dwOffset,
uint32_t dwEntriesToFetch,
PPMD_PLUGIN_TASK_LOG *ppTaskLogs
)
{
uint32_t dwError = 0;
uint32_t i = 0;
PPMD_PLUGIN_TASK_LOG pTaskLogs = NULL;
PPMD_PLUGIN_TASK pTask = NULL;
if(IsNullOrEmptyString(pszTaskUUID) || !ppTaskLogs)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = rolemgmt_find_task_by_id(pszTaskUUID, &pTask);
if (dwError != ERROR_PMD_ROLE_TASK_NOT_FOUND)
{
BAIL_ON_PMD_ERROR(dwError);
}
else
{
dwError = rolemgmt_find_archived_task_by_id(pszTaskUUID, &pTask);
BAIL_ON_PMD_ERROR(dwError);
}
pTaskLogs = pTask->pLogData;
for(i = 0; pTaskLogs && i < dwOffset; ++i, pTaskLogs = pTaskLogs->pNext);
if(!pTaskLogs)
{
dwError = ERROR_PMD_ROLE_TASK_NO_LOGS;
BAIL_ON_PMD_ERROR(dwError);
}
*ppTaskLogs = pTaskLogs;
cleanup:
return dwError;
error:
if(ppTaskLogs)
{
*ppTaskLogs = NULL;
}
goto cleanup;
}
void
rolemgmt_free_plugin_task_logs(
PPMD_PLUGIN_TASK_LOG pLogs
)
{
if(!pLogs)
{
return;
}
while(pLogs)
{
PPMD_PLUGIN_TASK_LOG pNextLog = pLogs->pNext;
PMD_SAFE_FREE_MEMORY(pLogs->pszLog);
PMDFreeMemory(pLogs);
pLogs = pNextLog;
}
}
void
rolemgmt_free_plugin_module_task(
PPMD_PLUGIN_MODULE pModule
)
{
PPMD_PLUGIN_TASK pTask = NULL;
if(!pModule && pModule->pCurrentTask)
{
return;
}
pTask = pModule->pCurrentTask;
PMD_SAFE_FREE_MEMORY(pTask->pszTaskUUID);
PMD_SAFE_FREE_MEMORY(pTask->pszConfigJson);
if(pTask->pRoleHandle)
{
pmd_rolemgmt_plugin_close(pModule, pTask->pRoleHandle);
}
rolemgmt_free_plugin_task_logs(pTask->pLogData);
PMDFreeMemory(pTask);
pModule->pCurrentTask = NULL;
}
void
rolemgmt_free_plugin_module_tasks(
PPMD_PLUGIN_MODULE pModule
)
{
if(!pModule || !pModule->pCurrentTask)
{
return;
}
pthread_mutex_lock(&pModule->mutexTasks);
rolemgmt_free_plugin_module_task(pModule);
pthread_mutex_unlock(&pModule->mutexTasks);
}
void
rolemgmt_free_plugin_module(
PPMD_PLUGIN_MODULE pModule
)
{
if(!pModule)
{
return;
}
pthread_mutex_lock(&pModule->mutexModule);
rolemgmt_free_plugin_module_tasks(pModule);
if(pModule->pFnUnload)
{
pModule->pFnUnload(pModule->pInterface);
pModule->pFnUnload = NULL;
}
if(pModule->pHandle)
{
dlclose(pModule->pHandle);
pModule->pHandle = NULL;
}
pthread_mutex_unlock(&pModule->mutexModule);
PMDFreeMemory(pModule);
}
void
rolemgmt_free_context(
PPMD_PLUGIN_CONTEXT pContext
)
{
if(!pContext)
{
return;
}
rolemgmt_free_plugin_module(pContext->pModule);
PMD_SAFE_FREE_MEMORY(pContext->pszPluginId);
PMD_SAFE_FREE_MEMORY(pContext->pszPluginPath);
PMDFreeMemory(pContext);
}
void
rolemgmt_free_contexts(
PPMD_PLUGIN_CONTEXT pContexts
)
{
if(!pContexts)
{
return;
}
while(pContexts)
{
PPMD_PLUGIN_CONTEXT pContext = pContexts->pNext;
rolemgmt_free_context(pContexts);
pContexts = pContext;
}
}
|
oliverkurth/pmd
|
client/rpc.c
|
/*
* Copyright © 2016-2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
void
chk_dce_err(
error_status_t ecode,
char* where,
char* why,
unsigned int fatal
)
{
dce_error_string_t errstr;
int error_status;
if (ecode != error_status_ok)
{
dce_error_inq_text(ecode, (unsigned char *) errstr, &error_status);
if (error_status == error_status_ok)
printf("ERROR. where = <%s> why = <%s> error code = 0x%x"
"reason = <%s>\n",
where, why, ecode, errstr);
else
printf("ERROR. where = <%s> why = <%s> error code = 0x%x\n",
where, why, ecode);
if (fatal) exit(1);
}
}
static
uint32_t
create_auth_identity(
const char *pszUser,
const char *pszDomain,
const char *pszPassword,
char **ppszUPN,
rpc_auth_identity_handle_t *pAuthHandle)
{
OM_uint32 dwError = 0;
OM_uint32 dwMin = 0;
const gss_OID_desc gss_srp_password_oid =
{GSSAPI_SRP_CRED_OPT_PW_LEN, (void *) GSSAPI_SRP_CRED_OPT_PW};
const gss_OID_desc gss_unix_password_oid =
{GSSAPI_UNIX_CRED_OPT_PW_LEN, (void *) GSSAPI_UNIX_CRED_OPT_PW};
const gss_OID_desc spnego_mech_oid =
{GSSAPI_MECH_SPNEGO_LEN, (void *) GSSAPI_MECH_SPNEGO};
gss_OID pSelectedOID = NULL;
gss_buffer_desc stNameBuff = {0};
gss_buffer_desc stPasswordBuff = {0};
gss_name_t gss_name_buf = NULL;
size_t nUPNLength = 0;
char *pszUPN = NULL;
gss_cred_id_t cred_handle = NULL;
gss_OID_desc mech_oid_array[1];
gss_OID_set_desc desired_mech = {0};
const char chSep = '@';
if(IsNullOrEmptyString(pszUser) ||
IsNullOrEmptyString(pszPassword) ||
!ppszUPN ||
!pAuthHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateStringPrintf(
&pszUPN,
"%s%s%s",
pszUser,
IsNullOrEmptyString(pszDomain) ? "" : "@",
IsNullOrEmptyString(pszDomain) ? "" : pszDomain);
BAIL_ON_PMD_ERROR(dwError);
stNameBuff.value = pszUPN;
stNameBuff.length = strlen(pszUPN);
dwError = gss_import_name(
&dwMin,
&stNameBuff,
GSS_C_NT_USER_NAME,
&gss_name_buf);
BAIL_ON_PMD_ERROR(dwError);
/*
* Use SPNEGO mech OID to acquire cred
*/
desired_mech.count = 1;
desired_mech.elements = mech_oid_array;
desired_mech.elements[0] = spnego_mech_oid;
dwError = gss_acquire_cred(
&dwMin,
gss_name_buf,
0,
&desired_mech,
GSS_C_INITIATE,
&cred_handle,
NULL,
NULL);
BAIL_ON_PMD_ERROR(dwError);
stPasswordBuff.value = (char *)pszPassword;
stPasswordBuff.length = strlen(stPasswordBuff.value);
pSelectedOID = strchr(pszUPN, chSep) ?
(gss_OID)&gss_srp_password_oid :
(gss_OID)&gss_unix_password_oid;
dwError = gss_set_cred_option(
&dwMin,
&cred_handle,
pSelectedOID,
&stPasswordBuff);
BAIL_ON_PMD_ERROR(dwError);
*ppszUPN = pszUPN;
*pAuthHandle = (rpc_auth_identity_handle_t) cred_handle;
cleanup:
return dwError;
error:
dwError = dwMin ? dwMin : dwError;
PMD_SAFE_FREE_MEMORY(pszUPN);
if (gss_name_buf)
{
gss_release_name(&dwMin, &gss_name_buf);
}
goto cleanup;
}
uint32_t
get_client_rpc_binding(
rpc_binding_handle_t* binding_handle,
rpc_if_handle_t interface_spec,
const char* hostname,
const char* username,
const char* domain,
const char* password,
const char* protocol,
const char* endpoint,
const char* spn
)
{
uint32_t dwError = 0;
char* string_binding = NULL;
error_status_t status;
unsigned char* pszUPN = NULL;
rpc_auth_identity_handle_t rpc_identity_h = NULL;
int nSetAuthInfo = 0;
/*
* create a string binding given the command line parameters and
* resolve it into a full binding handle using the endpoint mapper.
* The binding handle resolution is handled by the runtime library
*/
rpc_string_binding_compose(NULL,
(unsigned char *) protocol,
(unsigned char *) hostname,
(unsigned char *) endpoint,
NULL,
(unsigned char **) &string_binding,
&status);
chk_dce_err(status,
"rpc_string_binding_compose()",
"get_client_rpc_binding", 1);
rpc_binding_from_string_binding((unsigned char *)string_binding,
binding_handle,
&status);
chk_dce_err(status,
"rpc_binding_from_string_binding()",
"get_client_rpc_binding", 1);
rpc_string_free((unsigned char **) &string_binding, &status);
chk_dce_err(status, "rpc_string_free()", "get_client_rpc_binding", 1);
if(strcmp(protocol, PROTOCOL_NCALRPC) != 0)
{
nSetAuthInfo = 1;
}
//When using the privsep endpoint, REST calls will pass
//in credentials. dcerpc calls have reached till this point
//because they passed authentication.
else if(!strcmp(endpoint, PMD_PRIVSEP_NCALRPC_END_POINT))
{
if(!IsNullOrEmptyString(username) && !IsNullOrEmptyString(password))
{
nSetAuthInfo = 1;
}
}
if(nSetAuthInfo)
{
if(IsNullOrEmptyString(username) ||
IsNullOrEmptyString(password))
{
if(IsNullOrEmptyString(spn))
{
dwError = ERROR_PMD_ACCESS_DENIED;
BAIL_ON_PMD_ERROR(dwError);
}
rpc_binding_set_auth_info(
*binding_handle,
(unsigned char *)spn,
0,
PPMD_RPC_AUTHN_GSS_NEGOTIATE,
rpc_identity_h,
PPMD_RPC_AUTHZN_NAME,
&dwError);
BAIL_ON_PMD_ERROR(dwError);
}
else
{
dwError = create_auth_identity(
username,
domain,
password,
(char**)&pszUPN,
&rpc_identity_h);
BAIL_ON_PMD_ERROR(dwError);
rpc_binding_set_auth_info(
*binding_handle,
pszUPN,
PPMD_RPC_PROTECT_LEVEL_PKT_PRIVACY,
PPMD_RPC_AUTHN_GSS_NEGOTIATE,
rpc_identity_h,
PPMD_RPC_AUTHZN_NAME,
&dwError);
BAIL_ON_PMD_ERROR(dwError);
}
}
/*
* Get a printable rendition of the binding handle and echo to
* the user.
*/
rpc_binding_to_string_binding(*binding_handle,
(unsigned char **)&string_binding,
&status);
chk_dce_err(status,
"rpc_binding_to_string_binding()",
"get_client_rpc_binding", 1);
rpc_string_free((unsigned char **) &string_binding, &status);
chk_dce_err(status, "rpc_string_free()", "get_client_rpc_binding", 1);
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
rpc_open(
const char* pszModule,
const char* pszServer,
const char* pszUser,
const char* pszDomain,
const char* pszPass,
const char* pszSpn,
PPMDHANDLE* phHandle
)
{
uint32_t dwError = 0;
PMDHANDLE* hHandle = NULL;
char* pszProt = PROTOCOL_TCP;
char* pszEndpoint = PMD_RPC_TCP_END_POINT;
int nIndex = 0;
KNOWN_IF_SPEC knownIfspecs[] =
{
#ifdef DEMO_ENABLED
{"demo", demo_v1_0_c_ifspec},
#endif
{"fwmgmt", fwmgmt_v1_0_c_ifspec},
{"pkg", pkg_v1_0_c_ifspec},
{"pmd", pmd_v1_0_c_ifspec},
{"net", netmgmt_v1_0_c_ifspec},
{"usermgmt", usermgmt_v1_0_c_ifspec},
{"rolemgmt", rolemgmt_v1_0_c_ifspec},
};
int nNumKnownIfspecs =
sizeof(knownIfspecs)/sizeof(knownIfspecs[0]);
rpc_if_handle_t spec = NULL;
for(nIndex = 0; nIndex < nNumKnownIfspecs; ++nIndex)
{
if(!strcasecmp(knownIfspecs[nIndex].pszModule, pszModule))
{
spec = knownIfspecs[nIndex].interface_spec;
break;
}
}
if(!spec)
{
fprintf(stderr, "Module %s is not registered\n", pszModule);
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(!pszServer || !strcasecmp(pszServer, "localhost"))
{
pszProt = PROTOCOL_NCALRPC;
pszEndpoint = PMD_NCALRPC_END_POINT;
}
dwError = PMDAllocateMemory(
sizeof(PMDHANDLE),
(void**)&hHandle);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_client_rpc_binding(
&hHandle->hRpc,
spec,
pszServer,
pszUser,
pszDomain,
pszPass,
pszProt,
pszEndpoint,
pszSpn);
BAIL_ON_PMD_ERROR(dwError);
*phHandle = hHandle;
cleanup:
return dwError;
error:
if(phHandle)
{
*phHandle = NULL;
}
PMDFreeMemory(hHandle);
goto cleanup;
}
uint32_t
rpc_open_privsep(
const char *pszModule,
const char* pszUser,
const char* pszPass,
const char* pszDomain,
PPMDHANDLE* phHandle
)
{
uint32_t dwError = 0;
int nIndex = 0;
PPMDHANDLE hHandle = NULL;
struct stat stStat = {0};
KNOWN_IF_SPEC knownIfspecs[] =
{
#ifdef DEMO_ENABLED
{"demo_privsep", demo_privsep_v1_0_c_ifspec},
#endif
{"privsepd", privsepd_v1_0_c_ifspec},
{"pkg_privsep", pkg_privsep_v1_0_c_ifspec},
{"net_privsep", netmgmt_privsep_v1_0_c_ifspec},
{"fwmgmt_privsep", fwmgmt_privsep_v1_0_c_ifspec},
{"usermgmt_privsep", usermgmt_privsep_v1_0_c_ifspec},
};
int nNumKnownIfspecs =
sizeof(knownIfspecs)/sizeof(knownIfspecs[0]);
rpc_if_handle_t spec = NULL;
if(IsNullOrEmptyString(pszModule) || !phHandle)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(nIndex = 0; nIndex < nNumKnownIfspecs; ++nIndex)
{
if(!strcasecmp(knownIfspecs[nIndex].pszModule, pszModule))
{
spec = knownIfspecs[nIndex].interface_spec;
break;
}
}
if(!spec)
{
fprintf(stderr, "Module %s is not registered\n", pszModule);
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(
sizeof(PMDHANDLE),
(void**)&hHandle);
BAIL_ON_PMD_ERROR(dwError);
hHandle->nPrivSep = 1;
dwError = get_client_rpc_binding(
&hHandle->hRpc,
spec,
pszUser ? "localhost" : NULL,
pszUser,
pszDomain,
pszPass,
PROTOCOL_NCALRPC,
PMD_PRIVSEP_NCALRPC_END_POINT,
NULL);
BAIL_ON_PMD_ERROR(dwError);
//make sure that the privsep server is listening.
rpc_mgmt_is_server_listening(hHandle->hRpc, &dwError);
BAIL_ON_PMD_ERROR(dwError);
//make sure that domain socket file is owned by root
dwError = stat(PMD_PRIVSEP_NCALRPC_END_POINT,
&stStat);
BAIL_ON_PMD_ERROR(dwError);
if(stStat.st_uid != 0 || stStat.st_gid != 0)
{
dwError = ERROR_PMD_PRIVSEP_INTEGRITY;
BAIL_ON_PMD_ERROR(dwError);
}
*phHandle = hHandle;
cleanup:
return dwError;
error:
if(phHandle)
{
*phHandle = NULL;
}
rpc_free_handle(hHandle);
goto cleanup;
}
uint32_t
rpc_open_privsep_internal(
const char *pszModule,
PPMDHANDLE* phHandle
)
{
return rpc_open_privsep(pszModule, NULL, NULL, NULL, phHandle);
}
void
rpc_free_handle(
PPMDHANDLE hPMD
)
{
if(!hPMD)
{
return;
}
if(hPMD->hRpc)
{
PMDRpcFreeBinding(&hPMD->hRpc);
}
PMDFreeMemory(hPMD);
}
|
oliverkurth/pmd
|
include/pmd_pkgmgmt.h
|
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <tdnf/tdnftypes.h>
#include "pmdtypes.h"
uint32_t
pkg_open_handle(
PPMDHANDLE hHandle,
PTDNF_CMD_ARGS pArgs,
PPKGHANDLE *phPkgHandle
);
uint32_t
pkg_close_handle(
PPMDHANDLE hHandle,
PPKGHANDLE hPkgHandle
);
uint32_t
pkg_list(
PPMDHANDLE hHandle,
PPKGHANDLE phPkgHandle,
TDNF_SCOPE nScope,
char **ppszPkgNameSpecs,
PTDNF_PKG_INFO *ppPkgInfo,
uint32_t *pdwCount
);
uint32_t
pkg_count(
PPMDHANDLE hHandle,
PPKGHANDLE phPkgHandle,
uint32_t *pdwCount
);
uint32_t
pkg_repolist(
PPMDHANDLE hHandle,
PPKGHANDLE phPkgHandle,
TDNF_REPOLISTFILTER nRepoListFilter,
PTDNF_REPO_DATA *ppRepoData
);
uint32_t
pkg_updateinfo(
PPMDHANDLE hHandle,
PPKGHANDLE phPkgHandle,
char **ppszPackageNameSpecs,
PTDNF_UPDATEINFO *ppUpdateInfo
);
uint32_t
pkg_updateinfo_summary(
PPMDHANDLE hHandle,
PPKGHANDLE phPkgHandle,
TDNF_AVAIL nAvail,
char **ppszPackageNameSpecs,
PTDNF_UPDATEINFO_SUMMARY *ppSummary
);
uint32_t
pkg_resolve(
PPMDHANDLE hHandle,
PPKGHANDLE phPkgHandle,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO *ppSolvedInfo
);
uint32_t
pkg_alter(
PPMDHANDLE hHandle,
PPKGHANDLE phPkgHandle,
TDNF_ALTERTYPE nAlterType,
PTDNF_SOLVED_PKG_INFO pSolvedInfo
);
uint32_t
pkg_version(
PPMDHANDLE hHandle,
char **ppszVersion
);
uint32_t
pkg_get_error_string(
PPMDHANDLE hHandle,
uint32_t dwErrorCode,
char** ppszError
);
void
pkg_free_repos(
PTDNF_REPO_DATA pRepos
);
void
pkg_free_package_info_array(
PTDNF_PKG_INFO pPkgInfo,
uint32_t dwLength
);
void
pkg_free_package_info_list(
PTDNF_PKG_INFO pPkgInfo
);
void
pkg_free_updateinfo_summary(
PTDNF_UPDATEINFO_SUMMARY pSummary
);
void
pkg_free_solvedinfo(
PTDNF_SOLVED_PKG_INFO pSolvedInfo
);
#ifdef __cplusplus
}
#endif
|
oliverkurth/pmd
|
server/demo/demorestapi.c
|
<gh_stars>1-10
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
REST_MODULE _demo_rest_module[] =
{
{
"/v1/prime/version",
{demo_rest_version_json, NULL, NULL, NULL}
},
{
"/v1/prime/isprime",
{demo_rest_isprime_json, NULL, NULL, NULL}
},
{
"/v1/prime/primes",
{demo_rest_primes_json, NULL, NULL, NULL}
},
{
"/v1/prime/fav",
{
demo_rest_get_fav_json,
demo_rest_set_fav_json,
demo_rest_update_fav_json,
demo_rest_delete_fav_json
}
},
{0}
};
uint32_t
demo_rest_get_registration(
PREST_MODULE *ppRestModule
)
{
uint32_t dwError = 0;
if(!ppRestModule)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
*ppRestModule = _demo_rest_module;
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
demo_open_privsep_rest(
PREST_AUTH pRestAuth,
PPMDHANDLE *phPMD
)
{
uint32_t dwError = 0;
PPMDHANDLE hPMD = NULL;
char *pszUser = NULL;
char *pszPass = NULL;
if(!pRestAuth || !phPMD)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(pRestAuth->nAuthMethod != REST_AUTH_BASIC)
{
dwError = ERROR_INVALID_REST_AUTH;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = base64_get_user_pass(
pRestAuth->pszAuthBase64,
&pszUser,
&pszPass);
BAIL_ON_PMD_ERROR(dwError);
dwError = rpc_open_privsep(
DEMO_PRIVSEP,
pszUser,
pszPass,
NULL,
&hPMD);
BAIL_ON_PMD_ERROR(dwError);
*phPMD = hPMD;
cleanup:
PMD_SAFE_FREE_MEMORY(pszUser);
PMD_SAFE_FREE_MEMORY(pszPass);
return dwError;
error:
rpc_free_handle(hPMD);
goto cleanup;
}
uint32_t
demo_rest_version_json(
void *pInput,
void **ppOutputJson
)
{
uint32_t dwError = 0;
char *pszOutputJson = NULL;
char *pszVersion = NULL;
PPMDHANDLE hPMD = NULL;
PREST_FN_ARGS pArgs = (PREST_FN_ARGS)pInput;
if(!pArgs || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = demo_open_privsep_rest(pArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = demo_version(hPMD, &pszVersion);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringPrintf(&pszOutputJson,
"{\"version\":\"%s\"}",
pszVersion);
BAIL_ON_PMD_ERROR(dwError);
*ppOutputJson = pszOutputJson;
cleanup:
PMD_SAFE_FREE_MEMORY(pszVersion);
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
demo_rest_isprime_json(
void *pInput,
void **ppOutputJson
)
{
uint32_t dwError = 0;
int nIsPrime = 0;
int nPrimeToCheck = 0;
char *pszOutputJson = NULL;
const char *pszPrime = NULL;
json_t *pJsonRoot = NULL;
json_t *pJsonNum = NULL;
PPMDHANDLE hPMD = NULL;
PREST_FN_ARGS pArgs = (PREST_FN_ARGS)pInput;
const char *pszInputJson = pArgs->pszInputJson;
if(!pArgs || IsNullOrEmptyString(pszInputJson) || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = demo_open_privsep_rest(pArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_object_from_string(pszInputJson, &pJsonRoot);
BAIL_ON_PMD_ERROR(dwError);
pJsonNum = json_object_get(pJsonRoot, "num");
if(!pJsonNum)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszPrime = json_string_value(pJsonNum);
if(IsNullOrEmptyString(pszPrime))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
nPrimeToCheck = atoi(pszPrime);
dwError = demo_isprime(hPMD, nPrimeToCheck, &nIsPrime);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringPrintf(&pszOutputJson,
"{\"isprime\":\"%s\"}",
nIsPrime ? "yes" : "no");
BAIL_ON_PMD_ERROR(dwError);
*ppOutputJson = pszOutputJson;
cleanup:
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
demo_rest_primes_json(
void *pInput,
void **ppOutputJson
)
{
uint32_t dwError = 0;
int nCount = 0;
int nStart = 0;
int *pnPrimes = NULL;
int nPrimeCount = 0;
const char *pszStart = NULL;
const char *pszCount = NULL;
json_t *pJsonRoot = NULL;
json_t *pJsonStart = NULL;
json_t *pJsonCount = NULL;
char *pszOutputJson = NULL;
char *pszPrimes = NULL;
PPMDHANDLE hPMD = NULL;
PREST_FN_ARGS pArgs = (PREST_FN_ARGS)pInput;
const char *pszInputJson = pArgs->pszInputJson;
if(!pArgs || IsNullOrEmptyString(pszInputJson) || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = demo_open_privsep_rest(pArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_object_from_string(pszInputJson, &pJsonRoot);
BAIL_ON_PMD_ERROR(dwError);
pJsonStart = json_object_get(pJsonRoot, "start");
if(!pJsonStart)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszStart = json_string_value(pJsonStart);
if(IsNullOrEmptyString(pszStart))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
nStart= atoi(pszStart);
pJsonCount = json_object_get(pJsonRoot, "count");
if(!pJsonCount)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszCount = json_string_value(pJsonCount);
if(IsNullOrEmptyString(pszCount))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
nCount = atoi(pszCount);
dwError = demo_primes(hPMD, nStart, nCount, &pnPrimes, &nPrimeCount);
BAIL_ON_PMD_ERROR(dwError);
if(pnPrimes && nPrimeCount > 0)
{
int nIndex = 0;
int nOffset = 0;
char pszEnd[20];
sprintf(pszEnd, "%d", nStart + nCount);
dwError = PMDAllocateMemory(((strlen(pszEnd) + 1) * (nPrimeCount * 2)),
(void **)&pszPrimes);
BAIL_ON_PMD_ERROR(dwError);
do
{
if(nIndex > 0)
{
sprintf(pszPrimes + nOffset, ",");
nOffset++;
}
sprintf(pszPrimes + nOffset, "%d", pnPrimes[nIndex]);
nIndex++;
nOffset = strlen(pszPrimes);
}while(--nPrimeCount);
}
dwError = PMDAllocateStringPrintf(
&pszOutputJson,
"{\"primes\":[%s]}",
pszPrimes);
BAIL_ON_PMD_ERROR(dwError);
*ppOutputJson = pszOutputJson;
cleanup:
PMD_SAFE_FREE_MEMORY(pszPrimes);
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
demo_rest_get_fav_json(
void *pInputJson,
void **ppOutputJson
)
{
uint32_t dwError = 0;
BAIL_ON_PMD_ERROR(dwError);
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
demo_rest_set_fav_json(
void *pInputJson,
void **ppOutputJson
)
{
uint32_t dwError = 0;
BAIL_ON_PMD_ERROR(dwError);
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
demo_rest_delete_fav_json(
void *pInputJson,
void **ppOutputJson
)
{
uint32_t dwError = 0;
BAIL_ON_PMD_ERROR(dwError);
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
demo_rest_update_fav_json(
void *pInputJson,
void **ppOutputJson
)
{
uint32_t dwError = 0;
BAIL_ON_PMD_ERROR(dwError);
cleanup:
return dwError;
error:
goto cleanup;
}
|
oliverkurth/pmd
|
python/pkgmgmt_package_py.c
|
<reponame>oliverkurth/pmd
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
static char package__doc__[] = "";
static void
package_dealloc(PY_PKG_PACKAGE *self)
{
Py_XDECREF(self->name);
Py_XDECREF(self->version);
Py_XDECREF(self->arch);
Py_XDECREF(self->reponame);
Py_XDECREF(self->summary);
Py_XDECREF(self->description);
Py_XDECREF(self->sizeFormatted);
Py_XDECREF(self->release);
Py_XDECREF(self->license);
Py_XDECREF(self->url);
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
package_new(
PyTypeObject *type,
PyObject *args,
PyObject *kwds)
{
uint32_t dwError = 0;
PPY_PKG_PACKAGE self = NULL;
self = (PPY_PKG_PACKAGE)type->tp_alloc(type, 0);
if (self != NULL)
{
if(!(self->name = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->version = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->arch = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->reponame = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->summary = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->description = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->sizeFormatted = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->release = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->license = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
if(!(self->url = PyBytes_FromString("")))
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
}
cleanup:
return (PyObject *)self;
error:
Py_DECREF(self);
self = NULL;
goto cleanup;
}
static int
package_init(
PY_PKG_PACKAGE *self,
PyObject *args,
PyObject *kwds
)
{
uint32_t dwError = 0;
PyObject *name = NULL;
PyObject *version = NULL;
PyObject *arch = NULL;
PyObject *release = NULL;
PyObject *tmp = NULL;
static char *kwlist[] = {"name", "version", "arch", "release", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "|SSSS", kwlist,
&name, &version, &arch, &release))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (name)
{
tmp = self->name;
Py_INCREF(name);
self->name = name;
Py_XDECREF(tmp);
}
if (version)
{
tmp = self->version;
Py_INCREF(version);
self->version = version;
Py_XDECREF(tmp);
}
if (arch)
{
tmp = self->arch;
Py_INCREF(arch);
self->arch = arch;
Py_XDECREF(tmp);
}
if (release)
{
tmp = self->release;
Py_INCREF(release);
self->release = release;
Py_XDECREF(tmp);
}
cleanup:
return dwError > 0 ? -1 : 0;
error:
fprintf(stderr, "Error = %d\n", dwError);
goto cleanup;
}
uint32_t
py_make_package(
PTDNF_PKG_INFO pPackage,
PyObject **ppPyPackage
)
{
uint32_t dwError = 0;
PPY_PKG_PACKAGE pPyPackage = NULL;
PyTypeObject *retType = &packageType;
if(!pPackage || !ppPyPackage)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pPyPackage = (PPY_PKG_PACKAGE)retType->tp_alloc(retType, 0);
if(!pPyPackage)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
pPyPackage->name = PyBytes_FromString(pPackage->pszName);
pPyPackage->version = PyBytes_FromString(pPackage->pszVersion ?
pPackage->pszVersion : "");
pPyPackage->arch = PyBytes_FromString(pPackage->pszArch ?
pPackage->pszArch : "");
pPyPackage->reponame = PyBytes_FromString(pPackage->pszRepoName ?
pPackage->pszRepoName : "");
pPyPackage->summary = PyBytes_FromString(pPackage->pszSummary ?
pPackage->pszSummary : "");
pPyPackage->description = PyBytes_FromString(pPackage->pszDescription ?
pPackage->pszDescription : "");
pPyPackage->sizeFormatted = PyBytes_FromString(
pPackage->pszFormattedSize ?
pPackage->pszFormattedSize : "");
pPyPackage->release = PyBytes_FromString(pPackage->pszRelease ?
pPackage->pszRelease : "");
pPyPackage->license = PyBytes_FromString(pPackage->pszLicense ?
pPackage->pszLicense : "");
pPyPackage->url = PyBytes_FromString(pPackage->pszURL ?
pPackage->pszURL : "");
pPyPackage->epoch = pPackage->dwEpoch;
pPyPackage->size = pPackage->dwInstallSizeBytes;
*ppPyPackage = (PyObject *)pPyPackage;
cleanup:
return dwError;
error:
if(ppPyPackage)
{
*ppPyPackage = NULL;
}
goto cleanup;
}
static PyGetSetDef package_getset[] = {
{NULL} /* Sentinel */
};
static PyMethodDef package_methods[] = {
{NULL, NULL, 0, NULL} /* Sentinel */
};
static PyMemberDef package_members[] = {
{"name", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, name), 0,
"package name"},
{"version", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, version), 0,
"package version"},
{"arch", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, arch), 0,
"package arch"},
{"reponame", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, reponame), 0,
"package reponame"},
{"summary", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, summary), 0,
"package summary"},
{"description", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, description), 0,
"package description"},
{"sizeFormatted", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, sizeFormatted), 0,
"package size formatted in human readable form"},
{"release", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, release), 0,
"package release"},
{"license", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, license), 0,
"package license"},
{"url", T_OBJECT_EX, offsetof(PY_PKG_PACKAGE, url), 0,
"package url"},
{"epoch", T_INT, offsetof(PY_PKG_PACKAGE, epoch), 0,
"package epoch"},
{"size", T_INT, offsetof(PY_PKG_PACKAGE, size), 0,
"package size in bytes"},
{NULL} /* Sentinel */
};
PyTypeObject packageType = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"pkg.package", /*tp_name*/
sizeof(PY_PKG_PACKAGE), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)package_dealloc,/*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
package__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
package_methods, /* tp_methods */
package_members, /* tp_members */
package_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)package_init, /* tp_init */
0, /* tp_alloc */
package_new, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
|
oliverkurth/pmd
|
idl/usermgmtrpctypes.h
|
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#ifndef __USERMGMT_RPC_TYPES_H__
#define __USERMGMT_RPC_TYPES_H__
#ifdef __cplusplus
extern "C" {
#endif
#if (!defined NO_LIKEWISE && !defined _WIN32)
#include <lw/types.h>
#endif
#ifdef _DCE_IDL_
cpp_quote("#include <usermgmtrpctypes.h>")
cpp_quote("#if 0")
#endif
typedef struct _PMD_RPC_USER_
{
unsigned32 nUID;
unsigned32 nGID;
wstring_t pwszName;
wstring_t pwszRealName;
wstring_t pwszHomeDir;
wstring_t pwszShell;
}PMD_RPC_USER, *PPMD_RPC_USER;
typedef struct _PMD_RPC_USER_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_USER pUsers;
}PMD_RPC_USER_ARRAY, *PPMD_RPC_USER_ARRAY;
typedef struct _PMD_RPC_GROUP_
{
unsigned32 nGID;
wstring_t pwszName;
PPMD_WSTRING_ARRAY pMembers;
}PMD_RPC_GROUP, *PPMD_RPC_GROUP;
typedef struct _PMD_RPC_GROUP_ARRAY_
{
unsigned32 dwCount;
#ifdef _DCE_IDL_
[size_is(dwCount)]
#endif
PPMD_RPC_GROUP pGroups;
}PMD_RPC_GROUP_ARRAY, *PPMD_RPC_GROUP_ARRAY;
#ifdef _DCE_IDL_
cpp_quote("#endif")
#endif
#ifdef __cplusplus
}
#endif
#endif /* __USERMGMT_RPC_TYPES_H__ */
|
oliverkurth/pmd
|
server/restutils/prototypes.h
|
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#pragma once
//openidconnect.c
uint32_t
process_oidc_auth_header(
PREST_REQUEST pRequest,
PJWT_ERROR *ppError
);
uint32_t
get_jwt_parts(
const char *pszAuth,
PJWT_PARTS *ppParts
);
uint32_t
get_jwt(
PJWT_PARTS pParts,
PJWT *ppJWT
);
uint32_t
validate_jwt(
PJWT pJWT,
PJWT_ERROR *ppError
);
uint32_t
make_error(
int nStatus,
PJWT_ERROR *ppError
);
void
free_jwt_header(
PJWT_HEADER pHeader
);
void
free_jwt_claims(
PJWT_CLAIMS pClaims
);
void
free_jwt(
PJWT pJWT
);
void
free_jwt_parts(
PJWT_PARTS pParts
);
void
free_jwt_error(
PJWT_ERROR pError
);
//restapidef.c
uint32_t
load_api_def_from_string(
const char *pszString,
PREST_API_DEF *ppApiDef
);
uint32_t
load_api_def_from_file(
const char *pszFile,
PREST_API_DEF *ppApiDef
);
uint32_t
load_modules(
json_t *pRoot,
PREST_API_MODULE *ppApiModules
);
uint32_t
load_endpoints(
json_t *pRoot,
const char *pszBasePath,
PREST_API_MODULE pApiModules
);
uint32_t
load_parameters(
json_t *pMethod,
PREST_API_PARAM *ppParam
);
uint32_t
module_add_endpoint(
PREST_API_MODULE pModule,
PREST_API_ENDPOINT pEndPoint
);
uint32_t
find_tagged_module(
json_t *pPath,
PREST_API_MODULE pModules,
PREST_API_MODULE *ppModule
);
uint32_t
find_module_by_name(
const char *pszName,
PREST_API_MODULE pModules,
PREST_API_MODULE *ppModule
);
uint32_t
find_endpoint_by_name(
const char *pszName,
PREST_API_ENDPOINT pEndPoints,
PREST_API_ENDPOINT *ppEndPoint
);
uint32_t
find_module_impl_by_name(
const char *pszName,
PREST_MODULE pModules,
PREST_MODULE *ppModule
);
uint32_t
apispec_is_integer(
const char *pszValue,
int *pnValid
);
uint32_t
apispec_check_param(
PREST_API_PARAM pParam,
const char *pszValue,
int *pnValid
);
uint32_t
apispec_get_required_params(
PREST_API_METHOD pMethod,
PREST_API_PARAM **pppRequiredParams,
int *pnRequiredParamsCount
);
uint32_t
apispec_find_handler(
PREST_API_DEF pApiDef,
const char *pszEndPoint,
const char *pszMethod,
PREST_API_METHOD *ppMethod
);
uint32_t
map_rest_type(
const char *pszType,
RESTPARAMTYPE *pnType
);
uint32_t
map_rest_method(
const char *pszMethod,
RESTMETHOD *pnMethod
);
void
print_api_def(
PREST_API_DEF pApiDef
);
uint32_t
map_api_impl(
PREST_API_DEF pApiDef,
PMODULE_REG_MAP pRegMap
);
uint32_t
map_module_impl(
PREST_API_MODULE pModule,
PREST_MODULE pModuleImpl
);
void
free_api_def(
PREST_API_DEF pApiDef
);
//restauth.c
uint32_t
process_auth(
PVMREST_HANDLE pRestHandle,
PREST_REQUEST pRequest,
const char *pszPubKeyFile,
PREST_RESPONSE* ppResponse
);
//restutils.c
uint32_t
rest_register_api_spec(
PVMREST_HANDLE pRestHandle,
PREST_API_DEF pApiDef,
int nUseKerberos,
PREST_PROCESSOR *ppRestProcessor
);
uint32_t
rest_get_keyvalues(
PREST_REQUEST pRequest,
uint32_t dwCount,
PKEYVALUE *ppKeyValue
);
uint32_t
rest_method(
PVMREST_HANDLE pHandle,
PREST_REQUEST pRequest,
PREST_RESPONSE* ppResponse,
uint32_t paramsCount
);
uint32_t
handle_options(
PVMREST_HANDLE pHandle,
PREST_REQUEST pRequest,
PREST_RESPONSE* ppResponse,
uint32_t paramsCount
);
uint32_t
rest_set_privsep_pubkey(
const char *pszPubKeyFile
);
//
uint32_t
pmd_check_password(
const char* user_name,
const char* password,
uint32_t* valid
);
//restnegauth.c
uint32_t
request_negotiate_auth(
PVMREST_HANDLE pRestHandle,
PREST_REQUEST pRequest,
PREST_RESPONSE* ppResponse,
const char* pszToken
);
uint32_t
make_negotiate_string(
gss_buffer_desc *pBuffer,
PSTR *ppszNegotiate
);
uint32_t
verify_krb_auth(
PVMREST_HANDLE pRestHandle,
PREST_REQUEST pRequest,
PREST_RESPONSE* ppResponse
);
//restbasicauth.c
uint32_t
request_basic_auth(
PVMREST_HANDLE pRestHandle,
PREST_REQUEST pRequest,
PREST_RESPONSE* ppResponse
);
uint32_t
verify_basic_auth(
PVMREST_HANDLE pRestHandle,
PREST_REQUEST pRequest,
const char *pszPubKeyFile,
PREST_RESPONSE* ppResponse
);
uint32_t
pre_process_auth(
PREST_AUTH_ARGS pAuthArgs,
PREST_AUTH *ppResult
);
void
free_rest_auth(
PREST_AUTH pResult
);
|
oliverkurth/pmd
|
server/pkgmgmtrestapi.c
|
<reponame>oliverkurth/pmd<gh_stars>1-10
/*
* Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
REST_MODULE _pkg_rest_module[] =
{
{
"/v1/pkg/version",
{pkg_rest_get_version, NULL, NULL, NULL}
},
{
"/v1/pkg/count",
{pkg_rest_get_count, NULL, NULL, NULL}
},
{
"/v1/pkg/repos",
{pkg_rest_get_repolist, NULL, NULL, NULL}
},
{
"/v1/pkg/list",
{pkg_rest_list, NULL, NULL, NULL}
},
{
"/v1/pkg/install",
{NULL, NULL, pkg_rest_install, NULL}
},
{
"/v1/pkg/update",
{NULL, NULL, pkg_rest_update, NULL}
},
{
"/v1/pkg/erase",
{NULL, NULL, pkg_rest_erase, NULL}
},
{
"/v1/pkg/distro_sync",
{NULL, NULL, pkg_rest_distro_sync, NULL}
},
{
"/v1/pkg/downgrade",
{NULL, NULL, pkg_rest_downgrade, NULL}
},
{
"/v1/pkg/reinstall",
{NULL, NULL, pkg_rest_reinstall, NULL}
},
{0}
};
uint32_t
get_repodata_json_string(
PTDNF_REPO_DATA pRepoData,
char **ppszJson
);
uint32_t
get_pkginfo_json_string(
PTDNF_PKG_INFO pPkgInfo,
uint32_t dwCount,
char **ppszJson
);
uint32_t
pkg_json_get_alter_args(
const char *pszAlterCmd,
const char **pszPackages,
int nPkgCount,
PTDNF_CMD_ARGS *ppArgs
);
uint32_t
pkg_json_get_array(
const char *pszInputJson,
const char *pszName,
char ***pppszStrings,
int *pnCount
);
uint32_t
pkg_get_cmd_string(
TDNF_ALTERTYPE nAlterType,
char ** ppszAlterCmd
);
uint32_t
pkg_rest_get_registration(
PREST_MODULE *ppRestModule
)
{
uint32_t dwError = 0;
if(!ppRestModule)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
*ppRestModule = _pkg_rest_module;
cleanup:
return dwError;
error:
goto cleanup;
}
uint32_t
pkg_rest_get_cmd_args(
const char **ppszCmds,
int nCmdCount,
PTDNF_CMD_ARGS *ppArgs
)
{
uint32_t dwError = 0;
int nIndex = 0;
PTDNF_CMD_ARGS pArgs = NULL;
if(!ppszCmds || nCmdCount <= 0 || !ppArgs)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(sizeof(TDNF_CMD_ARGS), (void**)&pArgs);
BAIL_ON_PMD_ERROR(dwError);
pArgs->nAllowErasing = 0;
pArgs->nAssumeNo = 0;
pArgs->nAssumeYes = 0;
pArgs->nBest = 0;
pArgs->nCacheOnly = 0;
pArgs->nDebugSolver = 0;
pArgs->nNoGPGCheck = 0;
pArgs->nRefresh = 0;
pArgs->nRpmVerbosity = 0;
pArgs->nShowDuplicates= 0;
pArgs->nShowHelp = 0;
pArgs->nShowVersion = 0;
pArgs->nVerbose = 0;
pArgs->nIPv4 = 0;
pArgs->nIPv6 = 0;
dwError = PMDAllocateString("/", &pArgs->pszInstallRoot);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateString(PKG_CONFIG_FILE_NAME,
&pArgs->pszConfFile);
BAIL_ON_PMD_ERROR(dwError);
pArgs->nCmdCount = nCmdCount;
dwError = PMDAllocateMemory(sizeof(char **) * nCmdCount,
(void **)&pArgs->ppszCmds);
BAIL_ON_PMD_ERROR(dwError);
for(nIndex = 0; nIndex < nCmdCount; ++nIndex)
{
dwError = PMDAllocateString(ppszCmds[nIndex],
&pArgs->ppszCmds[nIndex]);
BAIL_ON_PMD_ERROR(dwError);
}
*ppArgs = pArgs;
cleanup:
return dwError;
error:
if(ppArgs)
{
*ppArgs = NULL;
}
pkg_free_cmd_args(pArgs);
goto cleanup;
}
uint32_t
pkg_open_privsep_rest(
PREST_AUTH pRestAuth,
PPMDHANDLE *phPMD
)
{
uint32_t dwError = 0;
PPMDHANDLE hPMD = NULL;
char *pszUser = NULL;
char *pszPass = NULL;
if(!pRestAuth || !phPMD)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(pRestAuth->nAuthMethod != REST_AUTH_BASIC)
{
dwError = ERROR_INVALID_REST_AUTH;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = base64_get_user_pass(
pRestAuth->pszAuthBase64,
&pszUser,
&pszPass);
BAIL_ON_PMD_ERROR(dwError);
dwError = rpc_open_privsep(
PKG_PRIVSEP,
pszUser,
pszPass,
NULL,
&hPMD);
BAIL_ON_PMD_ERROR(dwError);
*phPMD = hPMD;
cleanup:
PMD_SAFE_FREE_MEMORY(pszUser);
PMD_SAFE_FREE_MEMORY(pszPass);
return dwError;
error:
rpc_free_handle(hPMD);
goto cleanup;
}
uint32_t
pkg_rest_get_version(
void *pInput,
void **ppOutputJson
)
{
uint32_t dwError = 0;
char *pszVersion = NULL;
char *pszOutputJson = NULL;
PKEYVALUE pKeyValue = NULL;
PPMDHANDLE hPMD = NULL;
PREST_FN_ARGS pArgs = (PREST_FN_ARGS)pInput;
if(!pArgs || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_open_privsep_rest(pArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = make_keyvalue("version", NULL, &pKeyValue);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_version(hPMD, &pKeyValue->pszValue);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_string(pKeyValue, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppOutputJson = pszOutputJson;
cleanup:
if(pKeyValue)
{
free_keyvalue(pKeyValue);
}
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
pkg_rest_get_count(
void *pInput,
void **ppOutputJson
)
{
uint32_t dwError = 0;
uint32_t dwCount = 0;
char *pszOutputJson = NULL;
PKEYVALUE pKeyValue = NULL;
PTDNF_CMD_ARGS pArgs = NULL;
const char *ppszCmds[] = {"count"};
PPMDHANDLE hPMD = NULL;
PREST_FN_ARGS pRestArgs = (PREST_FN_ARGS)pInput;
PPKGHANDLE hPkgHandle = NULL;
if(!pRestArgs || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_open_privsep_rest(pRestArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_rest_get_cmd_args(ppszCmds, 1, &pArgs);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_open_handle(hPMD, pArgs, &hPkgHandle);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_count(hPMD, hPkgHandle, &dwCount);
BAIL_ON_PMD_ERROR(dwError);
dwError = make_keyvalue("count", NULL, &pKeyValue);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateStringPrintf(&pKeyValue->pszValue, "%d", dwCount);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_json_string(pKeyValue, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppOutputJson = pszOutputJson;
cleanup:
if(pKeyValue)
{
free_keyvalue(pKeyValue);
}
pkg_free_cmd_args(pArgs);
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
pkg_rest_get_repolist(
void *pInput,
void **ppOutputJson
)
{
uint32_t dwError = 0;
uint32_t dwCount = 0;
char *pszOutputJson = NULL;
PTDNF_CMD_ARGS pArgs = NULL;
PTDNF_REPO_DATA pRepoData = NULL;
const char *ppszCmds[] = {"repolist"};
PPMDHANDLE hPMD = NULL;
PREST_FN_ARGS pRestArgs = (PREST_FN_ARGS)pInput;
PPKGHANDLE hPkgHandle = NULL;
if(!pRestArgs || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_open_privsep_rest(pRestArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_rest_get_cmd_args(ppszCmds, 1, &pArgs);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_open_handle(hPMD, pArgs, &hPkgHandle);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_repolist(hPMD, hPkgHandle, REPOLISTFILTER_ALL, &pRepoData);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_repodata_json_string(pRepoData, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppOutputJson = pszOutputJson;
cleanup:
pkg_free_cmd_args(pArgs);
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
pkg_rest_list(
void *pInput,
void **ppOutputJson
)
{
uint32_t dwError = 0;
uint32_t dwCount = 0;
PTDNF_CMD_ARGS pArgs = NULL;
PTDNF_PKG_INFO pPkgInfo = NULL;
TDNF_SCOPE nScope = SCOPE_ALL;
json_t *pJson = NULL;
char *pszScope = NULL;
char *pszPkgNameSpecs[] = {NULL};
char *pszOutputJson = NULL;
const char *ppszCmds[] = {"list"};
PPMDHANDLE hPMD = NULL;
PREST_FN_ARGS pRestArgs = (PREST_FN_ARGS)pInput;
const char *pszInputJson = NULL;
PPKGHANDLE hPkgHandle = NULL;
if(!pRestArgs || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszInputJson = pRestArgs->pszInputJson;
if(pszInputJson)
{
dwError = get_json_object_from_string(pszInputJson, &pJson);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, "filter", &pszScope);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_get_scope_from_string(pszScope, &nScope);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_open_privsep_rest(pRestArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_rest_get_cmd_args(ppszCmds, 1, &pArgs);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_open_handle(hPMD, pArgs, &hPkgHandle);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_list(hPMD,
hPkgHandle,
nScope,
pszPkgNameSpecs,
&pPkgInfo,
&dwCount);
BAIL_ON_PMD_ERROR(dwError);
dwError = get_pkginfo_json_string(pPkgInfo, dwCount, &pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
*ppOutputJson = pszOutputJson;
cleanup:
pkg_free_package_info_array(pPkgInfo, dwCount);
pkg_free_cmd_args(pArgs);
PMD_SAFE_FREE_MEMORY(pszScope);
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
make_processed_pkgs_result(
const char *pszAlterCmd,
char **ppszPackages,
int nPkgCount,
char **ppszOutputJson
)
{
uint32_t dwError = 0;
json_t *pRoot = NULL;
json_t *pRequestArray = NULL;
char *pszOutputJson = NULL;
char *pszOutputKey = NULL;
int i = 0;
if(IsNullOrEmptyString(pszAlterCmd) ||
!ppszPackages ||
!nPkgCount ||
!ppszOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pRoot = json_object();
if(!pRoot)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
pRequestArray = json_array();
if(!pRequestArray)
{
dwError = ERROR_PMD_OUT_OF_MEMORY;
BAIL_ON_PMD_ERROR(dwError);
}
for(i = 0; i < nPkgCount; ++i)
{
json_array_append_new(pRequestArray, json_string(ppszPackages[i]));
}
dwError = PMDAllocateStringPrintf(&pszOutputKey, "%srequest", pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
json_object_set_new(pRoot, pszOutputKey, pRequestArray);
pszOutputJson = json_dumps(pRoot, 0);
*ppszOutputJson = pszOutputJson;
cleanup:
PMD_SAFE_FREE_MEMORY(pszOutputKey);
return dwError;
error:
if(ppszOutputJson)
{
*ppszOutputJson = NULL;
}
goto cleanup;
}
uint32_t
pkg_rest_alter(
TDNF_ALTERTYPE nAlterType,
PREST_FN_ARGS pRestArgs,
void **ppOutputJson
)
{
uint32_t dwError = 0;
char *pszOutputJson = NULL;
char *pszAlterCmd = NULL;
char **ppszPackages = NULL;
PTDNF_CMD_ARGS pArgs = NULL;
int nPkgCount = 0;
int i = 0;
const char *pszInputJson = NULL;
PPMDHANDLE hPMD = NULL;
PPKGHANDLE hPkgHandle = NULL;
int nNothingToDo = 0;
if(!pRestArgs || !ppOutputJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszInputJson = pRestArgs->pszInputJson;
if(nAlterType == ALTER_INSTALL ||
nAlterType == ALTER_ERASE ||
nAlterType == ALTER_REINSTALL)
{
if(IsNullOrEmptyString(pszInputJson))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
}
if(pszInputJson)
{
dwError = pkg_json_get_array(pszInputJson,
"packages",
&ppszPackages,
&nPkgCount);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_get_cmd_string(nAlterType, &pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_json_get_alter_args(pszAlterCmd,
(const char **)ppszPackages,
nPkgCount,
&pArgs);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_open_privsep_rest(pRestArgs->pAuthArgs->pRestAuth, &hPMD);
BAIL_ON_PMD_ERROR(dwError);
dwError = pkg_open_handle(hPMD, pArgs, &hPkgHandle);
BAIL_ON_PMD_ERROR(dwError);
//server will call resolve and alter - hence null for solvedinfo
dwError = pkg_alter(hPMD, hPkgHandle, nAlterType, NULL);
if(dwError == ERROR_PMD_FAIL)
{
dwError = 0;
nNothingToDo = 1;
}
BAIL_ON_PMD_ERROR(dwError);
if(nNothingToDo)
{
dwError = json_string_from_key_value(
"result",
"Nothing to do.",
&pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
}
else
{
dwError = make_processed_pkgs_result(
pszAlterCmd,
ppszPackages,
nPkgCount,
&pszOutputJson);
BAIL_ON_PMD_ERROR(dwError);
}
*ppOutputJson = pszOutputJson;
cleanup:
if(ppszPackages)
{
PMDFreeStringArrayWithCount(ppszPackages, nPkgCount);
}
pkg_free_cmd_args(pArgs);
PMD_SAFE_FREE_MEMORY(pszAlterCmd);
rpc_free_handle(hPMD);
return dwError;
error:
if(ppOutputJson)
{
*ppOutputJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutputJson);
goto cleanup;
}
uint32_t
pkg_rest_install(
void *pInput,
void **ppOutputJson
)
{
return pkg_rest_alter(ALTER_INSTALL, pInput, ppOutputJson);
}
uint32_t
pkg_rest_update(
void *pInput,
void **ppOutputJson
)
{
return pkg_rest_alter(ALTER_UPGRADE, pInput, ppOutputJson);
}
uint32_t
pkg_rest_erase(
void *pInput,
void **ppOutputJson
)
{
return pkg_rest_alter(ALTER_ERASE, pInput, ppOutputJson);
}
uint32_t
pkg_rest_distro_sync(
void *pInput,
void **ppOutputJson
)
{
return pkg_rest_alter(ALTER_DISTRO_SYNC, pInput, ppOutputJson);
}
uint32_t
pkg_rest_downgrade(
void *pInput,
void **ppOutputJson
)
{
return pkg_rest_alter(ALTER_DOWNGRADE, pInput, ppOutputJson);
}
uint32_t
pkg_rest_reinstall(
void *pInput,
void **ppOutputJson
)
{
return pkg_rest_alter(ALTER_REINSTALL, pInput, ppOutputJson);
}
uint32_t
get_repodata_json_string(
PTDNF_REPO_DATA pRepoData,
char **ppszJson
)
{
uint32_t dwError = 0;
char *pszJson = NULL;
json_t *pRoot = NULL;
if(!pRepoData || !ppszJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pRoot = json_array();
if(!pRoot)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(; pRepoData; pRepoData = pRepoData->pNext)
{
json_t *pRepoObj = json_object();
json_object_set_new(pRepoObj, "id", json_string(pRepoData->pszId));
json_object_set_new(pRepoObj, "name", json_string(pRepoData->pszName));
json_object_set_new(pRepoObj, "baseurl", json_string(pRepoData->pszBaseUrl));
json_object_set_new(pRepoObj, "gpgkey", json_string(pRepoData->pszUrlGPGKey));
json_object_set_new(pRepoObj, "metadata_expire", json_integer(0));
json_object_set_new(pRepoObj, "skip_if_unavailable", json_boolean(pRepoData->nSkipIfUnavailable));
json_object_set_new(pRepoObj, "enabled", json_boolean(pRepoData->nEnabled));
json_object_set_new(pRepoObj, "gpgcheck", json_boolean(pRepoData->nGPGCheck));
json_array_append_new(pRoot, pRepoObj);
}
pszJson = json_dumps(pRoot, 0);
*ppszJson = pszJson;
cleanup:
if(pRoot)
{
json_decref(pRoot);
}
return dwError;
error:
if(ppszJson)
{
*ppszJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszJson);
goto cleanup;
}
uint32_t
get_pkginfo_json_string(
PTDNF_PKG_INFO pPkgInfo,
uint32_t dwCount,
char **ppszJson
)
{
uint32_t dwError = 0;
char *pszJson = NULL;
json_t *pRoot = NULL;
uint32_t nIndex = 0;
if(!pPkgInfo || dwCount == 0 || !ppszJson)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pRoot = json_array();
if(!pRoot)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
for(nIndex = 0; nIndex < dwCount; ++nIndex, ++pPkgInfo)
{
PTDNF_PKG_INFO pInfo = pPkgInfo;
json_t *pInfoObj = json_object();
json_object_set_new(pInfoObj, "name", json_string(pInfo->pszName));
json_object_set_new(pInfoObj, "arch", json_string(pInfo->pszArch));
json_object_set_new(pInfoObj, "epoch", json_integer(pInfo->dwEpoch));
json_object_set_new(pInfoObj, "version", json_string(pInfo->pszVersion));
json_object_set_new(pInfoObj, "release", json_string(pInfo->pszRelease));
json_object_set_new(pInfoObj, "install_size", json_string(pInfo->pszFormattedSize));
json_object_set_new(pInfoObj, "reponame", json_string(pInfo->pszRepoName));
json_object_set_new(pInfoObj, "summary", json_string(pInfo->pszSummary));
json_object_set_new(pInfoObj, "url", json_string(pInfo->pszURL));
json_object_set_new(pInfoObj, "license", json_string(pInfo->pszLicense));
json_object_set_new(pInfoObj, "description", json_string(pInfo->pszDescription));
json_array_append_new(pRoot, pInfoObj);
}
pszJson = json_dumps(pRoot, 0);
*ppszJson = pszJson;
cleanup:
if(pRoot)
{
json_decref(pRoot);
}
return dwError;
error:
if(ppszJson)
{
*ppszJson = NULL;
}
PMD_SAFE_FREE_MEMORY(pszJson);
goto cleanup;
}
uint32_t
pkg_json_get_alter_args(
const char *pszAlterCmd,
const char **ppszPackages,
int nPkgCount,
PTDNF_CMD_ARGS *ppArgs
)
{
uint32_t dwError = 0;
PTDNF_CMD_ARGS pArgs = NULL;
char **ppszCmds = NULL;
int i = 0;
int nCmdCount = 0;
if(IsNullOrEmptyString(pszAlterCmd) || !ppArgs)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
//For commands that does not require args, nPkgCount will be 0.
nCmdCount = nPkgCount + 1;
dwError = PMDAllocateMemory(sizeof(char **) * (nCmdCount),
(void **)&ppszCmds);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateString(pszAlterCmd, &ppszCmds[0]);
BAIL_ON_PMD_ERROR(dwError);
for(i = 1; i < nCmdCount; ++i)
{
dwError = PMDAllocateString(ppszPackages[i-1], &ppszCmds[i]);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = pkg_rest_get_cmd_args((const char **)ppszCmds,
nCmdCount,
&pArgs);
BAIL_ON_PMD_ERROR(dwError);
*ppArgs = pArgs;
cleanup:
if(ppszCmds)
{
PMDFreeStringArrayWithCount(ppszCmds, nPkgCount + 1);
}
return dwError;
error:
if(ppArgs)
{
*ppArgs = NULL;
}
goto cleanup;
}
uint32_t
pkg_json_get_array(
const char *pszInputJson,
const char *pszName,
char ***pppszStrings,
int *pnCount
)
{
uint32_t dwError = 0;
char *pszStrings = NULL;
char *pszCommaSeparatedStrings = NULL;
char **ppszStrings = NULL;
int nCount = 0;
json_t *pJson = NULL;
char *pszPkgs = NULL;
if(IsNullOrEmptyString(pszInputJson) ||
IsNullOrEmptyString(pszName) ||
!pppszStrings ||
!pnCount)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = get_json_object_from_string(pszInputJson, &pJson);
BAIL_ON_PMD_ERROR(dwError);
dwError = json_get_string_value(pJson, pszName, &pszStrings);
BAIL_ON_PMD_ERROR(dwError);
dwError = string_replace(pszStrings,
REST_COMMA,
",",
&pszCommaSeparatedStrings);
if(dwError == ENOENT)
{
dwError = PMDAllocateString(pszStrings, &pszCommaSeparatedStrings);
BAIL_ON_PMD_ERROR(dwError);
}
dwError = make_array_from_string(pszCommaSeparatedStrings,
",",
&ppszStrings,
&nCount);
BAIL_ON_PMD_ERROR(dwError);
*pppszStrings = ppszStrings;
*pnCount = nCount;
cleanup:
PMD_SAFE_FREE_MEMORY(pszStrings);
PMD_SAFE_FREE_MEMORY(pszCommaSeparatedStrings);
return dwError;
error:
if(pppszStrings)
{
*pppszStrings = NULL;
}
if(pnCount)
{
*pnCount = 0;
}
goto cleanup;
}
uint32_t
pkg_get_cmd_string(
TDNF_ALTERTYPE nAlterType,
char ** ppszAlterCmd
)
{
uint32_t dwError = 0;
char *pszAlterCmd = NULL;
if(nAlterType == ALTER_INSTALL)
{
dwError = PMDAllocateString("install", &pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
}
else if(nAlterType == ALTER_UPGRADE)
{
dwError = PMDAllocateString("update", &pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
}
else if(nAlterType == ALTER_ERASE)
{
dwError = PMDAllocateString("erase", &pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
}
else if(nAlterType == ALTER_DOWNGRADE)
{
dwError = PMDAllocateString("downgrade", &pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
}
else if(nAlterType == ALTER_REINSTALL)
{
dwError = PMDAllocateString("reinstall", &pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
}
else if(nAlterType == ALTER_DISTRO_SYNC)
{
dwError = PMDAllocateString("distro-sync", &pszAlterCmd);
BAIL_ON_PMD_ERROR(dwError);
}
else
{
nAlterType = ERROR_PMD_NO_DATA;
BAIL_ON_PMD_ERROR(dwError);
}
*ppszAlterCmd = pszAlterCmd;
cleanup:
return dwError;
error:
if(ppszAlterCmd)
{
*ppszAlterCmd = NULL;
}
goto cleanup;
}
|
oliverkurth/pmd
|
common/utils.c
|
<reponame>oliverkurth/pmd
/*
* Copyright © 2016-2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
uint32_t
dup_argv(
int argc,
char* const* argv,
char*** argvDup
)
{
uint32_t dwError = 0;
int i = 0;
char** dup = NULL;
if(!argv || !argvDup)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(sizeof(char*) * argc, (void**)&dup);
BAIL_ON_PMD_ERROR(dwError);
for(i = 0; i < argc; ++i)
{
dup[i] = strdup(argv[i]);
}
*argvDup = dup;
cleanup:
return dwError;
error:
if(argvDup)
{
*argvDup = NULL;
}
goto cleanup;
}
uint32_t
PMDUtilsFormatSize(
uint32_t unSize,
char** ppszFormattedSize
)
{
uint32_t dwError = 0;
char* pszFormattedSize = NULL;
char* pszSizes = "bkMG";
double dSize = unSize;
int nIndex = 0;
int nLimit = strlen(pszSizes);
double dKiloBytes = 1024.0;
int nMaxSize = 25;
if(!ppszFormattedSize)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
while(nIndex < nLimit && dSize > dKiloBytes)
{
dSize /= dKiloBytes;
nIndex++;
}
dwError = PMDAllocateMemory(nMaxSize, (void**)&pszFormattedSize);
BAIL_ON_PMD_ERROR(dwError);
if(sprintf(pszFormattedSize, "%.2f %c", dSize, pszSizes[nIndex]) < 0)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
*ppszFormattedSize = pszFormattedSize;
cleanup:
return dwError;
error:
if(ppszFormattedSize)
{
*ppszFormattedSize = NULL;
}
PMD_SAFE_FREE_MEMORY(pszFormattedSize);
goto cleanup;
}
uint32_t
file_read_all_text(
const char *pszFileName,
char **ppszText
)
{
uint32_t dwError = 0;
FILE *fp = NULL;
char *pszText = NULL;
int nLength = 0;
int nBytesRead = 0;
if(!pszFileName || !ppszText)
{
dwError = EINVAL;
BAIL_ON_PMD_ERROR(dwError);
}
fp = fopen(pszFileName, "r");
if(!fp)
{
dwError = ENOENT;
BAIL_ON_PMD_SYSTEM_ERROR(dwError);
}
fseek(fp, 0, SEEK_END);
nLength = ftell(fp);
dwError = PMDAllocateMemory(nLength + 1, (void **)&pszText);
BAIL_ON_PMD_ERROR(dwError);
if(fseek(fp, 0, SEEK_SET))
{
dwError = errno;
BAIL_ON_PMD_ERROR(dwError);
}
nBytesRead = fread(pszText, 1, nLength, fp);
if(nBytesRead != nLength)
{
dwError = EBADFD;
BAIL_ON_PMD_ERROR(dwError);
}
*ppszText = pszText;
cleanup:
if(fp)
{
fclose(fp);
}
return dwError;
error:
if(ppszText)
{
*ppszText = NULL;
}
PMD_SAFE_FREE_MEMORY(pszText);
goto cleanup;
}
const char *
ltrim(
const char *pszStr
)
{
if(!pszStr) return NULL;
while(isspace(*pszStr)) ++pszStr;
return pszStr;
}
const char *
rtrim(
const char *pszStart,
const char *pszEnd
)
{
if(!pszStart || !pszEnd) return NULL;
while(pszEnd > pszStart && isspace(*pszEnd)) pszEnd--;
return pszEnd;
}
uint32_t
do_rtrim(
const char *pszString,
char **ppszTrimmedString
)
{
uint32_t dwError = 0;
char *pszTrimmedString = NULL;
const char *pszEnd = NULL;
int nLength = 0;
if(IsNullOrEmptyString(pszString) || !ppszTrimmedString)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszEnd = rtrim(pszString, pszString + (strlen(pszString)));
nLength = pszEnd - pszString;
if(nLength < 0)
{
dwError = EINVAL;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateMemory(nLength + 1, (void **)&pszTrimmedString);
BAIL_ON_PMD_ERROR(dwError);
strncpy(pszTrimmedString, pszString, nLength);
*ppszTrimmedString = pszTrimmedString;
cleanup:
return dwError;
error:
if(ppszTrimmedString)
{
*ppszTrimmedString = NULL;
}
PMD_SAFE_FREE_MEMORY(pszTrimmedString);
goto cleanup;
}
uint32_t
count_matches(
const char *pszString,
const char *pszFind,
int *pnCount
)
{
uint32_t dwError = 0;
int nCount = 0;
int nOffset = 0;
int nFindLength = 0;
char *pszMatch = NULL;
if(IsNullOrEmptyString(pszString) ||
IsNullOrEmptyString(pszFind) ||
!pnCount)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
nFindLength = strlen(pszFind);
while((pszMatch = strcasestr(pszString + nOffset, pszFind)))
{
++nCount;
nOffset = pszMatch - pszString + nFindLength;
}
*pnCount = nCount;
cleanup:
return dwError;
error:
if(pnCount)
{
*pnCount = 0;
}
goto cleanup;
}
uint32_t
string_replace(
const char *pszString,
const char *pszFind,
const char *pszReplace,
char **ppszResult
)
{
uint32_t dwError = 0;
char *pszResult = NULL;
char *pszBoundary = NULL;
int nCount = 0;
int nResultLength = 0;
int nFindLength = 0;
int nReplaceLength = 0;
int nOffset = 0;
if(IsNullOrEmptyString(pszString) ||
IsNullOrEmptyString(pszFind) ||
!ppszResult)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = count_matches(pszString, pszFind, &nCount);
BAIL_ON_PMD_ERROR(dwError);
if(nCount == 0)
{
dwError = ENOENT;
BAIL_ON_PMD_ERROR(dwError);
}
nFindLength = strlen(pszFind);
if(pszReplace)
{
nReplaceLength = strlen(pszReplace);
}
nResultLength = strlen(pszString) +
nCount * (nReplaceLength - nFindLength);
dwError = PMDAllocateMemory(sizeof(char) * (nResultLength + 1),
(void **)&pszResult);
BAIL_ON_PMD_ERROR(dwError);
nOffset = 0;
while((pszBoundary = strcasestr(pszString + nOffset, pszFind)))
{
int nLength = pszBoundary - (pszString + nOffset);
strncat(pszResult, pszBoundary - nLength, nLength);
if(pszReplace)
{
strcat(pszResult, pszReplace);
}
nOffset = pszBoundary - pszString + nFindLength;
}
strcat(pszResult, pszString + nOffset);
*ppszResult = pszResult;
cleanup:
return dwError;
error:
if(ppszResult)
{
*ppszResult = NULL;
}
PMD_SAFE_FREE_MEMORY(pszResult);
goto cleanup;
}
uint32_t
make_array_from_string(
const char *pszString,
const char *pszSeparator,
char ***pppszArray,
int *pnCount
)
{
uint32_t dwError = 0;
char **ppszArray = NULL;
char *pszBoundary = NULL;
int nOffset = 0;
int nSepLength = 0;
int nCount = 1;
int nIndex = 0;
if(IsNullOrEmptyString(pszString) ||
IsNullOrEmptyString(pszSeparator) ||
!pppszArray ||
!pnCount)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = count_matches(pszString, pszSeparator, &nCount);
BAIL_ON_PMD_ERROR(dwError);
++nCount;
dwError = PMDAllocateMemory(sizeof(char **) * (nCount),
(void **)&ppszArray);
BAIL_ON_PMD_ERROR(dwError);
nOffset = 0;
nIndex = 0;
nSepLength = strlen(pszSeparator);
while((pszBoundary = strcasestr(pszString + nOffset, pszSeparator)))
{
int nLength = pszBoundary - (pszString + nOffset);
dwError = PMDAllocateMemory(sizeof(char) * (nLength + 1),
(void **)&ppszArray[nIndex]);
BAIL_ON_PMD_ERROR(dwError);
memcpy(ppszArray[nIndex], pszString + nOffset, nLength);
nOffset = pszBoundary - pszString + nSepLength;
++nIndex;
}
dwError = PMDAllocateString(pszString + nOffset, &ppszArray[nIndex]);
BAIL_ON_PMD_ERROR(dwError);
*pppszArray = ppszArray;
*pnCount = nCount;
cleanup:
return dwError;
error:
if(pppszArray)
{
*pppszArray = NULL;
}
if(pnCount)
{
*pnCount = 0;
}
PMDFreeStringArrayWithCount(ppszArray, nCount);
goto cleanup;
}
uint32_t
read_password_no_echo(
char **ppszPassword
)
{
uint32_t dwError = 0;
char pszPasswordBuff[100] = {0};
char *pszPassword = NULL;
struct termios tp = {0};
struct termios save = {0};
int nLength = 0;
if(!ppszPassword)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
fflush(stdout);
tcgetattr(0, &tp) ;
memcpy (&save, &tp, sizeof (struct termios));
save.c_lflag &= ~ECHO; /* ECHO off, other bits unchanged */
tcsetattr(0, TCSANOW, &save);
if (!fgets(pszPasswordBuff, 100, stdin) && ferror(stdin))
{
dwError = ferror(stdin);
BAIL_ON_PMD_ERROR (dwError);
}
nLength = strlen(pszPasswordBuff);
if(nLength <= 0)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if (pszPasswordBuff[nLength - 1] == '\n')
{
pszPasswordBuff[nLength - 1] = '\0';
}
dwError = PMDAllocateString(pszPasswordBuff, &pszPassword);
BAIL_ON_PMD_ERROR (dwError);
*ppszPassword = <PASSWORD>;
cleanup:
tcsetattr(0, TCSANOW, &tp);
fflush (stdin);
return dwError;
error:
if (ppszPassword)
{
*ppszPassword = NULL;
}
PMD_SAFE_FREE_MEMORY(pszPassword);
goto cleanup;
}
uint32_t
validate_cmd(
const char *pszCmd
)
{
uint32_t dwError = 0;
if(IsNullOrEmptyString(pszCmd))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(strpbrk(pszCmd, INVALID_CMD_CHARS))
{
dwError = ERROR_PMD_INVALID_CMD;
BAIL_ON_PMD_ERROR(dwError);
}
error:
return dwError;
}
uint32_t
get_word(
const char *pszInput,
int *pnStart,
int *pnLength
)
{
uint32_t dwError = 0;
int nStart = 0;
int nLength = 0;
const char *pszCurrent = pszInput;
if(IsNullOrEmptyString(pszInput) || !pnStart || !pnLength)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
while(*pszCurrent && isspace(*pszCurrent))
{
++pszCurrent;
}
nStart = pszCurrent - pszInput;
while(*pszCurrent && !isspace(*pszCurrent))
{
++nLength;
++pszCurrent;
}
if(!nLength)
{
dwError = ERROR_PMD_NO_DATA;
BAIL_ON_PMD_ERROR(dwError);
}
*pnStart = nStart;
*pnLength = nLength;
cleanup:
return dwError;
error:
if(pnStart)
{
*pnStart = -1;
}
if(pnLength)
{
*pnLength = -1;
}
goto cleanup;
}
uint32_t
count_argv(
const char *pszInput,
int *pnCount
)
{
uint32_t dwError = 0;
int nCount = 0;
int nStart = 0;
int nLength = 0;
const char *pszCurrent = pszInput;
if(IsNullOrEmptyString(pszInput) || !pnCount)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
while(!get_word(pszCurrent, &nStart, &nLength))
{
pszCurrent += (nStart + nLength);
nCount++;
}
*pnCount = nCount;
error:
return dwError;
}
uint32_t
make_argv(
const char *pszCmd,
char ***pargv
)
{
uint32_t dwError = 0;
char **argv = NULL;
int nCount = 0;
int nStart = 0;
int nLength = 0;
int i = 0;
if(IsNullOrEmptyString(pszCmd) || !pargv)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = count_argv(pszCmd, &nCount);
BAIL_ON_PMD_ERROR(dwError);
dwError = PMDAllocateMemory(sizeof(char *) * (nCount + 1), (void **)&argv);
BAIL_ON_PMD_ERROR(dwError);
while(i < nCount && !get_word(pszCmd, &nStart, &nLength))
{
dwError = PMDAllocateMemory(sizeof(char) * (nLength + 1),
(void **)&argv[i]);
strncpy(argv[i], pszCmd+nStart, nLength);
pszCmd += (nStart + nLength);
i++;
}
*pargv = argv;
cleanup:
return dwError;
error:
if(pargv)
{
*pargv = NULL;
}
PMDFreeStringArray(argv);
goto cleanup;
}
uint32_t
exec_cmd(
const char *pszCmd
)
{
uint32_t dwError = 0;
pid_t pidChild = -1;
int ret = 0;
int nStatus = 0;
char **argv = NULL;
char *env[] = { NULL };
if(IsNullOrEmptyString(pszCmd))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = make_argv(pszCmd, &argv);
BAIL_ON_PMD_ERROR(dwError);
pidChild = fork();
if (pidChild == -1)
{
dwError = errno;
BAIL_ON_PMD_SYSTEM_ERROR(dwError);
}
if (pidChild != 0)
{
while ((ret = waitpid(pidChild, &nStatus, 0)) == -1)
{
if (errno != EINTR)
{
dwError = errno;
BAIL_ON_PMD_SYSTEM_ERROR(dwError);
}
}
if(WIFEXITED(nStatus))
{
dwError = WEXITSTATUS(nStatus);
BAIL_ON_PMD_SYSTEM_ERROR(dwError);
}
}
else //child
{
if (execve(argv[0], argv, env) == -1)
{
exit(127);
}
}
cleanup:
PMDFreeStringArray(argv);
return dwError;
error:
fprintf(stderr, "Error %d\n", dwError);
goto cleanup;
}
uint32_t
run_cmd(
const char *pszCmd,
const char *pszCmdToLog
)
{
uint32_t dwError = 0;
if(IsNullOrEmptyString(pszCmd) || IsNullOrEmptyString(pszCmdToLog))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = validate_cmd(pszCmd);
BAIL_ON_PMD_ERROR(dwError);
fprintf(stdout, "Executing command: %s\n", pszCmdToLog);
dwError = exec_cmd(pszCmd);
BAIL_ON_PMD_ERROR(dwError);
cleanup:
return dwError;
error:
if(!IsNullOrEmptyString(pszCmdToLog))
{
fprintf(stderr, "There was an error executing: %s", pszCmdToLog);
}
goto cleanup;
}
uint32_t
run_cmd_pipe_in(
const char *pszCmd,
const char *pszCmdToLog,
FILE *fpIn
)
{
uint32_t dwError = 0;
FILE *fpOut = NULL;
char pszLine[MAX_LINE_LENGTH] = {0};
if(IsNullOrEmptyString(pszCmd) || IsNullOrEmptyString(pszCmdToLog) || !fpIn)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = validate_cmd(pszCmd);
BAIL_ON_PMD_ERROR(dwError);
fprintf(stdout, "Executing command: %s\n", pszCmdToLog);
if(!(fpOut = popen(pszCmd, "w")))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = fseek(fpIn, SEEK_SET, 0);
BAIL_ON_PMD_ERROR(dwError);
while(fgets(pszLine, MAX_LINE_LENGTH, fpIn))
{
fputs(pszLine, fpOut);
}
cleanup:
if(fpOut)
{
pclose(fpOut);
}
return dwError;
error:
if(!IsNullOrEmptyString(pszCmdToLog))
{
fprintf(stderr, "There was an error executing: %s", pszCmdToLog);
}
goto cleanup;
}
uint32_t
url_decode(
const char *pszInput,
char **ppszOutput
)
{
uint32_t dwError = 0;
char *pszOutput = NULL;
char *pszCurlOut = NULL;
CURL *pCurl = NULL;
int nOutLen = 0;
if(IsNullOrEmptyString(pszInput) || !ppszOutput)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pCurl = curl_easy_init();
if(!pCurl)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszCurlOut = curl_easy_unescape(pCurl, pszInput, strlen(pszInput), &nOutLen);
if(IsNullOrEmptyString(pszCurlOut))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = PMDAllocateString(pszCurlOut, &pszOutput);
BAIL_ON_PMD_ERROR(dwError);
*ppszOutput = pszOutput;
cleanup:
if(pszCurlOut)
{
curl_free(pszCurlOut);
}
if(pCurl)
{
curl_easy_cleanup(pCurl);
}
return dwError;
error:
if(ppszOutput)
{
*ppszOutput = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutput);
goto cleanup;
}
uint32_t
PMDGetErrorString(
uint32_t dwErrorCode,
char** ppszError
)
{
uint32_t dwError = 0;
char* pszError = NULL;
char* pszSystemError = NULL;
int i = 0;
int nCount = 0;
uint32_t dwActualError = 0;
//Allow mapped error strings to override
PMD_ERROR_DESC arErrorDesc[] = PMD_ERROR_TABLE;
nCount = sizeof(arErrorDesc)/sizeof(arErrorDesc[0]);
for(i = 0; i < nCount; i++)
{
if (dwErrorCode == arErrorDesc[i].nCode)
{
dwError = PMDAllocateString(arErrorDesc[i].pszDesc, &pszError);
BAIL_ON_PMD_ERROR(dwError);
break;
}
}
//Get system error
if(!pszError && PMDIsDceRpcError(dwErrorCode))
{
dwError = PMDGetDceRpcErrorString(dwErrorCode, &pszError);
BAIL_ON_PMD_ERROR(dwError);
}
else if(!pszError && PMDIsSystemError(dwErrorCode))
{
dwError = PMDGetSystemErrorString(dwErrorCode, &pszError);
BAIL_ON_PMD_ERROR(dwError);
}
//If the above attempts did not yield an error string,
//do default unknown error.
if(!pszError)
{
dwError = PMDAllocateString(PMD_UNKNOWN_ERROR_STRING, &pszError);
BAIL_ON_PMD_ERROR(dwError);
}
*ppszError = pszError;
cleanup:
return dwError;
error:
if(ppszError)
{
*ppszError = NULL;
}
PMD_SAFE_FREE_MEMORY(pszError);
goto cleanup;
}
int
PMDIsSystemError(
uint32_t dwError
)
{
return dwError >= ERROR_PMD_SYSTEM_BASE &&
dwError <= ERROR_PMD_SYSTEM_END;
}
uint32_t
PMDGetSystemErrorString(
uint32_t dwSystemError,
char** ppszError
)
{
uint32_t dwError = 0;
char* pszError = NULL;
char* pszSystemError = NULL;
if(!ppszError || !PMDIsSystemError(dwSystemError))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(PMDIsSystemError(dwSystemError))
{
dwSystemError = dwSystemError - ERROR_PMD_SYSTEM_BASE;
pszSystemError = strerror(dwSystemError);
if(pszSystemError)
{
dwError = PMDAllocateString(pszSystemError, &pszError);
BAIL_ON_PMD_ERROR(dwError);
}
}
*ppszError = pszError;
cleanup:
return dwError;
error:
PMD_SAFE_FREE_MEMORY(pszError);
goto cleanup;
}
uint32_t
split_user_and_pass(
const char* pszUserPass,
char** ppszUser,
char** ppszPass
)
{
uint32_t dwError = 0;
char* pszUser = NULL;
char* pszPass = NULL;
char* pszSeparator = NULL;
char SEPARATOR = ':';
int nLength = 0;
if(IsNullOrEmptyString(pszUserPass) || !ppszUser || !ppszPass)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pszSeparator = strchr(pszUserPass, SEPARATOR);
if(!pszSeparator)
{
dwError = ERROR_PMD_USER_PASS_FORMAT;
BAIL_ON_PMD_ERROR(dwError);
}
nLength = pszSeparator - pszUserPass;
dwError = PMDAllocateMemory(nLength + 1, (void **)&pszUser);
BAIL_ON_PMD_ERROR(dwError);
strncpy(pszUser, pszUserPass, nLength);
nLength = strlen(pszUserPass) - (nLength + 1);
dwError = PMDAllocateMemory(nLength + 1, (void **)&pszPass);
BAIL_ON_PMD_ERROR(dwError);
strncpy(pszPass, pszSeparator+1, nLength);
*ppszUser = pszUser;
*ppszPass = pszPass;
cleanup:
return dwError;
error:
if(ppszUser)
{
*ppszUser = NULL;
}
if(ppszPass)
{
*ppszPass = NULL;
}
PMD_SAFE_FREE_MEMORY(pszUser);
PMD_SAFE_FREE_MEMORY(pszPass);
goto cleanup;
}
uint32_t
base64_encode(
const unsigned char* pszInput,
const size_t nInputLength,
char** ppszOutput
)
{
uint32_t dwError = 0;
char* pszOutput = NULL;
int nLength = 0;
BIO* pBio64 = NULL;
BIO* pBioMem = NULL;
BUF_MEM *pMemOut = NULL;
if(!pszInput || !ppszOutput)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
pBio64 = BIO_new(BIO_f_base64());
pBioMem = BIO_new(BIO_s_mem());
pBioMem = BIO_push(pBio64, pBioMem);
BIO_set_flags(pBioMem, BIO_FLAGS_BASE64_NO_NL);
BIO_set_close(pBioMem, BIO_CLOSE);
if(BIO_write(pBioMem, pszInput, nInputLength) <= 0)
{
dwError = ERROR_PMD_BASE64_ENCODE;
BAIL_ON_PMD_ERROR(dwError);
}
BIO_flush(pBioMem);
BIO_get_mem_ptr(pBioMem, &pMemOut);
dwError = PMDAllocateMemory(pMemOut->length + 1, (void **)&pszOutput);
BAIL_ON_PMD_ERROR(dwError);
memcpy(pszOutput, pMemOut->data, pMemOut->length);
*ppszOutput = pszOutput;
cleanup:
if(pBioMem)
{
BIO_free_all(pBioMem);
}
return dwError;
error:
if(ppszOutput)
{
*ppszOutput = NULL;
}
PMD_SAFE_FREE_MEMORY(pszOutput);
goto cleanup;
}
uint32_t
base64_decode(
const char *pszInput,
unsigned char **ppOutBytes,
int *pnLength
)
{
uint32_t dwError = 0;
unsigned char *pOutBytes = NULL;
int nLength = 0;
int nInputLength = 0;
BIO* pBio64 = NULL;
BIO* pBioMem = NULL;
char *pszModInput = NULL;
const char *pszTempInput = pszInput;
int nPaddingRequired = 0;
if(!pszInput || !ppOutBytes)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
nInputLength = strlen(pszInput);
nPaddingRequired = nInputLength % 4;
if(nPaddingRequired == 1)
{
dwError = EINVAL;
BAIL_ON_PMD_ERROR(dwError);
}
nPaddingRequired = nPaddingRequired == 3 ? 1 : nPaddingRequired;
nLength = nInputLength + nPaddingRequired;
if(nPaddingRequired)
{
char pszPadding[3] = {0};
while(--nPaddingRequired >= 0)
{
pszPadding[nPaddingRequired] = '=';
}
dwError = PMDAllocateStringPrintf(&pszModInput,
"%s%s",
pszInput,
pszPadding);
BAIL_ON_PMD_ERROR(dwError);
pszTempInput = pszModInput;
}
dwError = PMDAllocateMemory(nLength + 1, (void **)&pOutBytes);
BAIL_ON_PMD_ERROR(dwError);
pBio64 = BIO_new(BIO_f_base64());
pBioMem = BIO_new_mem_buf((char*)pszTempInput, -1);
pBioMem = BIO_push(pBio64, pBioMem);
BIO_set_flags(pBioMem, BIO_FLAGS_BASE64_NO_NL);
BIO_set_close(pBioMem, BIO_CLOSE);
nLength = BIO_read(pBioMem, pOutBytes, nLength - nPaddingRequired);
if(nLength <= 0)
{
dwError = ERROR_PMD_BASE64_DECODE;
BAIL_ON_PMD_ERROR(dwError);
}
*ppOutBytes = pOutBytes;
*pnLength = nLength;
cleanup:
PMD_SAFE_FREE_MEMORY(pszModInput);
if(pBioMem)
{
BIO_free_all(pBioMem);
}
return dwError;
error:
if(ppOutBytes)
{
*ppOutBytes = NULL;
}
if(pnLength)
{
*pnLength = 0;
}
PMD_SAFE_FREE_MEMORY(pOutBytes);
goto cleanup;
}
uint32_t
base64_get_user_pass(
const char *pszBase64,
char **ppszUser,
char **ppszPass
)
{
uint32_t dwError = 0;
int nLength = 0;
char *pszUserPass = NULL;
char *pszUser = NULL;
char *pszPass = NULL;
if(IsNullOrEmptyString(pszBase64) || !ppszUser || !ppszPass)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
dwError = base64_decode(
pszBase64,
(unsigned char **)&pszUserPass,
&nLength);
BAIL_ON_PMD_ERROR(dwError);
dwError = split_user_and_pass(pszUserPass, &pszUser, &pszPass);
BAIL_ON_PMD_ERROR(dwError);
*ppszUser = pszUser;
*ppszPass = pszPass;
cleanup:
PMD_SAFE_FREE_MEMORY(pszUserPass);
return dwError;
error:
if(ppszUser)
{
*ppszUser = NULL;
}
if(ppszPass)
{
*ppszPass = NULL;
}
PMD_SAFE_FREE_MEMORY(pszUser);
PMD_SAFE_FREE_MEMORY(pszPass);
goto cleanup;
}
uint32_t
isStringPrefix(
char *pszString,
char *pszPrefix,
int *pnResult
)
{
uint32_t dwError = 0;
uint32_t nPrefixLen = 0, nStrLen = 0;
if(pnResult == NULL || IsNullOrEmptyString(pszPrefix) || IsNullOrEmptyString(pszString))
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
*pnResult = 0;
nPrefixLen = strlen(pszPrefix);
nStrLen = strlen(pszString);
if(nStrLen <= nPrefixLen)
{
dwError = ERROR_PMD_INVALID_PARAMETER;
BAIL_ON_PMD_ERROR(dwError);
}
if(!strncmp(pszString, pszPrefix, nPrefixLen))
{
*pnResult = 1;
}
cleanup:
return dwError;
error:
goto cleanup;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.