repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/ContactUsViewController/IRContactViewController.h
<reponame>mohsinalimat/ExpenseManager // // IRContactViewController.h // ExpenseManager // // Created by <NAME> on 11/10/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> #import <MessageUI/MessageUI.h> @interface IRContactViewController : UIViewController<UITextViewDelegate,MFMailComposeViewControllerDelegate> @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRGeneralSettingsTableViewCell.h
// // IRGeneralSettingsTableViewCell.h // ExpenseManager // // Created by <NAME> on 14/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @protocol IRGeneralSettingsDelegate <NSObject> - (void)reminderSwitchValueChanged:(UISwitch *)reminderSwitch; @end @interface IRGeneralSettingsTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *name; @property (weak, nonatomic) IBOutlet UISwitch *reminderSwitch; @property (assign, nonatomic) id<IRGeneralSettingsDelegate> delegate; @property (weak, nonatomic) IBOutlet UILabel *timeLabel; @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRMenuTableViewCell.h
<filename>iRun/Classes/CustomCells/IRMenuTableViewCell.h // // IRMenuTableViewCell.h // iRun // // Created by <NAME> on 30/08/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRMenuTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *name; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/AppsViewController/IRAppsViewController.h
// // IRAppsViewController.h // ExpenseMobile // // Created by <NAME> on 05/06/15. // Copyright (c) 2015 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRAppsViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRHomeCollectionCell.h
// // IRHomeCollectionCell.h // ExpenseManager // // Created by <NAME> on 17/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRHomeCollectionCell : UICollectionViewCell @property (weak, nonatomic) IBOutlet UILabel *titleLabel; @property (weak, nonatomic) IBOutlet UILabel *amount; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/CurrencyViewController/IRCurrencyViewController.h
// // IRCurrencyViewController.h // ExpenseManager // // Created by <NAME> on 07/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRCurrencyViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate> @end
mohsinalimat/ExpenseManager
iRun/FAQ/IRFAQQuestionCell.h
// // GSFAQQuestionCell.h // GoSafe // // Created by <NAME> on 19/03/14. // Copyright (c) 2014 Tata Consultancy Services. All rights reserved. // #import <UIKit/UIKit.h> @interface IRFAQQuestionCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *question; @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRPointsTableViewCell.h
// // IRPointsTableViewCell.h // ExpenseMobile // // Created by <NAME> on 14/01/15. // Copyright (c) 2015 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @protocol PointTableDelegate <NSObject> - (void)switchTapped:(id)sender; @end @interface IRPointsTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *nameLabel; @property (weak, nonatomic) IBOutlet UILabel *pointsLabel; @property (weak, nonatomic) IBOutlet UISwitch *shareSwitch; @property (assign, nonatomic) id<PointTableDelegate> delegate; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/SettingsViewController/IRSettingsViewController.h
<gh_stars>1-10 // // IRSettingsViewController.h // iRun // // Created by <NAME> on 30/08/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> #import <MessageUI/MessageUI.h> #import "SWRevealViewController.h" #import <Social/Social.h> @interface IRSettingsViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,MFMailComposeViewControllerDelegate,UIAlertViewDelegate> @end
mohsinalimat/ExpenseManager
iRun/Classes/Model/IRCategory.h
<gh_stars>1-10 // // IRCategory.h // ExpenseManager // // Created by <NAME> on 07/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <Foundation/Foundation.h> @class CategoryGroup; @interface IRCategory : NSObject @property (strong, nonatomic) NSString *categoryName; @property (assign, nonatomic) int colorCode; @property (assign, nonatomic) BOOL isExpense; @property (assign, nonatomic) int categoryID; - (IRCategory *)readFromEntity:(CategoryGroup *)category; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/SyncViewController/IRSyncViewController.h
<filename>iRun/Classes/ViewControllers/SyncViewController/IRSyncViewController.h // // IRSyncViewController.h // ExpenseMobile // // Created by <NAME> on 05/06/15. // Copyright (c) 2015 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRSyncViewController : UIViewController @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRExpenseHeaderTableViewCell.h
// // IRExpenseHeaderTableViewCell.h // ExpenseManager // // Created by <NAME> on 08/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRExpenseHeaderTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *categoryName; @property (weak, nonatomic) IBOutlet UILabel *totalExpense; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/CalenderViewController/IRCalenderViewController.h
// // IRCalenderViewController.h // ExpenseManager // // Created by <NAME> on 06/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> #import "TSQCalendarCell.h" #import "TSQCalendarMonthHeaderCell.h" #import "TSQCalendarRowCell.h" #import "TSQCalendarView.h" @protocol IRCalenderViewDelegate <NSObject> - (void)didSelectDate:(NSDate *)date; @end @interface IRCalenderViewController : UIViewController<TSQCalendarViewDelegate> @property (nonatomic, strong) NSCalendar *calendar; @property (nonatomic, assign) id<IRCalenderViewDelegate> delegate; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/ExpenseListViewController/IRExpenseListViewController.h
// // IRExpenseDetailViewController.h // ExpenseManager // // Created by <NAME> on 08/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> #import <CoreData/CoreData.h> @interface IRExpenseListViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,NSFetchedResultsControllerDelegate> @property (strong, nonatomic) NSString *categoryName; @property (assign, nonatomic) float categoryExpense; @property (assign, nonatomic) BOOL isExpense; @property (nonatomic,strong) NSManagedObjectContext* managedObjectContext; @property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController; @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRHIstoryTableViewCell.h
<reponame>mohsinalimat/ExpenseManager<filename>iRun/Classes/CustomCells/IRHIstoryTableViewCell.h // // IRHIstoryTableViewCell.h // ExpenseManager // // Created by <NAME> on 15/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRHIstoryTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *amount; @property (weak, nonatomic) IBOutlet UILabel *expenseArrow; @property (weak, nonatomic) IBOutlet UIView *colorView; @property (weak, nonatomic) IBOutlet UILabel *dayLabel; @property (weak, nonatomic) IBOutlet UILabel *dateLabel; @property (weak, nonatomic) IBOutlet UILabel *categoryLabel; @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRCalenderRowCell.h
// // IRCalenderRowCell.h // ExpenseManager // // Created by <NAME> on 06/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import "TSQCalendarRowCell.h" @interface IRCalenderRowCell : TSQCalendarRowCell @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRAppsTableViewCell.h
// // IRAppsTableViewCell.h // ExpenseMobile // // Created by <NAME> on 05/06/15. // Copyright (c) 2015 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRAppsTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *appTitle; @property (weak, nonatomic) IBOutlet UILabel *appCategory; @property (weak, nonatomic) IBOutlet UIImageView *appImage; @end
mohsinalimat/ExpenseManager
iRun/Classes/ApplicationController/IRApplicationController.h
<gh_stars>1-10 // // IRApplicationController.h // ExpenseManager // // Created by <NAME> on 30/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <Foundation/Foundation.h> @interface IRApplicationController : NSObject + (IRApplicationController *)sharedInstance; - (void)showAlertForDailyReminder; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/BuyPremiumViewController/IRBuyPremiumViewController.h
<gh_stars>1-10 // // IRBuyPremiumViewController.h // ExpenseMobile // // Created by <NAME> on 05/06/15. // Copyright (c) 2015 Shibin. All rights reserved. // #import <UIKit/UIKit.h> #import <StoreKit/StoreKit.h> @interface IRBuyPremiumViewController : UIViewController<SKProductsRequestDelegate,SKPaymentTransactionObserver> @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRHistoryHeaderTableViewCell.h
<filename>iRun/Classes/CustomCells/IRHistoryHeaderTableViewCell.h<gh_stars>1-10 // // IRHistoryHeaderTableViewCell.h // ExpenseManager // // Created by <NAME> on 15/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRHistoryHeaderTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *headerText; @property (weak, nonatomic) IBOutlet UILabel *arrowImage; @property (weak, nonatomic) IBOutlet UILabel *profit; @property (weak, nonatomic) IBOutlet UILabel *profitArrow; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/MenuViewController/IRMenuTableViewController.h
// // IRMenuTableViewController.h // iRun // // Created by <NAME> on 30/08/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRMenuTableViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> @end
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRCategoryTableViewCell.h
// // IRCategoryTableViewCell.h // ExpenseManager // // Created by <NAME> on 04/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @protocol CategoryCellDelegate <NSObject> - (void)didTapCalenderButton; @end @interface IRCategoryTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *categoryName; @property (weak, nonatomic) IBOutlet UITextField *additionalInfoTextField; @property (weak, nonatomic) IBOutlet UILabel *colorLabel; @property (weak, nonatomic) IBOutlet UIButton *calenderButton; @property (assign, nonatomic) id<CategoryCellDelegate> delegate; @end
mohsinalimat/ExpenseManager
iRun/Classes/Components/Notification/IRNotification.h
// // IRNotification.h // ExpenseManager // // Created by <NAME> on 29/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <Foundation/Foundation.h> @interface IRNotification : NSObject - (void)showNotification:(IRNotification *)notifcationParams; - (void)cancelAllNotifications; - (void)cancelNotification:(IRNotification *)notifcationParams; @property (strong, nonatomic) NSString *notificationAlertBody; @property (strong, nonatomic) NSDate *notificationFireDate; @property (assign, nonatomic) NSCalendarUnit notificationRepeatInterval; @property (strong, nonatomic) UILocalNotification *localNotification; @end
mohsinalimat/ExpenseManager
iRun/Classes/Components/Gamification/IRGamification.h
// // IRGamification.h // ExpenseManager // // Created by <NAME> on 30/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <Foundation/Foundation.h> @interface IRGamification : NSObject + (IRGamification *)sharedInstance; - (NSArray *)getArrayOfOverViewText; - (NSArray *)getArrayOfOverViewTextForExpenseOnly; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/CategoryDetailViewController/IRCategoryDetailViewController.h
// // IRCategoryDetailViewController.h // ExpenseManager // // Created by <NAME> on 07/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> typedef enum { CTAdd, CTEdit } CategoryType; @interface IRCategoryDetailViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate> @property (strong, nonatomic) NSString *name; @property (assign, nonatomic) int colorCode; @property (assign, nonatomic) CategoryType type; @property (assign, nonatomic) BOOL isExpense; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/GeneralSettingsViewController/IRGeneralSettingsViewController.h
<filename>iRun/Classes/ViewControllers/GeneralSettingsViewController/IRGeneralSettingsViewController.h // // IRGeneralSettingsViewController.h // ExpenseManager // // Created by <NAME> on 13/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> #import "IRGeneralSettingsTableViewCell.h" @interface IRGeneralSettingsViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,IRGeneralSettingsDelegate> @end
mohsinalimat/ExpenseManager
iRun/Classes/Common/IRConstants.h
<gh_stars>1-10 // // IRConstants.h // iRun // // Created by <NAME> on 30/08/14. // Copyright (c) 2014 Shibin. All rights reserved. // #define THEME_COLOR [UIColor colorWithRed:16.0/255.0 green:100.0/255.0 blue:180.0/255.0 alpha:1.0] // Blue Color #define APPLICATION_NAME @"Expense Mobile" #define OK_TEXT @"OK" #define INFO_VIEW_ANIMATION_DURATION 0.6 #define DEFAULT_FONT_NAME @"Optima" //#define DEFAULT_FONT_NAME @"Helvetica" typedef enum { WeeklyGrouping, MonthlyGrouping, YearlyGrouping }Grouping;
mohsinalimat/ExpenseManager
iRun/Classes/CustomCells/IRThemeCollectionViewCell.h
// // IRThemeCollectionViewCell.h // ExpenseManager // // Created by <NAME> on 13/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRThemeCollectionViewCell : UICollectionViewCell @property (weak, nonatomic) IBOutlet UILabel *selectionLabel; @end
mohsinalimat/ExpenseManager
iRun/Classes/Components/NumberPad/FPNumberPadView.h
// // FPNumberPadView.h // FPNumberPadView // // Created by <NAME> on 5/11/12. // Copyright (c) 2012 Absolutely iOS. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. /* This is heavily inspired by the following post on Stack Overflow http://stackoverflow.com/questions/13205160/how-do-i-retrieve-keystrokes-from-a-custom-keyboard-on-an-ios-app */ #import <UIKit/UIKit.h> @protocol NumberPadDelegate <NSObject> - (void)didTapCancelButton:(NSString *)number; - (void)didTapOkButton:(NSString *)number; @end @interface FPNumberPadView : UIView @property (nonatomic, assign) UITextField *textField; @property (nonatomic, assign) id<NumberPadDelegate> delegate; @end
mohsinalimat/ExpenseManager
iRun/Classes/Entity/Expense.h
// // Expense.h // ExpenseManager // // Created by <NAME> on 13/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class CategoryGroup; @interface Expense : NSManagedObject @property (nonatomic) NSNumber * amount; @property (nonatomic) NSString * category; @property (nonatomic) NSString * currency; @property (nonatomic) NSDate * date; @property (nonatomic) NSString * expenseId; @property (nonatomic) NSString * image; @property (nonatomic) NSNumber * isExpense; @property (nonatomic) NSNumber * isRecurring; @property (nonatomic) NSString * note; @property (nonatomic) NSNumber * recurringDuration; @property (nonatomic) NSString * sectionIdentifier; @property (nonatomic) NSDate *timeStamp; @property (nonatomic) NSString *misc; @property (nonatomic) CategoryGroup *categoryRelationship; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/ThemeViewController/IRThemeViewController.h
<gh_stars>1-10 // // IRThemeViewController.h // ExpenseManager // // Created by <NAME> on 13/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> @interface IRThemeViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> @end
mohsinalimat/ExpenseManager
iRun/Classes/CoreData/IRCoreDataController.h
<filename>iRun/Classes/CoreData/IRCoreDataController.h<gh_stars>1-10 // // IRCoreDataController.h // ExpenseManager // // Created by <NAME> on 04/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class IRExpense; @class IRCategory; @interface IRCoreDataController : NSObject @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; - (void)saveContext; - (NSURL *)applicationDocumentsDirectory; // Expense + (IRCoreDataController *)sharedInstance; - (BOOL)saveExpense:(IRExpense *)expenseData; - (BOOL)updateExpense:(IRExpense *)expense forId:(NSString *)expenseId; - (NSArray *)fetchExpenseData; - (NSArray *)fetchExpenseData:(BOOL)isExpense; - (NSArray *)fetchExpenseForCurrentMonth:(BOOL)isExpense; - (NSArray *)fetchExpenseForCurrentMonth; - (BOOL)deleteExpenseWithExpenseId:(NSString *)expenseId; - (BOOL)deleteAllExpenseData; - (BOOL)deleteAllCategories; // Category - (NSArray *)fetchCategoriesForExpense:(BOOL)isExpense; - (BOOL)addCategory:(IRCategory *)category; - (BOOL)updateCategory:(NSString *)categoryName withCategory:(IRCategory *)category; - (BOOL)deleteCategoryWithName:(NSString *)category; - (BOOL)updateExpenseForCategory:(NSString *)oldCategory with:(NSString *)newCategory; - (NSArray *)getExpensesForCurrentMonthForCategory:(NSString *)category; @end
mohsinalimat/ExpenseManager
iRun/Classes/ViewControllers/CategoryViewController/IRCategoryViewController.h
// // IRAddCategoryViewController.h // ExpenseManager // // Created by <NAME> on 05/09/14. // Copyright (c) 2014 Shibin. All rights reserved. // #import <UIKit/UIKit.h> #import <iAd/iAd.h> @interface IRCategoryViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate> @end
dycodex/BQ35100-Arduino
src/BQ35100.h
<filename>src/BQ35100.h<gh_stars>0 #ifndef BATTERY_GAUGE_BQ35100_H #define BATTERY_GAUGE_BQ35100_H #include <Wire.h> #include <stdint.h> #include "BQ35100_registers.h" /** * BQ35100 battery status. */ typedef struct { bool isDischargeDetected; bool isAlertActive; } battery_status_t; /** * BQ35100 battery alert status enumeration */ enum battery_alert_t { BQ35100_BATLOW = 0, BQ35100_TEMPLOW, BQ35100_TEMPHIGH, BQ35100_SOH_LOW, BQ35100_EOS, BQ35100_G_DONE, BQ35100_INITCOMP }; /** * BQ35100 class for measuring battery */ class BQ35100 { public: BQ35100(); ~BQ35100(); bool begin(uint8_t address = 0x55); uint16_t readVoltage(); battery_status_t readBatteryStatus(); int16_t readCurrent(); private: uint8_t i2cAddress; }; #endif
dycodex/BQ35100-Arduino
src/BQ35100_registers.h
<reponame>dycodex/BQ35100-Arduino #ifndef BQ35100_REGISTERS_H #define BQ35100_REGISTERS_H #define BQ35100_READ_VOLTAGE_MSB 0x09 #define BQ35100_READ_VOLTAGE_LSB 0x08 #define BQ35100_READ_BATTERY_STATUS 0x0A #define BQ35100_READ_CURRENT_MSB 0x0D #define BQ35100_READ_CURRENT_LSB 0x0C #endif
hietalajulius/rs-torch-panda
franka_ws/src/controller_test/include/controller_test/cartesian_pose_example_controller.h
// Copyright (c) 2017 <NAME> GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #pragma once #include <array> #include <memory> #include <string> #include <controller_interface/multi_interface_controller.h> #include <franka_hw/franka_state_interface.h> #include <hardware_interface/robot_hw.h> #include <ros/node_handle.h> #include <ros/time.h> #include <franka_hw/franka_cartesian_command_interface.h> #include<ros/ros.h> #include<std_msgs/Int16.h> #include<Eigen/Eigen> #include <iostream> #include <math.h> using namespace Eigen; namespace controller_test { class CartesianPoseExampleController : public controller_interface::MultiInterfaceController<franka_hw::FrankaPoseCartesianInterface, franka_hw::FrankaStateInterface> { public: bool init(hardware_interface::RobotHW* robot_hardware, ros::NodeHandle& node_handle) override; void starting(const ros::Time&) override; void update(const ros::Time&, const ros::Duration& period) override; void update_current_number(const std_msgs::Int16& msg); private: franka_hw::FrankaPoseCartesianInterface* cartesian_pose_interface_; std::unique_ptr<franka_hw::FrankaCartesianPoseHandle> cartesian_pose_handle_; ros::Duration elapsed_time_; std::array<double, 16> initial_pose_{}; double actions; ros::Publisher pub; ros::Subscriber sub; double current_number; Eigen::VectorXd b_vec = Eigen::VectorXd(6); Eigen::VectorXd a_vec = Eigen::VectorXd(6); double delta_x; double t_f; }; } // namespace controller_test
hietalajulius/rs-torch-panda
franka_ws/devel/include/controller_test/JointTorqueComparison.h
<filename>franka_ws/devel/include/controller_test/JointTorqueComparison.h // Generated by gencpp from file controller_test/JointTorqueComparison.msg // DO NOT EDIT! #ifndef CONTROLLER_TEST_MESSAGE_JOINTTORQUECOMPARISON_H #define CONTROLLER_TEST_MESSAGE_JOINTTORQUECOMPARISON_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace controller_test { template <class ContainerAllocator> struct JointTorqueComparison_ { typedef JointTorqueComparison_<ContainerAllocator> Type; JointTorqueComparison_() : tau_error() , tau_commanded() , tau_measured() , root_mean_square_error(0.0) { tau_error.assign(0.0); tau_commanded.assign(0.0); tau_measured.assign(0.0); } JointTorqueComparison_(const ContainerAllocator& _alloc) : tau_error() , tau_commanded() , tau_measured() , root_mean_square_error(0.0) { (void)_alloc; tau_error.assign(0.0); tau_commanded.assign(0.0); tau_measured.assign(0.0); } typedef boost::array<double, 7> _tau_error_type; _tau_error_type tau_error; typedef boost::array<double, 7> _tau_commanded_type; _tau_commanded_type tau_commanded; typedef boost::array<double, 7> _tau_measured_type; _tau_measured_type tau_measured; typedef double _root_mean_square_error_type; _root_mean_square_error_type root_mean_square_error; typedef boost::shared_ptr< ::controller_test::JointTorqueComparison_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::controller_test::JointTorqueComparison_<ContainerAllocator> const> ConstPtr; }; // struct JointTorqueComparison_ typedef ::controller_test::JointTorqueComparison_<std::allocator<void> > JointTorqueComparison; typedef boost::shared_ptr< ::controller_test::JointTorqueComparison > JointTorqueComparisonPtr; typedef boost::shared_ptr< ::controller_test::JointTorqueComparison const> JointTorqueComparisonConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::controller_test::JointTorqueComparison_<ContainerAllocator> & v) { ros::message_operations::Printer< ::controller_test::JointTorqueComparison_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::controller_test::JointTorqueComparison_<ContainerAllocator1> & lhs, const ::controller_test::JointTorqueComparison_<ContainerAllocator2> & rhs) { return lhs.tau_error == rhs.tau_error && lhs.tau_commanded == rhs.tau_commanded && lhs.tau_measured == rhs.tau_measured && lhs.root_mean_square_error == rhs.root_mean_square_error; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::controller_test::JointTorqueComparison_<ContainerAllocator1> & lhs, const ::controller_test::JointTorqueComparison_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace controller_test namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::controller_test::JointTorqueComparison_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::controller_test::JointTorqueComparison_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::controller_test::JointTorqueComparison_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::controller_test::JointTorqueComparison_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::controller_test::JointTorqueComparison_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::controller_test::JointTorqueComparison_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::controller_test::JointTorqueComparison_<ContainerAllocator> > { static const char* value() { return "6c09db90263c92a2e4e4d736f67bc033"; } static const char* value(const ::controller_test::JointTorqueComparison_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x6c09db90263c92a2ULL; static const uint64_t static_value2 = 0xe4e4d736f67bc033ULL; }; template<class ContainerAllocator> struct DataType< ::controller_test::JointTorqueComparison_<ContainerAllocator> > { static const char* value() { return "controller_test/JointTorqueComparison"; } static const char* value(const ::controller_test::JointTorqueComparison_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::controller_test::JointTorqueComparison_<ContainerAllocator> > { static const char* value() { return "float64[7] tau_error\n" "float64[7] tau_commanded\n" "float64[7] tau_measured\n" "float64 root_mean_square_error\n" ; } static const char* value(const ::controller_test::JointTorqueComparison_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::controller_test::JointTorqueComparison_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.tau_error); stream.next(m.tau_commanded); stream.next(m.tau_measured); stream.next(m.root_mean_square_error); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct JointTorqueComparison_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::controller_test::JointTorqueComparison_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::controller_test::JointTorqueComparison_<ContainerAllocator>& v) { s << indent << "tau_error[]" << std::endl; for (size_t i = 0; i < v.tau_error.size(); ++i) { s << indent << " tau_error[" << i << "]: "; Printer<double>::stream(s, indent + " ", v.tau_error[i]); } s << indent << "tau_commanded[]" << std::endl; for (size_t i = 0; i < v.tau_commanded.size(); ++i) { s << indent << " tau_commanded[" << i << "]: "; Printer<double>::stream(s, indent + " ", v.tau_commanded[i]); } s << indent << "tau_measured[]" << std::endl; for (size_t i = 0; i < v.tau_measured.size(); ++i) { s << indent << " tau_measured[" << i << "]: "; Printer<double>::stream(s, indent + " ", v.tau_measured[i]); } s << indent << "root_mean_square_error: "; Printer<double>::stream(s, indent + " ", v.root_mean_square_error); } }; } // namespace message_operations } // namespace ros #endif // CONTROLLER_TEST_MESSAGE_JOINTTORQUECOMPARISON_H
jmpews/tcpscan
tcpscan.c
<filename>tcpscan.c #define _BSD_SOURCE 1 #include <stdio.h> #include <unistd.h> #include <time.h> #include <libnet.h> #include <pcap.h> #include <netinet/tcp.h> #include <netinet/ip.h> #include <net/ethernet.h> #include <pthread.h> static u_int32_t s_src_ipaddr; /* ip address of this host */ static libnet_t *s_netctx; /* libnet context */ static int* s_ports; static int s_port_num = 0; static int s_port_scanned; static u_int32_t s_ipaddr_begin; /* ip address to scan */ static u_int32_t s_ipaddr_end; static u_int32_t s_total_ip; static u_int32_t s_open_port = 0; static u_int32_t s_closed_port = 0; static u_int32_t s_sent_failed = 0; static int s_send_syn_thread_quit = 0; static unsigned int s_interval_us = 0; static unsigned int s_max_wait_time = 5; static int s_netprefix_length = 0; static u_int32_t TCP_ISN = 0; static const char* s_user_specified_device = NULL; static const char* s_device_name; static int s_gateway_macaddr_set = 0; static int s_netctx_gateway_macaddr_set = 0; static uint8_t s_gateway_macaddr[6]; static libnet_ptag_t s_tcpopt = 0, s_tcp = 0, s_ipv4 = 0, s_ether = 0; /* libnet protocol blocks */ static uint8_t* s_src_macaddr = 0; static void usage() { printf("tcpscan - SYN scan\n"); printf("Usage: tcpscan [-p Port1[, Port2[, ..., PortN]]]\n" " [-i ifname] [-t Timeout]\n" " [-u usInterval]\n" " IP[/PrefixLength]\n" "Example: tcpscan -p80,443 -ieth0 192.168.1.0/24\n"); } static void init_task(char* str_ip) { char* p_slash = NULL; in_addr_t ipaddr; int i; if ((p_slash = strchr(str_ip, '/')) != NULL) { u_int32_t netmask = 0xffffffff; s_netprefix_length = atoi(p_slash+1); char netprefix[16]; if (!s_netprefix_length) { exit(1); } memset(netprefix, 0, 16); strncpy(netprefix, str_ip, p_slash - str_ip); if ((ipaddr = libnet_name2addr4(s_netctx, netprefix, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Invalid address: %s(%s)\n", libnet_geterror(s_netctx), netprefix); exit(1); } netmask &= ~1; for (i = 1; i < 32-s_netprefix_length; ++i) { netmask <<= 1; netmask &= ~1; } s_ipaddr_begin = ntohl(ipaddr) & netmask; s_ipaddr_end = s_ipaddr_begin | ~netmask; s_total_ip = s_ipaddr_end - s_ipaddr_begin + 1; } else { if ((ipaddr = libnet_name2addr4(s_netctx, str_ip, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Invalid address: %s(%s)\n", libnet_geterror(s_netctx), str_ip); exit(1); } s_ipaddr_begin = ntohl(ipaddr); s_ipaddr_end = s_ipaddr_begin; s_total_ip = 1; } } static u_int32_t get_ip(u_int32_t index) { u_int32_t x = 0; int i; // reverse bits of index int n = 32 - s_netprefix_length; for (i = 0; i < n; ++i) { x |= ((index & (0x01 << i)) >> i) << (n-i-1); } return s_ipaddr_begin | x; } static void packet_handler(u_char* user, const struct pcap_pkthdr* header, const u_char* packet) { struct tcphdr *tcp = (struct tcphdr *) (packet + LIBNET_IPV4_H + LIBNET_ETH_H); struct ip *ip = (struct ip *) (packet + LIBNET_ETH_H); struct ether_header* ether = (struct ether_header*) packet; if (!s_gateway_macaddr_set) { char macaddr_str[20]; sprintf(macaddr_str, "%02x:%02x:%02x:%02x:%02x:%02x", ether->ether_shost[0], ether->ether_shost[1], ether->ether_shost[2], ether->ether_shost[3], ether->ether_shost[4], ether->ether_shost[5]); printf("Gateway MAC addr: %s\n", macaddr_str); memcpy(s_gateway_macaddr, ether->ether_shost, 6); s_gateway_macaddr_set = 1; } if (tcp->th_flags == (TH_ACK | TH_RST)) //TODO: We need to consider the 'spliting handshake' { ++s_closed_port; printf("- %s:%d\n", libnet_addr2name4(ip->ip_src.s_addr, LIBNET_DONT_RESOLVE), ntohs(tcp->th_sport)); } else if (tcp->th_flags == (TH_ACK | TH_SYN)) { ++s_open_port; printf("+ %s:%d\n", libnet_addr2name4(ip->ip_src.s_addr, LIBNET_DONT_RESOLVE), ntohs(tcp->th_sport)); } else { printf("* %s:%d\n", libnet_addr2name4(ip->ip_src.s_addr, LIBNET_DONT_RESOLVE), ntohs(tcp->th_sport)); } } static void send_syn(in_addr_t src_ipaddr, int src_port, in_addr_t dst_ipaddr, int dst_port) { unsigned char mss_opt[5] = {0x02,0x04,0x05,0xb4,0x00}; s_tcpopt = libnet_build_tcp_options(mss_opt, 4, s_netctx, s_tcpopt); if (s_tcpopt == -1) { fprintf(stderr, "Unable to build TCP options: %s\n", libnet_geterror(s_netctx)); exit(1); } /* build the TCP header */ s_tcp = libnet_build_tcp (src_port, /* src port */ dst_port, /* destination port */ TCP_ISN, /* sequence number */ 0, /* acknowledgement */ TH_SYN, /* control flags */ 1024, /* window */ 0, /* checksum - 0 = autofill */ 0, /* urgent */ LIBNET_TCP_H, /* header length */ NULL, /* payload */ 0, /* payload length */ s_netctx, /* libnet context */ s_tcp); /* protocol tag */ if (s_tcp == -1) { fprintf(stderr, "Unable to build TCP header: %s\n", libnet_geterror(s_netctx)); exit(1); } /* build the IP header */ s_ipv4 = libnet_build_ipv4(LIBNET_TCP_H + LIBNET_IPV4_H + 4, /* length */ 0, /* TOS */ libnet_get_prand(LIBNET_PRu16), /* IP ID */ 0, /* frag offset */ 127, /* TTL */ IPPROTO_TCP, /* upper layer protocol */ 0, /* checksum, 0=autofill */ src_ipaddr, /* src IP */ dst_ipaddr, /* dest IP */ NULL, /* payload */ 0, /* payload len */ s_netctx, /* libnet context */ s_ipv4); /* protocol tag */ if (s_ipv4 == -1) { fprintf(stderr, "Unable to build IPv4 header: %s\n", libnet_geterror(s_netctx)); exit(1); } if (s_netctx_gateway_macaddr_set) { //printf("ether\n"); s_ether = libnet_build_ethernet(s_gateway_macaddr, s_src_macaddr, ETHERTYPE_IP, NULL, 0, s_netctx, s_ether); if (s_ether == -1) { fprintf(stderr, "Unable to build Ether header: %s\n", libnet_geterror(s_netctx)); exit(1); } } /* write the packet */ if ((libnet_write(s_netctx)) == -1) { ++s_sent_failed; } //libnet_clear_packet(s_netctx); } static void init_net_context(int inj_type) { char libnet_errbuf[LIBNET_ERRBUF_SIZE]; /* libnet error messages */ s_tcpopt = 0; s_tcp = 0; s_ipv4 = 0; s_ether = 0; s_netctx = libnet_init(inj_type, s_user_specified_device, libnet_errbuf); if (s_netctx == NULL) { fprintf(stderr, "Error opening context (device: %s): %s\n", s_device_name, libnet_errbuf); exit (1); } libnet_seed_prand(s_netctx); /* get the ip address of the device */ if ((s_src_ipaddr = libnet_get_ipaddr4(s_netctx)) == -1) { fprintf (stderr, "Error getting IP: %s\n", libnet_geterror(s_netctx)); exit(1); } /* get the device we are using for libpcap */ if ((s_device_name = libnet_getdevice(s_netctx)) == NULL) { fprintf(stderr, "Device is NULL. Packet capture may be broken\n"); } if ((s_src_macaddr = (uint8_t*)libnet_get_hwaddr(s_netctx)) == NULL) { fprintf(stderr, "Get device MAC address error: %s", libnet_geterror(s_netctx)); } } static void *send_thread(void *arg) { int p; u_int32_t i; /* wait a while to make sure the main thread is ready to receive */ usleep(10000); for (p = 0; p < s_port_num; ++p) { for ( i = 0; i < s_total_ip; ++i) { if (!s_netctx_gateway_macaddr_set && s_gateway_macaddr_set) { libnet_destroy(s_netctx); init_net_context(LIBNET_LINK); s_netctx_gateway_macaddr_set = 1; } send_syn(s_src_ipaddr, libnet_get_prand(LIBNET_PRu16), htonl(get_ip(i)), s_ports[p]); if (s_interval_us) usleep(s_interval_us); } } /* wait a while before quit */ if (s_port_num * s_total_ip > s_open_port + s_closed_port) sleep(s_max_wait_time); s_send_syn_thread_quit = 1; return NULL; } int main (int argc, char *argv[]) { //const char *device = NULL; /* device for sniffing/sending */ char o; /* for option processing */ char libpcap_errbuf[PCAP_ERRBUF_SIZE]; /* pcap error messages */ pcap_t *handle; /* libpcap handle */ bpf_u_int32 netp, maskp; /* netmask and ip */ char filter[256]; struct bpf_program fp; /* compiled filter */ time_t tv; int i; while ((o = getopt(argc, argv, "u:i:t:p:")) > 0) { switch (o) { case 'i': { s_user_specified_device = optarg; break; } case 't': { s_max_wait_time = atoi(optarg); break; } case 'u': { s_interval_us = atoi(optarg); break; } case 'p': { char* p = NULL; char* optarg_copy = strdup(optarg); if (strlen(optarg_copy) > 0) s_port_num = 1; for (p = optarg_copy; *p != '\0'; ++p) { if (*p == ',') { ++s_port_num; } } int i = 0; s_ports = (int*) malloc(s_port_num * (sizeof (int))); while ((p = strsep(&optarg_copy, ",")) != NULL) { int temp = atoi(p); if (!temp) { printf("Illegal port: %s\n", p); usage(); exit(1); } s_ports[i++] = temp; } free(optarg_copy); break; } case '?': { printf("Unkown option: %c\n", optopt); break; } default: { usage(); exit(1); break; } } } if (argc != optind + 1) { usage(); exit(1); } if (geteuid()) { fprintf(stderr, "Please run as root privileges.\n"); exit(1); } if (s_port_num == 0) { int default_ports[] = {21, 22, 23, 80, 110, 443}; s_port_num = (sizeof default_ports) / (sizeof (int)); s_ports = (int*) malloc(s_port_num * (sizeof (int))); for (i = 0; i < s_port_num; ++i) { s_ports[i] = default_ports[i]; } } TCP_ISN = libnet_get_prand(LIBNET_PRu32); init_net_context(LIBNET_RAW4); init_task(argv[optind]); snprintf(filter, sizeof filter, "(dst host %s) && tcp[8:4] == %d", libnet_addr2name4(s_src_ipaddr, LIBNET_DONT_RESOLVE), TCP_ISN + 1); printf("Device: %s, IP: %s\n", s_device_name, libnet_addr2name4(s_src_ipaddr, LIBNET_DONT_RESOLVE)); /* open the device with pcap */ if ((handle = pcap_open_live(s_device_name, 1500, 0, 2000, libpcap_errbuf)) == NULL) { fprintf(stderr, "Error opening pcap: %s\n", libpcap_errbuf); exit(1); } if ((pcap_setnonblock(handle, 1, libpcap_errbuf)) == -1) { fprintf(stderr, "Error setting nonblocking: %s\n", libpcap_errbuf); exit(1); } if (pcap_lookupnet(s_device_name, &netp, &maskp, libpcap_errbuf) == -1) { fprintf(stderr, "Net lookup error: %s\n", libpcap_errbuf); exit(1); } if (pcap_compile(handle, &fp, filter, 0, maskp) == -1) { fprintf(stderr, "BPF error: %s\n", pcap_geterr(handle)); exit(1); } if (pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Error setting BPF: %s\n", pcap_geterr(handle)); exit(1); } pcap_freecode(&fp); s_port_scanned = 0; printf("%s-%s Total: %d\n", libnet_addr2name4(htonl(s_ipaddr_begin), LIBNET_DONT_RESOLVE), libnet_addr2name4(htonl(s_ipaddr_end), LIBNET_DONT_RESOLVE), s_total_ip); pthread_t ntid; pthread_create(&ntid, NULL, send_thread, NULL); while (s_port_scanned < s_port_num * s_total_ip) { int ret = pcap_dispatch(handle, 10, packet_handler, NULL); if (ret > 0) s_port_scanned += ret; if (s_send_syn_thread_quit) { break; } } printf("Open: %d, Closed: %d, Failed: %d\n", s_open_port, s_closed_port, s_sent_failed); pcap_close(handle); libnet_destroy(s_netctx); if (s_ports) free(s_ports); return 0; }
AlaricEgli/Openpilotcrazy
selfdrive/ui/tuning.h
/************************************** Tuning UI Author: pjlao307 This OpenPilot mod allows you to dynamically modify variables used by OpenPilot. The purpose of this mod is to make it easier to tweak certain variables instead of having to modify code, recompile, reboot after every change. To use this mod you need to do 2 things: 1. Create a file called /sdcard/tuning/params.txt Copy the file called params.example.txt into /sdcard/tuning (create the directory if needed). You will need to specify which variables you want the Tuning mod to manage by adding them to that file. 2. Modify OpenPilot code that uses the variable so that it is read from this file instead of hard coded. This is left for the user to figure out and implement. For questions or info about this mod, visit the comma slack channel #mod-tuning CHANGE LOG: v0.0.1 - Initial version **************************************/ #define VERSION "0.0.1" #define ERROR_NO_FILE 1 #define BTN_NONE 0 #define BTN_INCREASE 1 #define BTN_DECREASE 2 #define BTN_STEP_INCREASE 3 #define BTN_STEP_DECREASE 4 #define BTN_LEFT_ARROW 5 #define BTN_RIGHT_ARROW 6 #define BTN_TUNE 7 #define BTN_STEP 8 #define MAX_NUM_PARAMS 10 // max number of params we can track #define MAX_FILE_BYTES 100000 // max bytes to write to file bool debug = false; int status = 0; // Status code to tell us if something went wrong typedef struct ui_element { char name[50]; int pos_x; int pos_y; int width; int height; } ui_element; int left_arrow_icon; int right_arrow_icon; int tune_icon; int current_button = BTN_NONE; bool tune_enabled = false; ui_element increase_button; ui_element decrease_button; ui_element property_button; ui_element tune_values; ui_element step_increase; ui_element step_decrease; ui_element step_text; ui_element left_arrow_button; ui_element right_arrow_button; ui_element tune_button; char rootdir[50] = "/sdcard/tuning"; char params_file[256] = "params.txt"; char python_file[256]; // stores values as pyton variable bool init_tune = false; // Used to initialize stuff int num_lines = 0; float angles[MAX_NUM_PARAMS][3]; // List of angle values from the file char property[50] = "CL_MAXD_A"; // What property to tune char properties[50][MAX_NUM_PARAMS]; // List of property names int current_property = -1; // Which property value to adjust when clicking the increase/decrease buttons ui_element *property_buttons[MAX_NUM_PARAMS]; // Store the buttons that can be selected float step = 0.001; // Steps to adjust on each click float delta_step = 0.001; // Change step by this amount int step_toggle = 0; // Change to preset toggle step int param_index = 0; // Index to track which param label we're working with int param_value_count[MAX_NUM_PARAMS]; // Store the number of elements for each param char *param_labels[MAX_NUM_PARAMS]; // Store the names of the params // Used to delay button highlighting int frame_num = 0; int frame_delay = 15; // delay for X frames char *str_remove(const char *s, char ch) { int counter; char *new_str = malloc(strlen(s)+1); new_str[0] = '\0'; while(s[counter] != '\0') { if (s[counter] != ch) { size_t str_len = strlen(new_str); new_str[str_len] = s[counter]; new_str[str_len+1] = '\0'; } counter++; } //printf("new_str: %s\n",new_str); return new_str; } char *get_full_path(char *fname) { if (debug) { printf("get_full_path\n"); } char *filename = malloc(sizeof(char *) * 128); char fullpath[128]; snprintf(fullpath,sizeof(fullpath),"%s/%s", rootdir, fname); strcpy(filename, fullpath); return filename; } char **readfile(char *filename) { if (debug) { printf("readfile\n"); } FILE* file = fopen(filename, "r"); if (!file) { //printf("Could not open file!\n"); status = ERROR_NO_FILE; return NULL; } char line[256]; char **lines = malloc(sizeof(char *) * MAX_NUM_PARAMS); num_lines = 0; size_t ln; while(fgets(line, sizeof(line), file)) { //printf("line: %s\n", line); ln = strlen(line) - 1; line[ln] = '\0'; lines[num_lines] = malloc(256+1); strcpy(lines[num_lines],line); num_lines++; } fclose(file); //printf("num_lines: %d\n", num_lines); /* for (int i=0; i < num_lines; i++) { printf("line %d: %s\n", i, lines[i]); } */ return lines; } void parse_file(char *filename) { if (debug) { printf("parse_file\n"); } char **lines = readfile(filename); if (status == ERROR_NO_FILE) { return; } //printf("num_lines: %d\n",num_lines); for (int i=0; i < num_lines; i++) { int angle_index = 0; char* token_value; char* token_value2; char* token2; param_labels[i] = malloc(sizeof(char *)); //printf("line %d: %s\n", i, lines[i]); char* token = strtok(lines[i], "="); //printf("token1: %s\n", token); param_labels[i] = token; while (token != NULL ) { token = strtok(NULL, "="); if (token != NULL) { token_value = str_remove(str_remove(token,'['),']'); //printf("token_value: %s\n", token_value); char* token2 = strtok(token_value,","); //printf("token2: %s\n", token2); angles[i][angle_index++] = atof(token2); while (token2 != NULL) { token2 = strtok(NULL, ","); if (token2 != NULL) { token_value2 = token2; angles[i][angle_index++] = atof(token_value2); //printf("token_value2: %s\n", token_value2); } } } } param_value_count[i] = angle_index; } /* for (int i=0; i < num_lines; i++) { printf("%s: %d indexes\n",param_labels[i],param_value_count[i]); } for (int i=0; i < num_lines; i++) { int num_elements = param_value_count[i]; for (int j=0; j < num_elements; j++) { printf("%d, %d: %.3f\n", i, j, angles[i][j]); } } */ } void read_file_values(char *fname) { if (debug) { printf("read_file_values\n"); } char *filename = get_full_path(fname); //printf("file: %s\n",filename); parse_file(filename); } void update_params() { if (debug) { printf("update_params\n"); } // update the params file with the current values char content[MAX_FILE_BYTES] = ""; for (int i=0; i < num_lines; i++) { int num_elements = param_value_count[i]; char temp[128] = ""; for (int j=0; j < num_elements; j++) { char value_str[50]; snprintf(value_str,sizeof(value_str),"%.3f",angles[i][j]); strcat(temp, value_str); if (j < num_elements-1) { strcat(temp, ","); } //printf("%d, %d: %.3f\n", i, j, angles[i][j]); } char line[128] = ""; snprintf(line,sizeof(line),"%s=[%s]\n",param_labels[i],temp); //printf("line: %s\n",line); strcat(content,line); } //printf("Contents:\n\n"); //printf("%s", content); char *filename = get_full_path(params_file); FILE *out_file = fopen(filename, "w"); if (out_file == NULL) { printf("Error: Could not open file: %s", filename); return; } fprintf(out_file, content, sizeof(content)); //printf("python: %s\n",content); fclose(out_file); } void init_tuning(UIState *s) { if (debug) { printf("init_tuning\n"); } if (init_tune) { return; } left_arrow_icon = nvgCreateImage(s->vg, "../assets/left_arrow.png", 1); right_arrow_icon = nvgCreateImage(s->vg, "../assets/right_arrow.png", 1); tune_icon = nvgCreateImage(s->vg, "../assets/tune_icon.png", 1); read_file_values(params_file); //update_params(); init_tune = true; increase_button = (ui_element){ .name = "increase_button", .pos_x = (1920/2)-140, .pos_y = 1080-240, .width = 120, .height = 120 }; decrease_button = (ui_element){ .name = "decrease_button", .pos_x = (1920/2)+40, .pos_y = 1080-240, .width = 120, .height = 120 }; tune_values = (ui_element){ .name = "tune_values", .pos_x = (1920/2)-400, .pos_y = 1080-490, .width = 850, .height = 220 }; property_button = (ui_element){ .name = "property_button", .pos_x = (1920/2)-365, .pos_y = 1080-420, .width = 230, .height = 95 }; for (int j=0; j < num_lines; j++) { property_buttons[j] = malloc(sizeof(ui_element) * 3); for (int i=0; i < param_value_count[param_index]; i++) { property_buttons[j][i] = property_button; property_buttons[j][i].pos_x += i*(property_button.width+45); char valuename[50]; snprintf(valuename,sizeof(valuename),"value_%d",i); snprintf(property_buttons[j][i].name,sizeof(property_buttons[j][i].name),"%s",valuename); } } step_text = (ui_element){ .name = "step_text", .pos_x = (1920/2)-380, .pos_y = 1080-635, .width = 250, .height = 125 }; step_increase = (ui_element){ .name = "step_increase", .pos_x = (1920/2)-90, .pos_y = 1080-640, .width = 120, .height = 120 }; step_decrease = (ui_element){ .name = "step_decrease", .pos_x = step_increase.pos_x + step_increase.width + 15, .pos_y = 1080-640, .width = 120, .height = 120 }; left_arrow_button = (ui_element) { .name = "left_arrow", .pos_x = (1920/2)-400, .pos_y = 1080-240, .width = 85, .height = 85 }; right_arrow_button = (ui_element) { .name = "right_arrow", .pos_x = (1920/2)+335, .pos_y = 1080-240, .width = 85, .height = 85 }; tune_button = (ui_element) { .name = "tune_button", .pos_x = (1920/2)-610, .pos_y = 1080-240, .width = 120, .height = 120 }; } void draw_error( UIState *s) { //printf("No file!\n"); nvgBeginPath(s->vg); nvgRoundedRect(s->vg,350,400,1350,380,40); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); nvgFill(s->vg); nvgTextAlign(s->vg, NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE); nvgFillColor(s->vg, nvgRGBA(255, 255, 255, 200)); nvgFontSize(s->vg, 70); nvgText(s->vg,400,500,"ERROR - File not found:",NULL); nvgText(s->vg,400,600," /sdcard/tuning/params.txt",NULL); nvgText(s->vg,400,700,"Please check that this file exists",NULL); } void screen_draw_tuning(UIState *s) { if (debug) { printf("screen_draw_tuning\n"); } float alpha = 1.0f; NVGpaint imgPaint; if (!init_tune) { return; } if (status == ERROR_NO_FILE && tune_enabled) { draw_error(s); } if (tune_enabled && status != ERROR_NO_FILE) { if (current_property != -1) { // increase button nvgBeginPath(s->vg); nvgRoundedRect(s->vg, increase_button.pos_x, increase_button.pos_y, increase_button.width, increase_button.height, 100); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); if (current_button == BTN_INCREASE) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } nvgFill(s->vg); nvgFillColor(s->vg, nvgRGBA(255, 255, 255, 200)); nvgFontSize(s->vg, 120); nvgText(s->vg,increase_button.pos_x+30,increase_button.pos_y+90,"+",NULL); // decrease button nvgBeginPath(s->vg); nvgRoundedRect(s->vg, decrease_button.pos_x, decrease_button.pos_y, decrease_button.width, decrease_button.height, 100); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); if (current_button == BTN_DECREASE) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } nvgFill(s->vg); nvgFontSize(s->vg, 120); nvgFillColor(s->vg, nvgRGBA(255, 255, 255, 200)); nvgText(s->vg,decrease_button.pos_x+30,decrease_button.pos_y+90,"-",NULL); } // Draw current tune values nvgBeginPath(s->vg); nvgTextAlign(s->vg, NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE); nvgRoundedRect(s->vg, tune_values.pos_x, tune_values.pos_y, tune_values.width, tune_values.height, 10); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); nvgFill(s->vg); nvgFontSize(s->vg, 65); nvgFillColor(s->vg, nvgRGBA(255, 255, 255, 200)); nvgText(s->vg,tune_values.pos_x+20,tune_values.pos_y+50,param_labels[param_index],NULL); int pos_x; int pos_y; char thisValue[8]; for (int i=0; i < param_value_count[param_index]; i++) { pos_x = i*300; if (i > 0) { pos_x -= 40; } if (angles[param_index][i] < 1) { snprintf(thisValue,sizeof(thisValue),"%.3f",angles[param_index][i]); } else { snprintf(thisValue,sizeof(thisValue),"%.1f",angles[param_index][i]); } nvgFontSize(s->vg, 70); nvgText(s->vg,tune_values.pos_x+pos_x+60,tune_values.pos_y+140,thisValue,NULL); } // Render property buttons based on the number of elements in the params for (int i=0; i < param_value_count[param_index]; i++) { nvgBeginPath(s->vg); nvgRoundedRect(s->vg, property_buttons[param_index][i].pos_x, property_buttons[param_index][i].pos_y, property_buttons[param_index][i].width, property_buttons[param_index][i].height, 15); if (i == current_property) { nvgStrokeColor(s->vg, nvgRGBA(0,162,255,200)); } else { nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); } nvgStrokeWidth(s->vg, 9); nvgStroke(s->vg); } // Step increment buttons nvgBeginPath(s->vg); nvgRoundedRect(s->vg, step_text.pos_x, step_text.pos_y, step_text.width, step_text.height, 15); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); nvgFill(s->vg); nvgFillColor(s->vg, nvgRGBA(255, 255, 255, 200)); if (current_button == BTN_STEP) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } char step_str[8]; if (step >= 1) { snprintf(step_str,sizeof(step_str),"%.1f",step); } else { snprintf(step_str,sizeof(step_str),"%.3f",step); } nvgTextAlign(s->vg, NVG_ALIGN_CENTER | NVG_ALIGN_BASELINE); nvgFontSize(s->vg, 70); nvgText(s->vg,step_text.pos_x+120,step_increase.pos_y+55,"Steps",NULL); nvgFontSize(s->vg, 80); nvgText(s->vg,step_text.pos_x+125,step_increase.pos_y+112,step_str,NULL); nvgTextAlign(s->vg, NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE); nvgBeginPath(s->vg); nvgRoundedRect(s->vg, step_increase.pos_x, step_increase.pos_y, step_increase.width, step_increase.height, 100); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); if (current_button == BTN_STEP_INCREASE) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } nvgFill(s->vg); nvgFontSize(s->vg, 120); nvgFillColor(s->vg, nvgRGBA(255, 255, 255, 200)); nvgText(s->vg,step_increase.pos_x+25,step_increase.pos_y+90,"+",NULL); nvgBeginPath(s->vg); nvgRoundedRect(s->vg, step_decrease.pos_x, step_decrease.pos_y, step_decrease.width, step_decrease.height, 100); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); if (current_button == BTN_STEP_DECREASE) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } nvgFill(s->vg); nvgFontSize(s->vg, 150); nvgFillColor(s->vg, nvgRGBA(255, 255, 255, 200)); nvgText(s->vg,step_decrease.pos_x+25,step_increase.pos_y+100,"-",NULL); // left arrow nvgBeginPath(s->vg); nvgRoundedRect(s->vg, left_arrow_button.pos_x, left_arrow_button.pos_y, left_arrow_button.width+35, left_arrow_button.height+35, 100); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); if (current_button == BTN_LEFT_ARROW) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } nvgFill(s->vg); nvgBeginPath(s->vg); imgPaint = nvgImagePattern(s->vg, left_arrow_button.pos_x+15, left_arrow_button.pos_y+15, left_arrow_button.width, left_arrow_button.height, 0, left_arrow_icon, 1.0f); nvgRoundedRect(s->vg, left_arrow_button.pos_x+15, left_arrow_button.pos_y+15, left_arrow_button.width, left_arrow_button.height, 100); nvgFillPaint(s->vg, imgPaint); nvgFill(s->vg); // right arrow nvgBeginPath(s->vg); nvgRoundedRect(s->vg, right_arrow_button.pos_x, right_arrow_button.pos_y, right_arrow_button.width+35, right_arrow_button.height+35, 100); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); if (current_button == BTN_RIGHT_ARROW) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } nvgFill(s->vg); nvgBeginPath(s->vg); imgPaint = nvgImagePattern(s->vg, right_arrow_button.pos_x+15, right_arrow_button.pos_y+15, right_arrow_button.width, right_arrow_button.height, 0, right_arrow_icon, 1.0f); nvgRoundedRect(s->vg, right_arrow_button.pos_x+15, right_arrow_button.pos_y+15, right_arrow_button.width, right_arrow_button.height, 100); nvgFillPaint(s->vg, imgPaint); nvgFill(s->vg); } if (s->vision_connected) { //printf("vision connected\n"); // tune button nvgBeginPath(s->vg); nvgRoundedRect(s->vg, tune_button.pos_x, tune_button.pos_y, tune_button.width+35, tune_button.height+35, 100); nvgStrokeColor(s->vg, nvgRGBA(255,255,255,80)); nvgStrokeWidth(s->vg, 6); nvgStroke(s->vg); nvgFillColor(s->vg, nvgRGBA(0, 0, 0, 100)); if (current_button == BTN_TUNE) { nvgFillColor(s->vg, nvgRGBA(0, 162, 255, 100)); } nvgFill(s->vg); nvgBeginPath(s->vg); if (!tune_enabled) { alpha = 0.3f; } imgPaint = nvgImagePattern(s->vg, tune_button.pos_x+15, tune_button.pos_y+15, tune_button.width, tune_button.height, 0, tune_icon, alpha); nvgRoundedRect(s->vg, tune_button.pos_x+15, tune_button.pos_y+15, tune_button.width, tune_button.height, 100); nvgFillPaint(s->vg, imgPaint); nvgFill(s->vg); } } void next_param(int direction) { if (debug) { printf("next_param\n"); } // Load the next parameter to adjust param_index += direction; if (param_index >= num_lines) { param_index = 0; } else if (param_index < 0) { param_index = num_lines-1; } } void toggle_tune() { if (debug) { printf("toggle_tune\n"); } if (!tune_enabled) { tune_enabled = true; } else { tune_enabled = false; } } bool ui_element_clicked(int touch_x, int touch_y, ui_element el) { if (touch_x >= el.pos_x && touch_x <= (int)(el.pos_x+el.width)) { if (touch_y >= el.pos_y && touch_y <= (int)(el.pos_y+el.height)) { return true; } } return false; } void toggle_step() { //printf("step_toggle: %d\n",step_toggle); if (step_toggle == 0) { step_toggle++; delta_step = 0.01; } else if (step_toggle == 1) { step_toggle++; delta_step = 0.1; } else if (step_toggle == 2) { step_toggle++; delta_step = 1; } else if (step_toggle == 3) { step_toggle++; delta_step = 5; } else { step_toggle = 0; delta_step = 0.001; } step = delta_step; } void tuning( UIState *s, int touch_x, int touch_y ) { init_tuning(s); if (debug) { printf("tuning\n"); } /* if (touch_x > 0) { printf("touch: %d, %d\n", touch_x, touch_y); } */ screen_draw_tuning(s); if (ui_element_clicked(touch_x,touch_y,tune_button)) { toggle_tune(); current_button = BTN_TUNE; } if (current_button != BTN_NONE) { frame_num++; if (frame_num >= frame_delay) { current_button = BTN_NONE; frame_num = 0; } } if (status == ERROR_NO_FILE) { return; } if (ui_element_clicked(touch_x,touch_y,increase_button) && current_property != -1) { //printf("increase button clicked\n"); //printf("param_index: %d\n",param_index); //printf("current_prop: %d\n",current_property); angles[param_index][current_property] += step; update_params(); current_button = BTN_INCREASE; } else if (ui_element_clicked(touch_x,touch_y,decrease_button) && current_property != -1) { //printf("decrease button clicked\n"); angles[param_index][current_property] -= step; //snprintf(angles[param_index][current_property],sizeof(angles[param_index][current_property]),"%.3f",num); //angles[param_index][current_property] = num; update_params(); current_button = BTN_DECREASE; } else if (ui_element_clicked(touch_x,touch_y,step_increase)) { //printf("step increase button clicked\n"); step += delta_step; current_button = BTN_STEP_INCREASE; } else if (ui_element_clicked(touch_x,touch_y,step_decrease)) { //printf("step decrease button clicked\n"); step -= delta_step; current_button = BTN_STEP_DECREASE; } else if (ui_element_clicked(touch_x,touch_y,left_arrow_button)) { next_param(-1); current_button = BTN_LEFT_ARROW; } else if (ui_element_clicked(touch_x,touch_y,right_arrow_button)) { next_param(1); current_button = BTN_RIGHT_ARROW; } else if (ui_element_clicked(touch_x,touch_y,step_text)) { toggle_step(); current_button = BTN_STEP; } else { for (int i=0; i < param_value_count[param_index]; i++) { if (ui_element_clicked(touch_x,touch_y,property_buttons[param_index][i])) { if (current_property == i) { // Toggle off current_property = -1; } else { // Toggle on current_property = i; } //printf("param element %i clicked\n",i); } } } }
lucasfeijo/matrix-ios-sdk
MatrixSDK/Data/MXRoomMember.h
/* Copyright 2014 OpenMarket Ltd 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. */ #import <Foundation/Foundation.h> #import "MXEvent.h" #import "MXEnumConstants.h" /** `MXRoomMember` is the information about a user in a room. */ @interface MXRoomMember : NSObject /** The user id. */ @property (nonatomic, readonly) NSString *userId; /** The user display name as provided by the home sever. */ @property (nonatomic, readonly) NSString *displayname; /** The url of the avatar of the user. */ @property (nonatomic) NSString *avatarUrl; /** The membership state. */ @property (nonatomic, readonly) MXMembership membership; /** The previous membership state. */ @property (nonatomic, readonly) MXMembership prevMembership; /** The id of the user that made the last change on this member membership. */ @property (nonatomic, readonly) NSString *originUserId; /** If the m.room.member event is the successor of a m.room.third_party_invite event, 'thirdPartyInviteToken' is the token of this event. Else, nil. */ @property (nonatomic, readonly) NSString *thirdPartyInviteToken; /** The event used to build the MXRoomMember. */ @property (nonatomic, readonly) MXEvent *originalEvent; /** Create the room member from a Matrix room member event. @param roomMemberEvent The MXEvent room member event. */ - (instancetype)initWithMXEvent:(MXEvent*)roomMemberEvent; /** Create the room member from a Matrix room member event by specifying the content to use. MXEvents come with content and prev_content data. According to the situation, we may want to create an MXRoomMember from content or from prev_content. The method returns nil if the roomMemberEvent indicates that the user is not part of the room. @param roomMemberEvent The MXEvent room member event. @param roomMemberEventContent roomMemberEvent.content or roomMemberEvent.prevContent */ - (instancetype)initWithMXEvent:(MXEvent*)roomMemberEvent andEventContent:(NSDictionary<NSString *, id>*)roomMemberEventContent; @end
lucasfeijo/matrix-ios-sdk
MatrixSDK/Utils/MXBugReportRestClient.h
/* Copyright 2017 Vector Creations Ltd 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. */ #import <Foundation/Foundation.h> /** Call states. */ typedef enum : NSUInteger { // The `MXBugReportRestClient` instance is ready to send a bug report MXBugReportStateReady, // Log files are being zipped MXBugReportStateProgressZipping, // Bug report data is being sent MXBugReportStateProgressUploading } MXBugReportState; /** `MXBugReportRestClient` allows to report bugs. Bug reports are sent to the bugreport API (https://github.com/matrix-org/rageshake). It purposefully does not use Matrix as bug reports may be made when Matrix is not responsive (which may be the cause of the bug). */ @interface MXBugReportRestClient : NSObject /** The state of the instance. */ @property (nonatomic, readonly) MXBugReportState state; /** Create an instance based on an endpoint url. @param bugReportEndpoint the endpoint URL. @return a MXBugReportRestClient instance. */ - (nonnull instancetype)initWithBugReportEndpoint:(NSString *)bugReportEndpoint; /** Send a bug report. Note that only one submission can be done at a time. @param text the bug description. @param sendLogs flag to indicate to attached log files or not. @param sendCrashLog flag to indicate to attached crash log or not. @param files a list of local files to send. Their extension must be "jpg", "png" or "txt". @param gitHubLabels labels to attach to the created GitHub issue. @param progress A block object called to indicate the progress in the step of MXBugReportStateProgressZipping or MXBugReportStateProgressUploading. @param success A block object called when the operation succeeds. @param failure A block object called when the operation fails. */ - (void)sendBugReport:(NSString*)text sendLogs:(BOOL)sendLogs sendCrashLog:(BOOL)sendCrashLog sendFiles:(NSArray<NSURL*>*)files attachGitHubLabels:(NSArray<NSString*>*)gitHubLabels progress:(void (^)(MXBugReportState state, NSProgress *progress))progress success:(void (^)(NSString *reportUrl))success failure:(void (^)(NSError *error))failure; /** Interrupt any current operation. */ - (void)cancel; #pragma mark - Information sent with each bug report /** The app name. */ @property (nonatomic) NSString *appName; /** The app version. */ @property (nonatomic) NSString *version; /** The app build number. */ @property (nonatomic) NSString *build; /** The app user agent. Default is "iOS" or "MacOS". */ @property (nonatomic) NSString *userAgent; /** The device we are running. Default is UIDevice.model. */ @property (nonatomic) NSString *deviceModel; /** The OS name and version used by the device. */ @property (nonatomic) NSString *deviceOS; /** Additional custom information to send to the bug report API. */ @property (nonatomic) NSDictionary<NSString*, NSString*> *others; @end
lucasfeijo/matrix-ios-sdk
MatrixSDK/Data/Store/MXFileStore/MXFileStoreMetaData.h
/* Copyright 2014 OpenMarket Ltd 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. */ #import <Foundation/Foundation.h> #import "MXWellKnown.h" #import "MXCapabilities.h" #import "MXMatrixVersions.h" @interface MXFileStoreMetaData : NSObject <NSCoding, NSCopying> /** The home server name. */ @property (nonatomic) NSString *homeServer; /** The obtained user id. */ @property (nonatomic) NSString *userId; /** The token indicating from where to start listening event stream to get live events. */ @property (nonatomic) NSString *eventStreamToken; /** The id of the filter being used in /sync requests. */ @property (nonatomic) NSString *syncFilterId; /** The current version of the store. */ @property (nonatomic) NSUInteger version; /** User account data */ @property (nonatomic) NSDictionary *userAccountData; /** State of agreement to the identity server's terms of service. */ @property (nonatomic) BOOL areAllIdentityServerTermsAgreed; /** The homeserver .well-known. */ @property (nonatomic) MXWellKnown *homeserverWellknown; /** The homeserver capabilities. */ @property (nonatomic) MXCapabilities *homeserverCapabilities; /** Supported Matrix versions. */ @property (nonatomic) MXMatrixVersions *supportedMatrixVersions; /** The maximum size an upload can be in bytes. */ @property (nonatomic) NSInteger maxUploadSize; @end
lucasfeijo/matrix-ios-sdk
MatrixSDK/Data/EventsEnumerator/MXEventsEnumeratorOnArray.h
/* Copyright 2016 OpenMarket Ltd 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. */ #import <Foundation/Foundation.h> #import "MXEventsEnumerator.h" /** Data source which provides the most up-to-date event to an enumerator based on the event identifier. */ @protocol MXEventsEnumeratorDataSource - (MXEvent *)eventWithEventId:(NSString *)eventId; @end /** Generic events enumerator on an array of event identifiers that are translated to events on demand. */ @interface MXEventsEnumeratorOnArray : NSObject <MXEventsEnumerator> /** Construct an enumerator based on an array of event identifiers. @param eventIds the list of event identifiers to enumerate. The order is chronological where the first item is the oldest event @param dataSource object responsible for translating an event identifier into the most recent version of the event. @return the newly created instance. */ - (instancetype)initWithEventIds:(NSArray<NSString *> *)eventIds dataSource:(id<MXEventsEnumeratorDataSource>)dataSource; @end
lucasfeijo/matrix-ios-sdk
MatrixSDK/JSONModels/MXRoomAliasResolution.h
// // MXRoomAliasResolution.h // Pods // // Created by Element on 28/03/2022. // #ifndef MXRoomAliasResolution_h #define MXRoomAliasResolution_h #import "MXJSONModel.h" /** The result of a server resolving a room alias via /directory/room/ endpoint into a cannonical identifier with servers that are aware of this identifier. */ @interface MXRoomAliasResolution : MXJSONModel /** Resolved room identifier that matches a given alias */ @property (nonatomic, strong) NSString *roomId; /** A list of servers that are aware of the room identifier. */ @property (nonatomic, strong) NSArray<NSString *> *servers; @end #endif /* MXRoomAliasResolution_h */
lucasfeijo/matrix-ios-sdk
MatrixSDK/Data/EventsEnumerator/MXEventsEnumerator.h
<gh_stars>0 /* Copyright 2016 OpenMarket Ltd 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. */ #import "MXEvent.h" /** The `MXEventsEnumerator` protocol defines an interface that must be implemented in order to iterate on a list of events. This interface is used in the MXStore to manage the results of requests on the store database. The `MXEventsEnumerator` implementation must start the iteration on the most recent events of the list. */ @protocol MXEventsEnumerator <NSObject> /** Return next events in the enumerator. @param eventsCount the number of events to get. @param threadId identifier of the thread, to get next events from. Pass nil not to filter by a thread. @return an array of events in chronological order. Nil if there is no more events. Number of returned events may be higher than `eventsCount` if `threadId` not provided. */ - (NSArray<MXEvent*>*)nextEventsBatch:(NSUInteger)eventsCount threadId:(NSString *)threadId; /** The next event in the enumerator. Nil if there is no more events. */ @property (nonatomic, readonly) MXEvent *nextEvent; /** The number of events that still remain to get from this enumerator. @discussion For performance reason, the value may be not garanteed when the enumarator is done on a filtered list of events. In this case, the implementation returns NSUIntegerMax. */ @property (nonatomic, readonly) NSUInteger remaining; @end
lucasfeijo/matrix-ios-sdk
MatrixSDK/Data/EventsEnumerator/MXEventsByTypesEnumeratorOnArray.h
/* Copyright 2016 OpenMarket Ltd Copyright 2017 Vector Creations Ltd 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. */ #import <Foundation/Foundation.h> #import "MXEventsEnumerator.h" #import "MXEventsEnumeratorOnArray.h" /** Generic events enumerator on an array of event identifiers with a filter on events types. */ @interface MXEventsByTypesEnumeratorOnArray : NSObject <MXEventsEnumerator> /** Construct an enumerator based on an array of event identifiers. @param messages the list of messages to enumerate on. @param types an array of event types strings to use as a filter filter. @param dataSource object responsible for translating an event identifier into the most recent version of the event. @return the newly created instance. */ - (instancetype)initWithEventIds:(NSArray<NSString *> *)eventIds andTypesIn:(NSArray*)types dataSource:(id<MXEventsEnumeratorDataSource>)dataSource; @end
cztk/enet
address.c
<gh_stars>1-10 /** @file list.c @brief ENet linked list functions */ #define ENET_BUILDING_LIB 1 #include "enet/enet.h" #include <stdio.h> #include <string.h> // http://rosettacode.org/wiki/Parse_an_IP_Address#C static unsigned int _parseDecimal ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' ) { //shift digit in nVal *= 10; nVal += chNow - '0'; ++*pchCursor; } return nVal; } static unsigned int _parseHex ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor & 0x5f, //(collapses case, but mutilates digits) (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || (chNow >= 'A' && chNow <= 'F') ) { unsigned char nybbleValue; chNow -= 0x10; //scootch digital values down; hex now offset by x31 nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow ); //shift nybble in nVal <<= 4; nVal += nybbleValue; ++*pchCursor; } return nVal; } //Parse a textual IPv4 or IPv6 address, optionally with port, into a binary //array (for the address, in network order), and an optionally provided port. //Also, indicate which of those forms (4 or 6) was parsed. Return true on //success. ppszText must be a nul-terminated ASCII string. It will be //updated to point to the character which terminated parsing (so you can carry //on with other things. abyAddr must be 16 bytes. You can provide NULL for //abyAddr, nPort, bIsIPv6, if you are not interested in any of those //informations. If we request port, but there is no port part, then nPort will //be set to 0. There may be no whitespace leading or internal (though this may //be used to terminate a successful parse. //Note: the binary address and integer port are in network order. static int ParseIPv4OrIPv6 ( const char** ppszText, enet_uint8* abyAddr, enet_uint16* pnPort, int* pbIsIPv6 ) { unsigned char* abyAddrLocal; unsigned char abyDummyAddr[16]; //find first colon, dot, and open bracket const char* pchColon = strchr ( *ppszText, ':' ); const char* pchDot = strchr ( *ppszText, '.' ); const char* pchOpenBracket = strchr ( *ppszText, '[' ); const char* pchCloseBracket = NULL; //we'll consider this to (probably) be IPv6 if we find an open //bracket, or an absence of dots, or if there is a colon, and it //precedes any dots that may or may not be there int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot || ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) ); //OK, now do a little further sanity check our initial guess... if ( bIsIPv6local ) { //if open bracket, then must have close bracket that follows somewhere pchCloseBracket = strchr ( *ppszText, ']' ); if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket || pchCloseBracket < pchOpenBracket ) ) return 0; } else //probably ipv4 { //dots must exist, and precede any colons if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) ) return 0; } //we figured out this much so far.... if ( NULL != pbIsIPv6 ) *pbIsIPv6 = bIsIPv6local; //especially for IPv6 (where we will be decompressing and validating) //we really need to have a working buffer even if the caller didn't //care about the results. abyAddrLocal = abyAddr; //prefer to use the caller's if ( NULL == abyAddrLocal ) //but use a dummy if we must abyAddrLocal = abyDummyAddr; //OK, there should be no correctly formed strings which are miscategorized, //and now any format errors will be found out as we continue parsing //according to plan. if ( ! bIsIPv6local ) //try to parse as IPv4 { //4 dotted quad decimal; optional port if there is a colon //since there are just 4, and because the last one can be terminated //differently, I'm just going to unroll any potential loop. unsigned char* pbyAddrCursor = abyAddrLocal; unsigned int nVal; const char* pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); //get first val if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) //must be in range and followed by dot and nonempty return 0; *(pbyAddrCursor++) = (unsigned char) nVal; //stick it in addr ++(*ppszText); //past the dot pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); //get second val if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); //past the dot pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); //get third val if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); //past the dot pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); //get fourth val if ( nVal > 255 || pszTextBefore == *ppszText ) //(we can terminate this one in several ways) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it { ++(*ppszText); //past the colon pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; *pnPort = (enet_uint16) nVal; return 1; } else //finished just with ip address { if ( NULL != pnPort ) *pnPort = 0; //indicate we have no port part return 1; } } else //try to parse as IPv6 { unsigned char* pbyAddrCursor; unsigned char* pbyZerosLoc; int bIPv4Detected; int nIdx; //up to 8 16-bit hex quantities, separated by colons, with at most one //empty quantity, acting as a stretchy run of zeroes. optional port //if there are brackets followed by colon and decimal port number. //A further form allows an ipv4 dotted quad instead of the last two //16-bit quantities, but only if in the ipv4 space fdf8:f53e:61e4::18:x:x . if ( NULL != pchOpenBracket ) //start past the open bracket, if it exists *ppszText = pchOpenBracket + 1; pbyAddrCursor = abyAddrLocal; pbyZerosLoc = NULL; //if we find a 'zero compression' location bIPv4Detected = 0; for ( nIdx = 0; nIdx < 8; ++nIdx ) //we've got up to 8 of these, so we will use a loop { const char* pszTextBefore = *ppszText; unsigned nVal =_parseHex ( ppszText ); //get value; these are hex if ( pszTextBefore == *ppszText ) //if empty, we are zero compressing; note the loc { if ( NULL != pbyZerosLoc ) //there can be only one! { //unless it's a terminal empty field, then this is OK, it just means we're done with the host part if ( pbyZerosLoc == pbyAddrCursor ) { --nIdx; break; } return 0; //otherwise, it's a format error } if ( ':' != **ppszText ) //empty field can only be via : return 0; if ( 0 == nIdx ) //leading zero compression requires an extra peek, and adjustment { ++(*ppszText); if ( ':' != **ppszText ) return 0; } pbyZerosLoc = pbyAddrCursor; ++(*ppszText); } else { if ( '.' == **ppszText ) //special case of ipv4 convenience notation { //who knows how to parse ipv4? we do! const char* pszTextlocal = pszTextBefore; //back it up unsigned char abyAddrlocal[16]; int bIsIPv6local; int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local ); *ppszText = pszTextlocal; //success or fail, remember the terminating char if ( ! bParseResultlocal || bIsIPv6local ) //must parse and must be ipv4 return 0; //transfer addrlocal into the present location *(pbyAddrCursor++) = abyAddrlocal[0]; *(pbyAddrCursor++) = abyAddrlocal[1]; *(pbyAddrCursor++) = abyAddrlocal[2]; *(pbyAddrCursor++) = abyAddrlocal[3]; ++nIdx; //pretend like we took another short, since the ipv4 effectively is two shorts bIPv4Detected = 1; //remember how we got here for further validation later break; //totally done with address } if ( nVal > 65535 ) //must be 16 bit quantity return 0; *(pbyAddrCursor++) = nVal >> 8; //transfer in network order *(pbyAddrCursor++) = nVal & 0xff; if ( ':' == **ppszText ) //typical case inside; carry on { ++(*ppszText); } else //some other terminating character; done with this parsing parts { break; } } } //handle any zero compression we found if ( NULL != pbyZerosLoc ) { int nHead = (int)( pbyZerosLoc - abyAddrLocal ); //how much before zero compression int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); //how much after zero compression int nZeros = 16 - nTail - nHead; //how much zeros memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); //scootch stuff down memset ( pbyZerosLoc, 0, nZeros ); //clear the compressed zeros } //validation of ipv4 subspace ::ffff:x.x if ( bIPv4Detected ) { static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff }; if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) ) return 0; } //close bracket if ( NULL != pchOpenBracket ) { if ( ']' != **ppszText ) return 0; ++(*ppszText); } if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it { const char* pszTextBefore; unsigned int nVal; ++(*ppszText); //past the colon pszTextBefore = *ppszText; pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; *pnPort = (enet_uint16) nVal; return 1; } else //finished just with ip address { if ( NULL != pnPort ) *pnPort = 0; //indicate we have no port part return 1; } } } int enet_address_equal_host(const ENetAddress * firstAddress, const ENetAddress * secondAddress) { if (firstAddress->type != secondAddress->type) return 0; if (firstAddress->port != secondAddress->port) return 0; if (firstAddress->type == ENET_ADDRESS_TYPE_IPV4) { if (memcmp(&firstAddress->host.v4[0], &secondAddress->host.v4[0], 4*sizeof(enet_uint8)) != 0) return 0; } else if (firstAddress->type == ENET_ADDRESS_TYPE_IPV6) { if (memcmp(&firstAddress->host.v6[0], &secondAddress->host.v6[0], 8 * sizeof(enet_uint16)) != 0) return 0; } return 1; } int enet_address_equal(const ENetAddress * firstAddress, const ENetAddress * secondAddress) { if (!enet_address_equal_host(firstAddress, secondAddress)) return 0; if (firstAddress->port != secondAddress->port) return 0; return 1; } int enet_address_is_any(const ENetAddress * address) { switch (address->type) { case ENET_ADDRESS_TYPE_IPV4: { enet_uint8 zero[4] = { 0 }; return memcmp(&address->host.v4[0], zero, 4 * sizeof(enet_uint8)) != 0; } case ENET_ADDRESS_TYPE_IPV6: { enet_uint16 zero[8] = { 0 }; return memcmp(&address->host.v6[0], zero, 8 * sizeof(enet_uint16)) != 0; } default: break; } return 0; } int enet_address_is_broadcast(const ENetAddress * address) { /* there's no broadcast address in ipv6 */ if (address->type == ENET_ADDRESS_TYPE_IPV4 && address->host.v4[0] == 0xFF && address->host.v4[1] == 0xFF && address->host.v4[2] == 0xFF && address->host.v4[3] == 0xFF) { return 1; } return 0; } int enet_address_is_loopback(const ENetAddress * address) { switch (address->type) { case ENET_ADDRESS_TYPE_IPV4: return address->host.v4[0] == 127; case ENET_ADDRESS_TYPE_IPV6: { enet_uint16 loopback[8] = { 0, 0, 0, 0, 0, 0, 0, 1 }; return memcmp(&address->host.v6[0], loopback, 8 * sizeof(enet_uint16)) != 0; } default: break; } return 0; } int enet_address_get_host_ip (const ENetAddress * address, char * name, size_t nameLength) { enum MaxSize { MS_PortPart = 1 + 4, /* semicolon + 4 digits */ MS_IPv4 = 4 * 3 + 3 + 1, /* 4 * 3 digits plus three dots plus end of string character */ MS_IPv4MappedIPv6 = 7 + 4 * 3 + 3 + 1, /* prefix + 4 * 3 digits plus three dots plus end of string character */ MS_IPv6 = 8 * 4 + 7 + 1, /* 4 * 3 digits plus three dots plus end of string character */ MS_IPv4WithPort = MS_IPv4 + MS_PortPart, MS_IPv4MappedIPv6WithPort = MS_IPv4MappedIPv6 + MS_PortPart + 2, /* plus two brackets */ MS_IPv6WithPort = MS_IPv6 + MS_PortPart + 2, /* plus two brackets */ }; if (address -> type == ENET_ADDRESS_TYPE_IPV4) { if (address->port != 0) { if (nameLength < MS_IPv4WithPort) return -1; sprintf(name, "%u.%u.%u.%u:%u", address->host.v4[0], address->host.v4[1], address->host.v4[2], address->host.v4[3], address->port); } else { if (nameLength < MS_IPv4) return -1; sprintf(name, "%u.%u.%u.%u", address->host.v4[0], address->host.v4[1], address->host.v4[2], address->host.v4[3]); } } else if (address->type == ENET_ADDRESS_TYPE_IPV6) { /* check if ipv4-mapped address */ if (address -> host.v6[0] == 0 && address -> host.v6[1] == 0 && address -> host.v6[2] == 0 && address -> host.v6[3] == 0 && address -> host.v6[4] == 0 && address -> host.v6[5] == 0xFFFF) { if (address->port != 0) { if (nameLength < MS_IPv4MappedIPv6WithPort) return -1; sprintf(name, "[::ffff:%u.%u.%u.%u]:%u", (address->host.v6[6] >> 8) & 0xFF, (address->host.v6[6] >> 0) & 0xFF, (address->host.v6[7] >> 8) & 0xFF, (address->host.v6[7] >> 0) & 0xFF, address->port); } else { if (nameLength < MS_IPv4MappedIPv6) return -1; sprintf(name, "::ffff:%u.%u.%u.%u", (address->host.v6[6] >> 8) & 0xFF, (address->host.v6[6] >> 0) & 0xFF, (address->host.v6[7] >> 8) & 0xFF, (address->host.v6[7] >> 0) & 0xFF); } } else { /* standard IPv6 * canonical representation of an IPv6 * https://tools.ietf.org/html/rfc5952 */ const size_t maxSize = 8 * 4 + 7 + 1; /* 4 * 3 digits plus three dots plus end of string character */ char buffer[MS_IPv6WithPort]; /* find the longest zero sequence */ int f0 = -1; int l0 = -1; int i, j; char* p = buffer; int advance; for (i = 0; i < 8; ++i) { if (address -> host.v6[i] == 0) { for (j = i + 1; j < 8; ++j) { if (address -> host.v6[j] != 0) break; } if (f0 == -1 || j - i > l0 - f0) { f0 = i; l0 = j; } } } /* We need brackets around our IPv6 address if we have a port */ if (address->port != 0) *p++ = '['; for (i = 0; i < 8; ++i) { if (i == f0) { *p++ = ':'; *p++ = ':'; i = l0; if (i >= 8) break; } else if (i != 0) *p++ = ':'; advance = sprintf(p, "%x", address -> host.v6[i]); p += advance; } if (address->port != 0) { *p++ = ']'; *p++ = ':'; advance = sprintf(p, "%u", address->port); p += advance; } *p = '\0'; size_t addrLen = p - buffer; if (nameLength < addrLen) return -1; memcpy(name, buffer, addrLen); } } return 0; } int enet_address_set_host_ip (ENetAddress * address, const char * name) { enet_uint8 result[16]; int isIPv6; int i; enet_uint16 port; if (!ParseIPv4OrIPv6(&name, result, &port, &isIPv6)) return -1; if (isIPv6) { address->type = ENET_ADDRESS_TYPE_IPV6; for (i = 0; i < 8; ++i) address->host.v6[i] = (result[i * 2] << 8) | result[i * 2 + 1]; } else { address->type = ENET_ADDRESS_TYPE_IPV4; for (i = 0; i < 4; ++i) address->host.v4[i] = result[i]; } if (port) address->port = port; return 0; } void enet_address_build_any(ENetAddress * address, ENetAddressType type) { address->type = type; switch (type) { case ENET_ADDRESS_TYPE_IPV4: { memset(&address->host.v4, 0, sizeof(address->host.v4)); address->port = ENET_PORT_ANY; break; } case ENET_ADDRESS_TYPE_IPV6: { memset(&address->host.v6, 0, sizeof(address->host.v6)); address->port = ENET_PORT_ANY; break; } default: break; } } void enet_address_build_loopback(ENetAddress * address, ENetAddressType type) { address->type = type; switch (type) { case ENET_ADDRESS_TYPE_IPV4: { enet_uint8 loopbackIpV4[4] = { 127, 0, 0, 1 }; memcpy(&address->host.v4, loopbackIpV4, sizeof(address->host.v4)); address->port = ENET_PORT_ANY; break; } case ENET_ADDRESS_TYPE_IPV6: { enet_uint16 loopbackIpV6[8] = { 0, 0, 0, 0, 0, 0, 0, 1 }; memcpy(&address->host.v6, loopbackIpV6, sizeof(address->host.v6)); address->port = ENET_PORT_ANY; break; } default: break; } } void enet_address_convert_ipv6(ENetAddress * address) { enet_uint8 ipv4[4]; if (address->type == ENET_ADDRESS_TYPE_IPV4) { /* Turn into IPv4-mapped IPv6 */ address->type = ENET_ADDRESS_TYPE_IPV6; memcpy(&ipv4[0], &address->host.v4[0], 4 * sizeof(enet_uint8)); /* save IPv4 before modifying the IPv6 because of the union */ address->host.v6[0] = 0; address->host.v6[1] = 0; address->host.v6[2] = 0; address->host.v6[3] = 0; address->host.v6[4] = 0; address->host.v6[5] = 0xFFFF; address->host.v6[6] = ((enet_uint16) ipv4[0]) << 8 | ipv4[1]; address->host.v6[7] = ((enet_uint16) ipv4[2]) << 8 | ipv4[3]; } } /** @} */
cztk/enet
unix.c
<filename>unix.c /** @file unix.c @brief ENet Unix system specific functions */ #ifndef _WIN32 #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/time.h> #include <netinet/tcp.h> #include <netdb.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <time.h> #define ENET_BUILDING_LIB 1 #include "enet/enet.h" #ifdef __APPLE__ #ifdef HAS_POLL #undef HAS_POLL #endif #ifndef HAS_FCNTL #define HAS_FCNTL 1 #endif #ifndef HAS_INET_PTON #define HAS_INET_PTON 1 #endif #ifndef HAS_INET_NTOP #define HAS_INET_NTOP 1 #endif #ifndef HAS_MSGHDR_FLAGS #define HAS_MSGHDR_FLAGS 1 #endif #ifndef HAS_SOCKLEN_T #define HAS_SOCKLEN_T 1 #endif #ifndef HAS_GETADDRINFO #define HAS_GETADDRINFO 1 #endif #ifndef HAS_GETNAMEINFO #define HAS_GETNAMEINFO 1 #endif #endif #ifdef HAS_FCNTL #include <fcntl.h> #endif #ifdef HAS_POLL #include <poll.h> #endif #if !defined(HAS_SOCKLEN_T) && !defined(__socklen_t_defined) typedef int socklen_t; #endif #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif static enet_uint32 timeBase = 0; static int addressFamily[] = { AF_UNSPEC, //< ENET_ADDRESS_TYPE_ANY AF_INET, //< ENET_ADDRESS_TYPE_IPV4 AF_INET6 //< ENET_ADDRESS_TYPE_IPV6 }; static int enet_address_from_sock_addr4(ENetAddress * address, const struct sockaddr_in* sockAddr) { address->type = ENET_ADDRESS_TYPE_IPV4; address->port = ENET_NET_TO_HOST_16(sockAddr->sin_port); memcpy(&address->host.v4[0], &sockAddr->sin_addr.s_addr, 4 * sizeof(enet_uint8)); return 0; } static int enet_address_from_sock_addr6(ENetAddress * address, const struct sockaddr_in6* sockAddr) { int i; address->type = ENET_ADDRESS_TYPE_IPV6; address->port = ENET_NET_TO_HOST_16(sockAddr->sin6_port); for (i = 0; i < 8; ++i) address->host.v6[i] = ((enet_uint16) sockAddr->sin6_addr.s6_addr[i * 2]) << 8 | sockAddr->sin6_addr.s6_addr[i * 2 + 1]; return 0; } static int enet_address_from_addr_info(ENetAddress * address, const struct addrinfo * info) { switch (info->ai_family) { case AF_INET: return enet_address_from_sock_addr4(address, (struct sockaddr_in*) info->ai_addr); case AF_INET6: return enet_address_from_sock_addr6(address, (struct sockaddr_in6*) info->ai_addr); default: return -1; } } static int enet_address_from_sock_addr(ENetAddress * address, const struct sockaddr * sockAddr) { switch (sockAddr->sa_family) { case AF_INET: return enet_address_from_sock_addr4(address, (struct sockaddr_in*) sockAddr); case AF_INET6: return enet_address_from_sock_addr6(address, (struct sockaddr_in6*) sockAddr); default: return -1; } } static int enet_address_to_sock_addr(const ENetAddress * address, void * sockAddr) { switch (address->type) { case ENET_ADDRESS_TYPE_IPV4: { struct sockaddr_in* socketAddress = (struct sockaddr_in*) sockAddr; int addr; memset(socketAddress, 0, sizeof(struct sockaddr_in)); socketAddress->sin_family = AF_INET; socketAddress->sin_port = ENET_HOST_TO_NET_16(address->port); addr = ((unsigned int) address->host.v4[0]) << 24 | ((unsigned int) address->host.v4[1]) << 16 | ((unsigned int) address->host.v4[2]) << 8 | ((unsigned int) address->host.v4[3]) << 0; socketAddress->sin_addr.s_addr = htonl(addr); return sizeof(struct sockaddr_in); } case ENET_ADDRESS_TYPE_IPV6: { struct sockaddr_in6* socketAddress = (struct sockaddr_in6*) sockAddr; int i; memset(socketAddress, 0, sizeof(struct sockaddr_in6)); socketAddress->sin6_family = AF_INET6; socketAddress->sin6_port = ENET_HOST_TO_NET_16(address->port); for (i = 0; i < 8; ++i) { u_short addressPart = ENET_HOST_TO_NET_16(address->host.v6[i]); socketAddress->sin6_addr.s6_addr[i * 2 + 0] = addressPart >> 0; socketAddress->sin6_addr.s6_addr[i * 2 + 1] = addressPart >> 8; } return sizeof(struct sockaddr_in6); } default: return 0; } } int enet_initialize (void) { return 0; } void enet_deinitialize (void) { } enet_uint32 enet_host_random_seed (void) { return (enet_uint32) time (NULL); } enet_uint32 enet_time_get (void) { struct timeval timeVal; gettimeofday (& timeVal, NULL); return timeVal.tv_sec * 1000 + timeVal.tv_usec / 1000 - timeBase; } void enet_time_set (enet_uint32 newTimeBase) { struct timeval timeVal; gettimeofday (& timeVal, NULL); timeBase = timeVal.tv_sec * 1000 + timeVal.tv_usec / 1000 - newTimeBase; } int enet_address_set_host (ENetAddress * address, ENetAddressType type, const char * name) { #ifdef HAS_GETADDRINFO struct addrinfo hints; struct addrinfo* result; struct addrinfo* resultList = NULL; enet_uint16 port; ENetAddress tempAddress; int bestScore = -1; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; if (getaddrinfo(name, NULL, &hints, &resultList) != 0) return -1; port = address->port; /* preserve port */ for (result = resultList; result != NULL; result = result->ai_next) { if (result->ai_addr != NULL) { if (enet_address_from_addr_info(&tempAddress, result) == 0) { tempAddress.port = port; /* preserve port */ int addressScore = 0; if (type == ENET_ADDRESS_TYPE_ANY) { if (tempAddress.type == ENET_ADDRESS_TYPE_IPV6) addressScore += 10; else if (tempAddress.type == ENET_ADDRESS_TYPE_IPV4) { /* ANY basically means IPv6 with support for IPv4, but we still have to map our IPv4 to IPv6 */ addressScore += 5; enet_address_convert_ipv6(&tempAddress); } } else if (tempAddress.type == type) addressScore += 10; if (addressScore > bestScore) { memcpy(address, &tempAddress, sizeof(ENetAddress)); bestScore = addressScore; } } } } if (resultList != NULL) freeaddrinfo(resultList); if (bestScore >= 0) return 0; #else struct hostent * hostEntry = NULL; #ifdef HAS_GETHOSTBYNAME_R struct hostent hostData; char buffer [2048]; int errnum; #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & hostEntry, & errnum); #else hostEntry = gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & errnum); #endif #else hostEntry = gethostbyname (name); #endif /* TODO */ /*if (hostEntry != NULL && hostEntry -> h_addrtype == AF_INET) { address -> host = * (enet_uint32 *) hostEntry -> h_addr_list [0]; return 0; }*/ #endif if (enet_address_set_host_ip(address, name) == 0) { if (type == ENET_ADDRESS_TYPE_ANY) enet_address_convert_ipv6(address); return 0; } else return -1; } int enet_address_get_host (const ENetAddress * address, char * name, size_t nameLength) { unsigned char sockAddrBuf[sizeof(struct sockaddr_in6)]; int socketAddressLen = enet_address_to_sock_addr(address, sockAddrBuf); #ifdef HAS_GETNAMEINFO int err; err = getnameinfo ((struct sockaddr *) sockAddrBuf, socketAddressLen, name, nameLength, NULL, 0, NI_NAMEREQD); if (! err) { if (name != NULL && nameLength > 0 && ! memchr (name, '\0', nameLength)) return -1; return 0; } if (err != EAI_NONAME) return -1; #else struct in_addr in; struct hostent * hostEntry = NULL; #ifdef HAS_GETHOSTBYADDR_R struct hostent hostData; char buffer [2048]; int errnum; #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) gethostbyaddr_r ((char *) sockAddrBuf, socketAddressLen, addressFamily[address->type], & hostData, buffer, sizeof (buffer), & hostEntry, & errnum); #else hostEntry = gethostbyaddr_r ((char *) sockAddrBuf, socketAddressLen, addressFamily[address->type], & hostData, buffer, sizeof (buffer), & errnum); #endif #else hostEntry = gethostbyaddr ((char *) sockAddrBuf, socketAddressLen, addressFamily[address->type]); #endif if (hostEntry != NULL) { size_t hostLen = strlen (hostEntry -> h_name); if (hostLen >= nameLength) return -1; memcpy (name, hostEntry -> h_name, hostLen + 1); return 0; } #endif return enet_address_get_host_ip (address, name, nameLength); } int enet_socket_bind (ENetSocket socket, const ENetAddress * address) { unsigned char sockAddrBuf[sizeof(struct sockaddr_in6)]; int socketAddressLen = enet_address_to_sock_addr(address, sockAddrBuf); return bind(socket, (struct sockaddr *) sockAddrBuf, socketAddressLen); } int enet_socket_get_address (ENetSocket socket, ENetAddress * address) { unsigned char sockAddrBuf[sizeof(struct sockaddr_in6)] = { 0 }; int bufferLength; if (getsockname(socket, (struct sockaddr *) sockAddrBuf, &bufferLength) == -1) return -1; return enet_address_from_sock_addr(address, (struct sockaddr *) sockAddrBuf); } int enet_socket_listen (ENetSocket socket, int backlog) { return listen (socket, backlog < 0 ? SOMAXCONN : backlog); } ENetSocket enet_socket_create (ENetAddressType addressType, ENetSocketType socketType) { return socket(addressType == ENET_ADDRESS_TYPE_IPV4 ? PF_INET : PF_INET6, socketType == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0); } int enet_socket_set_option (ENetSocket socket, ENetSocketOption option, int value) { int result = -1; switch (option) { case ENET_SOCKOPT_NONBLOCK: #ifdef HAS_FCNTL result = fcntl (socket, F_SETFL, (value ? O_NONBLOCK : 0) | (fcntl (socket, F_GETFL) & ~O_NONBLOCK)); #else result = ioctl (socket, FIONBIO, & value); #endif break; case ENET_SOCKOPT_BROADCAST: result = setsockopt (socket, SOL_SOCKET, SO_BROADCAST, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_REUSEADDR: result = setsockopt (socket, SOL_SOCKET, SO_REUSEADDR, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_RCVBUF: result = setsockopt (socket, SOL_SOCKET, SO_RCVBUF, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_SNDBUF: result = setsockopt (socket, SOL_SOCKET, SO_SNDBUF, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_RCVTIMEO: { struct timeval timeVal; timeVal.tv_sec = value / 1000; timeVal.tv_usec = (value % 1000) * 1000; result = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) & timeVal, sizeof (struct timeval)); break; } case ENET_SOCKOPT_SNDTIMEO: { struct timeval timeVal; timeVal.tv_sec = value / 1000; timeVal.tv_usec = (value % 1000) * 1000; result = setsockopt (socket, SOL_SOCKET, SO_SNDTIMEO, (char *) & timeVal, sizeof (struct timeval)); break; } case ENET_SOCKOPT_NODELAY: result = setsockopt (socket, IPPROTO_TCP, TCP_NODELAY, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_IPV6ONLY: result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char *) & value, sizeof(int)); break; default: break; } return result == -1 ? -1 : 0; } int enet_socket_get_option (ENetSocket socket, ENetSocketOption option, int * value) { int result = -1; socklen_t len; switch (option) { case ENET_SOCKOPT_ERROR: len = sizeof (int); result = getsockopt (socket, SOL_SOCKET, SO_ERROR, value, & len); break; default: break; } return result == -1 ? -1 : 0; } int enet_socket_connect (ENetSocket socket, const ENetAddress * address) { unsigned char sockAddrBuf[sizeof(struct sockaddr_in6)]; int socketAddressLen = enet_address_to_sock_addr(address, sockAddrBuf); int result; result = connect(socket, (struct sockaddr*) sockAddrBuf, socketAddressLen); if (result == -1 && errno == EINPROGRESS) return 0; return result; } ENetSocket enet_socket_accept (ENetSocket socket, ENetAddress * address) { int result; unsigned char sockAddrBuf[sizeof(struct sockaddr_in6)] = { 0 }; int socketAddressLen = sizeof(sockAddrBuf); result = accept (socket, address != NULL ? (struct sockaddr*) sockAddrBuf : NULL, address != NULL ? & socketAddressLen : NULL); if (result == -1) return ENET_SOCKET_NULL; if (address != NULL) { if (enet_address_from_sock_addr(address, (struct sockaddr*) sockAddrBuf) != 0) return ENET_SOCKET_NULL; } return result; } int enet_socket_shutdown (ENetSocket socket, ENetSocketShutdown how) { return shutdown (socket, (int) how); } void enet_socket_destroy (ENetSocket socket) { if (socket != -1) close (socket); } int enet_socket_send (ENetSocket socket, const ENetAddress * address, const ENetBuffer * buffers, size_t bufferCount) { unsigned char sockAddrBuf[sizeof(struct sockaddr_in6)]; struct msghdr msgHdr; int sentLength; memset (& msgHdr, 0, sizeof (struct msghdr)); if (address != NULL) { msgHdr.msg_namelen = enet_address_to_sock_addr(address, sockAddrBuf); if (msgHdr.msg_namelen == 0) return -1; msgHdr.msg_name = (struct sockaddr *) sockAddrBuf; } msgHdr.msg_iov = (struct iovec *) buffers; msgHdr.msg_iovlen = bufferCount; sentLength = sendmsg (socket, & msgHdr, MSG_NOSIGNAL); if (sentLength == -1) { if (errno == EWOULDBLOCK) return 0; return -1; } return sentLength; } int enet_socket_receive (ENetSocket socket, ENetAddress * address, ENetBuffer * buffers, size_t bufferCount) { unsigned char sockAddrBuf[sizeof(struct sockaddr_in6)] = { 0 }; int socketAddressLen = sizeof(sockAddrBuf); struct msghdr msgHdr; struct sockaddr_in sin; int recvLength; memset (& msgHdr, 0, sizeof (struct msghdr)); if (address != NULL) { msgHdr.msg_name = (struct sockaddr*) &sockAddrBuf; msgHdr.msg_namelen = socketAddressLen; } msgHdr.msg_iov = (struct iovec *) buffers; msgHdr.msg_iovlen = bufferCount; recvLength = recvmsg (socket, & msgHdr, MSG_NOSIGNAL); if (recvLength == -1) { if (errno == EWOULDBLOCK) return 0; return -1; } #ifdef HAS_MSGHDR_FLAGS if (msgHdr.msg_flags & MSG_TRUNC) return -1; #endif if (address != NULL) { if (enet_address_from_sock_addr(address, (struct sockaddr*) sockAddrBuf) != 0) return -1; } return recvLength; } int enet_socketset_select (ENetSocket maxSocket, ENetSocketSet * readSet, ENetSocketSet * writeSet, enet_uint32 timeout) { struct timeval timeVal; timeVal.tv_sec = timeout / 1000; timeVal.tv_usec = (timeout % 1000) * 1000; return select (maxSocket + 1, readSet, writeSet, NULL, & timeVal); } int enet_socket_wait (ENetSocket socket, enet_uint32 * condition, enet_uint32 timeout) { #ifdef HAS_POLL struct pollfd pollSocket; int pollCount; pollSocket.fd = socket; pollSocket.events = 0; if (* condition & ENET_SOCKET_WAIT_SEND) pollSocket.events |= POLLOUT; if (* condition & ENET_SOCKET_WAIT_RECEIVE) pollSocket.events |= POLLIN; pollCount = poll (& pollSocket, 1, timeout); if (pollCount < 0) { if (errno == EINTR && * condition & ENET_SOCKET_WAIT_INTERRUPT) { * condition = ENET_SOCKET_WAIT_INTERRUPT; return 0; } return -1; } * condition = ENET_SOCKET_WAIT_NONE; if (pollCount == 0) return 0; if (pollSocket.revents & POLLOUT) * condition |= ENET_SOCKET_WAIT_SEND; if (pollSocket.revents & POLLIN) * condition |= ENET_SOCKET_WAIT_RECEIVE; return 0; #else fd_set readSet, writeSet; struct timeval timeVal; int selectCount; timeVal.tv_sec = timeout / 1000; timeVal.tv_usec = (timeout % 1000) * 1000; FD_ZERO (& readSet); FD_ZERO (& writeSet); if (* condition & ENET_SOCKET_WAIT_SEND) FD_SET (socket, & writeSet); if (* condition & ENET_SOCKET_WAIT_RECEIVE) FD_SET (socket, & readSet); selectCount = select (socket + 1, & readSet, & writeSet, NULL, & timeVal); if (selectCount < 0) { if (errno == EINTR && * condition & ENET_SOCKET_WAIT_INTERRUPT) { * condition = ENET_SOCKET_WAIT_INTERRUPT; return 0; } return -1; } * condition = ENET_SOCKET_WAIT_NONE; if (selectCount == 0) return 0; if (FD_ISSET (socket, & writeSet)) * condition |= ENET_SOCKET_WAIT_SEND; if (FD_ISSET (socket, & readSet)) * condition |= ENET_SOCKET_WAIT_RECEIVE; return 0; #endif } #endif
gongshuxuelang/cudaDBN
inc/rwDate_dec.h
#ifndef __RWDATE_DEC_H__ #define __RWDATE_DEC_H__ #include "MAT.h" class rwDate_dec:public rwDate { public: virtual bool ReadDate(); //读数据 virtual bool Write_Date(); //写数据 virtual void Print_rwDate(); //打印数据 virtual pRWD getRaw_Data(); //获得原始指针 private: int file_m; //读文件夹号 int file_n; //读文件夹中的txt int mode; //读取的模式 int DBN_N; //DBn小波系数 int data_row; //信号行 int data_line; //信号列 pRWD pRWdate; //原始数据 }; #endif
gongshuxuelang/cudaDBN
inc/rwDate.h
<reponame>gongshuxuelang/cudaDBN #ifndef __RWDATE_H__ #define __RWDATE_H__ #include "MAT.h" class rwDate { public: rwDate(){} virtual ~rwDate(){} virtual bool ReadDate() = 0; //读数据 virtual bool Write_Date() = 0; //写数据 virtual void Print_rwDate() = 0; //打印数据 virtual pRWD getRaw_Data() = 0; //获得原始指针 }; #endif
gongshuxuelang/cudaDBN
inc/head.h
#ifndef __HEAD_H__ #define __HEAD_H__ #include <iostream> #include <thread> #include <fstream> #include <iomanip> #include <vector> #include <algorithm> #include <string> #include <cassert> #include <cuda_runtime.h> //cuda头文件 #include <boost/lexical_cast.hpp> #include <boost/atomic.hpp>//boost原子操作 #define BOOST_THREAD_VERSION 5 //使用thread第五版,一共有v2,v3,v4,v5,四个版本 #include <boost/thread.hpp> #include <boost/thread/lock_factories.hpp> #include <boost/thread/lockable_adapter.hpp> #include <boost/thread/thread_guard.hpp> #include <boost/thread/scoped_thread.hpp> #include <boost/thread/shared_lock_guard.hpp> #include "Matrix.h" //矩阵类 #include "rwDate.h" //读写文件类 #include "rwDate_dec.h" //#include "DWT.h" //字母说明,dec为分解,signal为信号,Len为长度,filter为滤波器, //EX为延拓,CON为卷积,DSam为下采样,D为下,sam为采样。L为低频信号,H为高频信号 //ref为重构, /////////////宏函数//////////////////// #define ERR_EXIT(m) \ do \ { \ perror(m); \ exit(EXIT_FAILURE); \ }while(0) ///全局函数////////////////////////////////// int power(int base, int exponent);//指数函数 //void threadrFile1(RF prf,std::string str,std::string str1,int m,int n); //void threadrFile2(RF prf,std::string str,std::string str1,int m,int n); /////////常量定义区///////////////////////系数精度很高,采自matlab使用时需要翻转一下 const double db1_Lo_D[2] = { 0.70710678118654752440084436210485, 0.70710678118654752440084436210485 }; const double db1_Hi_D[2] = { -0.70710678118654752440084436210485, 0.70710678118654752440084436210485 }; const double db1_Lo_R[2] = { 0.70710678118654752440084436210485, 0.70710678118654752440084436210485 }; const double db1_Hi_R[2] = { 0.70710678118654752440084436210485, -0.70710678118654752440084436210485}; const double db2_Lo_D[4] = { -0.129409522550921, 0.224143868041857, 0.836516303737469, 0.482962913144690 }; // 小波变换分解低通滤波器 const double db2_Hi_D[4] = { -0.482962913144690, 0.836516303737469, -0.224143868041857, -0.129409522550921 }; // 小波变换分解高通滤波器 const double db2_Lo_R[4] = { 0.482962913144690, 0.836516303737469, 0.224143868041857, -0.129409522550921 }; // 小波变换重构低通滤波器 const double db2_Hi_R[4] = { -0.129409522550921, -0.224143868041857, 0.836516303737469, -0.482962913144690 }; // 小波变换重构高通滤波器 const double db3_Lo_D[6] = { 0.0352262918857095, -0.0854412738820267, -0.1350110200102546, 0.4598775021184914, 0.8068915093110924, 0.3326705529500825 }; const double db3_Hi_D[6] = { -0.3326705529500825, 0.8068915093110924, -0.4598775021184914, -0.1350110200102546, 0.0854412738820267, 0.0352262918857095 }; const double db3_Lo_R[6] = { 0.3326705529500825, 0.8068915093110924, 0.4598775021184914, -0.1350110200102546, -0.0854412738820267, 0.0352262918857095 }; const double db3_Hi_R[6] = { 0.0352262918857095, 0.0854412738820267, -0.1350110200102546, -0.4598775021184914, 0.8068915093110924, -0.3326705529500825 }; const double db4_Lo_D[8] = { -0.0105974017850690, 0.0328830116668852, 0.0308413818355607, -0.1870348117190931, -0.0279837694168599, 0.6308807679398587, 0.7148465705529154, 0.2303778133088964 }; const double db4_Hi_D[8] = { -0.2303778133088964, 0.7148465705529154, -0.6308807679398587, -0.0279837694168599, 0.1870348117190931, 0.0308413818355607, -0.0328830116668852, -0.0105974017850690 }; const double db4_Lo_R[8] = { 0.2303778133088964, 0.7148465705529154, 0.6308807679398587, -0.0279837694168599, -0.1870348117190931, 0.0308413818355607, 0.0328830116668852, -0.0105974017850690 }; const double db4_Hi_R[8] = { -0.0105974017850690, -0.0328830116668852, 0.0308413818355607, 0.1870348117190931, -0.0279837694168599, -0.6308807679398587, 0.7148465705529154, -0.2303778133088964 }; const double db5_Lo_D[10] = { 0.1601, 0.6038, 0.7243, 0.1384, -0.2423, -0.0322, 0.0776, -0.0062, -0.0126, 0.0033 }; const double db5_Hi_D[10] = { 0.0033, 0.0126, -0.0062, -0.0776, -0.0322, 0.2423, 0.1384, -0.7243, 0.6038, -0.1601 }; const double db5_Lo_R[10] = { 0.1601, 0.6038, 0.7243, 0.1384, -0.2423, -0.0322, 0.0776, -0.0062, -0.0126, 0.0033 }; const double db5_Hi_R[10] = { 0.0033, 0.0126, -0.0062, -0.0776, -0.0322, 0.2423, 0.1384, -0.7243, 0.6038, -0.1601 }; const double db6_Lo_D[12] = { -0.0011, 0.0048, 0.0006, -0.0316, 0.0275, 0.0975, -0.1298, -0.2263, 0.3153, 0.7511, 0.4946, 0.1115 }; const double db6_Hi_D[12] = { -0.1115, 0.4946, -0.7511, 0.3153, 0.2263, -0.1298, -0.0975, 0.0275, 0.0316, 0.0006, -0.0048, -0.0011 }; const double db6_Lo_R[12] = { 0.1115, 0.4946, 0.7511, 0.3153, -0.2263, -0.1298, 0.0975, 0.0275, -0.0316, 0.0006, 0.0048, -0.0011 }; const double db6_Hi_R[12] = { -0.0011, -0.0048, 0.0006, 0.0316, 0.0275, -0.0975, -0.1298, 0.2263, 0.3153, -0.7511, 0.4946, -0.1115 }; const double db7_Lo_D[14] = { 0.0004, -0.0018, 0.0004, 0.0126, -0.0166, -0.0380, 0.0806, 0.0713, -0.2240, -0.1439, 0.4698, 0.7291, 0.3965, 0.0779 }; const double db7_Hi_D[14] = { -0.0779, 0.3965, -0.7291, 0.4698, 0.1439, -0.2240, -0.0713, 0.0806, 0.0380 - 0.0166, -0.0126, 0.0004, 0.0018, 0.0004 }; const double db7_Lo_R[14] = { 0.0779, 0.3965, 0.7291, 0.4698, -0.1439, -0.2240, 0.0713, 0.0806, -0.0380, -0.0166, 0.0126, 0.0004, -0.0018, 0.0004 }; const double db7_Hi_R[14] = { 0.0004, 0.0018, 0.0004, -0.0126, -0.0166, 0.0380, 0.0806, -0.0713, -0.2240, 0.1439, 0.4698, -0.7291, 0.3965, -0.0779 }; const double db8_Lo_D[16] = { -0.0001, 0.0007, -0.0004, -0.0049, 0.0087, 0.0140, -0.0441, -0.0174, 0.1287, 0.0005, -0.2840, -0.0158, 0.5854, 0.6756, 0.3129, 0.0544 }; const double db8_Hi_D[16] = { -0.0544, 0.3129, -0.6756, 0.5854, 0.0158, -0.2840, -0.0005, 0.1287, 0.0174, -0.0441, -0.0140, 0.0087, 0.0049, -0.0004, -0.0007, -0.0001 }; const double db8_Lo_R[16] = { 0.0544, 0.3129, 0.6756, 0.5854, -0.0158, -0.2840, 0.0005, 0.1287, -0.0174, -0.0441, 0.0140, 0.0087, -0.0049, -0.0004, 0.0007, -0.0001 }; const double db8_Hi_R[16] = { -0.0001, -0.0007, -0.0004, 0.0049, 0.0087, -0.0140, -0.0441, 0.0174, 0.1287, -0.0005, -0.2840, 0.0158, 0.5854, -0.6756, 0.3129, -0.0544 }; const double db9_Lo_D[18] = { 0.0000, -0.0003, 0.0002, 0.0018, -0.0043, -0.0047, 0.0224, 0.0003, -0.0676, 0.0307, 0.1485, -0.0968, -0.2933, 0.1332, 0.6573, 0.6048, 0.2438, 0.0381 }; const double db9_Hi_D[18] = { -0.0381, 0.2438, -0.6048, 0.6573, -0.1332, -0.2933, 0.0968, 0.1485, -0.0307, -0.0676, -0.0003, 0.0224, 0.0047, -0.0043, -0.0018, 0.0002, 0.0003, 0.0000 }; const double db9_Lo_R[18] = { 0.0381, 0.2438, 0.6048, 0.6573, 0.1332, -0.2933, -0.0968, 0.1485, 0.0307, -0.0676, 0.0003, 0.0224, -0.0047, -0.0043, 0.0018, 0.0002, -0.0003, 0.0000 }; const double db9_Hi_R[18] = { 0.0000, 0.0003, 0.0002, -0.0018, -0.0043, 0.0047, 0.0224, -0.0003, -0.0676, -0.0307, 0.1485, 0.0968, -0.2933, -0.1332, 0.6573, -0.6048, 0.2438, -0.0381 }; const double db10_Lo_D[20] = { -0.0000, 0.0001, -0.0001, -0.0007, 0.0020, 0.0014, -0.0107, 0.0036, 0.0332, -0.0295, -0.0714, 0.0931, 0.1274, -0.1959, -0.2498, 0.2812, 0.6885, 0.5272, 0.1882, 0.0267 }; const double db10_Hi_D[20] = { -0.0267, 0.1882, -0.5272, 0.6885, -0.2812, -0.2498, 0.1959, 0.1274, -0.0931, -0.0714, 0.0295, 0.0332, -0.0036, -0.0107, -0.0014, 0.0020, 0.0007, -0.0001, -0.0001, -0.0000 }; const double db10_Lo_R[20] = { 0.0267, 0.1882, 0.5272, 0.6885, 0.2812, -0.2498, -0.1959, 0.1274, 0.0931, -0.0714, -0.0295, 0.0332, 0.0036, -0.0107, 0.0014, 0.0020, -0.0007, -0.0001, 0.0001, -0.0000 }; const double db10_Hi_R[20] = { -0.0000, -0.0001, -0.0001, 0.0007, 0.0020, -0.0014, -0.0107, -0.0036, 0.0332, 0.0295, -0.0714, -0.0931, 0.1274, 0.1959, -0.2498, -0.2812, 0.6885, -0.5272, 0.1882, -0.0267 }; #endif
guidoreina/classes
util/skiplist.h
#ifndef UTIL_SKIPLIST_H #define UTIL_SKIPLIST_H // Implementation of the skiplist invented by <NAME>: // ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf // ftp://ftp.cs.umd.edu/pub/skipLists/skipLists.c // // Limitations: // This implementation is not thread-safe. #include <stdlib.h> #include <new> #include "util/minus.h" namespace util { template<typename _Key, typename _Compare = util::minus<_Key> > class skiplist { private: struct node { // Key. const _Key key; // Level. int level; // Previous node. node* prev; // Forward nodes. node* forward[1]; // Constructor. node(int height); node(const _Key& k, int height); }; public: // Constructor. skiplist(); skiplist(const _Compare& cmp); // Destructor. ~skiplist(); // Initialize. bool init(); // Insert. bool insert(const _Key& k); // Erase. bool erase(const _Key& k); bool erase(const _Key& k, _Key& fullkey); // Contains. bool contains(const _Key& k) const; // Clear. void clear(); class iterator { friend class skiplist; public: const _Key& key() const; private: const node* n; }; // Begin. bool begin(iterator& it) const; // End. bool end(iterator& it) const; // Previous. bool previous(iterator& it) const; // Next. bool next(iterator& it) const; // Seek. bool seek(const _Key& k, iterator& it) const; private: // [Probability] p = 0.25 // [Maximum number of elements] N = 4294967296 // L(n) = log1/p(n) // kMaxLevel = L(N) = log4(4294967296) = 16 static const int kMaxLevel = 16; static const int kBitsInRandom = 31; node* _M_header; node* _M_tail; int _M_level; int _M_random; int _M_randoms_left; _Compare _M_compare; // Find. const node* find(const _Key& k) const; // Make node. node* make_node(int height); node* make_node(const _Key& k, int height); // Allocate node. node* allocate_node(int height); // Unlink. node* unlink(const _Key& k); // Delete node. void delete_node(node* n); // Random level. int random_level(); }; template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::skiplist() : _M_header(NULL), _M_level(1), _M_random(random()), _M_randoms_left(kBitsInRandom / 2), _M_compare() { } template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::skiplist(const _Compare& cmp) : _M_header(NULL), _M_level(1), _M_random(random()), _M_randoms_left(kBitsInRandom / 2), _M_compare(cmp) { } template<typename _Key, typename _Compare> skiplist<_Key, _Compare>::~skiplist() { node* n = _M_header; while (n) { node* next = n->forward[0]; delete_node(n); n = next; } } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::init() { // Create header. if ((_M_header = make_node(kMaxLevel)) == NULL) { return false; } // Initialize forward pointers to NULL. for (int i = 0; i < kMaxLevel; i++) { _M_header->forward[i] = NULL; } _M_tail = _M_header; return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::insert(const _Key& k) { int ret = -1; node* update[kMaxLevel]; node* x = _M_header; for (int i = _M_level - 1; i >= 0; i--) { node* next; while (((next = x->forward[i]) != NULL) && ((ret = _M_compare(next->key, k)) < 0)) { x = next; } update[i] = x; } if (ret == 0) { // Already inserted. return false; } int level = random_level(); // Create node. if ((x = make_node(k, level)) == NULL) { return false; } if (level > _M_level) { for (int i = _M_level; i < level; i++) { update[i] = _M_header; } _M_level = level; } for (int i = 0; i < level; i++) { x->forward[i] = update[i]->forward[i]; update[i]->forward[i] = x; } // Set previous pointer. x->prev = update[0]; if (x->forward[0]) { x->forward[0]->prev = x; } else { _M_tail = x; } return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::erase(const _Key& k) { node* x; if ((x = unlink(k)) == NULL) { return false; } delete_node(x); return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::erase(const _Key& k, _Key& fullkey) { node* x; if ((x = unlink(k)) == NULL) { return false; } fullkey = x->key; delete_node(x); return true; } template<typename _Key, typename _Compare> inline bool skiplist<_Key, _Compare>::contains(const _Key& k) const { return (find(k) != NULL); } template<typename _Key, typename _Compare> void skiplist<_Key, _Compare>::clear() { node* n = _M_header->forward[0]; while (n) { node* next = n->forward[0]; delete_node(n); n = next; } // Initialize forward pointers to NULL. for (int i = 0; i < kMaxLevel; i++) { _M_header->forward[i] = NULL; } _M_tail = _M_header; } template<typename _Key, typename _Compare> inline const _Key& skiplist<_Key, _Compare>::iterator::key() const { return n->key; } template<typename _Key, typename _Compare> inline bool skiplist<_Key, _Compare>::begin(iterator& it) const { // If the list is empty... if (!_M_header->forward[0]) { return false; } it.n = _M_header->forward[0]; return true; } template<typename _Key, typename _Compare> inline bool skiplist<_Key, _Compare>::end(iterator& it) const { // If the list is empty... if (!_M_header->forward[0]) { return false; } it.n = _M_tail; return true; } template<typename _Key, typename _Compare> inline bool skiplist<_Key, _Compare>::previous(iterator& it) const { if (it.n->prev == _M_header) { return false; } it.n = it.n->prev; return true; } template<typename _Key, typename _Compare> inline bool skiplist<_Key, _Compare>::next(iterator& it) const { if (!it.n->forward[0]) { return false; } it.n = it.n->forward[0]; return true; } template<typename _Key, typename _Compare> inline bool skiplist<_Key, _Compare>::seek(const _Key& k, iterator& it) const { const node* x = _M_header; const node* next = NULL; for (int i = _M_level - 1; i >= 0; i--) { while ((next = x->forward[i]) != NULL) { int ret; if ((ret = _M_compare(next->key, k)) < 0) { x = next; } else if (ret == 0) { it.n = next; return true; } else { break; } } } if (!next) { return false; } it.n = next; return true; } template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::node::node(int height) : key(), level(height) { } template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::node::node(const _Key& k, int height) : key(k), level(height) { } template<typename _Key, typename _Compare> const struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::find(const _Key& k) const { const node* x = _M_header; for (int i = _M_level - 1; i >= 0; i--) { const node* next; while ((next = x->forward[i]) != NULL) { int ret; if ((ret = _M_compare(next->key, k)) < 0) { x = next; } else if (ret == 0) { return next; } else { break; } } } return NULL; } template<typename _Key, typename _Compare> inline struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::make_node(int height) { node* n; if ((n = allocate_node(height)) == NULL) { return NULL; } return new (n) node(height); } template<typename _Key, typename _Compare> inline struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::make_node(const _Key& k, int height) { node* n; if ((n = allocate_node(height)) == NULL) { return NULL; } return new (n) node(k, height); } template<typename _Key, typename _Compare> inline struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::allocate_node(int height) { return reinterpret_cast<node*>(malloc(sizeof(node) + ((height - 1) * sizeof(node*)))); } template<typename _Key, typename _Compare> struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::unlink(const _Key& k) { int ret = -1; node* update[kMaxLevel]; node* x = _M_header; for (int i = _M_level - 1; i >= 0; i--) { node* next; while (((next = x->forward[i]) != NULL) && ((ret = _M_compare(next->key, k)) < 0)) { x = next; } update[i] = x; } if (ret != 0) { // Not found. return NULL; } x = x->forward[0]; for (int i = 0; i < _M_level; i++) { if (update[i]->forward[i] != x) { break; } update[i]->forward[i] = x->forward[i]; } if (update[0]->forward[0]) { update[0]->forward[0]->prev = update[0]; } else { _M_tail = update[0]; } while ((_M_level > 1) && (!_M_header->forward[_M_level - 1])) { _M_level--; } return x; } template<typename _Key, typename _Compare> inline void skiplist<_Key, _Compare>::delete_node(node* n) { // Call the destructor. n->~node(); // Free the memory. free(n); } template<typename _Key, typename _Compare> int skiplist<_Key, _Compare>::random_level() { int level = 1; int b; do { if ((b = _M_random & 3) == 0) { level++; } _M_random >>= 2; if (--_M_randoms_left == 0) { _M_random = random(); _M_randoms_left = kBitsInRandom / 2; } } while (b == 0); return (level > kMaxLevel) ? kMaxLevel : level; } } #endif // UTIL_SKIPLIST_H
guidoreina/classes
io/sequential_write_only_file.h
<gh_stars>1-10 #ifndef IO_SEQUENTIAL_WRITE_ONLY_FILE_H #define IO_SEQUENTIAL_WRITE_ONLY_FILE_H #include "io/write_only_file.h" namespace io { class sequential_write_only_file : public write_only_file { public: // Constructor. sequential_write_only_file(); // Destructor. ~sequential_write_only_file(); // Open. bool open(const char* filename); // Close. bool close(); // Write. bool write(const void* buf, size_t count); protected: static const uint64_t kFileIncrement = 4 * 1024 * 1024; uint64_t _M_filesize; }; inline sequential_write_only_file::sequential_write_only_file() { _M_fd = -1; } inline sequential_write_only_file::~sequential_write_only_file() { if (_M_fd != -1) { close(); } } } #endif // IO_SEQUENTIAL_WRITE_ONLY_FILE_H
guidoreina/classes
util/number.h
#ifndef UTIL_NUMBER_H #define UTIL_NUMBER_H #include <sys/types.h> #include <stdint.h> #include <limits.h> namespace util { class number { public: static size_t length(off_t number); // Parse. enum parse_result { kParseError, kParseUnderflow, kParseOverflow, kParseSucceeded }; static parse_result parse(const void* buf, size_t len, int32_t& n, int32_t min = INT_MIN, int32_t max = INT_MAX); static parse_result parse(const void* buf, size_t len, uint32_t& n, uint32_t min = 0, uint32_t max = UINT_MAX); static parse_result parse(const void* buf, size_t len, int64_t& n, int64_t min = LLONG_MIN, int64_t max = LLONG_MAX); static parse_result parse(const void* buf, size_t len, uint64_t& n, uint64_t min = 0, uint64_t max = ULLONG_MAX); }; inline number::parse_result number::parse(const void* buf, size_t len, int32_t& n, int32_t min, int32_t max) { int64_t int64; parse_result res; if ((res = parse(buf, len, int64, min, max)) != kParseSucceeded) { return res; } n = static_cast<int32_t>(int64); return kParseSucceeded; } inline number::parse_result number::parse(const void* buf, size_t len, uint32_t& n, uint32_t min, uint32_t max) { uint64_t uint64; parse_result res; if ((res = parse(buf, len, uint64, min, max)) != kParseSucceeded) { return res; } n = static_cast<uint32_t>(uint64); return kParseSucceeded; } } #endif // UTIL_NUMBER_H
guidoreina/classes
util/pair.h
#ifndef UTIL_PAIR_H #define UTIL_PAIR_H #include "util/move.h" namespace util { template<typename _T1, typename _T2> struct pair { typedef _T1 first_type; typedef _T2 second_type; _T1 first; _T2 second; // Constructor. pair(); pair(const _T1& a, const _T2& b); pair(_T1&& a, _T2&& b); }; inline pair::pair() : first(), second() { } inline pair::pair(const _T1& a, const _T2& b) : first(a), second(b) { } inline pair::pair(_T1&& a, _T2&& b) { first = util::move(a); second = util::move(b); } } #endif // UTIL_PAIR_H
guidoreina/classes
io/write_only_file.h
#ifndef IO_WRITE_ONLY_FILE_H #define IO_WRITE_ONLY_FILE_H #include <stdint.h> namespace io { class write_only_file { public: // Open. virtual bool open(const char* filename) = 0; // Close. virtual bool close() = 0; // Write. virtual bool write(const void* buf, size_t count) = 0; protected: int _M_fd; uint64_t _M_offset; }; } #endif // IO_WRITE_ONLY_FILE_H
guidoreina/classes
util/minus.h
#ifndef UTIL_MINUS_H #define UTIL_MINUS_H namespace util { template<typename _T> struct minus { int operator()(const _T& x, const _T& y) const; }; template<typename _T> inline int minus<_T>::operator()(const _T& x, const _T& y) const { return x - y; } } #endif // UTIL_MINUS_H
guidoreina/classes
util/concurrent/locks/mutex.h
#ifndef UTIL_CONCURRENT_LOCKS_MUTEX_H #define UTIL_CONCURRENT_LOCKS_MUTEX_H #include <stdlib.h> #include <string.h> #include <stdio.h> #include <pthread.h> namespace util { namespace concurrent { namespace locks { class mutex { public: // Constructor. mutex(); // Destructor. ~mutex(); // Lock. bool lock(); // Try lock. bool try_lock(); // Unlock. bool unlock(); private: pthread_mutex_t _M_mutex; }; inline mutex::mutex() { int ret; if ((ret = pthread_mutex_init(&_M_mutex, NULL)) != 0) { fprintf(stderr, "pthread_mutex_init() failed (%s).\n", strerror(ret)); abort(); } } inline mutex::~mutex() { pthread_mutex_destroy(&_M_mutex); } inline bool mutex::lock() { return (pthread_mutex_lock(&_M_mutex) == 0); } inline bool mutex::try_lock() { return (pthread_mutex_trylock(&_M_mutex) == 0); } inline bool mutex::unlock() { return (pthread_mutex_unlock(&_M_mutex) == 0); } class scoped_lock { public: // Constructor. scoped_lock(mutex& m); // Destructor. ~scoped_lock(); private: mutex& _M_mutex; }; inline scoped_lock::scoped_lock(mutex& m) : _M_mutex(m) { _M_mutex.lock(); } inline scoped_lock::~scoped_lock() { _M_mutex.unlock(); } } } } #endif // UTIL_CONCURRENT_LOCKS_MUTEX_H
guidoreina/classes
net/internet/url.h
#ifndef NET_INTERNET_URL_H #define NET_INTERNET_URL_H #include "net/internet/scheme.h" #include "string/buffer.h" #include "macros/macros.h" namespace net { namespace internet { bool is_unreserved(unsigned char c); bool is_reserved(unsigned char c); bool is_gen_delim(unsigned char c); bool is_sub_delim(unsigned char c); bool is_pchar(unsigned char c); class url { public: static const size_t kUserinfoMaxLen = 255; static const size_t kHostMaxLen = 255; static const size_t kPathMaxLen = 16 * 1024; static const size_t kQueryMaxLen = 16 * 1024; static const size_t kFragmentMaxLen = 16 * 1024; // Constructor. url(); // Destructor. ~url(); // Reset. void reset(); // Get scheme. const struct scheme& scheme() const; // Get userinfo. const char* userinfo() const; const char* userinfo(unsigned short& len) const; // Get host. const char* host() const; const char* host(unsigned short& len) const; // IP literal? bool ip_literal() const; // Get port. unsigned short port() const; // Get path. const char* path() const; const char* path(unsigned short& len) const; // Get query. const char* query() const; const char* query(unsigned short& len) const; // Get fragment. const char* fragment() const; const char* fragment(unsigned short& len) const; // Parse. enum parse_result { kNoMemory, kInvalidUrl, kUrlTooLong, kSuccess }; parse_result parse(const void* buf, size_t count); // Encode. static bool encode(const char* url, size_t len, string::buffer& buf); private: string::buffer _M_buf; struct scheme _M_scheme; unsigned short _M_token; unsigned short _M_tokenlen; unsigned short _M_userinfo; unsigned short _M_userinfolen; unsigned short _M_host; unsigned short _M_hostlen; unsigned short _M_port; unsigned short _M_path; unsigned short _M_pathlen; unsigned short _M_query; unsigned short _M_querylen; unsigned short _M_fragment; unsigned short _M_fragmentlen; unsigned char _M_ip_literal:1; unsigned char _M_state:6; }; inline bool is_unreserved(unsigned char c) { if ((IS_ALPHA(c)) || (IS_DIGIT(c))) { return true; } else { switch (c) { case '-': case '.': case '_': case '~': return true; default: return false; } } } inline bool is_reserved(unsigned char c) { return ((is_gen_delim(c)) || (is_sub_delim(c))); } inline bool is_gen_delim(unsigned char c) { switch (c) { case ':': case '/': case '?': case '#': case '[': case ']': case '@': return true; default: return false; } } inline bool is_sub_delim(unsigned char c) { switch (c) { case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': return true; default: return false; } } inline bool is_pchar(unsigned char c) { if ((is_unreserved(c)) || (is_sub_delim(c))) { return true; } else { switch (c) { case '%': case ':': case '@': return true; default: return false; } } } inline url::~url() { } inline const struct scheme& url::scheme() const { return _M_scheme; } inline const char* url::userinfo() const { return (_M_userinfolen == 0) ? NULL : _M_buf.data() + _M_userinfo; } inline const char* url::userinfo(unsigned short& len) const { len = _M_userinfolen; return (_M_userinfolen == 0) ? NULL : _M_buf.data() + _M_userinfo; } inline const char* url::host() const { return (_M_hostlen == 0) ? NULL : _M_buf.data() + _M_host; } inline const char* url::host(unsigned short& len) const { len = _M_hostlen; return (_M_hostlen == 0) ? NULL : _M_buf.data() + _M_host; } inline bool url::ip_literal() const { return (bool) _M_ip_literal; } inline unsigned short url::port() const { return _M_port; } inline const char* url::path() const { return (_M_pathlen == 0) ? "/" : _M_buf.data() + _M_path; } inline const char* url::path(unsigned short& len) const { if (_M_pathlen == 0) { len = 1; return "/"; } else { len = _M_pathlen; return _M_buf.data() + _M_path; } } inline const char* url::query() const { return (_M_querylen == 0) ? NULL : _M_buf.data() + _M_query; } inline const char* url::query(unsigned short& len) const { len = _M_querylen; return (_M_querylen == 0) ? NULL : _M_buf.data() + _M_query; } inline const char* url::fragment() const { return (_M_fragmentlen == 0) ? NULL : _M_buf.data() + _M_fragment; } inline const char* url::fragment(unsigned short& len) const { len = _M_fragmentlen; return (_M_fragmentlen == 0) ? NULL : _M_buf.data() + _M_fragment; } } } #endif // NET_INTERNET_URL_H
guidoreina/classes
util/concurrent/arena.h
<gh_stars>1-10 #ifndef UTIL_CONCURRENT_ARENA_H #define UTIL_CONCURRENT_ARENA_H // Simple thread-safe allocator. #include <stdlib.h> #include "util/concurrent/locks/mutex.h" namespace util { namespace concurrent { class arena { public: // Constructor. arena(); // Destructor. ~arena(); // Allocate. void* allocate(size_t size); // Get count. size_t count() const; private: static const size_t kBlockSize = 4 * 1024; static const size_t kDataSize = kBlockSize - sizeof(void*); struct block { struct block* next; char data[1]; }; block* _M_head; size_t _M_used; size_t _M_count; locks::mutex _M_lock; // Create block. bool create_block(size_t data_size); }; inline arena::arena() : _M_head(NULL), _M_used(kDataSize), _M_count(0) { } inline size_t arena::count() const { return _M_count; } } } #endif // UTIL_CONCURRENT_ARENA_H
guidoreina/classes
string/memcasemem.h
<gh_stars>1-10 #ifndef STRING_MEMCASEMEM_H #define STRING_MEMCASEMEM_H namespace string { void* memcasemem(const void* haystack, size_t haystacklen, const void* needle, size_t needlelen); } #endif // STRING_MEMCASEMEM_H
guidoreina/classes
util/min_priority_queue.h
<reponame>guidoreina/classes #ifndef UTIL_MIN_PRIORITY_QUEUE_H #define UTIL_MIN_PRIORITY_QUEUE_H #include <stdlib.h> #include <string.h> #include <new> #include "util/move.h" namespace util { template<typename _Tp> class min_priority_queue { public: typedef _Tp value_type; // Constructor. min_priority_queue(); min_priority_queue(min_priority_queue&& other); // Destructor. ~min_priority_queue(); // Move assignment operator. min_priority_queue& operator=(min_priority_queue&& other); // Swap content. void swap(min_priority_queue& other); // Free priority queue. void free(); // Clear priority queue. void clear(); // Empty? bool empty() const; // Get the number of elements. size_t size() const; // Insert element. bool push(const value_type& x); bool push(value_type&& x); // Return top element. const value_type* top() const; // Remove top element. bool pop(); private: static const size_t kInitialSize = 32; value_type* _M_values; size_t _M_size; size_t _M_used; // Build min-heap. void build_min_heap(); // Min-heapify. void min_heapify(size_t i); // Allocate. bool allocate(); // Disable copy constructor and assignment operator. min_priority_queue(const min_priority_queue&); min_priority_queue& operator=(const min_priority_queue&); }; #define PARENT(i) (((i) - 1) >> 1) #define LEFT(i) (((i) << 1) + 1) #define RIGHT(i) (((i) << 1) + 2) template<typename _Tp> inline min_priority_queue<_Tp>::min_priority_queue() : _M_values(NULL), _M_size(0), _M_used(0) { } template<typename _Tp> inline min_priority_queue<_Tp>::min_priority_queue(min_priority_queue&& other) : _M_values(other._M_values), _M_size(other._M_size), _M_used(other._M_used) { other._M_values = NULL; other._M_size = 0; other._M_used = 0; } template<typename _Tp> inline min_priority_queue<_Tp>::~min_priority_queue() { free(); } template<typename _Tp> min_priority_queue<_Tp>& min_priority_queue<_Tp>::operator=(min_priority_queue&& other) { // http://scottmeyers.blogspot.de/2014/06/the-drawbacks-of-implementing-move.html // It is better not to swap the objects. if (_M_values) { // Invoke the destructors. for (size_t i = 0; i < _M_used; i++) { _M_values[i].value_type::~value_type(); } ::free(_M_values); } _M_values = other._M_values; _M_size = other._M_size; _M_used = other._M_used; other._M_values = NULL; other._M_size = 0; other._M_used = 0; return *this; } template<typename _Tp> inline void min_priority_queue<_Tp>::swap(min_priority_queue& other) { util::swap(_M_values, other._M_values); util::swap(_M_size, other._M_size); util::swap(_M_used, other,_M_used); } template<typename _Tp> void min_priority_queue<_Tp>::free() { if (_M_values) { // Invoke the destructors. for (size_t i = 0; i < _M_used; i++) { _M_values[i].value_type::~value_type(); } ::free(_M_values); _M_values = NULL; } _M_size = 0; _M_used = 0; } template<typename _Tp> inline void min_priority_queue<_Tp>::clear() { // Invoke the destructors. for (size_t i = 0; i < _M_used; i++) { _M_values[i].value_type::~value_type(); } _M_used = 0; } template<typename _Tp> inline bool min_priority_queue<_Tp>::empty() const { return (_M_used == 0); } template<typename _Tp> inline size_t min_priority_queue<_Tp>::size() const { return _M_used; } template<typename _Tp> bool min_priority_queue<_Tp>::push(const value_type& x) { if (!allocate()) { return false; } new (&_M_values[_M_used]) value_type(x); size_t i = _M_used++; while (i > 0) { size_t parent = PARENT(i); if (_M_values[i] < _M_values[parent]) { util::swap(_M_values[i], _M_values[parent]); i = parent; } else { break; } } return true; } template<typename _Tp> bool min_priority_queue<_Tp>::push(value_type&& x) { if (!allocate()) { return false; } new (&_M_values[_M_used]) value_type(util::move(x)); size_t i = _M_used++; while (i > 0) { size_t parent = PARENT(i); if (_M_values[i] < _M_values[parent]) { util::swap(_M_values[i], _M_values[parent]); i = parent; } else { break; } } return true; } template<typename _Tp> inline const typename min_priority_queue<_Tp>::value_type* min_priority_queue<_Tp>::top() const { return (_M_used != 0) ? &_M_values[0] : NULL; } template<typename _Tp> bool min_priority_queue<_Tp>::pop() { // If the priority queue is empty... if (_M_used == 0) { return false; } // Invoke the destructor. _M_values[0].value_type::~value_type(); // Decrement number of elements. _M_used--; if (_M_used > 0) { memcpy(&_M_values[0], &_M_values[_M_used], sizeof(value_type)); if (_M_used > 1) { min_heapify(0); } } return true; } template<typename _Tp> inline void min_priority_queue<_Tp>::build_min_heap() { for (ssize_t i = (_M_used / 2) - 1; i >= 0; i--) { min_heapify(i); } } template<typename _Tp> void min_priority_queue<_Tp>::min_heapify(size_t i) { size_t l = LEFT(i); size_t r = RIGHT(i); size_t smallest; if ((l < _M_used) && (_M_values[l] < _M_values[i])) { smallest = l; } else { smallest = i; } if ((r < _M_used) && (_M_values[r] < _M_values[smallest])) { smallest = r; } if (smallest != i) { util::swap(_M_values[i], _M_values[smallest]); min_heapify(smallest); } } template<typename _Tp> bool min_priority_queue<_Tp>::allocate() { if (_M_used == _M_size) { size_t size = (_M_size == 0) ? kInitialSize : (_M_size * 2); value_type* values; if ((values = reinterpret_cast<value_type*>( realloc(_M_values, size * sizeof(value_type)) )) == NULL) { return false; } _M_values = values; _M_size = size; } return true; } #undef PARENT #undef LEFT #undef RIGHT } #endif // UTIL_MIN_PRIORITY_QUEUE_H
guidoreina/classes
util/concurrent/locks/spinlock.h
#ifndef UTIL_CONCURRENT_LOCKS_SPINLOCK_H #define UTIL_CONCURRENT_LOCKS_SPINLOCK_H #include <stdlib.h> #include <string.h> #include <stdio.h> #include <pthread.h> namespace util { namespace concurrent { namespace locks { class spinlock { public: // Constructor. spinlock(); // Destructor. ~spinlock(); // Lock. bool lock(); // Try lock. bool try_lock(); // Unlock. bool unlock(); private: pthread_spinlock_t _M_spinlock; }; inline spinlock::spinlock() { int ret; if ((ret = pthread_spin_init(&_M_spinlock, 0)) != 0) { fprintf(stderr, "pthread_spin_init failed (%s).\n", strerror(ret)); abort(); } } inline spinlock::~spinlock() { pthread_spin_destroy(&_M_spinlock); } inline bool spinlock::lock() { return (pthread_spin_lock(&_M_spinlock) == 0); } inline bool spinlock::try_lock() { return (pthread_spin_trylock(&_M_spinlock) == 0); } inline bool spinlock::unlock() { return (pthread_spin_unlock(&_M_spinlock) == 0); } class scoped_spinlock { public: // Constructor. scoped_spinlock(spinlock& sl); // Destructor. ~scoped_spinlock(); private: spinlock& _M_spinlock; }; inline scoped_spinlock::scoped_spinlock(spinlock& sl) : _M_spinlock(sl) { _M_spinlock.lock(); } inline scoped_spinlock::~scoped_spinlock() { _M_spinlock.unlock(); } } } } #endif // UTIL_CONCURRENT_LOCKS_SPINLOCK_H
guidoreina/classes
util/vector.h
<filename>util/vector.h #ifndef UTIL_VECTOR_H #define UTIL_VECTOR_H #include <stdlib.h> #include <new> #include "util/move.h" namespace util { template<typename _Tp> class vector { public: typedef _Tp value_type; // Constructor. vector(); vector(vector&& other); // Destructor. ~vector(); // Move assignment operator. vector& operator=(vector&& other); // Swap content. void swap(vector& other); // Free vector. void free(); // Clear vector. void clear(); // Empty? bool empty() const; // Get the number of elements. size_t size() const; // Get size of allocated storage capacity. size_t capacity() const; // Reserve. bool reserve(size_t n); // Add element at the end. bool push_back(const value_type& x); // Construct and insert element at the end. bool emplace_back(value_type&& x); // Delete last element. bool pop_back(); // Access element. const value_type* at(size_t n) const; bool at(size_t n, const value_type& x); // Construct and insert element at position. bool emplace_at(size_t n, value_type&& x); private: static const size_t kInitialSize = 32; value_type* _M_values; size_t _M_size; size_t _M_used; // Allocate. bool allocate(size_t n = 1); // Disable copy constructor and assignment operator. vector(const vector&); vector& operator=(const vector&); }; template<typename _Tp> inline vector<_Tp>::vector() : _M_values(NULL), _M_size(0), _M_used(0) { } template<typename _Tp> inline vector<_Tp>::vector(vector&& other) : _M_values(other._M_values), _M_size(other._M_size), _M_used(other._M_used) { other._M_values = NULL; other._M_size = 0; other._M_used = 0; } template<typename _Tp> inline vector<_Tp>::~vector() { free(); } template<typename _Tp> vector<_Tp>& vector<_Tp>::operator=(vector&& other) { // http://scottmeyers.blogspot.de/2014/06/the-drawbacks-of-implementing-move.html // It is better not to swap the objects. if (_M_values) { // Invoke the destructors. for (size_t i = 0; i < _M_used; i++) { _M_values[i].value_type::~value_type(); } ::free(_M_values); } _M_values = other._M_values; _M_size = other._M_size; _M_used = other._M_used; other._M_values = NULL; other._M_size = 0; other._M_used = 0; return *this; } template<typename _Tp> inline void vector<_Tp>::swap(vector& other) { util::swap(_M_values, other._M_values); util::swap(_M_size, other._M_size); util::swap(_M_used, other._M_used); } template<typename _Tp> void vector<_Tp>::free() { if (_M_values) { // Invoke the destructors. for (size_t i = 0; i < _M_used; i++) { _M_values[i].value_type::~value_type(); } ::free(_M_values); _M_values = NULL; } _M_size = 0; _M_used = 0; } template<typename _Tp> inline void vector<_Tp>::clear() { // Invoke the destructors. for (size_t i = 0; i < _M_used; i++) { _M_values[i].value_type::~value_type(); } _M_used = 0; } template<typename _Tp> inline bool vector<_Tp>::empty() const { return (_M_used == 0); } template<typename _Tp> inline size_t vector<_Tp>::size() const { return _M_used; } template<typename _Tp> inline size_t vector<_Tp>::capacity() const { return _M_size; } template<typename _Tp> bool vector<_Tp>::reserve(size_t n) { if (n <= _M_size) { return true; } size_t size = (_M_size == 0) ? kInitialSize : _M_size; while (size < n) { // Overflow? size_t tmp; if ((tmp = size * 2) < size) { return false; } size = tmp; } value_type* values; if ((values = reinterpret_cast<value_type*>( realloc(_M_values, size * sizeof(value_type)) )) == NULL) { return false; } _M_values = values; _M_size = size; return true; } template<typename _Tp> inline bool vector<_Tp>::push_back(const value_type& x) { if (!allocate()) { return false; } new (&_M_values[_M_used++]) value_type(x); return true; } template<typename _Tp> inline bool vector<_Tp>::emplace_back(value_type&& x) { if (!allocate()) { return false; } new (&_M_values[_M_used++]) value_type(util::move(x)); return true; } template<typename _Tp> inline bool vector<_Tp>::pop_back() { if (_M_used == 0) { return false; } // Invoke the destructor. _M_values[--_M_used].value_type::~value_type(); return true; } template<typename _Tp> inline const typename vector<_Tp>::value_type* vector<_Tp>::at(size_t n) const { if (n >= _M_used) { return NULL; } return &_M_values[n]; } template<typename _Tp> inline bool vector<_Tp>::at(size_t n, const value_type& x) { if (n >= _M_used) { return false; } // Invoke the destructor. _M_values[n].value_type::~value_type(); new (&_M_values[n]) value_type(x); return true; } template<typename _Tp> inline bool vector<_Tp>::emplace_at(size_t n, value_type&& x) { if (n >= _M_used) { return false; } // Invoke the destructor. _M_values[n].value_type::~value_type(); new (&_M_values[n]) value_type(util::move(x)); return true; } template<typename _Tp> inline bool vector<_Tp>::allocate(size_t n) { return reserve(_M_used + n); } } #endif // UTIL_VECTOR_H
guidoreina/classes
util/concurrent/atomic/pointer.h
<filename>util/concurrent/atomic/pointer.h #ifndef UTIL_CONCURRENT_ATOMIC_POINTER_H #define UTIL_CONCURRENT_ATOMIC_POINTER_H #include "util/concurrent/atomic/atomic.h" namespace util { namespace concurrent { namespace atomic { template<typename _T> class pointer { public: // Constructor. pointer(); pointer(_T* ptr); pointer(const pointer& ptr); // Assignment operator. pointer& operator=(_T* ptr); pointer& operator=(const pointer& ptr); // Get pointer. _T* get() const; // Set pointer. void set(_T* ptr); // Pointer operator. _T* operator->() const; // Dereference operator. _T& operator*() const; // Compare and swap. bool compare_and_swap(_T* oldval, _T* newval); private: _T* _M_ptr; }; template<typename _T> inline pointer<_T>::pointer() { } template<typename _T> inline pointer<_T>::pointer(_T* ptr) : _M_ptr(ptr) { } template<typename _T> inline pointer<_T>::pointer(const pointer& ptr) : _M_ptr(ptr._M_ptr) { } template<typename _T> inline pointer<_T>& pointer<_T>::operator=(_T* ptr) { _M_ptr = ptr; return *this; } template<typename _T> inline pointer<_T>& pointer<_T>::operator=(const pointer& ptr) { _M_ptr = ptr._M_ptr; return *this; } template<typename _T> inline _T* pointer<_T>::get() const { return _M_ptr; } template<typename _T> inline void pointer<_T>::set(_T* ptr) { _M_ptr = ptr; } template<typename _T> inline _T* pointer<_T>::operator->() const { return _M_ptr; } template<typename _T> inline _T& pointer<_T>::operator*() const { return *_M_ptr; } template<typename _T> inline bool pointer<_T>::compare_and_swap(_T* oldval, _T* newval) { return util::concurrent::atomic::bool_compare_and_swap<_T*>(&_M_ptr, oldval, newval); } } } } #endif // UTIL_CONCURRENT_ATOMIC_POINTER_H
guidoreina/classes
util/block.h
#ifndef UTIL_BLOCK_H #define UTIL_BLOCK_H #include <stdint.h> #include <endian.h> namespace util { typedef uint32_t blocklen_t; class block { private: struct header { blocklen_t size; }; const unsigned char* _M_data; public: static const size_t kMinSize = sizeof(struct header); static const size_t kMaxSize = 1024 * 1024; // Constructor. block(); block(const unsigned char* data); // Get size. blocklen_t size() const; // Get data length. blocklen_t datalen() const; // Get data. const unsigned char* data() const; const unsigned char* data(blocklen_t& len) const; }; inline block::block() : _M_data(NULL) { } inline block::block(const unsigned char* data) : _M_data(data) { } inline blocklen_t block::size() const { const struct header* h = reinterpret_cast<const struct header*>(_M_data); switch (sizeof(blocklen_t)) { case 1: return h->size; case 2: return be16toh(h->size); case 4: return be32toh(h->size); case 8: return be64toh(h->size); default: return 0; } } inline blocklen_t block::datalen() const { return size() - sizeof(struct header); } inline const unsigned char* block::data() const { return (datalen() == 0) ? reinterpret_cast<const unsigned char*>("") : _M_data + sizeof(struct header); } inline const unsigned char* block::data(blocklen_t& len) const { len = datalen(); return (len == 0) ? reinterpret_cast<const unsigned char*>("") : _M_data + sizeof(struct header); } } #endif // UTIL_BLOCK_H
guidoreina/classes
string/memrchr.h
#ifndef STRING_MEMRCHR_H #define STRING_MEMRCHR_H namespace string { const void* memrchr(const void* s, int c, size_t n); } #endif // STRING_MEMRCHR_H
guidoreina/classes
util/red_black_tree.h
#ifndef UTIL_RED_BLACK_TREE_H #define UTIL_RED_BLACK_TREE_H // Implementation of the Red-Black-Tree algorithm of the book: // "Introduction to Algorithms", by Cormen, Leiserson, Rivest and Stein. #include <stdlib.h> #include <stdint.h> #include <memory> #include "util/minus.h" namespace util { template<typename _Key, typename _Value, typename _Compare = util::minus<_Key> > class red_black_tree { private: typedef uint8_t color_t; struct node { _Key key; _Value value; color_t color; node* left; node* right; node* p; // Constructor. node(); node(const _Key& k, const _Value& v); }; public: class iterator { friend class red_black_tree; public: _Key* first; _Value* second; private: node* _M_node; }; class const_iterator { friend class red_black_tree; public: const _Key* first; const _Value* second; private: const node* _M_node; }; // Constructor. red_black_tree(); red_black_tree(const _Compare& comp); red_black_tree(red_black_tree&& other); // Destructor. ~red_black_tree(); // Clear. void clear(); // Get number of elements. size_t count() const; // Insert. bool insert(const _Key& key, const _Value& value); // Erase. bool erase(iterator& it); bool erase(const _Key& key); // Find. bool find(const _Key& key, iterator& it); bool find(const _Key& key, const_iterator& it) const; // Begin. bool begin(iterator& it); bool begin(const_iterator& it) const; // End. bool end(iterator& it); bool end(const_iterator& it) const; // Previous. bool prev(iterator& it); bool prev(const_iterator& it) const; // Next. bool next(iterator& it); bool next(const_iterator& it) const; private: enum { kRed = 0, kBlack = 1 }; static node _M_nil; node* _M_root; #if HAVE_FREE_LIST node* _M_free; #endif // HAVE_FREE_LIST size_t _M_count; _Compare _M_comp; // Search. node* search(const _Key& key); const node* search(const _Key& key) const; // Minimum. node* minimum(node* x); const node* minimum(const node* x) const; // Maximum. node* maximum(node* x); const node* maximum(const node* x) const; // Predecessor. node* predecessor(node* x); const node* predecessor(const node* x) const; // Successor. node* successor(node* x); const node* successor(const node* x) const; // Left rotate. void left_rotate(node* x); // Right rotate. void right_rotate(node* x); // Insert fixup. void insert_fixup(node* z); // Transplant. void transplant(node* u, node* v); // Delete fixup. void delete_fixup(node* x); // Create node. node* create(const _Key& key, const _Value& value); #if HAVE_FREE_LIST // Add node to free list. void add_free_list(node* node); #endif // HAVE_FREE_LIST // Erase subtree. void erase_subtree(node* node); // Get nil. static node* nil(); // Disable copy constructor and assignment operator. red_black_tree(const red_black_tree&) = delete; red_black_tree& operator=(const red_black_tree&) = delete; }; template<typename _Key, typename _Value, typename _Compare> typename red_black_tree<_Key, _Value, _Compare>::node red_black_tree<_Key, _Value, _Compare>::_M_nil; template<typename _Key, typename _Value, typename _Compare> inline red_black_tree<_Key, _Value, _Compare>::node::node() : color(kBlack) { } template<typename _Key, typename _Value, typename _Compare> inline red_black_tree<_Key, _Value, _Compare>::node::node(const _Key& k, const _Value& v) : key(k), value(v) { } template<typename _Key, typename _Value, typename _Compare> inline red_black_tree<_Key, _Value, _Compare>::red_black_tree() : _M_root(nil()), #if HAVE_FREE_LIST _M_free(NULL), #endif // HAVE_FREE_LIST _M_count(0), _M_comp() { } template<typename _Key, typename _Value, typename _Compare> inline red_black_tree<_Key, _Value, _Compare>::red_black_tree(const _Compare& comp) : _M_root(nil()), #if HAVE_FREE_LIST _M_free(NULL), #endif // HAVE_FREE_LIST _M_count(0), _M_comp(comp) { } template<typename _Key, typename _Value, typename _Compare> inline red_black_tree<_Key, _Value, _Compare>::red_black_tree(red_black_tree&& other) { _M_root = other._M_root; #if HAVE_FREE_LIST _M_free = other._M_free; #endif // HAVE_FREE_LIST _M_count = other._M_count; _M_comp = other._M_comp; other._M_root = nil(); other._M_free = NULL; } template<typename _Key, typename _Value, typename _Compare> inline red_black_tree<_Key, _Value, _Compare>::~red_black_tree() { clear(); } template<typename _Key, typename _Value, typename _Compare> void red_black_tree<_Key, _Value, _Compare>::clear() { if (_M_root != nil()) { erase_subtree(_M_root); _M_root = nil(); } #if HAVE_FREE_LIST while (_M_free) { node* next = _M_free->left; delete _M_free; _M_free = next; } #endif // HAVE_FREE_LIST _M_count = 0; } template<typename _Key, typename _Value, typename _Compare> inline size_t red_black_tree<_Key, _Value, _Compare>::count() const { return _M_count; } template<typename _Key, typename _Value, typename _Compare> bool red_black_tree<_Key, _Value, _Compare>::insert(const _Key& key, const _Value& value) { node* z; if ((z = create(key, value)) == NULL) { return false; } node* y = nil(); node* x = _M_root; while (x != nil()) { y = x; if (_M_comp(z->key, x->key) < 0) { x = x->left; } else { x = x->right; } } z->p = y; if (y == nil()) { _M_root = z; } else if (_M_comp(z->key, y->key) < 0) { y->left = z; } else { y->right = z; } z->left = nil(); z->right = nil(); z->color = kRed; insert_fixup(z); _M_count++; return true; } template<typename _Key, typename _Value, typename _Compare> bool red_black_tree<_Key, _Value, _Compare>::erase(iterator& it) { node* z = it._M_node; it._M_node = successor(z); node* x; node* y = z; color_t ycolor = y->color; if (z->left == nil()) { x = z->right; transplant(z, z->right); } else if (z->right == nil()) { x = z->left; transplant(z, z->left); } else { y = minimum(z->right); ycolor = y->color; x = y->right; if (y->p == z) { x->p = y; } else { transplant(y, y->right); y->right = z->right; y->right->p = y; } transplant(z, y); y->left = z->left; y->left->p = y; y->color = z->color; } if (ycolor == kBlack) { delete_fixup(x); } _M_count--; #if HAVE_FREE_LIST // Call destructor. z->~node(); add_free_list(z); #else delete z; #endif if (it._M_node == nil()) { return false; } it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::erase(const _Key& key) { iterator it; if ((it._M_node = search(key)) == nil()) { return false; } erase(it); return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::find(const _Key& key, iterator& it) { if ((it._M_node = search(key)) == nil()) { return false; } it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::find(const _Key& key, const_iterator& it) const { if ((it._M_node = search(key)) == nil()) { return false; } it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::begin(iterator& it) { if (_M_root == nil()) { return false; } it._M_node = minimum(_M_root); it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::begin(const_iterator& it) const { if (_M_root == nil()) { return false; } it._M_node = minimum(_M_root); it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::end(iterator& it) { if (_M_root == nil()) { return false; } it._M_node = maximum(_M_root); it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::end(const_iterator& it) const { if (_M_root == nil()) { return false; } it._M_node = maximum(_M_root); it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::prev(iterator& it) { if ((it._M_node = predecessor(it._M_node)) == nil()) { return false; } it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::prev(const_iterator& it) const { if ((it._M_node = predecessor(it._M_node)) == nil()) { return false; } it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::next(iterator& it) { if ((it._M_node = successor(it._M_node)) == nil()) { return false; } it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline bool red_black_tree<_Key, _Value, _Compare>::next(const_iterator& it) const { if ((it._M_node = successor(it._M_node)) == nil()) { return false; } it.first = &it._M_node->key; it.second = &it._M_node->value; return true; } template<typename _Key, typename _Value, typename _Compare> inline typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::search(const _Key& key) { return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>( const_cast<const red_black_tree<_Key, _Value, _Compare>&>( *this ).search(key) ); } template<typename _Key, typename _Value, typename _Compare> const typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::search(const _Key& key) const { const node* x = _M_root; while (x != nil()) { int ret; if ((ret = _M_comp(key, x->key)) < 0) { x = x->left; } else if (ret == 0) { return x; } else { x = x->right; } } return nil(); } template<typename _Key, typename _Value, typename _Compare> inline typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::minimum(node* x) { return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>( const_cast<const red_black_tree<_Key, _Value, _Compare>&>( *this ).minimum(x) ); } template<typename _Key, typename _Value, typename _Compare> inline const typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::minimum(const node* x) const { while (x->left != nil()) { x = x->left; } return x; } template<typename _Key, typename _Value, typename _Compare> inline typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::maximum(node* x) { return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>( const_cast<const red_black_tree<_Key, _Value, _Compare>&>( *this ).maximum(x) ); } template<typename _Key, typename _Value, typename _Compare> inline const typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::maximum(const node* x) const { while (x->right != nil()) { x = x->right; } return x; } template<typename _Key, typename _Value, typename _Compare> inline typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::predecessor(node* x) { return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>( const_cast<const red_black_tree<_Key, _Value, _Compare>&>( *this ).predecessor(x) ); } template<typename _Key, typename _Value, typename _Compare> const typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::predecessor(const node* x) const { if (x->left != nil()) { return maximum(x->left); } const node* y = x->p; while ((y != nil()) && (x == y->left)) { x = y; y = y->p; } return y; } template<typename _Key, typename _Value, typename _Compare> inline typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::successor(node* x) { return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>( const_cast<const red_black_tree<_Key, _Value, _Compare>&>( *this ).successor(x) ); } template<typename _Key, typename _Value, typename _Compare> const typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::successor(const node* x) const { if (x->right != nil()) { return minimum(x->right); } const node* y = x->p; while ((y != nil()) && (x == y->right)) { x = y; y = y->p; } return y; } template<typename _Key, typename _Value, typename _Compare> void red_black_tree<_Key, _Value, _Compare>::left_rotate(node* x) { node* y = x->right; x->right = y->left; if (y->left != nil()) { y->left->p = x; } y->p = x->p; if (x->p == nil()) { _M_root = y; } else if (x == x->p->left) { x->p->left = y; } else { x->p->right = y; } y->left = x; x->p = y; } template<typename _Key, typename _Value, typename _Compare> void red_black_tree<_Key, _Value, _Compare>::right_rotate(node* x) { node* y = x->left; x->left = y->right; if (y->right != nil()) { y->right->p = x; } y->p = x->p; if (x->p == nil()) { _M_root = y; } else if (x == x->p->right) { x->p->right = y; } else { x->p->left = y; } y->right = x; x->p = y; } template<typename _Key, typename _Value, typename _Compare> void red_black_tree<_Key, _Value, _Compare>::insert_fixup(node* z) { while (z->p->color == kRed) { if (z->p == z->p->p->left) { node* y = z->p->p->right; if (y->color == kRed) { z->p->color = kBlack; y->color = kBlack; z->p->p->color = kRed; z = z->p->p; } else { if (z == z->p->right) { z = z->p; left_rotate(z); } z->p->color = kBlack; z->p->p->color = kRed; right_rotate(z->p->p); } } else { node* y = z->p->p->left; if (y->color == kRed) { z->p->color = kBlack; y->color = kBlack; z->p->p->color = kRed; z = z->p->p; } else { if (z == z->p->left) { z = z->p; right_rotate(z); } z->p->color = kBlack; z->p->p->color = kRed; left_rotate(z->p->p); } } } _M_root->color = kBlack; } template<typename _Key, typename _Value, typename _Compare> inline void red_black_tree<_Key, _Value, _Compare>::transplant(node* u, node* v) { if (u->p == nil()) { _M_root = v; } else if (u == u->p->left) { u->p->left = v; } else { u->p->right = v; } v->p = u->p; } template<typename _Key, typename _Value, typename _Compare> void red_black_tree<_Key, _Value, _Compare>::delete_fixup(node* x) { while ((x != _M_root) && (x->color == kBlack)) { if (x == x->p->left) { node* w = x->p->right; if (w->color == kRed) { w->color = kBlack; x->p->color = kRed; left_rotate(x->p); w = x->p->right; } if ((w->left->color == kBlack) && (w->right->color == kBlack)) { w->color = kRed; x = x->p; } else { if (w->right->color == kBlack) { w->left->color = kBlack; w->color = kRed; right_rotate(w); w = x->p->right; } w->color = x->p->color; x->p->color = kBlack; w->right->color = kBlack; left_rotate(x->p); x = _M_root; } } else { node* w = x->p->left; if (w->color == kRed) { w->color = kBlack; x->p->color = kRed; right_rotate(x->p); w = x->p->left; } if ((w->right->color == kBlack) && (w->left->color == kBlack)) { w->color = kRed; x = x->p; } else { if (w->left->color == kBlack) { w->right->color = kBlack; w->color = kRed; left_rotate(w); w = x->p->left; } w->color = x->p->color; x->p->color = kBlack; w->left->color = kBlack; right_rotate(x->p); x = _M_root; } } } x->color = kBlack; } template<typename _Key, typename _Value, typename _Compare> inline typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::create(const _Key& key, const _Value& value) { #if HAVE_FREE_LIST if (!_M_free) { return new (std::nothrow) node(key, value); } node* n = _M_free; _M_free = _M_free->left; return new (n) node(key, value); #else return new (std::nothrow) node(key, value); #endif } #if HAVE_FREE_LIST template<typename _Key, typename _Value, typename _Compare> inline void red_black_tree<_Key, _Value, _Compare>::add_free_list(node* node) { node->left = _M_free; _M_free = node; } #endif // HAVE_FREE_LIST template<typename _Key, typename _Value, typename _Compare> void red_black_tree<_Key, _Value, _Compare>::erase_subtree(node* node) { if (node->left != nil()) { erase_subtree(node->left); } if (node->right != nil()) { erase_subtree(node->right); } delete node; } template<typename _Key, typename _Value, typename _Compare> inline typename red_black_tree<_Key, _Value, _Compare>::node* red_black_tree<_Key, _Value, _Compare>::nil() { return &_M_nil; } } #endif // UTIL_RED_BLACK_TREE_H
guidoreina/classes
util/concurrent/skiplist.h
#ifndef UTIL_CONCURRENT_SKIPLIST_H #define UTIL_CONCURRENT_SKIPLIST_H // Implementation of a concurrent skiplist following the algorithm described // in the book: "The Art of Multiprocessor Programming, Revised Print" // http://www.amazon.com/books/dp/0123973376 // and in the algorithm described in: "Practical lock-freedom" // http://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf // // Notes: // As nodes cannot be freed directly, they are saved in a list until the // list reaches 'kThreshold' nodes. At this point the oldest node will be // deleted. #include <stdlib.h> #include <new> #include "util/minus.h" #include "util/concurrent/atomic/markable_ptr.h" #include "util/concurrent/atomic/atomic.h" #include "util/concurrent/locks/spinlock.h" // For the list of deleted nodes. // Thread Local Storage. static __thread struct drand48_data random_data = {{0xc0}}; namespace util { namespace concurrent { template<typename _Key, typename _Compare = util::minus<_Key> > class skiplist { public: // Constructor. skiplist(); skiplist(const _Compare& cmp); // Destructor. ~skiplist(); // Initialize. bool init(); // Insert. bool insert(const _Key& k); // Erase. bool erase(const _Key& k); // Contains. bool contains(const _Key& k) const; class iterator { friend class skiplist; public: const _Key& key() const; private: _Key k; }; // Begin. bool begin(iterator& it) const; // End. bool end(iterator& it) const; // Previous. bool previous(iterator& it) const; // Next. bool next(iterator& it) const; // Seek. bool seek(const _Key& k, iterator& it) const; private: // [Probability] p = 0.25 // [Maximum number of elements] N = 4294967296 // L(n) = log1/p(n) // kMaxLevel = L(N) = log4(4294967296) = 16 static const int kMaxLevel = 16; struct node { // Key. const _Key key; // Level. int level; // Next deleted node. node* next_deleted; // Previous deleted node. node* prev_deleted; concurrent::atomic::markable_ptr<node> next[1]; // Constructor. node(int height); node(const _Key& k, int height); }; node* _M_header; int _M_level_hint; _Compare _M_compare; struct nodelist { static const int kThreshold = 32 * 1024; node* head; node* tail; int count; concurrent::locks::spinlock lock; // Insert. void insert(node* n); }; nodelist _M_free_nodes; // Find. bool find(const _Key& k, node** preds, node** succs); bool find(const _Key& k, const node** preds, const node** succs) const; // Make node. node* make_node(int height); node* make_node(const _Key& k, int height); // Allocate node. node* allocate_node(int height); // Delete node. void delete_node(node* n); // Random level. int random_level(); }; template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::skiplist() : _M_header(NULL), _M_level_hint(1), _M_compare() { _M_free_nodes.head = NULL; _M_free_nodes.tail = NULL; _M_free_nodes.count = 0; } template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::skiplist(const _Compare& cmp) : _M_header(NULL), _M_level_hint(1), _M_compare(cmp) { _M_free_nodes.head = NULL; _M_free_nodes.tail = NULL; _M_free_nodes.count = 0; } template<typename _Key, typename _Compare> skiplist<_Key, _Compare>::~skiplist() { node* n = _M_header; while (n) { node* next = n->next[0].get(); delete_node(n); n = next; } n = _M_free_nodes.head; while (n) { node* next = n->next_deleted; delete_node(n); n = next; } } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::init() { // Create header. if ((_M_header = make_node(kMaxLevel)) == NULL) { return false; } // Initialize forward pointers to NULL. for (int i = 0; i < kMaxLevel; i++) { _M_header->next[i] = NULL; } return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::insert(const _Key& k) { int level = random_level(); node* preds[kMaxLevel]; node* succs[kMaxLevel]; node* new_node = NULL; do { if (find(k, preds, succs)) { // Already inserted. if (new_node) { delete_node(new_node); } return false; } // Create node. if ((!new_node) && ((new_node = make_node(k, level)) == NULL)) { return false; } // Set successor pointers. for (int i = 0; i < level; i++) { new_node->next[i] = succs[i]; } // Node is considered inserted when it is linked at level 0. if (preds[0]->next[0].compare_and_swap(succs[0], new_node, false, false)) { break; } } while (true); for (int i = 1; i < level; i++) { do { // If 'new_node' has been marked as deleted... concurrent::atomic::markable_ptr<node> next = new_node->next[i]; if (next.marked()) { find(k, preds, succs); return true; } if (next.get() != succs[i]) { bool oldmark; if ((!new_node->next[i].compare_and_swap(next.get(), succs[i], false, false, oldmark)) && (oldmark)) { // 'new_node' has been marked as deleted... find(k, preds, succs); return true; } } if (preds[i]->next[i].compare_and_swap(succs[i], new_node, false, false)) { break; } find(k, preds, succs); } while (true); } // If 'new_node' has been marked as deleted... if (new_node->next[level - 1].marked()) { find(k, preds, succs); } return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::erase(const _Key& k) { node* preds[kMaxLevel]; node* succs[kMaxLevel]; if (!find(k, preds, succs)) { // Not found. return false; } node* node_to_delete = succs[0]; for (int level = node_to_delete->level - 1; level >= 0; level--) { do { bool oldmark; node* succ = node_to_delete->next[level].get(); // Try to mark the node as deleted. if (!node_to_delete->next[level].compare_and_swap(succ, succ, false, true, oldmark)) { // If the node has been already marked as deleted... if (oldmark) { if (level == 0) { // Another thread has just deleted the same node. return false; } // Some other thread has marked the node as deleted. break; } } else { // Node has been marked as deleted. break; } } while (true); } find(k, preds, succs); // Add node to the list of free nodes. _M_free_nodes.insert(node_to_delete); return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::contains(const _Key& k) const { const node* pred = _M_header; for (int level = _M_level_hint - 1; level >= 0; level--) { bool marked; const node* curr = pred->next[level].get(marked); // If 'pred' has just been marked as deleted... if (marked) { return contains(k); } while (curr) { // While 'curr' has been marked as deleted... const node* succ = curr->next[level].get(marked); while (marked) { if ((curr = succ) == NULL) { break; } succ = curr->next[level].get(marked); } if (curr) { int ret; if ((ret = _M_compare(curr->key, k)) < 0) { pred = curr; curr = succ; } else if (ret == 0) { return true; } else { break; } } else { break; } } } return false; } template<typename _Key, typename _Compare> inline const _Key& skiplist<_Key, _Compare>::iterator::key() const { return k; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::begin(iterator& it) const { const node* pred = _M_header; const node* curr; if ((curr = pred->next[0].get()) == NULL) { return false; } // While 'curr' has been marked as deleted... bool marked; const node* succ = curr->next[0].get(marked); while (marked) { if ((curr = succ) == NULL) { return false; } succ = curr->next[0].get(marked); } it.k = curr->key; return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::end(iterator& it) const { const node* pred = _M_header; for (int level = _M_level_hint - 1; level >= 0; level--) { bool marked; const node* curr = pred->next[level].get(marked); // If 'pred' has just been marked as deleted... if (marked) { return end(it); } while (curr) { // While 'curr' has been marked as deleted... const node* succ = curr->next[level].get(marked); while (marked) { if ((curr = succ) == NULL) { break; } succ = curr->next[level].get(marked); } if (curr) { pred = curr; curr = succ; } else { break; } } } // If the list is empty... if (pred == _M_header) { return false; } it.k = pred->key; return true; } template<typename _Key, typename _Compare> inline bool skiplist<_Key, _Compare>::previous(iterator& it) const { const node* preds[kMaxLevel]; const node* succs[kMaxLevel]; find(it.k, preds, succs); if (preds[0] == _M_header) { return false; } it.k = preds[0]->key; return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::next(iterator& it) const { const node* preds[kMaxLevel]; const node* succs[kMaxLevel]; const node* curr; if (!find(it.k, preds, succs)) { if ((curr = succs[0]) == NULL) { return false; } } else { if (((curr = succs[0]) == NULL) || ((curr = curr->next[0].get()) == NULL)) { return false; } // While 'curr' has been marked as deleted... bool marked; const node* succ = curr->next[0].get(marked); while (marked) { if ((curr = succ) == NULL) { return false; } succ = curr->next[0].get(marked); } } it.k = curr->key; return true; } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::seek(const _Key& k, iterator& it) const { const node* preds[kMaxLevel]; const node* succs[kMaxLevel]; const node* succ; find(k, preds, succs); if ((succ = succs[0]) == NULL) { return false; } it.k = succ->key; return true; } template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::node::node(int height) : key(), level(height) { } template<typename _Key, typename _Compare> inline skiplist<_Key, _Compare>::node::node(const _Key& k, int height) : key(k), level(height) { } template<typename _Key, typename _Compare> void skiplist<_Key, _Compare>::nodelist::insert(node* n) { lock.lock(); n->prev_deleted = NULL; n->next_deleted = head; if (!tail) { tail = n; count++; } else { head->prev_deleted = n; if (count == kThreshold) { node* last = tail; tail = tail->prev_deleted; tail->next_deleted = NULL; // Call the destructor. last->~node(); // Free the memory. free(last); } else { count++; } } head = n; lock.unlock(); } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::find(const _Key& k, node** preds, node** succs) { int ret = -1; node* pred = _M_header; for (int level = _M_level_hint - 1; level >= 0; level--) { bool marked; node* curr = pred->next[level].get(marked); // If 'pred' has just been marked as deleted... if (marked) { return find(k, preds, succs); } while (curr) { // While 'curr' has been marked as deleted... node* succ = curr->next[level].get(marked); while (marked) { if (!pred->next[level].compare_and_swap(curr, succ, false, false)) { // Retry. return find(k, preds, succs); } if ((curr = succ) == NULL) { break; } succ = curr->next[level].get(marked); } if ((curr) && ((ret = _M_compare(curr->key, k)) < 0)) { pred = curr; curr = succ; } else { break; } } preds[level] = pred; succs[level] = curr; } return (ret == 0); } template<typename _Key, typename _Compare> bool skiplist<_Key, _Compare>::find(const _Key& k, const node** preds, const node** succs) const { int ret = -1; const node* pred = _M_header; for (int level = _M_level_hint - 1; level >= 0; level--) { bool marked; const node* curr = pred->next[level].get(marked); // If 'pred' has just been marked as deleted... if (marked) { return find(k, preds, succs); } while (curr) { // While 'curr' has been marked as deleted... const node* succ = curr->next[level].get(marked); while (marked) { if ((curr = succ) == NULL) { break; } succ = curr->next[level].get(marked); } if ((curr) && ((ret = _M_compare(curr->key, k)) < 0)) { pred = curr; curr = succ; } else { break; } } preds[level] = pred; succs[level] = curr; } return (ret == 0); } template<typename _Key, typename _Compare> inline struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::make_node(int height) { node* n; if ((n = allocate_node(height)) == NULL) { return NULL; } return new (n) node(height); } template<typename _Key, typename _Compare> inline struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::make_node(const _Key& k, int height) { node* n; if ((n = allocate_node(height)) == NULL) { return NULL; } return new (n) node(k, height); } template<typename _Key, typename _Compare> inline struct skiplist<_Key, _Compare>::node* skiplist<_Key, _Compare>::allocate_node(int height) { return reinterpret_cast<node*>(malloc(sizeof(node) + ((height - 1) * sizeof(concurrent::atomic::markable_ptr<node>)))); } template<typename _Key, typename _Compare> inline void skiplist<_Key, _Compare>::delete_node(node* n) { // Call the destructor. n->~node(); // Free the memory. free(n); } template<typename _Key, typename _Compare> int skiplist<_Key, _Compare>::random_level() { static const unsigned FRACTION_P = 4; int level = 1; long rand; do { lrand48_r(&random_data, &rand); if ((rand % FRACTION_P) == 0) { level++; } else { break; } } while (level < kMaxLevel); // Increment level hint if required. int level_hint; do { if ((level_hint = _M_level_hint) >= level) { break; } } while (!concurrent::atomic::bool_compare_and_swap(&_M_level_hint, level_hint, level)); return level; } } } #endif // UTIL_CONCURRENT_SKIPLIST_H
guidoreina/classes
util/concurrent/locks/condvar.h
#ifndef UTIL_CONCURRENT_LOCKS_CONDVAR_H #define UTIL_CONCURRENT_LOCKS_CONDVAR_H #include <stdlib.h> #include <string.h> #include <stdio.h> #include <time.h> #include <pthread.h> namespace util { namespace concurrent { namespace locks { class condvar { public: // Constructor. condvar(); // Destructor. ~condvar(); // Lock. bool lock(); // Notify one thread. bool notify(); // Notify all threads. bool notify _all(); // Wait. bool wait(); bool wait(unsigned long usec); private: pthread_cond_t _M_cond; pthread_mutex_t _M_mutex; }; inline condvar::condvar() { int ret; if ((ret = pthread_cond_init(&_M_cond, NULL)) != 0) { fprintf(stderr, "pthread_cond_init() failed (%s).\n", strerror(ret)); abort(); } if ((ret = pthread_mutex_init(&_M_mutex, NULL)) != 0) { fprintf(stderr, "pthread_mutex_init() failed (%s).\n", strerror(ret)); pthread_cond_destroy(&_M_cond); abort(); } } inline condvar::~condvar() { pthread_cond_destroy(&_M_cond); pthread_mutex_destroy(&_M_mutex); } inline bool condvar::lock() { return (pthread_mutex_lock(&_M_mutex) == 0); } inline bool condvar::notify() { return (pthread_cond_signal(&_M_cond) == 0); } inline bool condvar::notify_all() { return (pthread_cond_broadcast(&_M_cond) == 0); } inline bool condvar::wait() { return (pthread_cond_wait(&_M_cond, &_M_mutex) == 0); } inline bool condvar::wait(unsigned long usec) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); long tv_nsec = ts.tv_nsec + ((usec % 1000000) * 1000); ts.tv_sec += ((usec / 1000000) + (tv_nsec % 1000000000)); ts.tv_nsec = tv_nsec % 1000000000; return (pthread_cond_timedwait(&_M_cond, &_M_mutex, &ts) == 0); } } } } #endif // UTIL_CONCURRENT_LOCKS_CONDVAR_H
guidoreina/classes
util/move.h
<filename>util/move.h #ifndef UTIL_MOVE_H #define UTIL_MOVE_H namespace util { template<typename _T> struct remove_reference { typedef _T type; }; template<typename _T> struct remove_reference<_T&> { typedef _T type; }; template<typename _T> struct remove_reference<_T&&> { typedef _T type; }; template<typename _T> constexpr typename remove_reference<_T>::type&& move(_T&& a) noexcept { return static_cast<typename remove_reference<_T>::type&&>(a); } template<typename _T> inline void swap(_T& a, _T& b) { _T tmp(util::move(a)); a = util::move(b); b = util::move(tmp); } } #endif // UTIL_MOVE_H
guidoreina/classes
string/buffer.h
<filename>string/buffer.h<gh_stars>1-10 #ifndef STRING_BUFFER_H #define STRING_BUFFER_H #include <stdlib.h> #include <string.h> #include <stdarg.h> namespace string { class buffer { public: static const size_t kDefaultInitialSize = 64; // Constructor. buffer(size_t initial_size = kDefaultInitialSize); // Destructor. virtual ~buffer(); // Free buffer. void free(); // Reset buffer. void reset(); // Get data. const char* data() const; char* data(); // Get end. char* end(); // Get size. size_t size() const; // Get count. size_t count() const; // Set count. void count(size_t value); // Increment count. void increment_count(size_t inc); // Set initial size. void set_initial_size(size_t initial_size); // Allocate memory. bool allocate(size_t size); // Append. bool append(char c); bool append(const char* string); bool append(const char* string, size_t len); // Append NUL-terminated string. bool append_nul_terminated_string(const char* string, size_t len); // Format string. bool format(const char* format, ...); bool vformat(const char* format, va_list ap); protected: char* _M_data; size_t _M_size; size_t _M_used; size_t _M_initial_size; }; inline buffer::buffer(size_t initial_size) { _M_data = NULL; _M_size = 0; _M_used = 0; set_initial_size(initial_size); } inline buffer::~buffer() { free(); } inline void buffer::free() { if (_M_data) { ::free(_M_data); _M_data = NULL; } _M_size = 0; _M_used = 0; } inline void buffer::reset() { _M_used = 0; } inline const char* buffer::data() const { return _M_data; } inline char* buffer::data() { return _M_data; } inline char* buffer::end() { return _M_data + _M_used; } inline size_t buffer::size() const { return _M_size; } inline size_t buffer::count() const { return _M_used; } inline void buffer::count(size_t value) { _M_used = value; } inline void buffer::increment_count(size_t inc) { _M_used += inc; } inline void buffer::set_initial_size(size_t initial_size) { if (initial_size == 0) { _M_initial_size = kDefaultInitialSize; } else { _M_initial_size = initial_size; } } inline bool buffer::append(char c) { if (!allocate(1)) { return false; } _M_data[_M_used++] = c; return true; } inline bool buffer::append(const char* string) { if (!string) { return true; } return append(string, strlen(string)); } inline bool buffer::append(const char* string, size_t len) { if (len == 0) { return true; } if (!allocate(len)) { return false; } memcpy(_M_data + _M_used, string, len); _M_used += len; return true; } inline bool buffer::append_nul_terminated_string(const char* string, size_t len) { if (!allocate(len + 1)) { return false; } memcpy(_M_data + _M_used, string, len); _M_used += len; _M_data[_M_used++] = 0; return true; } inline bool buffer::format(const char* format, ...) { va_list ap; va_start(ap, format); bool ret = vformat(format, ap); va_end(ap); return ret; } } #endif // STRING_BUFFER_H
guidoreina/classes
util/concurrent/atomic/atomic.h
#ifndef UTIL_CONCURRENT_ATOMIC_ATOMIC_H #define UTIL_CONCURRENT_ATOMIC_ATOMIC_H namespace util { namespace concurrent { namespace atomic { static inline void memory_barrier() { asm volatile("" : : : "memory"); } template<typename _T> static inline bool bool_compare_and_swap(_T* ptr, _T oldval, _T newval) { return __sync_bool_compare_and_swap(ptr, oldval, newval); } template<typename _T> static inline _T val_compare_and_swap(_T* ptr, _T oldval, _T newval) { return __sync_val_compare_and_swap(ptr, oldval, newval); } template<typename _T> static inline _T add(_T* ptr, _T val) { return __sync_fetch_and_add(ptr, val); } template<typename _T> static inline _T sub(_T* ptr, _T val) { return __sync_fetch_and_sub(ptr, val); } template<typename _T> static inline _T acquire_load(const _T* ptr) { #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) return __atomic_load_n(ptr, __ATOMIC_ACQUIRE); #else __sync_synchronize(); _T res = *ptr; __sync_synchronize(); return res; #endif } template<typename _T> static inline void release_store(_T* ptr, _T val) { #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) __atomic_store_n(ptr, val, __ATOMIC_RELEASE); #else __sync_synchronize(); *ptr = val; __sync_synchronize(); #endif } } } } #endif // UTIL_CONCURRENT_ATOMIC_ATOMIC_H
guidoreina/classes
util/file_block_reader.h
<reponame>guidoreina/classes<filename>util/file_block_reader.h<gh_stars>1-10 #ifndef UTIL_FILE_BLOCK_READER_H #define UTIL_FILE_BLOCK_READER_H #include "util/block_reader.h" #include "fs/file.h" namespace util { class file_block_reader : public block_reader { public: // Constructor. file_block_reader(fs::file& file); protected: ssize_t read(void* buf, size_t count, int timeout, error& err); private: fs::file& _M_file; }; inline file_block_reader::file_block_reader(fs::file& file) : _M_file(file) { } } #endif // UTIL_FILE_BLOCK_READER_H
guidoreina/classes
util/fifo.h
#ifndef UTIL_FIFO_H #define UTIL_FIFO_H #include <stdlib.h> #include <memory> #include "util/move.h" namespace util { template<typename _T> class fifo { public: // Constructor. fifo(); fifo(fifo&& other); // Destructor. ~fifo(); // Clear. void clear(); // Empty? bool empty() const; // Get number of elements. size_t count() const; // Push element. bool push(const _T& x); bool push(_T&& x); // Pop element. bool pop(); // Front element. _T* front(); const _T* front() const; // Back element. _T* back(); const _T* back() const; private: struct node { _T elem; node* next; // Constructor. node(const _T& x); node(_T&& x); }; node* _M_head; node* _M_tail; #if HAVE_FREE_LIST node* _M_free; #endif // HAVE_FREE_LIST size_t _M_count; // Create node. node* create(const _T& x); node* create(_T&& x); // Push. void push(node* node); #if HAVE_FREE_LIST // Add node to free list. void add_free_list(node* node); #endif // HAVE_FREE_LIST // Disable copy constructor and assignment operator. fifo(const fifo&) = delete; fifo& operator=(const fifo&) = delete; }; template<typename _T> inline fifo<_T>::fifo() : _M_head(NULL), _M_tail(NULL), #if HAVE_FREE_LIST _M_free(NULL), #endif // HAVE_FREE_LIST _M_count(0) { } template<typename _T> inline fifo<_T>::fifo(fifo&& other) { _M_head = other._M_head; _M_tail = other._M_tail; #if HAVE_FREE_LIST _M_free = other._M_free; #endif // HAVE_FREE_LIST _M_count = other._M_count; other._M_head = NULL; other._M_tail = NULL; #if HAVE_FREE_LIST other._M_free = NULL; #endif // HAVE_FREE_LIST } template<typename _T> inline fifo<_T>::~fifo() { clear(); } template<typename _T> void fifo<_T>::clear() { while (_M_head) { node* next = _M_head->next; delete _M_head; _M_head = next; } _M_tail = NULL; #if HAVE_FREE_LIST while (_M_free) { node* next = _M_free->next; delete _M_free; _M_free = next; } #endif // HAVE_FREE_LIST _M_count = 0; } template<typename _T> inline bool fifo<_T>::empty() const { return (_M_head == NULL); } template<typename _T> inline size_t fifo<_T>::count() const { return _M_count; } template<typename _T> inline bool fifo<_T>::push(const _T& x) { node* node; if ((node = create(x)) == NULL) { return false; } push(node); return true; } template<typename _T> inline bool fifo<_T>::push(_T&& x) { node* node; if ((node = create(x)) == NULL) { return false; } push(node); return true; } template<typename _T> bool fifo<_T>::pop() { // If the list is empty... if (!_M_head) { return false; } // Save head. node* node = _M_head; // Advance head. if ((_M_head = _M_head->next) == NULL) { _M_tail = NULL; } #if HAVE_FREE_LIST // Call destructor. node->~node(); add_free_list(node); #else delete node; #endif _M_count--; return true; } template<typename _T> inline _T* fifo<_T>::front() { return _M_head ? &_M_head->elem : NULL; } template<typename _T> inline const _T* fifo<_T>::front() const { return _M_head ? &_M_head->elem : NULL; } template<typename _T> inline _T* fifo<_T>::back() { return _M_tail ? &_M_tail->elem : NULL; } template<typename _T> inline const _T* fifo<_T>::back() const { return _M_tail ? &_M_tail->elem : NULL; } template<typename _T> inline fifo<_T>::node::node(const _T& x) : elem(x) { } template<typename _T> inline fifo<_T>::node::node(_T&& x) : elem(util::move(x)) { } template<typename _T> inline typename fifo<_T>::node* fifo<_T>::create(const _T& x) { #if HAVE_FREE_LIST if (!_M_free) { return new (std::nothrow) node(x); } node* n = _M_free; _M_free = _M_free->next; return new (n) node(x); #else return new (std::nothrow) node(x); #endif } template<typename _T> inline typename fifo<_T>::node* fifo<_T>::create(_T&& x) { #if HAVE_FREE_LIST if (!_M_free) { return new (std::nothrow) node(x); } node* n = _M_free; _M_free = _M_free->next; return new (n) node(x); #else return new (std::nothrow) node(x); #endif } template<typename _T> void fifo<_T>::push(node* node) { node->next = NULL; if (!_M_head) { _M_head = node; } else { _M_tail->next = node; } _M_tail = node; _M_count++; } #if HAVE_FREE_LIST template<typename _T> inline void fifo<_T>::add_free_list(node* node) { node->next = _M_free; _M_free = node; } #endif // HAVE_FREE_LIST } #endif // UTIL_FIFO_H
guidoreina/classes
util/concurrent/atomic/markable_ptr.h
#ifndef UTIL_CONCURRENT_ATOMIC_MARKABLE_PTR_H #define UTIL_CONCURRENT_ATOMIC_MARKABLE_PTR_H #include <stdint.h> #include "util/concurrent/atomic/atomic.h" namespace util { namespace concurrent { namespace atomic { template<typename _T> class markable_ptr { public: // Constructor. markable_ptr(); markable_ptr(_T* ptr); markable_ptr(const markable_ptr& ptr); // Assignment operator. markable_ptr& operator=(_T* ptr); markable_ptr& operator=(const markable_ptr& ptr); // Get raw pointer. _T* get() const; // Get raw pointer and mark. _T* get(bool& marked) const; // Set raw pointer and mark. void set(_T* ptr, bool mark); // Pointer operator. _T* operator->() const; // Dereference operator. _T& operator*() const; // Mark. void mark(); // Unmark. void unmark(); // Marked? bool marked() const; // Compare and swap. bool compare_and_swap(_T* expected_ptr, _T* newptr, bool expected_mark, bool newmark); bool compare_and_swap(_T* expected_ptr, _T* newptr, bool expected_mark, bool newmark, bool& oldmark); private: _T* _M_ptr; }; template<typename _T> inline markable_ptr<_T>::markable_ptr() { } template<typename _T> inline markable_ptr<_T>::markable_ptr(_T* ptr) : _M_ptr(ptr) { } template<typename _T> inline markable_ptr<_T>::markable_ptr(const markable_ptr& ptr) : _M_ptr(ptr._M_ptr) { } template<typename _T> inline markable_ptr<_T>& markable_ptr<_T>::operator=(_T* ptr) { _M_ptr = ptr; return *this; } template<typename _T> inline markable_ptr<_T>& markable_ptr<_T>::operator=(const markable_ptr& ptr) { _M_ptr = ptr._M_ptr; return *this; } template<typename _T> inline _T* markable_ptr<_T>::get() const { return reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(_M_ptr) & ~0x1); } template<typename _T> inline _T* markable_ptr<_T>::get(bool& marked) const { _T* ptr = _M_ptr; marked = ((reinterpret_cast<uintptr_t>(ptr) & 0x1) != 0); return reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(ptr) & ~0x1); } template<typename _T> inline void markable_ptr<_T>::set(_T* ptr, bool mark) { _M_ptr = reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(ptr) | (!!mark)); } template<typename _T> inline _T* markable_ptr<_T>::operator->() const { return reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(_M_ptr) & ~0x1); } template<typename _T> inline _T& markable_ptr<_T>::operator*() const { return *(reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(_M_ptr) & ~0x1)); } template<typename _T> inline void markable_ptr<_T>::mark() { _M_ptr = reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(_M_ptr) | 0x1); } template<typename _T> inline void markable_ptr<_T>::unmark() { _M_ptr = reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(_M_ptr) & ~0x1); } template<typename _T> inline bool markable_ptr<_T>::marked() const { return ((reinterpret_cast<uintptr_t>(_M_ptr) & 0x1) != 0); } template<typename _T> inline bool markable_ptr<_T>::compare_and_swap(_T* expected_ptr, _T* newptr, bool expected_mark, bool newmark) { _T* oldval = reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(expected_ptr) | (!!expected_mark)); _T* newval = reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(newptr) | (!!newmark)); return util::concurrent::atomic::bool_compare_and_swap<_T*>(&_M_ptr, oldval, newval); } template<typename _T> inline bool markable_ptr<_T>::compare_and_swap(_T* expected_ptr, _T* newptr, bool expected_mark, bool newmark, bool& oldmark) { _T* oldval = reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(expected_ptr) | (!!expected_mark)); _T* newval = reinterpret_cast<_T*>(reinterpret_cast<uintptr_t>(newptr) | (!!newmark)); _T* ptr; if ((ptr = util::concurrent::atomic::val_compare_and_swap<_T*>(&_M_ptr, oldval, newval)) == oldval) { return true; } oldmark = ((reinterpret_cast<uintptr_t>(ptr) & 0x1) != 0); return false; } } } } #endif // UTIL_CONCURRENT_ATOMIC_MARKABLE_PTR_H
guidoreina/classes
ipc/message_queue.h
<reponame>guidoreina/classes<filename>ipc/message_queue.h<gh_stars>1-10 #ifndef IPC_MESSAGE_QUEUE_H #define IPC_MESSAGE_QUEUE_H #include <fcntl.h> #include <stdio.h> #include <mqueue.h> #include <limits.h> namespace ipc { class message_queue { public: // Constructor. message_queue(bool unlink_in_destructor = false); // Destructor. ~message_queue(); // Open. bool open(const char* name); bool open(const char* name, unsigned maxmsgs, size_t msgsize); // Close. bool close(); // Unlink message queue. bool unlink(); // Receive message. ssize_t recv(void* buf, size_t count, int timeout = -1); // Timeout in milliseconds. // Send message. bool send(const void* buf, size_t count, int timeout = -1); // Timeout in milliseconds. bool send(const void* buf, size_t count, unsigned priority, int timeout = -1); // Timeout in milliseconds. // Wait readable. bool wait_readable(int timeout); // Timeout in milliseconds. // Wait writable. bool wait_writable(int timeout); // Timeout in milliseconds. // Get message queue descriptor. mqd_t qd() const; private: char _M_name[NAME_MAX + 1]; mqd_t _M_qd; bool _M_unlink_in_destructor; }; inline message_queue::message_queue(bool unlink_in_destructor) : _M_qd(-1), _M_unlink_in_destructor(unlink_in_destructor) { *_M_name = 0; } inline message_queue::~message_queue() { close(); if ((_M_unlink_in_destructor) && (*_M_name)) { unlink(); } } inline bool message_queue::open(const char* name) { snprintf(_M_name, sizeof(_M_name), "/%s", name); return ((_M_qd = mq_open(_M_name, O_CREAT | O_RDWR | O_NONBLOCK, 0644, NULL)) != -1); } inline bool message_queue::open(const char* name, unsigned maxmsgs, size_t msgsize) { snprintf(_M_name, sizeof(_M_name), "/%s", name); struct mq_attr attr; attr.mq_flags = 0; attr.mq_maxmsg = maxmsgs; attr.mq_msgsize = msgsize; attr.mq_curmsgs = 0; return ((_M_qd = mq_open(_M_name, O_CREAT | O_RDWR | O_NONBLOCK, 0644, &attr)) != -1); } inline bool message_queue::close() { if (_M_qd != -1) { if (mq_close(_M_qd) < 0) { return false; } _M_qd = -1; } return true; } inline bool message_queue::unlink() { return (mq_unlink(_M_name) == 0); } inline bool message_queue::send(const void* buf, size_t count, int timeout) { return send(buf, count, 0, timeout); } inline mqd_t message_queue::qd() const { return _M_qd; } } #endif // IPC_MESSAGE_QUEUE_H
guidoreina/classes
net/http/date.h
<filename>net/http/date.h #ifndef NET_HTTP_DATE_H #define NET_HTTP_DATE_H #include <stdint.h> #include <time.h> #include "util/ctype.h" #include "macros/macros.h" namespace net { namespace http { class date { public: static time_t parse(const void* buf, size_t len, struct tm& timestamp); static time_t parse(const void* buf, size_t len); private: static time_t _M_parse_ansic(const uint8_t* begin, const uint8_t* end, struct tm& timestamp); static bool _M_parse_year(const uint8_t* ptr, unsigned& year); static bool _M_parse_month(const uint8_t* ptr, unsigned& mon); static bool _M_parse_time(const uint8_t* ptr, unsigned& hour, unsigned& min, unsigned& sec); }; inline time_t date::parse(const void* buf, size_t len) { struct tm timestamp; return parse(buf, len, timestamp); } inline bool date::_M_parse_year(const uint8_t* ptr, unsigned& year) { if ((!util::is_digit(*ptr)) || (!util::is_digit(*(ptr + 1))) || (!util::is_digit(*(ptr + 2))) || (!util::is_digit(*(ptr + 3)))) { return false; } year = ((*ptr - '0') * 1000) + ((*(ptr + 1) - '0') * 100) + ((*(ptr + 2) - '0') * 10) + (*(ptr + 3) - '0'); return (year >= 1970); } } } #endif // NET_HTTP_DATE_H
guidoreina/classes
util/varint.h
#ifndef UTIL_VARINT_H #define UTIL_VARINT_H // Varint: // https://developers.google.com/protocol-buffers/docs/encoding#varints #include <stdint.h> #include "string/buffer.h" namespace util { class varint { public: // Encode. static bool encode(uint64_t n, string::buffer& buf); static bool encode(uint64_t n, string::buffer& buf, size_t& len); // Decode. static bool decode(const char* s, size_t len, uint32_t& n); static bool decode(const char* s, size_t len, uint32_t& n, size_t& numlen); static bool decode(const char* s, size_t len, uint64_t& n); static bool decode(const char* s, size_t len, uint64_t& n, size_t& numlen); // Length. static size_t length(uint64_t n); }; inline bool varint::encode(uint64_t n, string::buffer& buf) { size_t len; return encode(n, buf, len); } inline bool varint::decode(const char* s, size_t len, uint32_t& n) { size_t numlen; return decode(s, len, n, numlen); } inline bool varint::decode(const char* s, size_t len, uint64_t& n) { size_t numlen; return decode(s, len, n, numlen); } inline size_t varint::length(uint64_t n) { size_t l = 1; while (n >= 0x80) { n >>= 7; l++; } return l; } } #endif // UTIL_VARINT_H
guidoreina/classes
util/block_reader.h
#ifndef UTIL_BLOCK_READER_H #define UTIL_BLOCK_READER_H #include "util/block.h" #include "string/buffer.h" namespace util { class block_reader { public: static const size_t kBufferSize = 4 * 1024; // Constructor. block_reader(); // Get next block. enum error { kNoMemory, kBlockTooBig, kReadError, kEndOfFile, kTimeout }; bool next(block& block, string::buffer& buf, int timeout); bool next(block& block, string::buffer& buf, int timeout, error& err); protected: unsigned char _M_buf[kBufferSize]; size_t _M_end; size_t _M_block; virtual ssize_t read(void* buf, size_t count, int timeout, error& err) = 0; }; inline block_reader::block_reader() : _M_end(0), _M_block(0) { } inline bool block_reader::next(block& block, string::buffer& buf, int timeout) { error err; return next(block, buf, timeout, err); } } #endif // UTIL_BLOCK_READER_H
guidoreina/classes
net/internet/scheme.h
#ifndef NET_INTERNET_SCHEME_H #define NET_INTERNET_SCHEME_H // Subset of the schemes. // http://www.iana.org/assignments/uri-schemes.html #include "macros/macros.h" namespace net { namespace internet { struct scheme { public: static const size_t kMaxLen = 32; static const unsigned char kFile = 0; static const unsigned char kFtp = 1; static const unsigned char kHttp = 2; static const unsigned char kHttps = 3; static const unsigned char kIcap = 4; static const unsigned char kImap = 5; static const unsigned char kLdap = 6; static const unsigned char kMailto = 7; static const unsigned char kNews = 8; static const unsigned char kNfs = 9; static const unsigned char kPop = 10; static const unsigned char kTelnet = 11; static const unsigned char kUnknown = 12; unsigned char value; // Constructor. scheme(); scheme(unsigned char v); const char* name() const; bool operator==(unsigned char v) const; bool operator!=(unsigned char v) const; // Search. static scheme search(const char* name, size_t len); // Valid scheme character? static bool valid_character(unsigned char c); private: struct _scheme { const char* name; size_t len; }; static const struct _scheme _M_schemes[]; }; inline scheme::scheme() { } inline scheme::scheme(unsigned char v) { value = v; } inline const char* scheme::name() const { if (value >= kUnknown) { return NULL; } return _M_schemes[value].name; } inline bool scheme::operator==(unsigned char v) const { return (v == value); } inline bool scheme::operator!=(unsigned char v) const { return (v != value); } inline bool scheme::valid_character(unsigned char c) { if ((IS_ALPHA(c)) || (IS_DIGIT(c))) { return true; } else { switch (c) { case '+': case '-': case '.': return true; default: return false; } } } } } #endif // NET_INTERNET_SCHEME_H
npmccallum/krb5-pake
src/server.c
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <krb5/kdcpreauth_plugin.h> #include "global.h" #include "common.h" #include "cookie.h" #include "kconv.h" #include "pake/conv.h" #include "pake/pake.h" #include <errno.h> #include <string.h> struct krb5_kdcpreauth_moddata_st { global global; }; typedef struct { ASN1_OCTET_STRING *hash; ASN1_OCTET_STRING *next; ASN1_OCTET_STRING *key; ASN1_OCTET_STRING *prv; } COOKIE; ASN1_SEQUENCE(COOKIE) = { ASN1_EXP_OPT(COOKIE, hash, ASN1_OCTET_STRING, 0), ASN1_EXP_OPT(COOKIE, next, ASN1_OCTET_STRING, 1), ASN1_EXP_OPT(COOKIE, key, ASN1_OCTET_STRING, 2), ASN1_EXP_OPT(COOKIE, prv, ASN1_OCTET_STRING, 3), } ASN1_SEQUENCE_END(COOKIE) IMPLEMENT_ASN1_FUNCTIONS(COOKIE) static krb5_error_code make_info_padata(const global *g, const krb5_keyblock *keys, krb5_pa_data **pa) { PAKE_MESSAGE msg = { .type = PAKE_MESSAGE_TYPE_INFO }; /* Get the info based on the keys. */ msg.value.info = global_info(g, keys); if (msg.value.info == NULL) return ENOTSUP; /* Encode the data. */ *pa = item2padata(&msg, PAKE_MESSAGE, PA_PAKE); PAKE_INFO_free(msg.value.info); return *pa == NULL ? ENOMEM : 0; } static krb5_error_code make_info_hash_cookie(const global *g, const krb5_keyblock *keys, const EVP_MD *md, COOKIE **cookie) { krb5_octet hbuf[EVP_MD_size(md)]; krb5_error_code retval = 0; krb5_pa_data *tmp = NULL; retval = make_info_padata(g, keys, &tmp); if (retval != 0) return retval; retval = common_hash_padata(md, NULL, tmp, hbuf); free(tmp->contents); free(tmp); if (retval != 0) return retval; *cookie = COOKIE_new(); if (cookie == NULL) return ENOMEM; (*cookie)->hash = str2os(hbuf, sizeof(hbuf)); if ((*cookie)->hash == NULL) { COOKIE_free(*cookie); *cookie = NULL; return ENOMEM; } return 0; } static krb5_error_code load_cookie(krb5_context context, const krb5_kdc_req *request, const krb5_keyblock *ask, COOKIE **cookie) { krb5_error_code retval = 0; *cookie = NULL; for (size_t i = 0; request->padata[i] != NULL; i++) { const unsigned char *tmp = NULL; krb5_pa_data *c = NULL; if (request->padata[i]->pa_type != KRB5_PADATA_FX_COOKIE) continue; retval = cookie_decrypt(context, request->server, ask, request->padata[i], &c); if (retval != 0) continue; tmp = c->contents; *cookie = d2i_COOKIE(NULL, &tmp, c->length); free(c->contents); free(c); if (*cookie == NULL) retval = EINVAL; else break; } return retval; } static krb5_error_code verify_exchange(krb5_context context, const krb5_kdc_req *request, const krb5_keyblock *ask, krb5_int32 ptype, const EC_GROUP *grp, const EVP_MD *md, COOKIE *cookie, const krb5_pa_data *pa, PAKE_MESSAGE *in, krb5_pa_data ***out, BN_CTX *ctx) { krb5_octet hbuf[EVP_MD_size(md)]; krb5_error_code retval = 0; krb5_keyblock *dsk = NULL; krb5_pa_data *tmp = NULL; EC_POINT *kek = NULL; COOKIE c = {}; if (cookie == NULL || cookie->hash == NULL || cookie->hash->length != EVP_MD_size(md)) return EINVAL; /* Create the PA data array. */ *out = calloc(3, sizeof(**out)); if (*out == NULL) { retval = ENOMEM; goto error; } /* Hash the incoming packet. */ retval = common_hash_padata(md, cookie->hash->data, pa, hbuf); if (retval != 0) goto error; /* On the first pass... */ if (cookie->prv == NULL && cookie->next == NULL) { /* Perform PAKE iteration. */ retval = common_pake(ptype, request, ask, true, grp, md, NULL, NULL, &cookie->next, &cookie->prv, &kek, ctx); if (retval != 0) goto error; } /* Create the output PA data. */ retval = common_padata(ptype, ask->enctype, grp, md, PAKE_MESSAGE_TYPE_EXCHANGE, cookie->next, &(*out)[0]); if (retval != 0) goto error; /* Hash the outgoing message. */ retval = common_hash_padata(md, hbuf, (*out)[0], hbuf); if (retval != 0) goto error; /* Store the hash state in the cookie. */ c.hash = str2os(hbuf, sizeof(hbuf)); if (c.hash == NULL) { retval = ENOMEM; goto error; } /* Perform next PAKE iteration. */ retval = common_pake(ptype, request, ask, true, grp, md, in->value.data->data, cookie->prv, &c.next, &c.prv, &kek, ctx); if (retval != 0) goto error; /* If the key is generated, save it for next time. */ if (kek != NULL) { retval = common_derive(context, request, ask, grp, md, hbuf, kek, &dsk, ctx); if (retval != 0) goto error; c.key = str2os(dsk->contents, dsk->length); if (c.key == NULL) { retval = ENOMEM; goto error; } } tmp = item2padata(&c, COOKIE, KRB5_PADATA_FX_COOKIE); if (tmp == NULL) { retval = ENOMEM; goto error; } retval = cookie_encrypt(context, request->server, ask, tmp, &(*out)[1]); free(tmp->contents); free(tmp); if (retval != 0) goto error; retval = KRB5KDC_ERR_MORE_PREAUTH_DATA_REQUIRED; error: if (retval != KRB5KDC_ERR_MORE_PREAUTH_DATA_REQUIRED) common_free_padata(out); krb5_free_keyblock(context, dsk); ASN1_OCTET_STRING_free(c.hash); ASN1_OCTET_STRING_free(c.next); ASN1_OCTET_STRING_free(c.key); ASN1_OCTET_STRING_free(c.prv); EC_POINT_free(kek); return retval; } static krb5_error_code verify_verifier(krb5_context context, const krb5_keyblock *ask, const EVP_MD *md, const PAKE_MESSAGE *in, const COOKIE *cookie, krb5_keyblock **dsk) { ASN1_OCTET_STRING *verifier = NULL; krb5_error_code retval = 0; if (cookie == NULL || cookie->key == NULL || (size_t) cookie->key->length != ask->length) return EINVAL; /* Load the key back from the cookie. */ retval = krb5_init_keyblock(context, ask->enctype, ask->length, dsk); if (retval != 0) return retval; memcpy((*dsk)->contents, cookie->key->data, cookie->key->length); /* Create the verifier. */ verifier = common_verifier(md, *dsk); if (verifier == NULL) { retval = ENOMEM; goto error; } /* Validate the password. */ if (ASN1_OCTET_STRING_cmp(verifier, in->value.data->data) != 0) { retval = KRB5KDC_ERR_PREAUTH_FAILED; goto error; } error: if (retval != 0) { krb5_free_keyblock(context, *dsk); *dsk = NULL; } ASN1_OCTET_STRING_free(verifier); return retval; } static void pake_edata(krb5_context context, krb5_kdc_req *request, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_preauthtype pa_type, krb5_kdcpreauth_edata_respond_fn respond, void *arg) { const global *g = &moddata->global; krb5_error_code retval = ENOMEM; krb5_pa_data *padata = NULL; krb5_keyblock *keys = NULL; /* If we have received a message, padata will be sent by pake_verify(). */ for (size_t i = 0; request->padata[i] != NULL; i++) { if (request->padata[i]->pa_type == PA_PAKE) { (*respond)(arg, EINVAL, NULL); return; } } /* Get the key for the client. */ retval = cb->client_keys(context, rock, &keys); if (retval != 0) goto error; retval = make_info_padata(g, keys, &padata); error: cb->free_keys(context, rock, keys); (*respond)(arg, retval, padata); } static void pake_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg) { const global *g = &moddata->global; const krb5_keyblock *ask = NULL; const EC_GROUP *grp = NULL; const EVP_MD *md = NULL; krb5_error_code retval = ENOMEM; krb5_pa_data **padata = NULL; krb5_keyblock *keys = NULL; krb5_keyblock *dsk = NULL; PAKE_MESSAGE *in = NULL; COOKIE *cookie = NULL; krb5_int32 ptype; /* Get the key. */ retval = cb->client_keys(context, rock, &keys); if (retval) goto error; /* Decode the PA data. */ in = padata2item(pa, PAKE_MESSAGE); switch (in == NULL ? PAKE_MESSAGE_TYPE_INFO : in->type) { case PAKE_MESSAGE_TYPE_EXCHANGE: case PAKE_MESSAGE_TYPE_VERIFIER: break; default: retval = EINVAL; /* Bad input. */ goto error; } /* Setup crypto. */ retval = global_profile(g, keys, in, &ptype, &ask, &grp, &md); if (retval != 0) goto error; /* Load the cookie. */ retval = load_cookie(context, request, ask, &cookie); if (retval != 0) { /* If no cookie was found, synthesize one containing * the hash of the (theoretically) sent PAKE_INFO. */ retval = make_info_hash_cookie(g, keys, md, &cookie); if (retval != 0) goto error; } switch (in->type) { case PAKE_MESSAGE_TYPE_EXCHANGE: retval = verify_exchange(context, request, ask, ptype, grp, md, cookie, pa, in, &padata, g->ctx); break; case PAKE_MESSAGE_TYPE_VERIFIER: retval = verify_verifier(context, ask, md, in, cookie, &dsk); if (retval == 0) enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH; break; default: retval = EINVAL; break; } error: cb->free_keys(context, rock, keys); COOKIE_free(cookie); PAKE_MESSAGE_free(in); (*respond)(arg, retval, (krb5_kdcpreauth_modreq) dsk, padata, NULL); } static krb5_error_code pake_return_padata(krb5_context context, krb5_pa_data *padata, krb5_data *req_pkt, krb5_kdc_req *request, krb5_kdc_rep *reply, krb5_keyblock *encrypting_key, krb5_pa_data **send_pa_out, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_modreq modreq) { krb5_keyblock *kb = (krb5_keyblock *) modreq; krb5_error_code retval; krb5_free_keyblock_contents(context, encrypting_key); retval = krb5_copy_keyblock_contents(context, kb, encrypting_key); krb5_free_keyblock(context, kb); return retval; } static krb5_error_code pake_init(krb5_context context, krb5_kdcpreauth_moddata *moddata_out, const char **realmnames) { krb5_kdcpreauth_moddata md; krb5_error_code retval; *moddata_out = calloc(1, sizeof(*md)); if (*moddata_out == NULL) return ENOMEM; retval = global_init(&(*moddata_out)->global); if (retval != 0) { free(*moddata_out); return retval; } OpenSSL_add_all_digests(); return 0; } static void pake_fini(krb5_context context, krb5_kdcpreauth_moddata moddata) { global_free(&moddata->global); free(moddata); EVP_cleanup(); } static int pake_flags(krb5_context context, krb5_preauthtype pa_type) { return PA_REPLACES_KEY; } krb5_error_code kdcpreauth_pake_initvt(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable) { static krb5_preauthtype types[] = { PA_PAKE, 0 }; krb5_kdcpreauth_vtable vt; if (maj_ver != 1) return KRB5_PLUGIN_VER_NOTSUPP; vt = (krb5_kdcpreauth_vtable)vtable; vt->name = "pake"; vt->pa_type_list = types; vt->init = pake_init; vt->fini = pake_fini; vt->flags = pake_flags; vt->edata = pake_edata; vt->verify = pake_verify; vt->return_padata = pake_return_padata; return 0; }
npmccallum/krb5-pake
src/pake/test.c
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "spake.h" #include "jpake.h" #include <openssl/err.h> #include <openssl/engine.h> #include <string.h> #include <stdint.h> #define ONE_OF(a, b) ((a != NULL) ^ (b != NULL)) #define OK "\e[0;32m" #define FAIL "\e[0;31m" #define RESET "\e[0m" typedef int (*pake_func)(const pake_ctx *pctx, const ASN1_OCTET_STRING *inmsg, const ASN1_OCTET_STRING *inprv, ASN1_OCTET_STRING **outmsg, ASN1_OCTET_STRING **outprv, EC_POINT **key); static BIGNUM * make_order(EC_GROUP *grp, BN_CTX *ctx) { BIGNUM *ord; ord = BN_new(); if (ord == NULL) return NULL; if (!EC_GROUP_get_order(grp, ord, ctx)) { BN_free(ord); return NULL; } return ord; } static bool test(pake_func pake, EC_GROUP *grp, const EVP_MD *md, const char *cpwd, const char *spwd, BN_CTX *ctx) { pake_ctx sctx = { .cname = "alice", .sname = "bob", .kdc = true, .ctx = ctx, .sec = BN_bin2bn((uint8_t *) spwd, strlen(spwd), NULL), .grp = grp, .ord = make_order(grp, ctx), .md = md }; pake_ctx cctx = { .cname = "alice", .sname = "bob", .kdc = false, .ctx = ctx, .sec = BN_bin2bn((uint8_t *) cpwd, strlen(cpwd), NULL), .grp = grp, .ord = make_order(grp, ctx), .md = md }; ASN1_OCTET_STRING *sinmsg = NULL; ASN1_OCTET_STRING *cinmsg = NULL; ASN1_OCTET_STRING *soutmsg = NULL; ASN1_OCTET_STRING *coutmsg = NULL; ASN1_OCTET_STRING *sinprv = NULL; ASN1_OCTET_STRING *cinprv = NULL; ASN1_OCTET_STRING *soutprv = NULL; ASN1_OCTET_STRING *coutprv = NULL; EC_POINT *skey = NULL; EC_POINT *ckey = NULL; bool result = false; int retval; if (cctx.sec == NULL || cctx.ord == NULL || sctx.sec == NULL || sctx.ord == NULL) goto egress; while (true) { /* Do the server side. */ retval = pake(&sctx, sinmsg, sinprv, &soutmsg, &soutprv, &skey); if (retval != 0 || ONE_OF(soutmsg, soutprv) || !ONE_OF(soutmsg, skey)) goto egress; /* Do the client side. */ retval = pake(&cctx, cinmsg, cinprv, &coutmsg, &coutprv, &ckey); if (retval != 0 || ONE_OF(coutmsg, coutprv) || !ONE_OF(coutmsg, ckey)) goto egress; /* Make sure that the client and server results are the same. */ if (ONE_OF(soutmsg, coutmsg)) goto egress; /* If a key was specified, we are done. */ if (skey != NULL && ckey != NULL) { result = EC_POINT_cmp(grp, ckey, skey, ctx) == 0; if (strcmp(cpwd, spwd) != 0) result = !result; goto egress; } /* Exchange messages. */ ASN1_OCTET_STRING_free(sinmsg); ASN1_OCTET_STRING_free(sinprv); ASN1_OCTET_STRING_free(cinmsg); ASN1_OCTET_STRING_free(cinprv); sinmsg = coutmsg; sinprv = soutprv; cinmsg = soutmsg; cinprv = coutprv; soutmsg = NULL; soutprv = NULL; coutmsg = NULL; coutprv = NULL; } egress: ASN1_OCTET_STRING_free(soutmsg); ASN1_OCTET_STRING_free(soutprv); ASN1_OCTET_STRING_free(coutmsg); ASN1_OCTET_STRING_free(coutprv); ASN1_OCTET_STRING_free(sinmsg); ASN1_OCTET_STRING_free(sinprv); ASN1_OCTET_STRING_free(cinmsg); ASN1_OCTET_STRING_free(cinprv); BN_free(sctx.sec); BN_free(sctx.ord); BN_free(cctx.sec); BN_free(cctx.ord); EC_POINT_free(skey); EC_POINT_free(ckey); return result; } #include <sys/time.h> static unsigned long gettime(void) { struct timeval tv = {}; unsigned long sec; while (gettimeofday(&tv, NULL) != 0) continue; sec = tv.tv_sec - 60 * 60 * 24 * 365 * 45; return sec * 1000 + tv.tv_usec / 1000; } int main() { static const struct { pake_func func; const char *name; } PAKES[] = { { SPAKE, "SPAKE" }, { JPAKE, "JPAKE" }, {} }; const EVP_MD *HASHES[] = { #ifndef OPENSSL_NO_MD5 EVP_md5(), #endif #ifndef OPENSSL_NO_SHA EVP_sha1(), #endif #ifndef OPENSSL_NO_SHA256 EVP_sha224(), EVP_sha256(), #endif #ifndef OPENSSL_NO_SHA512 EVP_sha384(), EVP_sha512(), #endif #ifndef OPENSSL_NO_WHIRLPOOL EVP_whirlpool(), #endif NULL }; bool megafail = false; BN_CTX *ctx; EC_builtin_curve curves[EC_get_builtin_curves(NULL, 0)]; EC_get_builtin_curves(curves, sizeof(curves) / sizeof(*curves)); OpenSSL_add_all_digests(); ctx = BN_CTX_new(); if (ctx == NULL) return 1; for (size_t i = 0; PAKES[i].func != NULL; i++) { for (size_t j = 0; j < sizeof(curves) / sizeof(*curves); j++) { EC_GROUP *grp; grp = EC_GROUP_new_by_curve_name(curves[j].nid); if (grp == NULL) continue; if (OBJ_nid2obj(curves[j].nid) == NULL) continue; for (size_t k = 0; HASHES[k] != NULL; k++) { unsigned long before = 0; unsigned long after = 0; bool fail = false; before = gettime(); fail |= !test(PAKES[i].func, grp, HASHES[k], "foo", "foo", ctx); fail |= !test(PAKES[i].func, grp, HASHES[k], "foo", "bar", ctx); after = gettime(); megafail |= fail; printf("%s⚫%s %5s %-10s %30s %05lu\n", fail ? FAIL : OK, RESET, PAKES[i].name, OBJ_nid2sn(EVP_MD_type(HASHES[k])), OBJ_nid2sn(curves[j].nid), after - before); } EC_GROUP_free(grp); } } BN_CTX_free(ctx); ENGINE_cleanup(); ERR_free_strings(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); return megafail ? 1 : 0; }
npmccallum/krb5-pake
src/pake/spake_constants.c
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define _GNU_SOURCE #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/sha.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #define SEED_TEMPLATE "%s point generation seed (%c)" /* Make the OID for the given group. */ static char * make_oid(const EC_GROUP *grp) { ASN1_OBJECT *obj = NULL; char *oid = NULL; int size; obj = OBJ_nid2obj(EC_GROUP_get_curve_name(grp)); if (obj == NULL) return NULL; size = OBJ_obj2txt(NULL, 0, obj, 1); if (size != 0) { oid = OPENSSL_malloc(size + 1); if (oid != NULL) { if (OBJ_obj2txt(oid, size + 1, obj, 1) != size) { OPENSSL_free(oid); oid = NULL; } } } ASN1_OBJECT_free(obj); return oid; } /* Find the smallest digest that is >= the point size. * If the point size is larger than all digests, use the largest digest. */ static const EVP_MD * find_digest(const EC_GROUP *grp, BN_CTX *ctx) { static struct { size_t size; int nid; } hashes[] = { { SHA_DIGEST_LENGTH, NID_sha1 }, { SHA224_DIGEST_LENGTH, NID_sha224 }, { SHA256_DIGEST_LENGTH, NID_sha256 }, { SHA384_DIGEST_LENGTH, NID_sha384 }, { SHA512_DIGEST_LENGTH, NID_sha512 }, {} }; size_t size; int hnid; size = EC_POINT_point2oct(grp, EC_GROUP_get0_generator(grp), POINT_CONVERSION_COMPRESSED, NULL, 0, ctx); if (size-- == 0) return NULL; for (size_t i = 0; hashes[i].size != 0; i++) { hnid = hashes[i].nid; if (size <= hashes[i].size) break; } return EVP_get_digestbynid(hnid); } /* Try to make a point on the curve given the digest. */ static EC_POINT * attempt(const EC_GROUP *grp, const uint8_t *digest, size_t dlen, BN_CTX *ctx) { EC_POINT *p = NULL; BIGNUM *x = NULL; size_t glen; int y; if (grp == NULL || digest == NULL) return NULL; glen = EC_POINT_point2oct(grp, EC_GROUP_get0_generator(grp), POINT_CONVERSION_COMPRESSED, NULL, 0, ctx); if (glen-- == 0) return NULL; y = digest[dlen - 1] & 1; /* Last bit. */ x = BN_bin2bn(digest, glen < dlen ? glen : dlen, NULL); if (x == NULL) return NULL; p = EC_POINT_new(grp); if (p == NULL) goto error; if (!EC_POINT_set_compressed_coordinates_GFp(grp, p, x, y, ctx)) { EC_POINT_free(p); p = NULL; } error: BN_free(x); return p; } /* Hash the seed onto the curve. Fails after 1,000 attempts. */ static EC_POINT * make_constant(const EC_GROUP *grp, const EVP_MD *md, const char *oid, char var, BN_CTX *ctx) { EC_POINT *p = NULL; int len; if (grp == NULL || md == NULL || oid == NULL) return NULL; len = snprintf(NULL, 0, SEED_TEMPLATE, oid, var); if (len < 1) return NULL; char seed[len + 1]; if (snprintf(seed, sizeof(seed), SEED_TEMPLATE, oid, var) != len) return NULL; uint8_t digest[EVP_MD_size(md)]; if (!EVP_Digest(seed, strlen(seed), digest, NULL, md, NULL)) return NULL; for (size_t i = 0; i < 1000 && p == NULL; i++) { p = attempt(grp, digest, sizeof(digest), ctx); EVP_Digest(digest, sizeof(digest), digest, NULL, md, NULL); } return p; } static bool print_curve(void *misc, EC_builtin_curve *curve, int digest, const char *oid, const char *m, const char *n) { if (printf("%s,%s,M,%s\n", OBJ_nid2sn(curve->nid), oid, m) < 0) return false; if (printf("%s,%s,N,%s\n", OBJ_nid2sn(curve->nid), oid, n) < 0) return false; return true; } static bool write_curve(void *misc, EC_builtin_curve *curve, int digest, const char *oid, const char *m, const char *n) { FILE *file = misc; if (fprintf(file, " { %d, /* %s (%s): %s */\n", curve->nid, OBJ_nid2sn(curve->nid), oid, curve->comment) < 0) return false; if (fprintf(file, " \"%s\",\n", m) < 0) return false; if (fprintf(file, " \"%s\" },\n\n", n) < 0) return false; return true; } static bool output_curve(EC_builtin_curve *curve, BN_CTX *ctx, void *misc, bool (*writer)(void *misc, EC_builtin_curve *curve, int digest, const char *oid, const char *m, const char *n)) { const EVP_MD *md = NULL; EC_GROUP *grp = NULL; EC_POINT *m = NULL; EC_POINT *n = NULL; char *hexm = NULL; char *hexn = NULL; char *oid = NULL; int ret = false; grp = EC_GROUP_new_by_curve_name(curve->nid); if (grp == NULL) goto error; oid = make_oid(grp); if (oid == NULL) { ret = true; /* Skip OIDless curves. */ goto error; } md = find_digest(grp, ctx); if (md == NULL) goto error; m = make_constant(grp, md, oid, 'M', ctx); n = make_constant(grp, md, oid, 'N', ctx); if (m == NULL || n == NULL) goto error; hexm = EC_POINT_point2hex(grp, m, POINT_CONVERSION_COMPRESSED, ctx); hexn = EC_POINT_point2hex(grp, n, POINT_CONVERSION_COMPRESSED, ctx); if (hexm == NULL || hexn == NULL) goto error; ret = writer(misc, curve, EVP_MD_type(md), oid, hexm, hexn); error: OPENSSL_free(hexn); OPENSSL_free(hexm); EC_POINT_free(n); EC_POINT_free(m); OPENSSL_free(oid); EC_GROUP_free(grp); return ret; } static void write_header(FILE *file) { fprintf(file, "/* This file is autogenerated: DO NOT EDIT. */\n\n"); fprintf(file, "static const struct {\n"); fprintf(file, " int curve;\n"); fprintf(file, " const char *m;\n"); fprintf(file, " const char *n;\n"); fprintf(file, "} SPAKE_CONSTANTS[] = {\n"); } static void write_footer(FILE *file) { fprintf(file, " {}\n"); fprintf(file, "};\n"); } int main(int argc, const char **argv) { BN_CTX *ctx = NULL; FILE *file = NULL; int ret = 1; if (argc > 2) { fprintf(stderr, "Usage: %s [<filename>]", argv[0]); return 1; } OpenSSL_add_all_algorithms(); EC_builtin_curve curves[EC_get_builtin_curves(NULL, 0)]; if (!EC_get_builtin_curves(curves, sizeof(curves) / sizeof(*curves))) return 1; if (argc == 2) { file = fopen(argv[1], "w"); if (file == NULL) { fprintf(stderr, "Error opening file (%s)!", argv[1]); return 1; } write_header(file); } ctx = BN_CTX_new(); if (ctx == NULL) goto error; for (size_t i = 0; i < sizeof(curves) / sizeof(*curves); i++) { bool success; if (file == NULL) success = output_curve(&curves[i], ctx, NULL, print_curve); else success = output_curve(&curves[i], ctx, file, write_curve); if (!success) { fprintf(stderr, "Error writing curve (%s)!\n", OBJ_nid2sn(curves[i].nid)); goto error; } } if (file != NULL) write_footer(file); ret = 0; error: BN_CTX_free(ctx); if (file != NULL) fclose(file); EVP_cleanup(); return ret; }
npmccallum/krb5-pake
src/cookie.c
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cookie.h" #include "pake/asn1.h" #include "pake/conv.h" #include "kconv.h" #include <kdb.h> #include <errno.h> #include <string.h> static krb5_error_code make_cookie_key(krb5_context context, krb5_const_principal tgs, const krb5_keyblock *key, krb5_keyblock **ekey) { krb5_db_entry *entry = NULL; krb5_key_data *kdata = NULL; krb5_error_code retval = 0; krb5_keyblock kblock = {}; krb5_int32 start = 0; /* Look up the TGS principal. */ retval = krb5_db_get_principal(context, tgs, KRB5_KDB_FLAG_ALIAS_OK, &entry); if (retval != 0) goto error; /* Find the key with the same enctype as the client key. */ retval = krb5_dbe_search_enctype(context, entry, &start, key->enctype, -1, 0, &kdata); if (retval != 0) goto error; /* Decrypt the TGS key. */ retval = krb5_dbe_decrypt_key_data(context, NULL, kdata, &kblock, NULL); if (retval != 0) goto error; /* Calculate the new key used for encrypting the cookie. */ retval = krb5_c_fx_cf2_simple(context, &kblock, "PAKE TGS", (krb5_keyblock *) key, "PAKE Client", ekey); krb5_free_keyblock_contents(context, &kblock); error: return retval; } krb5_error_code cookie_encrypt(krb5_context context, krb5_const_principal tgs, const krb5_keyblock *key, const krb5_pa_data *in, krb5_pa_data **out) { KRB5_ENCRYPTED_DATA ed = {}; krb5_error_code retval = 0; krb5_keyblock *ekey = NULL; krb5_enc_data ct = {}; krb5_data pt = { .data = (char *) in->contents, .length = in->length }; size_t ctlen; if (in->pa_type != KRB5_PADATA_FX_COOKIE) return EINVAL; /* Get the key used to encrypt the cookie. */ retval = make_cookie_key(context, tgs, key, &ekey); if (retval != 0) return retval; /* Find out how much buffer to allocate. */ retval = krb5_c_encrypt_length(context, ekey->enctype, in->length, &ctlen); if (retval != 0) { krb5_free_keyblock(context, ekey); return retval; } /* Allocate the output buffer. */ char buffer[ctlen]; ct.ciphertext.length = ctlen; ct.ciphertext.data = buffer; /* Perform the encryption. */ retval = krb5_c_encrypt(context, ekey, KRB5_KEYUSAGE_PA_FX_COOKIE, NULL, &pt, &ct); if (retval != 0) return retval; ed.cipher = str2os((krb5_octet *) ct.ciphertext.data, ct.ciphertext.length); ed.etype = int2integer(ct.enctype); ed.kvno = int2integer(0); if (ed.cipher == NULL || ed.etype == NULL || ed.kvno == NULL) { retval = ENOMEM; goto error; } /* Create the PA data. */ *out = item2padata(&ed, KRB5_ENCRYPTED_DATA, KRB5_PADATA_FX_COOKIE); if (*out == NULL) goto error; error: krb5_free_keyblock(context, ekey); ASN1_OCTET_STRING_free(ed.cipher); ASN1_INTEGER_free(ed.etype); ASN1_INTEGER_free(ed.kvno); return retval; } krb5_error_code cookie_decrypt(krb5_context context, krb5_const_principal tgs, const krb5_keyblock *key, const krb5_pa_data *in, krb5_pa_data **out) { KRB5_ENCRYPTED_DATA *ed = NULL; krb5_error_code retval = 0; krb5_keyblock *dkey = NULL; krb5_enc_data ct = {}; krb5_data pt = {}; if (in->pa_type != KRB5_PADATA_FX_COOKIE) return EINVAL; /* Parse the incoming data. */ ed = padata2item(in, KRB5_ENCRYPTED_DATA); if (ed == NULL) { retval = EINVAL; goto error; } /* Get the key used to encrypt the cookie. */ retval = make_cookie_key(context, tgs, key, &dkey); if (retval != 0) goto error; /* Make sure that the encrypted data has the same enctype as our key. */ if (ASN1_INTEGER_get(ed->etype) != dkey->enctype) { retval = EINVAL; goto error; } /* Prepare input for decryption. */ ct.enctype = ASN1_INTEGER_get(ed->etype); ct.ciphertext.length = ed->cipher->length; ct.ciphertext.data = (char *) ed->cipher->data; pt.length = ct.ciphertext.length; pt.data = malloc(pt.length); if (pt.data == NULL) { retval = ENOMEM; goto error; } /* Perform decryption. */ retval = krb5_c_decrypt(context, dkey, KRB5_KEYUSAGE_PA_FX_COOKIE, NULL, &ct, &pt); if (retval != 0) goto error; *out = calloc(1, sizeof(krb5_pa_data)); if (*out == NULL) goto error; (*out)->contents = (krb5_octet *) pt.data; (*out)->length = pt.length; (*out)->pa_type = KRB5_PADATA_FX_COOKIE; pt.data = NULL; error: krb5_free_keyblock(context, dkey); KRB5_ENCRYPTED_DATA_free(ed); free(pt.data); return retval; }
npmccallum/krb5-pake
src/global.c
/* * Copyright 2015 Red Hat, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "global.h" #include "pake/conv.h" #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/whrlpool.h> #include <errno.h> #include <stdbool.h> #include <string.h> /* The current ratio is 1.75, which allows (for instance): * AES128 => P224 */ #define CURVE_KEY_RATIO 1.75 struct curve { EC_GROUP *curve; const ASN1_OBJECT *obj; size_t size; }; struct hash { const EVP_MD *hash; const ASN1_OBJECT *obj; size_t size; }; static int curve_cmp(const void *a, const void *b) { const curve *const *aa = a; const curve *const *bb = b; return (*aa)->size - (*bb)->size; } static STACK_OF(ASN1_INTEGER) * ptypes(const global *g) { static const krb5_int32 pakes[] = { PA_PAKE_SPAKE, PA_PAKE_JPAKE, 0 }; STACK_OF(ASN1_INTEGER) *ptypes = NULL; ASN1_INTEGER *tmp = NULL; ptypes = sk_ASN1_INTEGER_new(NULL); if (ptypes == NULL) return NULL; for (size_t i = 0; pakes[i] != 0; i++) { tmp = int2integer(pakes[i]); if (tmp == NULL) goto error; if (!sk_ASN1_INTEGER_push(ptypes, tmp)) goto error; } return ptypes; error: sk_ASN1_INTEGER_free(ptypes); ASN1_INTEGER_free(tmp); return NULL; } static STACK_OF(ASN1_OBJECT) * groups(const global *g, const krb5_keyblock *key) { STACK_OF(ASN1_OBJECT) *sk; sk = sk_ASN1_OBJECT_new(NULL); if (sk == NULL) return NULL; for (size_t j = 0; g->curves[j] != NULL; j++) { if (g->curves[j]->size < key->length * CURVE_KEY_RATIO) continue; if (!sk_ASN1_OBJECT_push(sk, g->curves[j]->obj)) { sk_ASN1_OBJECT_free(sk); return NULL; } } return sk; } static STACK_OF(ASN1_OBJECT) * hashes(const global *g, const krb5_keyblock *key) { STACK_OF(ASN1_OBJECT) *sk; sk = sk_ASN1_OBJECT_new(NULL); if (sk == NULL) return NULL; for (size_t j = 0; g->hashes[j] != NULL; j++) { if (g->hashes[j]->size != key->length) continue; if (!sk_ASN1_OBJECT_push(sk, g->hashes[j]->obj)) { sk_ASN1_OBJECT_free(sk); return NULL; } } return sk; } static STACK_OF(PAKE_SUPPORT) * supports(const global *g, const krb5_keyblock *keys) { STACK_OF(PAKE_SUPPORT) *supports; supports = SKM_sk_new(PAKE_SUPPORT, NULL); if (supports == NULL) return NULL; for (size_t i = 0; keys[i].enctype != ENCTYPE_NULL; i++) { PAKE_SUPPORT *support; support = PAKE_SUPPORT_new(); if (support == NULL) goto error; support->etype = int2integer(keys[i].enctype); support->groups = groups(g, &keys[i]); support->hashes = hashes(g, &keys[i]); if (support->etype == NULL || support->groups == NULL || support->hashes == NULL) { PAKE_SUPPORT_free(support); goto error; } /* Skip keys with empty lists. */ if (sk_ASN1_OBJECT_num(support->groups) == 0 || sk_ASN1_OBJECT_num(support->hashes) == 0) { PAKE_SUPPORT_free(support); continue; } if (!SKM_sk_push(PAKE_SUPPORT, supports, support)) { PAKE_SUPPORT_free(support); goto error; } } return supports; error: SKM_sk_free(PAKE_SUPPORT, supports); return NULL; } static const EC_GROUP * group_load(const global *g, const krb5_keyblock *key, const ASN1_OBJECT *obj) { if (g == NULL || key == NULL || obj == NULL) return NULL; for (size_t i = 0; g->curves[i] != NULL; i++) { if (OBJ_cmp(g->curves[i]->obj, obj) != 0) continue; if (g->curves[i]->size >= key->length * CURVE_KEY_RATIO) return g->curves[i]->curve; } return NULL; } static const EC_GROUP * group_choose(const global *g, const krb5_keyblock *key, const STACK_OF(ASN1_OBJECT) *options) { if (g == NULL || key == NULL || options == NULL) return NULL; for (int i = 0; i < sk_ASN1_OBJECT_num(options); i++) { ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(options, i); const EC_GROUP *grp = group_load(g, key, obj); if (grp != NULL) return grp; } return NULL; } static const EVP_MD * hash_load(const global *g, const krb5_keyblock *key, const ASN1_OBJECT *obj) { if (g == NULL || key == NULL || obj == NULL) return NULL; for (size_t j = 0; g->hashes[j] != NULL; j++) { if (OBJ_cmp(g->hashes[j]->obj, obj) != 0) continue; if (g->hashes[j]->size == key->length) return g->hashes[j]->hash; } return NULL; } static const EVP_MD * hash_choose(const global *g, const krb5_keyblock *key, const STACK_OF(ASN1_OBJECT) *options) { if (g == NULL || key == NULL || options == NULL) return NULL; for (int i = 0; i < sk_ASN1_OBJECT_num(options); i++) { ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(options, i); const EVP_MD *md = hash_load(g, key, obj); if (md != NULL) return md; } return NULL; } static krb5_int32 ptype_load(const global *g, const ASN1_INTEGER *ptype) { switch (ASN1_INTEGER_get(ptype)) { case PA_PAKE_SPAKE: case PA_PAKE_JPAKE: return ASN1_INTEGER_get(ptype); } return 0; } static krb5_int32 ptype_choose(const global *g, const STACK_OF(ASN1_INTEGER) *options) { krb5_int32 ptype; for (int i = 0; i < sk_ASN1_INTEGER_num(options); i++) { ptype = ptype_load(g, sk_ASN1_INTEGER_value(options, i)); if (ptype != 0) return ptype; } return 0; } void global_free(global *g) { if (g == NULL) return; for (size_t i = 0; g->curves[i] != NULL; i++) { EC_GROUP_clear_free(g->curves[i]->curve); free(g->curves[i]); } free(g->curves); for (size_t i = 0; g->hashes[i] != NULL; i++) free(g->hashes[i]); free(g->hashes); BN_CTX_free(g->ctx); memset(g, 0, sizeof(*g)); } krb5_error_code global_init(global *g) { size_t ncurves; ncurves = EC_get_builtin_curves(NULL, 0); if (ncurves == 0) return EINVAL; EC_builtin_curve curves[ncurves]; const hash HASHES[] = { #ifndef OPENSSL_NO_MD5 { EVP_md5(), OBJ_nid2obj(NID_md5), MD5_DIGEST_LENGTH }, #endif #ifndef OPENSSL_NO_SHA { EVP_sha1(), OBJ_nid2obj(NID_sha1), SHA_DIGEST_LENGTH }, #endif #ifndef OPENSSL_NO_SHA256 { EVP_sha224(), OBJ_nid2obj(NID_sha224), SHA224_DIGEST_LENGTH }, { EVP_sha256(), OBJ_nid2obj(NID_sha256), SHA256_DIGEST_LENGTH }, #endif #ifndef OPENSSL_NO_SHA512 { EVP_sha384(), OBJ_nid2obj(NID_sha384), SHA384_DIGEST_LENGTH }, { EVP_sha512(), OBJ_nid2obj(NID_sha512), SHA512_DIGEST_LENGTH }, #endif #ifndef OPENSSL_NO_WHIRLPOOL { EVP_whirlpool(), OBJ_nid2obj(NID_whirlpool), WHIRLPOOL_DIGEST_LENGTH }, #endif {} }; g->ctx = BN_CTX_new(); g->curves = calloc(ncurves + 1, sizeof(curve *)); g->hashes = calloc(sizeof(HASHES) / sizeof(*HASHES), sizeof(hash *)); if (g->ctx == NULL || g->curves == NULL || g->hashes == NULL) goto error; EC_get_builtin_curves(curves, ncurves); for (size_t i = 0, j = 0; i < ncurves; i++) { const EC_POINT *gen; ASN1_OBJECT *obj; obj = OBJ_nid2obj(curves[i].nid); if (obj == NULL) continue; /* Skip curves without OIDs. */ g->curves[j] = malloc(sizeof(curve)); if (g->curves[j] == NULL) goto error; g->curves[j]->curve = EC_GROUP_new_by_curve_name(curves[i].nid); if (g->curves[j]->curve == NULL) goto error; gen = EC_GROUP_get0_generator(g->curves[j]->curve); g->curves[j]->size = EC_POINT_point2oct(g->curves[j]->curve, gen, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, g->ctx) / 2; g->curves[j]->obj = obj; j++; } /* Sort curves in size order to reduce unnecessary network traffic. */ for (ncurves = 0; g->curves[ncurves] != NULL; ncurves++) continue; qsort(g->curves, ncurves, sizeof(curve *), curve_cmp); for (size_t i = 0, j = 0; HASHES[i].size != 0; i++) { if (HASHES[i].hash == NULL) continue; g->hashes[j] = malloc(sizeof(hash)); if (g->hashes[j] == NULL) goto error; *g->hashes[j++] = HASHES[i]; } return 0; error: global_free(g); return ENOMEM; } PAKE_INFO * global_info(const global *g, const krb5_keyblock *keys) { PAKE_INFO *pinfo; pinfo = PAKE_INFO_new(); if (pinfo == NULL) return NULL; pinfo->ptypes = ptypes(g); pinfo->supports = supports(g, keys); if (pinfo->ptypes == NULL || pinfo->supports == NULL) { PAKE_INFO_free(pinfo); return NULL; } return pinfo; } krb5_error_code global_profile(const global *g, const krb5_keyblock *key_or_keys, const PAKE_MESSAGE *in, krb5_int32 *ptype, const krb5_keyblock **ask, const EC_GROUP **grp, const EVP_MD **md) { const krb5_keyblock *key = NULL; size_t nkeys = 1; int n; if (ask != NULL) { for (nkeys = 0; key_or_keys[nkeys].enctype != ENCTYPE_NULL; nkeys++) continue; } if (nkeys == 0) return EINVAL; /* Setup crypto. */ switch (in->type) { case PAKE_MESSAGE_TYPE_INFO: *ptype = ptype_choose(g, in->value.info->ptypes); if (*ptype == 0) return ENOTSUP; n = SKM_sk_num(PAKE_SUPPORT, in->value.info->supports); for (int i = 0; i < n; i++) { const PAKE_SUPPORT *s; s = SKM_sk_value(PAKE_SUPPORT, in->value.info->supports, i); for (size_t i = 0; i < nkeys; i++) { if (key_or_keys[i].enctype == ASN1_INTEGER_get(s->etype)) { key = &key_or_keys[i]; break; } } if (key == NULL) continue; *grp = group_choose(g, key, s->groups); *md = hash_choose(g, key, s->hashes); goto egress; } return KRB5KDC_ERR_ETYPE_NOSUPP; case PAKE_MESSAGE_TYPE_EXCHANGE: case PAKE_MESSAGE_TYPE_VERIFIER: *ptype = ptype_load(g, in->value.data->ptype); if (*ptype == 0) return ENOTSUP; for (size_t i = 0; i < nkeys; i++) { krb5_int32 etype = ASN1_INTEGER_get(in->value.data->etype); if (key_or_keys[i].enctype == etype) { key = &key_or_keys[i]; break; } } *grp = group_load(g, key, in->value.data->group); *md = hash_load(g, key, in->value.data->hash); goto egress; } return EINVAL; egress: if (*grp == NULL) return ENOTSUP; if (*md == NULL) return KRB5KDC_ERR_SUMTYPE_NOSUPP; if (ask != NULL) *ask = key; return 0; }
npmccallum/krb5-pake
src/pake/asn1.h
<filename>src/pake/asn1.h /* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <openssl/asn1t.h> #define PA_PAKE 150 /* FIXME */ #define PA_PAKE_SPAKE 1 /* FIXME */ #define PA_PAKE_JPAKE 2 /* FIXME */ /* * Kerberos */ typedef struct { ASN1_INTEGER *etype; ASN1_INTEGER *kvno; ASN1_OCTET_STRING *cipher; } KRB5_ENCRYPTED_DATA; DECLARE_ASN1_FUNCTIONS(KRB5_ENCRYPTED_DATA) /* * PAKE */ typedef struct { ASN1_INTEGER *etype; STACK_OF(ASN1_OBJECT) *groups; STACK_OF(ASN1_OBJECT) *hashes; } PAKE_SUPPORT; typedef struct { STACK_OF(ASN1_INTEGER) *ptypes; STACK_OF(PAKE_SUPPORT) *supports; } PAKE_INFO; typedef struct { ASN1_INTEGER *ptype; ASN1_INTEGER *etype; ASN1_OBJECT *group; ASN1_OBJECT *hash; ASN1_OCTET_STRING *data; } PAKE_DATA; typedef enum { PAKE_MESSAGE_TYPE_INFO = 0, PAKE_MESSAGE_TYPE_EXCHANGE = 1, PAKE_MESSAGE_TYPE_VERIFIER = 2, } PAKE_MESSAGE_TYPE; typedef struct { PAKE_MESSAGE_TYPE type; union { PAKE_INFO *info; PAKE_DATA *data; } value; } PAKE_MESSAGE; DECLARE_ASN1_FUNCTIONS(PAKE_SUPPORT) DECLARE_ASN1_FUNCTIONS(PAKE_INFO) DECLARE_ASN1_FUNCTIONS(PAKE_DATA) DECLARE_ASN1_FUNCTIONS(PAKE_MESSAGE) /* * JPAKE */ typedef struct { ASN1_OCTET_STRING *gv; ASN1_OCTET_STRING *r; ASN1_OCTET_STRING *x; } JPAKE_KEY; typedef struct { JPAKE_KEY *x1; JPAKE_KEY *x2; } JPAKE_STEP1; typedef enum { JPAKE_MESSAGE_TYPE_STEP1 = 0, JPAKE_MESSAGE_TYPE_STEP2 = 1, } JPAKE_MESSAGE_TYPE; typedef struct { JPAKE_MESSAGE_TYPE type; union { JPAKE_STEP1 *step1; JPAKE_KEY *step2; } value; } JPAKE_MESSAGE; DECLARE_ASN1_FUNCTIONS(JPAKE_KEY) DECLARE_ASN1_FUNCTIONS(JPAKE_STEP1) DECLARE_ASN1_FUNCTIONS(JPAKE_MESSAGE)
npmccallum/krb5-pake
src/client.c
<reponame>npmccallum/krb5-pake<filename>src/client.c<gh_stars>1-10 /* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <krb5/clpreauth_plugin.h> #include "global.h" #include "common.h" #include "kconv.h" #include "pake/pake.h" #include <errno.h> #include <string.h> struct krb5_clpreauth_moddata_st { krb5_octet buffer[EVP_MAX_MD_SIZE]; ASN1_OCTET_STRING *prv; global global; }; static krb5_error_code pake_client_prep_questions(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt, krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock, krb5_kdc_req *request, krb5_data *encoded_request_body, krb5_data *encoded_previous_request, krb5_pa_data *pa_data) { cb->need_as_key(context, rock); return 0; } static krb5_error_code pake_client_process(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt, krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock, krb5_kdc_req *request, krb5_data *encoded_request_body, krb5_data *encoded_previous_request, krb5_pa_data *pa_data, krb5_prompter_fct prompter, void *prompter_data, krb5_pa_data ***pa_data_out) { const ASN1_OCTET_STRING *inmsg = NULL; const global *g = &moddata->global; const krb5_octet *hbuf = NULL; const EC_GROUP *grp = NULL; const EVP_MD *md = NULL; ASN1_OCTET_STRING *outmsg = NULL; ASN1_OCTET_STRING *outprv = NULL; krb5_error_code retval = 0; krb5_keyblock *ask = NULL; /* Alias; don't free. */ krb5_keyblock *dsk = NULL; PAKE_MESSAGE *in = NULL; EC_POINT *kek = NULL; krb5_int32 ptype; /* Create the PA data array. */ *pa_data_out = calloc(2, sizeof(**pa_data_out)); if (*pa_data_out == NULL) { goto error; } /* Get the key. */ retval = cb->get_as_key(context, rock, &ask); if (retval) goto error; /* Decode the PA data. */ in = padata2item(pa_data, PAKE_MESSAGE); if (in == NULL) { retval = EINVAL; /* Bad input. */ goto error; } if (in->type == PAKE_MESSAGE_TYPE_EXCHANGE) inmsg = in->value.data->data; /* Setup crypto. */ retval = global_profile(g, ask, in, &ptype, NULL, &grp, &md); if (retval != 0) goto error; /* Hash the incoming packet. */ if (in->type != PAKE_MESSAGE_TYPE_INFO) hbuf = moddata->buffer; retval = common_hash_padata(md, hbuf, pa_data, moddata->buffer); if (retval != 0) goto error; /* Perform PAKE iteration. */ retval = common_pake(ptype, request, ask, FALSE, grp, md, inmsg, moddata->prv, &outmsg, &outprv, &kek, g->ctx); ASN1_OCTET_STRING_free(moddata->prv); moddata->prv = outprv; if (retval != 0) goto error; if (outmsg != NULL) { /* Make the output PA data. */ retval = common_padata(ptype, ask->enctype, grp, md, PAKE_MESSAGE_TYPE_EXCHANGE, outmsg, &(*pa_data_out)[0]); if (retval != 0) goto error; /* Hash the outgoing packet. */ retval = common_hash_padata(md, moddata->buffer, (*pa_data_out)[0], moddata->buffer); if (retval != 0) goto error; } else { if (kek == NULL) { retval = EINVAL; goto error; } /* Derive the key. */ retval = common_derive(context, request, ask, grp, md, moddata->buffer, kek, &dsk, g->ctx); if (retval != 0) goto error; /* Make the verifier. */ outmsg = common_verifier(md, dsk); if (outmsg == NULL) { retval = ENOMEM; goto error; } /* Make the output PA data. */ retval = common_padata(ptype, ask->enctype, grp, md, PAKE_MESSAGE_TYPE_VERIFIER, outmsg, &(*pa_data_out)[0]); if (retval != 0) goto error; retval = cb->set_as_key(context, rock, dsk); if (retval != 0) goto error; } error: if (retval != 0) common_free_padata(pa_data_out); krb5_free_keyblock(context, dsk); ASN1_OCTET_STRING_free(outmsg); PAKE_MESSAGE_free(in); EC_POINT_free(kek); return retval; } static krb5_error_code pake_init(krb5_context context, krb5_clpreauth_moddata *moddata_out) { krb5_clpreauth_moddata md; krb5_error_code retval; *moddata_out = calloc(1, sizeof(*md)); if (*moddata_out == NULL) return ENOMEM; retval = global_init(&(*moddata_out)->global); if (retval != 0) { free(*moddata_out); return retval; } OpenSSL_add_all_digests(); return 0; } static void pake_fini(krb5_context context, krb5_clpreauth_moddata moddata) { ASN1_OCTET_STRING_free(moddata->prv); global_free(&moddata->global); free(moddata); EVP_cleanup(); } krb5_error_code clpreauth_pake_initvt(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable) { static krb5_preauthtype types[] = { PA_PAKE, 0 }; krb5_clpreauth_vtable vt; if (maj_ver != 1) return KRB5_PLUGIN_VER_NOTSUPP; vt = (krb5_clpreauth_vtable)vtable; vt->name = "pake"; vt->pa_type_list = types; vt->init = pake_init; vt->fini = pake_fini; vt->prep_questions = pake_client_prep_questions; vt->process = pake_client_process; return 0; }
npmccallum/krb5-pake
src/common.c
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "common.h" #include "kconv.h" #include "pake/conv.h" #include "pake/hash.h" #include "pake/pake.h" #include <openssl/evp.h> #include <errno.h> #include <string.h> static BIGNUM * make_order(const EC_GROUP *grp, BN_CTX *ctx) { BIGNUM *ord; ord = BN_new(); if (ord == NULL) return NULL; if (!EC_GROUP_get_order(grp, ord, ctx)) { BN_free(ord); return NULL; } return ord; } krb5_error_code common_derive(krb5_context context, const krb5_kdc_req *request, const krb5_keyblock *ask, const EC_GROUP *grp, const EVP_MD *md, krb5_octet *phash, const EC_POINT *kek, krb5_keyblock **dsk, BN_CTX *ctx) { char cname[princ2str(request->client, NULL, 0) + 1]; char sname[princ2str(request->server, NULL, 0) + 1]; krb5_error_code retval = 0; bool err = false; EVP_MD_CTX mdctx; princ2str(request->client, cname, sizeof(cname)); princ2str(request->server, sname, sizeof(sname)); retval = krb5_init_keyblock(context, ask->enctype, EVP_MD_size(md), dsk); if (retval != 0) return retval; /* Add all the required items to the buffer for hashing. */ if (!EVP_DigestInit(&mdctx, md)) goto error; err |= !hash_append_data(&mdctx, (krb5_octet *) cname, strlen(cname)); err |= !hash_append_data(&mdctx, (krb5_octet *) sname, strlen(sname)); err |= !hash_append_data(&mdctx, phash, EVP_MD_size(md)); err |= !hash_append_data(&mdctx, ask->contents, ask->length); err |= !hash_append_point(&mdctx, grp, kek, ctx); err |= !EVP_DigestFinal(&mdctx, (*dsk)->contents, NULL); if (err) goto error; return 0; error: krb5_free_keyblock(context, *dsk); *dsk = NULL; return ENOMEM; } ASN1_OCTET_STRING * common_verifier(const EVP_MD *md, const krb5_keyblock *dsk) { krb5_octet buffer[EVP_MD_size(md)]; if (!EVP_Digest(dsk->contents, dsk->length, buffer, NULL, md, NULL)) return NULL; return str2os(buffer, sizeof(buffer)); } krb5_error_code common_hash_padata(const EVP_MD *md, const krb5_octet *prev, const krb5_pa_data *padata, krb5_octet *output) { EVP_MD_CTX ctx; if (!EVP_DigestInit(&ctx, md)) return ENOMEM; if (prev != NULL) { if (!hash_append_data(&ctx, prev, EVP_MD_size(md))) return ENOMEM; } if (!hash_append_data(&ctx, padata->contents, padata->length)) return ENOMEM; if (!EVP_DigestFinal(&ctx, output, NULL)) return ENOMEM; return 0; } krb5_error_code common_padata(krb5_int32 ptype, krb5_int32 etype, const EC_GROUP *grp, const EVP_MD *md, PAKE_MESSAGE_TYPE mtype, const ASN1_OCTET_STRING *outmsg, krb5_pa_data **pa) { krb5_error_code retval = 0; PAKE_DATA data = {}; PAKE_MESSAGE msg = { .type = mtype, .value.data = &data }; /* Create the output message. */ data.ptype = int2integer(ptype); data.etype = int2integer(etype); data.group = OBJ_nid2obj(EC_GROUP_get_curve_name(grp)); data.hash = OBJ_nid2obj(EVP_MD_type(md)); data.data = (ASN1_OCTET_STRING *) outmsg; if (data.ptype == NULL || data.etype == NULL || data.group == NULL || data.hash == NULL) { retval = ENOMEM; goto error; } *pa = item2padata(&msg, PAKE_MESSAGE, PA_PAKE); if (*pa == NULL) { retval = ENOMEM; goto error; } error: ASN1_INTEGER_free(data.ptype); ASN1_INTEGER_free(data.etype); ASN1_OBJECT_free(data.group); ASN1_OBJECT_free(data.hash); return retval; } krb5_error_code common_pake(krb5_int32 ptype, const krb5_kdc_req *request, const krb5_keyblock *ask, krb5_boolean kdc, const EC_GROUP *grp, const EVP_MD *md, const ASN1_OCTET_STRING *inmsg, const ASN1_OCTET_STRING *inprv, ASN1_OCTET_STRING **outmsg, ASN1_OCTET_STRING **outprv, EC_POINT **kek, BN_CTX *ctx) { char cname[princ2str(request->client, NULL, 0) + 1]; char sname[princ2str(request->server, NULL, 0) + 1]; krb5_error_code retval = 0; pake_ctx pctx = { .cname = cname, .sname = sname, .kdc = kdc, .ctx = ctx, .sec = BN_bin2bn(ask->contents, ask->length, NULL), .grp = grp, .ord = make_order(grp, ctx), .md = md }; princ2str(request->client, cname, sizeof(cname)); princ2str(request->server, sname, sizeof(sname)); if (pctx.sec == NULL || pctx.ord == NULL) { retval = ENOMEM; goto error; } retval = pake(ptype, &pctx, inmsg, inprv, outmsg, outprv, kek); error: BN_free(pctx.sec); BN_free(pctx.ord); return retval; } void common_free_padata(krb5_pa_data ***pa) { if (pa == NULL) return; for (size_t i = 0; (*pa)[i] != NULL; i++) { free((*pa)[i]->contents); free((*pa)[i]); } free(*pa); *pa = NULL; }
npmccallum/krb5-pake
src/kconv.c
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "kconv.h" #undef padata2item #undef item2padata #include <string.h> int princ2str(krb5_const_principal princ, char *buf, size_t len) { int plen = 0; size_t c = 0; /* Calculate the length of the principal string. */ for (krb5_int32 i = 0; i < princ->length; i++) plen += princ->data[i].length + 1; plen += princ->realm.length; /* If there is no buffer, return. */ if (buf == NULL || len == 0) return plen; for (int i = 0; i < princ->length && c < len; i++) { if (i > 0) buf[c++] = '/'; for (size_t j = 0; j < princ->data[i].length && c < len; j++) buf[c++] = princ->data[i].data[j]; } if (c < len) buf[c++] = '@'; for (size_t j = 0; j < princ->realm.length && c < len; j++) buf[c++] = princ->realm.data[j]; if (c < len) buf[c] = '\0'; return plen; } void * padata2item(const krb5_pa_data *padata, const ASN1_ITEM *type) { const krb5_octet *tmp = NULL; if (padata == NULL) return NULL; tmp = padata->contents; return ASN1_item_d2i(NULL, &tmp, padata->length, type); } krb5_pa_data * item2padata(void *msg, const ASN1_ITEM *type, krb5_preauthtype patype) { krb5_pa_data *pa = NULL; krb5_octet *tmp = NULL; int enclen = 0; enclen = ASN1_item_i2d(msg, &tmp, type); if (enclen < 1) return NULL; pa = calloc(1, sizeof(krb5_pa_data)); if (pa == NULL) { OPENSSL_free(tmp); return NULL; } pa->contents = calloc(enclen, 1); if (pa->contents == NULL) { OPENSSL_free(tmp); free(pa); return NULL; } memcpy(pa->contents, tmp, enclen); pa->pa_type = patype; pa->length = enclen; OPENSSL_free(tmp); return pa; }
npmccallum/krb5-pake
src/pake/spake.c
<filename>src/pake/spake.c /* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "spake.h" #include "spake_constants.h" #include "conv.h" #include <errno.h> static EC_POINT * make_mask(const pake_ctx *pctx, bool m) { const char *hex = NULL; for (size_t i = 0; SPAKE_CONSTANTS[i].curve != 0; i++) { if (SPAKE_CONSTANTS[i].curve != EC_GROUP_get_curve_name(pctx->grp)) continue; hex = m ? SPAKE_CONSTANTS[i].m : SPAKE_CONSTANTS[i].n; return EC_POINT_hex2point(pctx->grp, hex, NULL, pctx->ctx); } return NULL; } static EC_POINT * step1(const pake_ctx *pctx, const BIGNUM *prv) { EC_POINT *mask = NULL; EC_POINT *pub = NULL; mask = make_mask(pctx, pctx->kdc); if (mask == NULL) return NULL; pub = EC_POINT_new(pctx->grp); if (pub == NULL) { EC_POINT_free(mask); return NULL; } /* Generate the client public key: g * prv + mask * sec. */ if (!EC_POINT_mul(pctx->grp, pub, prv, mask, pctx->sec, pctx->ctx)) { EC_POINT_free(mask); EC_POINT_free(pub); return NULL; } EC_POINT_free(mask); return pub; } static EC_POINT * step2(const pake_ctx *pctx, const BIGNUM *prv, const EC_POINT *pub) { EC_POINT *mask = NULL; EC_POINT *key = NULL; /* Make our temporary variables. */ mask = make_mask(pctx, !pctx->kdc); key = EC_POINT_new(pctx->grp); if (mask == NULL || key == NULL) goto error; /* Multiply the remote's mask by the secret. * tmp = mask * sec */ if (!EC_POINT_mul(pctx->grp, key, NULL, mask, pctx->sec, pctx->ctx)) goto error; /* Subtract the above product from the remote public key. * tmp = pub - tmp */ if (!EC_POINT_invert(pctx->grp, key, pctx->ctx) || !EC_POINT_add(pctx->grp, key, pub, key, pctx->ctx)) goto error; /* Multiply the above with the private key to obtain the session key. * k = tmp * prv */ if (!EC_POINT_mul(pctx->grp, key, NULL, key, prv, pctx->ctx)) goto error; EC_POINT_free(mask); return key; error: EC_POINT_free(mask); EC_POINT_free(key); return NULL; } int SPAKE(const pake_ctx *pctx, const ASN1_OCTET_STRING *inmsg, const ASN1_OCTET_STRING *inprv, ASN1_OCTET_STRING **outmsg, ASN1_OCTET_STRING **outprv, EC_POINT **key) { EC_POINT *pub = NULL; int retval = ENOMEM; BIGNUM *prv = NULL; *outmsg = NULL; *outprv = NULL; *key = NULL; if (inprv == NULL) { /* Make a random prv. */ prv = BN_new(); if (prv == NULL) goto error; if (!BN_rand_range(prv, pctx->ord)) goto error; /* Make the public key. */ pub = step1(pctx, prv); if (pub == NULL) goto error; /* Save the private value for later. */ *outprv = bn2os(prv, pctx->ctx); if (*outprv == NULL) goto error; /* Send the public key. */ *outmsg = point2os(pctx->grp, pub, pctx->ctx); EC_POINT_free(pub); if (*outmsg == NULL) { ASN1_OCTET_STRING_free(*outprv); *outprv = NULL; goto error; } } else { /* Load the private key. */ prv = os2bn(inprv, pctx->ctx); if (prv == NULL) return EINVAL; /* Get the remote public key. */ pub = os2point(pctx->grp, inmsg, pctx->ctx); if (pub == NULL) { retval = EINVAL; goto error; } /* Calculate the shared key. */ *key = step2(pctx, prv, pub); EC_POINT_free(pub); if (*key == NULL) goto error; } retval = 0; error: BN_free(prv); return retval; }
npmccallum/krb5-pake
src/pake/asn1.c
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "asn1.h" #include <errno.h> #include <stdbool.h> /* * Kerberos */ ASN1_SEQUENCE(KRB5_ENCRYPTED_DATA) = { ASN1_EXP(KRB5_ENCRYPTED_DATA, etype, ASN1_INTEGER, 0), ASN1_EXP_OPT(KRB5_ENCRYPTED_DATA, kvno, ASN1_INTEGER, 1), ASN1_EXP(KRB5_ENCRYPTED_DATA, cipher, ASN1_OCTET_STRING, 2), } ASN1_SEQUENCE_END(KRB5_ENCRYPTED_DATA) IMPLEMENT_ASN1_FUNCTIONS(KRB5_ENCRYPTED_DATA) /* * PAKE */ ASN1_SEQUENCE(PAKE_SUPPORT) = { ASN1_SIMPLE(PAKE_SUPPORT, etype, ASN1_INTEGER), ASN1_SEQUENCE_OF(PAKE_SUPPORT, groups, ASN1_OBJECT), ASN1_SEQUENCE_OF(PAKE_SUPPORT, hashes, ASN1_OBJECT), } ASN1_SEQUENCE_END(PAKE_SUPPORT) ASN1_SEQUENCE(PAKE_INFO) = { ASN1_SEQUENCE_OF(PAKE_INFO, ptypes, ASN1_INTEGER), ASN1_SEQUENCE_OF(PAKE_INFO, supports, PAKE_SUPPORT), } ASN1_SEQUENCE_END(PAKE_INFO) ASN1_SEQUENCE(PAKE_DATA) = { ASN1_SIMPLE(PAKE_DATA, ptype, ASN1_INTEGER), ASN1_SIMPLE(PAKE_DATA, etype, ASN1_INTEGER), ASN1_SIMPLE(PAKE_DATA, group, ASN1_OBJECT), ASN1_SIMPLE(PAKE_DATA, hash, ASN1_OBJECT), ASN1_SIMPLE(PAKE_DATA, data, ASN1_OCTET_STRING), } ASN1_SEQUENCE_END(PAKE_DATA) ASN1_CHOICE(PAKE_MESSAGE) = { ASN1_EXP(PAKE_MESSAGE, value.info, PAKE_INFO, PAKE_MESSAGE_TYPE_INFO), ASN1_EXP(PAKE_MESSAGE, value.data, PAKE_DATA, PAKE_MESSAGE_TYPE_EXCHANGE), ASN1_EXP(PAKE_MESSAGE, value.data, PAKE_DATA, PAKE_MESSAGE_TYPE_VERIFIER), } ASN1_CHOICE_END(PAKE_MESSAGE) IMPLEMENT_ASN1_FUNCTIONS(PAKE_SUPPORT) IMPLEMENT_ASN1_FUNCTIONS(PAKE_INFO) IMPLEMENT_ASN1_FUNCTIONS(PAKE_DATA) IMPLEMENT_ASN1_FUNCTIONS(PAKE_MESSAGE) /* * JPAKE */ ASN1_SEQUENCE(JPAKE_KEY) = { ASN1_SIMPLE(JPAKE_KEY, gv, ASN1_OCTET_STRING), ASN1_SIMPLE(JPAKE_KEY, r, ASN1_OCTET_STRING), ASN1_SIMPLE(JPAKE_KEY, x, ASN1_OCTET_STRING), } ASN1_SEQUENCE_END(JPAKE_KEY) ASN1_SEQUENCE(JPAKE_STEP1) = { ASN1_SIMPLE(JPAKE_STEP1, x1, JPAKE_KEY), ASN1_SIMPLE(JPAKE_STEP1, x2, JPAKE_KEY), } ASN1_SEQUENCE_END(JPAKE_STEP1) ASN1_CHOICE(JPAKE_MESSAGE) = { ASN1_EXP(JPAKE_MESSAGE, value.step1, JPAKE_STEP1, JPAKE_MESSAGE_TYPE_STEP1), ASN1_EXP(JPAKE_MESSAGE, value.step2, JPAKE_KEY, JPAKE_MESSAGE_TYPE_STEP2), } ASN1_CHOICE_END(JPAKE_MESSAGE) IMPLEMENT_ASN1_FUNCTIONS(JPAKE_KEY) IMPLEMENT_ASN1_FUNCTIONS(JPAKE_STEP1) IMPLEMENT_ASN1_FUNCTIONS(JPAKE_MESSAGE)
npmccallum/krb5-pake
src/pake/jpake.c
<gh_stars>1-10 /* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "jpake.h" #include "asn1.h" #include "conv.h" #include "hash.h" #include <errno.h> #include <stdint.h> #include <string.h> typedef struct { ASN1_OCTET_STRING *prv; ASN1_OCTET_STRING *pub; ASN1_OCTET_STRING *g; } JPAKE_PRV; ASN1_SEQUENCE(JPAKE_PRV) = { ASN1_SIMPLE(JPAKE_PRV, prv, ASN1_OCTET_STRING), ASN1_SIMPLE(JPAKE_PRV, pub, ASN1_OCTET_STRING), ASN1_SIMPLE(JPAKE_PRV, g, ASN1_OCTET_STRING), } ASN1_SEQUENCE_END(JPAKE_PRV) IMPLEMENT_ASN1_FUNCTIONS(JPAKE_PRV) static BIGNUM * make_zero(void) { unsigned char z = 0; return BN_bin2bn(&z, sizeof(z), NULL); } static BIGNUM * make_random(const pake_ctx *pctx, bool one) { BIGNUM *zero = NULL; BIGNUM *prv = NULL; prv = BN_new(); if (prv == NULL) return NULL; if (!one) { zero = make_zero(); if (zero == NULL) goto error; } do { if (!BN_rand_range(prv, pctx->ord)) { BN_free(prv); return NULL; } } while(zero != NULL && BN_cmp(prv, zero) == 0); BN_free(zero); return prv; error: BN_free(zero); BN_free(prv); return NULL; } /* h = H(g, g^r, g^x, name) */ static bool hash_zkp(const pake_ctx *pctx, const char *name, const EC_POINT *gv, const EC_POINT *gx, uint8_t *hash) { const EC_POINT *g; EVP_MD_CTX mdctx; bool err = false; g = EC_GROUP_get0_generator(pctx->grp); if (!EVP_DigestInit(&mdctx, pctx->md)) return false; err |= !hash_append_point(&mdctx, pctx->grp, g, pctx->ctx); err |= !hash_append_point(&mdctx, pctx->grp, gv, pctx->ctx); err |= !hash_append_point(&mdctx, pctx->grp, gx, pctx->ctx); err |= !hash_append_data(&mdctx, (uint8_t *) name, strlen(name)); err |= !EVP_DigestFinal(&mdctx, hash, NULL); return !err; } static bool make_key(const pake_ctx *pctx, const EC_POINT *g, const BIGNUM *prv, const EC_POINT *pub, JPAKE_KEY *jkey) { uint8_t hash[EVP_MD_size(pctx->md)]; EC_POINT *gv = NULL; BIGNUM *acc = NULL; BIGNUM *v = NULL; bool ret = false; if (g == NULL) g = EC_GROUP_get0_generator(pctx->grp); gv = EC_POINT_new(pctx->grp); v = make_random(pctx, true); if (gv == NULL || v == NULL) goto error; /* Do the Schnorr signature. */ if (!EC_POINT_mul(pctx->grp, gv, NULL, g, v, pctx->ctx)) goto error; if (!hash_zkp(pctx, pctx->kdc ? pctx->sname : pctx->cname, gv, pub, hash)) goto error; acc = BN_bin2bn(hash, sizeof(hash), NULL); if (acc == NULL || !BN_mod_mul(acc, prv, acc, pctx->ord, pctx->ctx) || !BN_mod_sub(acc, v, acc, pctx->ord, pctx->ctx)) goto error; /* Encode the results. */ jkey->gv = point2os(pctx->grp, gv, pctx->ctx); jkey->r = bn2os(acc, pctx->ctx); jkey->x = point2os(pctx->grp, pub, pctx->ctx); if (jkey->gv == NULL || jkey->r == NULL || jkey->x == NULL) goto error; ret = true; error: EC_POINT_free(gv); BN_free(acc); BN_free(v); return ret; } static bool make_prv(const pake_ctx *pctx, const BIGNUM *prv, const ASN1_OCTET_STRING *pub, const EC_POINT *g, JPAKE_PRV *jprv) { jprv->pub = ASN1_OCTET_STRING_dup(pub); jprv->prv = bn2os(prv, pctx->ctx); jprv->g = point2os(pctx->grp, g, pctx->ctx); return jprv->pub != NULL && jprv->prv != NULL && jprv->g != NULL; } static EC_POINT * verify_key(const pake_ctx *pctx, bool one, const EC_POINT *g, const JPAKE_KEY *key) { uint8_t hash[EVP_MD_size(pctx->md)]; EC_POINT *gvv = NULL; EC_POINT *gv = NULL; EC_POINT *x = NULL; EC_POINT *p = NULL; BIGNUM *tmp = NULL; BIGNUM *r = NULL; bool ret = false; if (g == NULL) g = EC_GROUP_get0_generator(pctx->grp); gvv = EC_POINT_new(pctx->grp); gv = os2point(pctx->grp, key->gv, pctx->ctx); x = os2point(pctx->grp, key->x, pctx->ctx); r = os2bn(key->r, pctx->ctx); p = EC_POINT_new(pctx->grp); if (gvv == NULL || gv == NULL || x == NULL || r == NULL || p == NULL) goto error; if (!hash_zkp(pctx, pctx->kdc ? pctx->cname : pctx->sname, gv, x, hash)) goto error; tmp = BN_bin2bn(hash, sizeof(hash), NULL); if (tmp == NULL) goto error; if (!EC_POINT_mul(pctx->grp, p, NULL, g, r, pctx->ctx) || !EC_POINT_mul(pctx->grp, gvv, NULL, x, tmp, pctx->ctx) || !EC_POINT_add(pctx->grp, gvv, gvv, p, pctx->ctx)) goto error; ret = EC_POINT_cmp(pctx->grp, gv, gvv, pctx->ctx) == 0; if (ret && !one) { BN_free(tmp); ret = false; tmp = make_zero(); if (tmp == NULL) goto error; if (!EC_POINT_mul(pctx->grp, p, NULL, g, tmp, pctx->ctx)) goto error; ret = EC_POINT_cmp(pctx->grp, x, p, pctx->ctx) != 0; } error: EC_POINT_free(gvv); EC_POINT_free(gv); EC_POINT_free(p); BN_free(tmp); BN_free(r); if (!ret) { EC_POINT_free(x); return NULL; } return x; } static int step1(const pake_ctx *pctx, JPAKE_STEP1 *step1, JPAKE_PRV *prv) { int retval = ENOMEM; EC_POINT *X1 = NULL; EC_POINT *X2 = NULL; BIGNUM *x1 = NULL; BIGNUM *x2 = NULL; X1 = EC_POINT_new(pctx->grp); X2 = EC_POINT_new(pctx->grp); x1 = make_random(pctx, true); x2 = make_random(pctx, false); if (x1 == NULL || x2 == NULL) goto error; /* Calculate the public keys. */ if (!EC_POINT_mul(pctx->grp, X1, x1, NULL, NULL, pctx->ctx) || !EC_POINT_mul(pctx->grp, X2, x2, NULL, NULL, pctx->ctx)) goto error; /* Encode it. */ if (!make_key(pctx, NULL, x1, X1, step1->x1) || !make_key(pctx, NULL, x2, X2, step1->x2)) goto error; /* Start computing the generator for step3. */ if (!EC_POINT_add(pctx->grp, X1, X1, X2, pctx->ctx)) goto error; if (!make_prv(pctx, x2, step1->x1->x, X1, prv)) goto error; retval = 0; error: EC_POINT_free(X1); EC_POINT_free(X2); BN_free(x1); BN_free(x2); return retval; } static int step2(const pake_ctx *pctx, const JPAKE_STEP1 *step1, const JPAKE_PRV *inprv, JPAKE_KEY *step2, JPAKE_PRV *outprv) { int retval = ENOMEM; EC_POINT *x1 = NULL; EC_POINT *x3 = NULL; EC_POINT *x4 = NULL; EC_POINT *g = NULL; BIGNUM *x2 = NULL; BIGNUM *S = NULL; S = BN_new(); x1 = os2point(pctx->grp, inprv->pub, pctx->ctx); x2 = os2bn(inprv->prv, pctx->ctx); g = os2point(pctx->grp, inprv->g, pctx->ctx); if (S == NULL || x1 == NULL || x2 == NULL || g == NULL) goto egress; x3 = verify_key(pctx, true, NULL, step1->x1); x4 = verify_key(pctx, false, NULL, step1->x2); if (x3 == NULL || x4 == NULL) { retval = EINVAL; goto egress; } /* Calculate the generator used to verify the next ZKP. */ if (!EC_POINT_add(pctx->grp, g, g, x3, pctx->ctx)) goto egress; /* S = sec * x2 * x1 = x1 + x3 + x4 * x3 = x1 * S */ if (!BN_mod_mul(S, x2, pctx->sec, pctx->ord, pctx->ctx) || !EC_POINT_add(pctx->grp, x1, x1, x3, pctx->ctx) || !EC_POINT_add(pctx->grp, x1, x1, x4, pctx->ctx) || !EC_POINT_mul(pctx->grp, x3, NULL, x1, S, pctx->ctx)) goto egress; if (!make_key(pctx, x1, S, x3, step2)) goto egress; if (!make_prv(pctx, x2, step1->x2->x, g, outprv)) goto egress; retval = 0; egress: EC_POINT_free(x1); EC_POINT_free(x3); EC_POINT_free(x4); EC_POINT_free(g); BN_free(x2); BN_free(S); return retval; } static int step3(const pake_ctx *pctx, const JPAKE_KEY *step2, const JPAKE_PRV *prv, EC_POINT *key) { EC_POINT *x4 = NULL; EC_POINT *x = NULL; EC_POINT *g = NULL; BIGNUM *x2 = NULL; /* Restore values from private. */ x4 = os2point(pctx->grp, prv->pub, pctx->ctx); x2 = os2bn(prv->prv, pctx->ctx); g = os2point(pctx->grp, prv->g, pctx->ctx); if (x4 == NULL || x2 == NULL || g == NULL) goto error; /* Verify the incoming key. */ x = verify_key(pctx, true, g, step2); if (x == NULL) return EINVAL; /* Finish the algorithm: K = (x - x4 * x2 * sec) ^ x2. */ if (!EC_POINT_mul(pctx->grp, g, NULL, x4, x2, pctx->ctx) || !EC_POINT_mul(pctx->grp, g, NULL, g, pctx->sec, pctx->ctx) || !EC_POINT_invert(pctx->grp, g, pctx->ctx) || !EC_POINT_add(pctx->grp, g, x, g, pctx->ctx) || !EC_POINT_mul(pctx->grp, key, NULL, g, x2, pctx->ctx)) goto error; EC_POINT_free(x4); EC_POINT_free(x); EC_POINT_free(g); BN_free(x2); return 0; error: EC_POINT_free(x4); EC_POINT_free(x); EC_POINT_free(g); BN_free(x2); return ENOMEM; } int JPAKE(const pake_ctx *pctx, const ASN1_OCTET_STRING *inmsg, const ASN1_OCTET_STRING *inprv, ASN1_OCTET_STRING **outmsg, ASN1_OCTET_STRING **outprv, EC_POINT **key) { JPAKE_MESSAGE *joutmsg = NULL; JPAKE_MESSAGE *jinmsg = NULL; JPAKE_PRV *joutprv = NULL; JPAKE_PRV *jinprv = NULL; EC_POINT *k = NULL; int retval = 0; /* Decode the input. */ if (inmsg != NULL && inprv != NULL) { jinmsg = os2item(inmsg, JPAKE_MESSAGE); jinprv = os2item(inprv, JPAKE_PRV); if (jinmsg == NULL || jinprv == NULL) { retval = ENOMEM; goto egress; } } /* If we are on step1 or step2, make an out message and prv. */ if (jinmsg == NULL || jinmsg->type == JPAKE_MESSAGE_TYPE_STEP1) { joutmsg = JPAKE_MESSAGE_new(); joutprv = JPAKE_PRV_new(); if (joutmsg == NULL || joutprv == NULL) { retval = ENOMEM; goto egress; } } /* Handle step1. */ if (jinmsg == NULL) { retval = ENOMEM; joutmsg->type = JPAKE_MESSAGE_TYPE_STEP1; joutmsg->value.step1 = JPAKE_STEP1_new(); if (joutmsg->value.step1 == NULL) goto egress; joutmsg->value.step1->x1 = JPAKE_KEY_new(); joutmsg->value.step1->x2 = JPAKE_KEY_new(); if (joutmsg->value.step1->x1 == NULL || joutmsg->value.step1->x2 == NULL) goto egress; retval = step1(pctx, joutmsg->value.step1, joutprv); } else { switch (jinmsg->type) { /* Handle step2. */ case JPAKE_MESSAGE_TYPE_STEP1: retval = ENOMEM; joutmsg->type = JPAKE_MESSAGE_TYPE_STEP2; joutmsg->value.step2 = JPAKE_KEY_new(); if (joutmsg->value.step2 == NULL) goto egress; retval = step2(pctx, jinmsg->value.step1, jinprv, joutmsg->value.step2, joutprv); break; /* Handle step3. */ case JPAKE_MESSAGE_TYPE_STEP2: retval = ENOMEM; k = EC_POINT_new(pctx->grp); if (k == NULL) goto egress; retval = step3(pctx, jinmsg->value.step2, jinprv, k); if (retval != 0) EC_POINT_free(k); else *key = k; break; } } if (retval != 0) goto egress; if (joutmsg != NULL && joutprv != NULL) { *outmsg = item2os(joutmsg, JPAKE_MESSAGE); *outprv = item2os(joutprv, JPAKE_PRV); if (*outmsg == NULL || *outprv == NULL) { ASN1_OCTET_STRING_free(*outmsg); *outmsg = NULL; retval = ENOMEM; } } egress: JPAKE_MESSAGE_free(joutmsg); JPAKE_MESSAGE_free(jinmsg); JPAKE_PRV_free(joutprv); JPAKE_PRV_free(jinprv); return retval; }
npmccallum/krb5-pake
src/common.h
/* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "global.h" #include "pake/pake.h" krb5_error_code common_derive(krb5_context context, const krb5_kdc_req *request, const krb5_keyblock *ask, const EC_GROUP *grp, const EVP_MD *md, krb5_octet *phash, const EC_POINT *kek, krb5_keyblock **dsk, BN_CTX *ctx); ASN1_OCTET_STRING * common_verifier(const EVP_MD *md, const krb5_keyblock *dsk); krb5_error_code common_hash_padata(const EVP_MD *md, const krb5_octet *prev, const krb5_pa_data *padata, krb5_octet *output); krb5_error_code common_padata(krb5_int32 ptype, krb5_int32 etype, const EC_GROUP *grp, const EVP_MD *md, PAKE_MESSAGE_TYPE mtype, const ASN1_OCTET_STRING *outmsg, krb5_pa_data **pa); krb5_error_code common_pake(krb5_int32 ptype, const krb5_kdc_req *request, const krb5_keyblock *ask, krb5_boolean kdc, const EC_GROUP *grp, const EVP_MD *md, const ASN1_OCTET_STRING *inmsg, const ASN1_OCTET_STRING *inprv, ASN1_OCTET_STRING **outmsg, ASN1_OCTET_STRING **outprv, EC_POINT **kek, BN_CTX *ctx); void common_free_padata(krb5_pa_data ***pa);
npmccallum/krb5-pake
src/pake/conv.c
<gh_stars>1-10 /* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "conv.h" #undef item2os #undef os2item #include <stdio.h> #include <string.h> ASN1_OCTET_STRING * point2os(const EC_GROUP *grp, const EC_POINT *point, BN_CTX *ctx) { ASN1_OCTET_STRING *os; size_t size; size = EC_POINT_point2oct(grp, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx); if (size == 0) return NULL; unsigned char buffer[size]; if (EC_POINT_point2oct(grp, point, POINT_CONVERSION_COMPRESSED, buffer, size, ctx) != size) return NULL; os = ASN1_OCTET_STRING_new(); if (os == NULL) return NULL; if (!ASN1_OCTET_STRING_set(os, buffer, size)) { ASN1_OCTET_STRING_free(os); return NULL; } return os; } EC_POINT * os2point(const EC_GROUP *grp, const ASN1_OCTET_STRING *os, BN_CTX *ctx) { EC_POINT *point; point = EC_POINT_new(grp); if (point == NULL) return NULL; if (!EC_POINT_oct2point(grp, point, os->data, os->length, ctx)) goto error; if (!EC_POINT_is_on_curve(grp, point, ctx)) goto error; return point; error: EC_POINT_free(point); return NULL; } ASN1_OCTET_STRING * bn2os(const BIGNUM *n, BN_CTX *ctx) { ASN1_OCTET_STRING *os; unsigned char buffer[BN_num_bytes(n)]; BN_bn2bin(n, buffer); os = ASN1_OCTET_STRING_new(); if (os == NULL) return NULL; if (!ASN1_OCTET_STRING_set(os, buffer, sizeof(buffer))) { ASN1_OCTET_STRING_free(os); return NULL; } return os; } BIGNUM * os2bn(const ASN1_OCTET_STRING *os, BN_CTX *ctx) { return BN_bin2bn(os->data, os->length, NULL); } ASN1_OCTET_STRING * item2os(void *item, const ASN1_ITEM *type) { ASN1_OCTET_STRING *os; os = ASN1_OCTET_STRING_new(); if (os == NULL) return NULL; os->length = ASN1_item_i2d(item, &os->data, type); if (os->length < 1) { ASN1_OCTET_STRING_free(os); return NULL; } return os; } void * os2item(const ASN1_OCTET_STRING *os, const ASN1_ITEM *type) { const unsigned char *data = os->data; return ASN1_item_d2i(NULL, &data, os->length, type); } ASN1_INTEGER * int2integer(int i) { ASN1_INTEGER *ai; ai = ASN1_INTEGER_new(); if (ai == NULL) return NULL; if (!ASN1_INTEGER_set(ai, i)) { ASN1_INTEGER_free(ai); return NULL; } return ai; } ASN1_OCTET_STRING * str2os(const unsigned char *str, size_t len) { ASN1_OCTET_STRING *os; if (len == 0) len = strlen((char *) str); os = ASN1_OCTET_STRING_new(); if (os == NULL) return NULL; if (!ASN1_OCTET_STRING_set(os, str, len)) { ASN1_OCTET_STRING_free(os); return NULL; } return os; }
smiley/ebpf-for-windows
libs/api/unwind_helper.h
/* * Copyright (c) Microsoft Corporation * SPDX-License-Identifier: MIT */ #pragma once #include <functional> /** * @brief A helper object to invoke a function when the object goes out of * scope. * */ class _unwind_helper { public: /** * @brief Construct a new unwind helper object * * @param[in] unwind Function to invoke when the unwind object is destroyed. */ _unwind_helper(std::function<void()> unwind) : _unwind(unwind) {} /** * @brief Destroy the unwind helper object * */ ~_unwind_helper() { _unwind(); } private: std::function<void()> _unwind; };
smiley/ebpf-for-windows
libs/execution_context/ebpf_protocol.h
<reponame>smiley/ebpf-for-windows /* * Copyright (c) Microsoft Corporation * SPDX-License-Identifier: MIT */ #pragma once #include "ebpf_helpers.h" #include "ebpf_windows.h" typedef enum _ebpf_operation_id { EBPF_OPERATION_RESOLVE_HELPER, EBPF_OPERATION_RESOLVE_MAP, EBPF_OPERATION_CREATE_PROGRAM, EBPF_OPERATION_CREATE_MAP, EBPF_OPERATION_LOAD_CODE, EBPF_OPERATION_MAP_FIND_ELEMENT, EBPF_OPERATION_MAP_UPDATE_ELEMENT, EBPF_OPERATION_MAP_DELETE_ELEMENT, EBPF_OPERATION_MAP_GET_NEXT_KEY, EBPF_OPERATION_GET_NEXT_MAP, EBPF_OPERATION_GET_NEXT_PROGRAM, EBPF_OPERATION_QUERY_MAP_DEFINITION, EBPF_OPERATION_QUERY_PROGRAM_INFORMATION, EBPF_OPERATION_UPDATE_PINNING, EBPF_OPERATION_GET_PINNING, EBPF_OPERATION_LINK_PROGRAM, EBPF_OPERATION_CLOSE_HANDLE, EBPF_OPERATION_GET_EC_FUNCTION, EBPF_OPERATION_GET_PROGRAM_INFORMATION, } ebpf_operation_id_t; typedef enum _ebpf_code_type { EBPF_CODE_NATIVE, EBPF_CODE_EBPF } ebpf_code_type_t; typedef struct _ebpf_operation_header { uint16_t length; ebpf_operation_id_t id; } ebpf_operation_header_t; typedef enum _ebpf_ec_function { EBPF_EC_FUNCTION_LOG } ebpf_ec_function_t; typedef struct _ebpf_operation_resolve_helper_request { struct _ebpf_operation_header header; uint64_t program_handle; uint32_t helper_id[1]; } ebpf_operation_resolve_helper_request_t; typedef struct _ebpf_operation_resolve_helper_reply { struct _ebpf_operation_header header; uint64_t address[1]; } ebpf_operation_resolve_helper_reply_t; typedef struct _ebpf_operation_resolve_map_request { struct _ebpf_operation_header header; uint64_t program_handle; uint64_t map_handle[1]; } ebpf_operation_resolve_map_request_t; typedef struct _ebpf_operation_resolve_map_reply { struct _ebpf_operation_header header; uint64_t address[1]; } ebpf_operation_resolve_map_reply_t; typedef struct _ebpf_operation_create_program_request { struct _ebpf_operation_header header; ebpf_program_type_t program_type; uint16_t section_name_offset; uint8_t data[1]; } ebpf_operation_create_program_request_t; typedef struct _ebpf_operation_create_program_reply { struct _ebpf_operation_header header; uint64_t program_handle; } ebpf_operation_create_program_reply_t; typedef struct _ebpf_operation_load_code_request { struct _ebpf_operation_header header; uint64_t program_handle; ebpf_code_type_t code_type; uint8_t code[1]; } ebpf_operation_load_code_request_t; typedef struct _ebpf_operation_create_map_request { struct _ebpf_operation_header header; struct _ebpf_map_definition ebpf_map_definition; } ebpf_operation_create_map_request_t; typedef struct _ebpf_operation_create_map_reply { struct _ebpf_operation_header header; uint64_t handle; } ebpf_operation_create_map_reply_t; typedef struct _ebpf_operation_map_find_element_request { struct _ebpf_operation_header header; uint64_t handle; uint8_t key[1]; } ebpf_operation_map_find_element_request_t; typedef struct _ebpf_operation_map_find_element_reply { struct _ebpf_operation_header header; uint8_t value[1]; } ebpf_operation_map_find_element_reply_t; typedef struct _ebpf_operation_map_update_element_request { struct _ebpf_operation_header header; uint64_t handle; uint8_t data[1]; // data is key+value } epf_operation_map_update_element_request_t; typedef struct _ebpf_operation_map_delete_element_request { struct _ebpf_operation_header header; uint64_t handle; uint8_t key[1]; } ebpf_operation_map_delete_element_request_t; typedef struct _ebpf_operation_get_next_map_request { struct _ebpf_operation_header header; uint64_t previous_handle; } ebpf_operation_get_next_map_request; typedef struct _ebpf_operation_get_next_map_reply { struct _ebpf_operation_header header; uint64_t next_handle; } ebpf_operation_get_next_map_reply_t; typedef struct _ebpf_operation_get_next_program_request { struct _ebpf_operation_header header; uint64_t previous_handle; } ebpf_operation_get_next_program_request; typedef struct _ebpf_operation_get_next_program_reply { struct _ebpf_operation_header header; uint64_t next_handle; } ebpf_operation_get_next_program_reply_t; typedef struct _ebpf_operation_query_map_definition_request { struct _ebpf_operation_header header; uint64_t handle; } ebpf_operation_query_map_definition_request; typedef struct _ebpf_operation_query_map_definition_reply { struct _ebpf_operation_header header; struct _ebpf_map_definition map_definition; } ebpf_operation_query_map_definition_reply; typedef struct _ebpf_operation_query_program_information_request { struct _ebpf_operation_header header; uint64_t handle; } ebpf_operation_query_program_information_request; typedef struct _ebpf_operation_query_program_information_reply { struct _ebpf_operation_header header; ebpf_code_type_t code_type; uint16_t file_name_offset; uint16_t section_name_offset; uint8_t data[1]; } ebpf_operation_query_program_information_reply; typedef struct _ebpf_operation_map_get_next_key_request { struct _ebpf_operation_header header; uint64_t handle; uint8_t previous_key[1]; } ebpf_operation_map_get_next_key_request_t; typedef struct _ebpf_operation_map_get_next_key_reply { struct _ebpf_operation_header header; uint64_t handle; uint8_t next_key[1]; } ebpf_operation_map_get_next_key_reply_t; typedef struct _ebpf_operation_update_map_pinning_request { struct _ebpf_operation_header header; uint64_t handle; uint8_t name[1]; } ebpf_operation_update_pinning_request_t; typedef struct _ebpf_operation_get_pinning_request { struct _ebpf_operation_header header; uint8_t name[1]; } ebpf_operation_get_pinning_request_t; typedef struct _ebpf_operation_get_pinning_reply { struct _ebpf_operation_header header; uint64_t handle; } ebpf_operation_get_map_pinning_reply_t; typedef struct _ebpf_operation_link_program_request { struct _ebpf_operation_header header; uint64_t program_handle; ebpf_attach_type_t attach_type; } ebpf_operation_link_program_request_t; typedef struct _ebpf_operation_link_program_reply { struct _ebpf_operation_header header; uint64_t link_handle; } ebpf_operation_link_program_reply_t; typedef struct _ebpf_operation_close_handle_request { struct _ebpf_operation_header header; uint64_t handle; } ebpf_operation_close_handle_request_t; typedef struct _ebpf_operation_get_ec_function_request { struct _ebpf_operation_header header; ebpf_ec_function_t function; } ebpf_operation_get_ec_function_request_t; typedef struct _ebpf_operation_get_ec_function_reply { struct _ebpf_operation_header header; uint64_t address; } ebpf_operation_get_ec_function_reply_t; typedef struct _ebpf_operation_get_program_information_request { struct _ebpf_operation_header header; uint64_t program_handle; } ebpf_operation_get_program_information_request_t; typedef struct _ebpf_operation_get_program_information_reply { struct _ebpf_operation_header header; uint16_t version; uint16_t size; uint8_t data[1]; } ebpf_operation_get_program_information_reply_t;
smiley/ebpf-for-windows
libs/execution_context/ebpf_program.c
/* * Copyright (c) Microsoft Corporation * SPDX-License-Identifier: MIT */ #include "ebpf_program.h" #include "ebpf_core.h" #include "ebpf_epoch.h" #include "ebpf_link.h" #include "ebpf_object.h" typedef struct _FILE FILE; #include "ubpf.h" typedef struct _ebpf_program { ebpf_object_t object; ebpf_program_parameters_t parameters; // determinant is parameters.code_type union { // EBPF_CODE_NATIVE uint8_t* code; // EBPF_CODE_EBPF struct ubpf_vm* vm; } code_or_vm; ebpf_extension_client_t* global_helper_extension_client; ebpf_extension_data_t* global_helper_provider_data; ebpf_extension_dispatch_table_t* global_helper_provider_dispatch_table; ebpf_map_t** maps; size_t count_of_maps; ebpf_extension_client_t* program_information_client; const void* program_information_binding_context; const ebpf_extension_data_t* program_information_data; const ebpf_extension_dispatch_table_t* program_information_provider_dispatch_table; bool program_invalidated; size_t trampoline_entry_count; ebpf_trampoline_entry_t* trampoline_entries; } ebpf_program_t; static void _ebpf_program_program_information_provider_changed( void* client_binding_context, const void* provider_binding_context, const ebpf_extension_data_t* provider_data, const ebpf_extension_dispatch_table_t* provider_dispatch_table) { ebpf_error_code_t return_value; ebpf_program_t* program = (ebpf_program_t*)client_binding_context; if (program->program_information_provider_dispatch_table != NULL) { if (provider_dispatch_table == NULL) { program->program_invalidated = true; return; } return_value = ebpf_build_trampoline_table( &program->trampoline_entry_count, &program->trampoline_entries, provider_dispatch_table); if (return_value != EBPF_ERROR_SUCCESS) { program->program_invalidated = true; return; } } program->program_information_provider_dispatch_table = provider_dispatch_table; program->program_information_binding_context = provider_binding_context; program->program_information_data = provider_data; } static void _ebpf_program_free(ebpf_object_t* object) { size_t index; ebpf_program_t* program = (ebpf_program_t*)object; if (!program) return; ebpf_epoch_free(program->trampoline_entries); ebpf_extension_unload(program->global_helper_extension_client); ebpf_extension_unload(program->program_information_client); if (program->parameters.code_type == EBPF_CODE_NATIVE) { ebpf_epoch_free(program->code_or_vm.code); } else { ubpf_destroy(program->code_or_vm.vm); } ebpf_free(program->parameters.program_name.value); ebpf_free(program->parameters.section_name.value); for (index = 0; index < program->count_of_maps; index++) ebpf_object_release_reference((ebpf_object_t*)program->maps[index]); ebpf_free(program->maps); ebpf_epoch_free(object); } static ebpf_error_code_t ebpf_program_load_providers(ebpf_program_t* program) { ebpf_error_code_t return_value; void* provider_binding_context; program->program_invalidated = false; return_value = ebpf_extension_load( &program->global_helper_extension_client, &ebpf_global_helper_function_interface_id, program, NULL, NULL, &provider_binding_context, &program->global_helper_provider_data, &program->global_helper_provider_dispatch_table, NULL); if (return_value != EBPF_ERROR_SUCCESS) goto Done; return_value = ebpf_extension_load( &program->program_information_client, &program->parameters.program_type, program, NULL, NULL, (void**)&program->program_information_binding_context, &program->program_information_data, &program->program_information_provider_dispatch_table, _ebpf_program_program_information_provider_changed); if (return_value != EBPF_ERROR_SUCCESS) goto Done; Done: return return_value; } ebpf_error_code_t ebpf_program_create(ebpf_program_t** program) { ebpf_error_code_t retval; ebpf_program_t* local_program; local_program = (ebpf_program_t*)ebpf_epoch_allocate(sizeof(ebpf_program_t), EBPF_MEMORY_NO_EXECUTE); if (!local_program) { retval = EBPF_ERROR_OUT_OF_RESOURCES; goto Done; } memset(local_program, 0, sizeof(ebpf_program_t)); ebpf_object_initialize(&local_program->object, EBPF_OBJECT_PROGRAM, _ebpf_program_free); *program = local_program; local_program = NULL; retval = EBPF_ERROR_SUCCESS; Done: if (local_program) _ebpf_program_free(&local_program->object); return retval; } ebpf_error_code_t ebpf_program_initialize(ebpf_program_t* program, const ebpf_program_parameters_t* program_parameters) { ebpf_error_code_t return_value; ebpf_utf8_string_t local_program_name = {NULL, 0}; ebpf_utf8_string_t local_section_name = {NULL, 0}; return_value = ebpf_duplicate_utf8_string(&local_program_name, &program_parameters->program_name); if (return_value != EBPF_ERROR_SUCCESS) goto Done; return_value = ebpf_duplicate_utf8_string(&local_section_name, &program_parameters->section_name); if (return_value != EBPF_ERROR_SUCCESS) goto Done; program->parameters = *program_parameters; program->parameters.program_name = local_program_name; local_program_name.value = NULL; program->parameters.section_name = local_section_name; local_section_name.value = NULL; return_value = ebpf_program_load_providers(program); if (return_value != EBPF_ERROR_SUCCESS) { goto Done; } return_value = EBPF_ERROR_SUCCESS; Done: ebpf_free(local_program_name.value); ebpf_free(local_section_name.value); return return_value; } ebpf_error_code_t ebpf_program_get_properties(ebpf_program_t* program, ebpf_program_parameters_t* program_parameters) { *program_parameters = program->parameters; return EBPF_ERROR_SUCCESS; } ebpf_error_code_t ebpf_program_associate_maps(ebpf_program_t* program, ebpf_map_t** maps, size_t maps_count) { size_t index; program->maps = ebpf_allocate(maps_count * sizeof(ebpf_map_t*), EBPF_MEMORY_NO_EXECUTE); if (!program->maps) return EBPF_ERROR_OUT_OF_RESOURCES; memcpy(program->maps, maps, sizeof(ebpf_map_t*) * maps_count); program->count_of_maps = maps_count; for (index = 0; index < program->count_of_maps; index++) ebpf_object_acquire_reference((ebpf_object_t*)program->maps[index]); return EBPF_ERROR_SUCCESS; } ebpf_error_code_t ebpf_program_load_machine_code(ebpf_program_t* program, uint8_t* machine_code, size_t machine_code_size) { ebpf_error_code_t return_value; uint8_t* local_machine_code = NULL; if (program->code_or_vm.code) { return_value = EBPF_ERROR_INVALID_PARAMETER; goto Done; } local_machine_code = ebpf_epoch_allocate(machine_code_size, EBPF_MEMORY_EXECUTE); if (!local_machine_code) { return_value = EBPF_ERROR_OUT_OF_RESOURCES; goto Done; } memcpy(local_machine_code, machine_code, machine_code_size); program->parameters.code_type = EBPF_CODE_NATIVE; program->code_or_vm.code = local_machine_code; local_machine_code = NULL; return_value = EBPF_ERROR_SUCCESS; Done: ebpf_epoch_free(local_machine_code); return return_value; } static ebpf_error_code_t _ebpf_program_register_helpers(ebpf_program_t* program) { size_t index = 0; size_t count = (program->global_helper_provider_dispatch_table->size - EBPF_OFFSET_OF(ebpf_extension_dispatch_table_t, function)) / sizeof(program->global_helper_provider_dispatch_table->function); for (index = 0; index < count; index++) { const void* helper = (void*)program->global_helper_provider_dispatch_table->function[index]; if (helper == NULL) continue; if (ubpf_register(program->code_or_vm.vm, (unsigned int)index, NULL, (void*)helper) < 0) return EBPF_ERROR_INVALID_PARAMETER; } return EBPF_ERROR_SUCCESS; } ebpf_error_code_t ebpf_program_load_byte_code(ebpf_program_t* program, ebpf_instuction_t* instructions, size_t instruction_count) { ebpf_error_code_t return_value; char* error_message = NULL; program->parameters.code_type = EBPF_CODE_EBPF; program->code_or_vm.vm = ubpf_create(); if (!program->code_or_vm.vm) { return_value = EBPF_ERROR_OUT_OF_RESOURCES; goto Done; } // BUG - ubpf implements bounds checking to detect interpreted code accessing // memory out of bounds. Currently this is flagging valid access checks and // failing. toggle_bounds_check(program->code_or_vm.vm, false); return_value = _ebpf_program_register_helpers(program); if (return_value != EBPF_ERROR_SUCCESS) goto Done; if (ubpf_load( program->code_or_vm.vm, instructions, (uint32_t)(instruction_count * sizeof(ebpf_instuction_t)), &error_message) != 0) { ebpf_free(error_message); return_value = EBPF_ERROR_INVALID_PARAMETER; goto Done; } Done: if (return_value != EBPF_ERROR_SUCCESS) { ubpf_destroy(program->code_or_vm.vm); program->code_or_vm.vm = NULL; } return return_value; } void ebpf_program_invoke(ebpf_program_t* program, void* context, uint32_t* result) { if (program->program_invalidated) return; if (program->parameters.code_type == EBPF_CODE_NATIVE) { ebpf_program_entry_point_t function_pointer; function_pointer = (ebpf_program_entry_point_t)(program->code_or_vm.code); *result = (function_pointer)(context); } else { char* error_message = NULL; *result = (uint32_t)(ubpf_exec(program->code_or_vm.vm, context, 1024, &error_message)); ebpf_free(error_message); } } ebpf_error_code_t ebpf_program_get_helper_function_address(const ebpf_program_t* program, uint32_t helper_function_id, uint64_t* address) { size_t count = (program->global_helper_provider_dispatch_table->size - EBPF_OFFSET_OF(ebpf_extension_dispatch_table_t, function)) / sizeof(program->global_helper_provider_dispatch_table->function); if (helper_function_id > EBPF_MAX_GLOBAL_HELPER_FUNCTION) { helper_function_id >>= 16; if ((program->trampoline_entries == NULL) || (helper_function_id > program->trampoline_entry_count)) return EBPF_ERROR_INVALID_PARAMETER; *address = (uint64_t)(program->trampoline_entries + helper_function_id); } else { if (helper_function_id > count) { return EBPF_ERROR_INVALID_PARAMETER; } *address = (uint64_t)program->global_helper_provider_dispatch_table->function[helper_function_id]; } return EBPF_ERROR_SUCCESS; } ebpf_error_code_t ebpf_program_get_program_information_data( const ebpf_program_t* program, const ebpf_extension_data_t** program_information_data) { if (program->program_invalidated) return EBPF_ERROR_EXTENSION_FAILED_TO_LOAD; if (!program->program_information_data) return EBPF_ERROR_EXTENSION_FAILED_TO_LOAD; *program_information_data = program->program_information_data; return EBPF_ERROR_SUCCESS; }
smiley/ebpf-for-windows
include/ebpf_api.h
/* * Copyright (c) Microsoft Corporation * SPDX-License-Identifier: MIT */ #pragma once #include "ebpf_windows.h" #ifdef __cplusplus extern "C" { #endif __declspec(selectany) ebpf_attach_type_t EBPF_ATTACH_TYPE_UNSPECIFIED = {0}; __declspec(selectany) ebpf_attach_type_t EBPF_ATTACH_TYPE_XDP = { 0x85e0d8ef, 0x579e, 0x4931, {0xb0, 0x72, 0x8e, 0xe2, 0x26, 0xbb, 0x2e, 0x9d}}; __declspec(selectany) ebpf_attach_type_t EBPF_ATTACH_TYPE_BIND = { 0xb9707e04, 0x8127, 0x4c72, {0x83, 0x3e, 0x05, 0xb1, 0xfb, 0x43, 0x94, 0x96}}; __declspec(selectany) ebpf_attach_type_t EBPF_PROGRAM_TYPE_UNSPECIFIED = {0}; __declspec(selectany) ebpf_program_type_t EBPF_PROGRAM_TYPE_XDP = { 0xf1832a85, 0x85d5, 0x45b0, {0x98, 0xa0, 0x70, 0x69, 0xd6, 0x30, 0x13, 0xb0}}; __declspec(selectany) ebpf_program_type_t EBPF_PROGRAM_TYPE_BIND = { 0x608c517c, 0x6c52, 0x4a26, {0xb6, 0x77, 0xbb, 0x1c, 0x34, 0x42, 0x5a, 0xdf}}; typedef void* ebpf_handle_t; const ebpf_handle_t ebpf_handle_invalid = (ebpf_handle_t)-1; typedef struct _tlv_type_length_value tlv_type_length_value_t; typedef enum _ebpf_execution_type { EBPF_EXECUTION_JIT, EBPF_EXECUTION_INTERPRET } ebpf_execution_type_t; /** * @brief Initialize the eBPF user mode library. */ uint32_t ebpf_api_initiate(); /** * @brief Terminate the eBPF user mode library. */ void ebpf_api_terminate(); /** * @brief Load an eBFP program into the kernel execution context. * @param[in] file An ELF file containing one or more eBPF programs. * @param[in] section_name Name of the section in the ELF file to load. * @param[in] execution_type How this program should be run in the execution * context. * @param[out] handle Handle to eBPF program. * @param[out] error_message Error message describing what failed. */ uint32_t ebpf_api_load_program( const char* file, const char* section_name, ebpf_execution_type_t execution_type, ebpf_handle_t* handle, uint32_t* count_of_map_handles, ebpf_handle_t* map_handles, const char** error_message); /** * @brief Find an element in an eBPF map. * @param[in] handle Handle to eBPF map. * @param[in] key_size Size of the key buffer. * @param[in] key Pointer to buffer containing key. * @param[in] value_size Size of the value buffer. * @param[out] value Pointer to buffer that contains value on success. */ uint32_t ebpf_api_map_find_element( ebpf_handle_t handle, uint32_t key_size, const uint8_t* key, uint32_t value_size, uint8_t* value); /** * @brief Update an element in an eBPF map. * @param[in] handle Handle to eBPF map. * @param[in] key_size Size of the key buffer. * @param[in] key Pointer to buffer containing key. * @param[in] value_size Size of the value buffer. * @param[out] value Pointer to buffer containing value. */ uint32_t ebpf_api_map_update_element( ebpf_handle_t handle, uint32_t key_size, const uint8_t* key, uint32_t value_size, const uint8_t* value); /** * @brief Delete an element in an eBPF map. * @param[in] handle Handle to eBPF map. * @param[in] key_size Size of the key buffer. * @param[in] key Pointer to buffer containing key. */ uint32_t ebpf_api_map_delete_element(ebpf_handle_t handle, uint32_t key_size, const uint8_t* key); /** * @brief Return the next key in an eBPF map. * @param[in] handle Handle to eBPF map. * @param[in] key_size Size of the key buffer. * @param[in] previous_key Pointer to buffer containing previous key or NULL to restart enumeration. * @param[out] next_key Pointer to buffer that contains next * key on success. * @retval ERROR_NO_MORE_ITEMS previous_key was the last key. */ uint32_t ebpf_api_get_next_map_key(ebpf_handle_t handle, uint32_t key_size, const uint8_t* previous_key, uint8_t* next_key); /** * @brief Get the next eBPF map. * @param[in] previous_handle Handle to previous eBPF map or * ebpf_handle_invalid to start enumeration. * @param[out] next_handle The next eBPF map or ebpf_handle_invalid if this * is the last map. */ uint32_t ebpf_api_get_next_map(ebpf_handle_t previous_handle, ebpf_handle_t* next_handle); /** * @brief Get the next eBPF program. * @param[in] previous_handle Handle to previous eBPF program or * ebpf_handle_invalid to start enumeration. * @param[out] next_handle The next eBPF program or ebpf_handle_invalid if this * is the last map. */ uint32_t ebpf_api_get_next_program(ebpf_handle_t previous_handle, ebpf_handle_t* next_handle); /** * @brief Query properties of an eBPF map. * @param[in] handle Handle to an eBPF map. * @param[out] size Size of the eBPF map definition. * @param[out] type Type of the eBPF map. * @param[out] key_size Size of keys in the eBPF map. * @param[out] value_size Size of values in the eBPF map. * @param[out] max_entries Maximum number of entries in the map. */ uint32_t ebpf_api_map_query_definition( ebpf_handle_t handle, uint32_t* size, uint32_t* type, uint32_t* key_size, uint32_t* value_size, uint32_t* max_entries); /** * @brief Query information about an eBPF program. * @param[in] handle Handle to an eBPF program. */ uint32_t ebpf_api_program_query_information( ebpf_handle_t handle, ebpf_execution_type_t* program_type, const char** file_name, const char** section_name); /** * @brief Get list of programs and stats in an ELF eBPF file. * @param[in] file Name of ELF file containing eBPF program. * @param[in] section Optionally, the name of the section to query. * @param[in] verbose Obtain additional information about the programs. * @param[out] data On success points to a list of eBPF programs. * @param[out] error_message On failure points to a text description of * the error. * * The list of eBPF programs from this function is TLV formatted as follows:\n * * sections ::= SEQUENCE {\n * section SEQUENCE of section\n * }\n * \n * section ::= SEQUENCE {\n * name STRING\n * platform_specific_data INTEGER\n * count_of_maps INTEGER\n * byte_code BLOB\n * statistic SEQUENCE of statistic\n * }\n * \n * statistic ::= SEQUENCE {\n * name STRING\n * value INTEGER\n * }\n */ uint32_t ebpf_api_elf_enumerate_sections( const char* file, const char* section, bool verbose, const tlv_type_length_value_t** data, const char** error_message); /** * @brief Convert an eBPF program to human readable byte code. * @param[in] file Name of ELF file containing eBPF program. * @param[in] section The name of the section to query. * @param[out] disassembly On success points text version of the program. * @param[out] error_message On failure points to a text description of * the error. */ uint32_t ebpf_api_elf_disassemble_section( const char* file, const char* section, const char** disassembly, const char** error_message); /** * @brief Convert an eBPF program to human readable byte code. * @param[in] file Name of ELF file containing eBPF program. * @param[in] section The name of the section to query. * @param[in] verbose Obtain additional information about the programs. * @param[out] report Points to a text section describing why the program * failed verification. * @param[out] error_message On failure points to a text description of * the error. */ uint32_t ebpf_api_elf_verify_section( const char* file, const char* section, bool verbose, const char** report, const char** error_message); /** * @brief Free a TLV returned from ebpf_api_elf_enumerate_sections * @param[in] data Memory to free. */ void ebpf_api_elf_free(const tlv_type_length_value_t* data); /** * @brief Free memory for a string returned from eBPF API. * @param[in] string Memory to free. */ void ebpf_api_free_string(const char* string); /** * @brief Associate a name with an object handle. * @param[in] handle Handle to object. * @param[in] name Name to associate with handle. */ uint32_t ebpf_api_pin_object(ebpf_handle_t handle, const uint8_t* name, uint32_t name_length); /** * @brief Dissociate a name with an object handle. * @param[in] name Name to dissociate. */ uint32_t ebpf_api_unpin_object(const uint8_t* name, uint32_t name_length); /** * @brief Find a map given its associated name. * @param[in] name Name to find. */ uint32_t ebpf_api_get_pinned_map(const uint8_t* name, uint32_t name_length, ebpf_handle_t* handle); /** * @brief Bind a program to an attach point and return a handle representing * the link. * * @param[in] program_handle Handle to program to attach. * @param[in] attach_type Attach point to attach program to. * @param[out] link_handle Pointer to memory that contains the link handle * on success. * @retval ERROR_SUCCESS The operations succeeded. * @retval ERROR_INVALID_PARAMETER One or more parameters are incorrect. */ uint32_t ebpf_api_link_program(ebpf_handle_t program_handle, ebpf_attach_type_t attach_type, ebpf_handle_t* link_handle); /** * @brief Close an ebpf handle. * * @param handle Handle to close. * @return ERROR_SUCCESS Handle was closed. * @retval ERROR_INVALID_HANDLE Handle is not valid. */ uint32_t ebpf_api_close_handle(ebpf_handle_t handle); #ifdef __cplusplus } #endif
smiley/ebpf-for-windows
include/ebpf_program_types.h
/* * Copyright (c) Microsoft Corporation * SPDX-License-Identifier: MIT */ #pragma once #ifdef __midl #define MIDL(x) x #else #define MIDL(x) #endif typedef enum _ebpf_helper_return_type { EBPF_RETURN_TYPE_INTEGER = 0, EBPF_RETURN_TYPE_PTR_TO_MAP_VALUE_OR_NULL, EBPF_RETURN_TYPE_VOID, } ebpf_helper_return_type_t; typedef enum _ebpf_helper_argument_type { EBPF_ARGUMENT_TYPE_DONTCARE = 0, EBPF_ARGUMENT_TYPE_ANYTHING, // All values are valid, e.g., 64-bit flags. EBPF_ARGUMENT_TYPE_CONST_SIZE, EBPF_ARGUMENT_TYPE_CONST_SIZE_OR_ZERO, EBPF_ARGUMENT_TYPE_PTR_TO_CTX, EBPF_ARGUMENT_TYPE_PTR_TO_MAP, EBPF_ARGUMENT_TYPE_PTR_TO_MAP_KEY, EBPF_ARGUMENT_TYPE_PTR_TO_MAP_VALUE, EBPF_ARGUMENT_TYPE_PTR_TO_MEM, EBPF_ARGUMENT_TYPE_PTR_TO_MEM_OR_NULL, EBPF_ARGUMENT_TYPE_PTR_TO_UNINIT_MEM, } ebpf_helper_argument_type_t; typedef struct _ebpf_context_descriptor { int size; // Size of ctx struct. int data; // Offset into ctx struct of pointer to data. int end; // Offset into ctx struct of pointer to end of data. int meta; // Offset into ctx struct of pointer to metadata. } ebpf_context_descriptor_t; typedef struct _ebpf_program_type_descriptor { MIDL([string]) const char* name; ebpf_context_descriptor_t* context_descriptor; uint64_t platform_specific_data; char is_privileged; } ebpf_program_type_descriptor_t; typedef struct _ebpf_helper_function_prototype { uint32_t helper_id; MIDL([string]) const char* name; ebpf_helper_return_type_t return_type; ebpf_helper_argument_type_t arguments[5]; } ebpf_helper_function_prototype_t; typedef struct _ebpf_program_information { ebpf_program_type_descriptor_t program_type_descriptor; uint32_t count_of_helpers; MIDL([size_is(count_of_helpers)]) ebpf_helper_function_prototype_t* helper_prototype; } ebpf_program_information_t;