repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
streamglider/streamglider
|
StreamGlider App/NSAttributedString-HTML/Classes/DTAttributedTextContentView.h
|
//
// TextView.h
// CoreTextExtensions
//
// Created by <NAME> on 1/9/11.
// Copyright 2011 D<EMAIL>. All rights reserved.
//
#import <CoreText/CoreText.h>
#import "NSAttributedString+HTML.h"
#import "DTCoreTextLayouter.h"
#import "DTTextAttachment.h"
@class DTAttributedTextContentView;
@class DTCoreTextLayoutFrame;
@protocol DTAttributedTextContentViewDelegate <NSObject>
@optional
// called after a layout frame or a part of it is drawn
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView didDrawLayoutFrame:(DTCoreTextLayoutFrame *)layoutFrame inContext:(CGContextRef)context;
// provide custom view for an attachment, e.g. an imageView for images
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame;
// provide button to be placed over links, the identifier is used to link multiple parts of the same A tag
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForLink:(NSURL *)url identifier:(NSString *)identifier frame:(CGRect)frame;
// old style
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttributedString:(NSAttributedString *)string frame:(CGRect)frame;
@end
@interface DTAttributedTextContentView : UIView
{
NSAttributedString *_attributedString;
UIEdgeInsets edgeInsets;
BOOL drawDebugFrames;
BOOL shouldDrawImages;
BOOL shouldLayoutCustomSubviews;
NSMutableSet *customViews;
NSMutableDictionary *customViewsForLinksIndex;
NSMutableDictionary *customViewsForAttachmentsIndex;
id <DTAttributedTextContentViewDelegate> _delegate;
BOOL _delegateSupportsCustomViewsForAttachments;
BOOL _delegateSupportsCustomViewsForLinks;
BOOL _delegateSupportsGenericCustomViews;
BOOL _delegateSupportsNotificationAfterDrawing;
BOOL _isTiling;
DTCoreTextLayouter *_layouter;
DTCoreTextLayoutFrame *_layoutFrame;
CGPoint _layoutOffset;
CGSize _backgroundOffset;
}
- (id)initWithAttributedString:(NSAttributedString *)attributedString width:(CGFloat)width;
- (void)layoutSubviewsInRect:(CGRect)rect;
- (void)relayoutText;
- (void)removeAllCustomViews;
@property (retain) DTCoreTextLayouter *layouter;
@property (retain) DTCoreTextLayoutFrame *layoutFrame;
@property (nonatomic, retain) NSMutableSet *customViews;
@property (nonatomic, copy) NSAttributedString *attributedString;
@property (nonatomic) UIEdgeInsets edgeInsets;
@property (nonatomic) BOOL drawDebugFrames;
@property (nonatomic) BOOL shouldDrawImages;
@property (nonatomic) BOOL shouldLayoutCustomSubviews;
@property (nonatomic) CGPoint layoutOffset;
@property (nonatomic) CGSize backgroundOffset;
@property (nonatomic, assign) IBOutlet id <DTAttributedTextContentViewDelegate> delegate;
@end
@interface DTAttributedTextContentView (Tiling)
+ (void)setLayerClass:(Class)layerClass;
+ (Class)layerClass;
@end
|
streamglider/streamglider
|
StreamGlider App/Classes/StreamCastStateController.h
|
<gh_stars>1-10
//
// StreamCastStateController.h
// StreamCast
//
// Created by <NAME> on 17/12/2010.
// Copyright 2010 StreamGlider, Inc. All rights reserved.
//
// This program is free software if used non-commercially: you can redistribute it and/or modify
// it under the terms of the BSD 4 Clause License as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// BSD 4 Clause License for more details.
//
// You should have received a copy of the BSD 4 Clause License
// along with this program. If not, see the README.md file with this program.
#import <Foundation/Foundation.h>
typedef enum {
StreamLayoutTable,
StreamLayoutSlideshow,
StreamLayoutCombined,
StreamLayoutPreview,
StreamLayoutBrowser,
StreamLayoutEditing
} MainScreenLayoutType;
@class StreamCastViewController;
@class SmallFrameViewController;
@interface StreamCastStateController : NSObject
@property (nonatomic, assign) StreamCastViewController *streamCastViewController;
@property (nonatomic, assign, setter=setIsPlaying:) BOOL isPlaying;
@property (nonatomic, assign) MainScreenLayoutType currentState;
@property (assign) BOOL animationInProgress;
@property (nonatomic, assign) UIView *animateView;
@property (nonatomic, assign) CGRect animateRect;
+ (StreamCastStateController*)sharedInstance;
- (void)switchToState:(MainScreenLayoutType)state;
- (void)exitBrowser;
- (void)exitPreview;
- (void)exitEditing;
@end
|
streamglider/streamglider
|
StreamGlider App/NSAttributedString-HTML/Classes/DTWebVideoView.h
|
<reponame>streamglider/streamglider
//
// DTWebVideoView.h
// CoreTextExtensions
//
// Created by <NAME> on 8/5/11.
// Copyright 2011 <EMAIL>. All rights reserved.
//
#import <UIKit/UIKit.h>
@class DTTextAttachment;
@class DTWebVideoView;
@protocol DTWebVideoViewDelegate <NSObject>
@optional
- (BOOL)videoView:(DTWebVideoView *)videoView shouldOpenExternalURL:(NSURL *)url;
@end
@interface DTWebVideoView : UIView <UIWebViewDelegate>
{
DTTextAttachment *_attachment;
id <DTWebVideoViewDelegate> _delegate;
UIWebView *_webView;
}
@property (nonatomic, assign) id <DTWebVideoViewDelegate> delegate;
@property (nonatomic, retain) DTTextAttachment *attachment;
@end
|
streamglider/streamglider
|
StreamGlider App/Classes/Loader.h
|
//
// Loader.h
// StreamCast
//
// Created by <NAME> on 7/16/10.
// Copyright 2010 StreamGlider, Inc. All rights reserved.
//
// This program is free software if used non-commercially: you can redistribute it and/or modify
// it under the terms of the BSD 4 Clause License as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// BSD 4 Clause License for more details.
//
// You should have received a copy of the BSD 4 Clause License
// along with this program. If not, see the README.md file with this program.
#import <Foundation/Foundation.h>
#import "LoaderDelegate.h"
#import "FeedSourceType.h"
#import "APIDelegate.h"
#import "StreamsLoaderDelegate.h"
@class Core;
@class FeaturedFeedsLoader;
@interface Loader : NSObject <APIDelegate, StreamsLoaderDelegate>
@property (nonatomic, assign) id<LoaderDelegate> delegate;
@property (nonatomic, retain) FeaturedFeedsLoader *ffLoader;
+ (Loader*)sharedInstance;
- (void)loadWithCore:(Core*)core;
- (void)storeSources;
- (void)storeStreams;
@end
|
streamglider/streamglider
|
StreamGlider App/NSAttributedString-HTML/Classes/DTCoreTextGlyphRun.h
|
//
// DTCoreTextGlyphRun.h
// CoreTextExtensions
//
// Created by <NAME> on 1/25/11.
// Copyright 2011 <EMAIL>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreText/CoreText.h>
@class DTCoreTextLayoutLine;
@class DTTextAttachment;
@interface DTCoreTextGlyphRun : NSObject
{
CTRunRef _run;
CGRect _frame;
CGFloat _offset; // x distance from line origin
CGFloat ascent;
CGFloat descent;
CGFloat leading;
CGFloat width;
NSInteger numberOfGlyphs;
const CGPoint *glyphPositionPoints;
BOOL needToFreeGlyphPositionPoints;
DTCoreTextLayoutLine *_line;
NSDictionary *attributes;
NSArray *stringIndices;
DTTextAttachment *_attachment;
BOOL _didCheckForAttachmentInAttributes;
BOOL _didCalculateMetrics;
}
- (id)initWithRun:(CTRunRef)run layoutLine:(DTCoreTextLayoutLine *)layoutLine offset:(CGFloat)offset;
- (CGRect)frameOfGlyphAtIndex:(NSInteger)index;
- (CGRect)imageBoundsInContext:(CGContextRef)context;
- (NSRange)stringRange;
- (NSArray *)stringIndices;
- (void)drawInContext:(CGContextRef)context;
- (void)fixMetricsFromAttachment;
@property (nonatomic, assign, readonly) CGRect frame;
@property (nonatomic, assign, readonly) NSInteger numberOfGlyphs;
@property (nonatomic, assign, readonly) NSDictionary *attributes;
@property (nonatomic, assign, readonly) CGFloat ascent;
@property (nonatomic, assign, readonly) CGFloat descent;
@property (nonatomic, assign, readonly) CGFloat leading;
@property (nonatomic, assign, readonly) CGFloat width;
@property (nonatomic, retain) DTTextAttachment *attachment;
@end
|
streamglider/streamglider
|
StreamGlider App/HMTL-Parser/HTMLParser.h
|
<reponame>streamglider/streamglider
//
// HTMLParser.h
// StackOverflow
//
// Created by <NAME> on 09/03/2010.
// Copyright 2010 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <libxml/HTMLparser.h>
#import "HTMLNode.h"
@class HTMLNode;
@interface HTMLParser : NSObject
{
@public
htmlDocPtr _doc;
}
-(id)initWithContentsOfURL:(NSURL*)url error:(NSError**)error;
-(id)initWithData:(NSData*)data error:(NSError**)error;
-(id)initWithString:(NSString*)string error:(NSError**)error;
//Returns the doc tag
-(HTMLNode*)doc;
//Returns the body tag
-(HTMLNode*)body;
//Returns the html tag
-(HTMLNode*)html;
@end
|
streamglider/streamglider
|
StreamGlider App/NSAttributedString-HTML/Classes/DTCSSListStyle.h
|
<gh_stars>1-10
//
// DTCSSListStyle.h
// CoreTextExtensions
//
// Created by <NAME> on 8/11/11.
// Copyright 2011 <EMAIL>. All rights reserved.
//
typedef enum
{
DTCSSListStyleTypeInherit = 0,
DTCSSListStyleTypeNone,
DTCSSListStyleTypeCircle,
DTCSSListStyleTypeDecimal,
DTCSSListStyleTypeDecimalLeadingZero,
DTCSSListStyleTypeDisc,
DTCSSListStyleTypeUpperAlpha,
DTCSSListStyleTypeUpperLatin,
DTCSSListStyleTypeLowerAlpha,
DTCSSListStyleTypeLowerLatin,
DTCSSListStyleTypePlus,
DTCSSListStyleTypeUnderscore
} DTCSSListStyleType;
typedef enum
{
DTCSSListStylePositionInherit = 0,
DTCSSListStylePositionInside,
DTCSSListStylePositionOutside
} DTCSSListStylePosition;
@interface DTCSSListStyle : NSObject
{
BOOL _inherit;
DTCSSListStyleType _type;
DTCSSListStylePosition _position;
}
@property (nonatomic, assign) BOOL inherit;
@property (nonatomic, assign) DTCSSListStyleType type;
@property (nonatomic, assign) DTCSSListStylePosition position;
+ (DTCSSListStyle *)listStyleWithStyles:(NSDictionary *)styles;
+ (DTCSSListStyle *)decimalListStyle;
+ (DTCSSListStyle *)discListStyle;
+ (DTCSSListStyle *)inheritedListStyle;
+ (DTCSSListStyleType)listStyleTypeFromString:(NSString *)string;
+ (DTCSSListStylePosition)listStylePositionFromString:(NSString *)string;
- (id)initWithStyles:(NSDictionary *)styles;
- (NSString *)prefixWithCounter:(NSInteger)counter;
@end
|
mono0926/flutter_text_to_speech
|
ios/Classes/FlutterTextToSpeechPlugin.h
|
<gh_stars>1-10
#import <Flutter/Flutter.h>
@interface FlutterTextToSpeechPlugin : NSObject<FlutterPlugin>
@end
|
jk1mly/fm-bcd
|
fmled.c
|
/*
* FM tuner for PIC16F1503
* indicates a frequency by BCD(Binary-coded decimal)
*
* JA1YTS:Toshiba Amature Radio Station
* JK1MLY:<NAME>
*
* (C)2022 JA1YTS,JK1MLY All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
*
* data sheet
* https://datasheet.lcsc.com/szlcsc/RDA5807M_C82537.pdf
*
*/
#include <stdio.h>
#include <stdint.h>
#include <xc.h>
#include <pic.h>
#include <pic16F1503.h>
#define _XTAL_FREQ 4000000
// CONFIG1
#pragma config FOSC = INTOSC // Oscillator Selection
#pragma config WDTE = OFF // Watchdog Timer
#pragma config PWRTE = OFF // Power-up Timer
#pragma config MCLRE = OFF // MCLR Pin Function Select
#pragma config CP = OFF // Flash Program Memory Code Protection
#pragma config BOREN = ON // Brown-out Reset Enable
#pragma config CLKOUTEN = OFF // Clock Out Enable
// CONFIG2
#pragma config WRT = OFF // Flash Memory Self-Write Protection
// #pragma config PLLEN = OFF // 4x PLL OFF
#pragma config STVREN = OFF // Stack Overflow/Underflow Reset Enable
#pragma config BORV = LO // Brown-out Reset Voltage Selection
// #pragma config LPBOREN = OFF // Low Power Brown-out Reset Enable
#pragma config LVP = OFF // Low-Voltage Programming Enable
#define I2C_SDA_LOW LATA5 = 0;TRISA5 = 0 // 0
#define I2C_SDA_HIGH LATA5 = 1;TRISA5 = 1 // Z(1)
#define I2C_SDA_READ LATA5 = 0;TRISA5 = 1 // Input
#define I2C_SDA_DATA RA5
#define I2C_SCK_LOW LATA4 = 0
#define I2C_SCK_HIGH LATA4 = 1
#define LED_WAIT asm ("NOP");asm ("NOP");asm ("NOP")
#define LED1_ON LATA0 = 1; LATA1 = 0
#define LED1_OFF LATA0 = 0; LATA1 = 0
#define LED2_ON LATA1 = 1; LATA2 = 0
#define LED2_OFF LATA1 = 0; LATA2 = 0
#define LED3_ON LATA2 = 1; LATC0 = 0
#define LED3_OFF LATA2 = 0; LATC0 = 0
#define LED4_ON LATC0 = 1; LATC1 = 0
#define LED4_OFF LATC0 = 0; LATC1 = 0
#define LED5_ON LATC1 = 1; LATC2 = 0
#define LED5_OFF LATC1 = 0; LATC2 = 0
#define SW_UP RC5
#define SW_DN RC4
#define SW_FN RC3
#define PUSH_ON 0
#define M_FRQ_SET 1
#define M_SEQ_DN 2
#define M_SEQ_UP 3
#define M_VOL_SET 4
#define M_TUN_CHK 8
#define VOL_LMT_H 12
#define VOL_LMT_L 1
#define SET_TFM 100
#define SET_NAK 95
#define SET_JWV 113
#define SET_NHK 125
// I2C mode CHAN[9:0] BAND=2 CHAN = (Freq - 76.0M) / Ch_s
// TFM Freq=80.0 BAND=2 Ch_s=100k CHAN=40 0x28 00 0010 1000
#define TUN_ADR 0x20
#define REG02_H 0xC0
#define MON02_H 0xE0
#define FUP02_H 0xC3
#define FDN02_H 0xC1
#define REG02_L 0x01
#define REG03_H 0x0A
#define TFM03_H 0x0A
#define REG03_L 0x08
#define TUN03_L 0x18
#define TFM03_L 0x18
#define REG04_H 0x08
#define AFC04_H 0x09
#define REG04_L 0x80
#define REG05_H 0x88
#define TUN05_H 0x8C
#define REG05_L 0x86
#define BRIT1 15
#define BRIT0 45
#define DARK1 1
#define DARK0 59
void port_init(void) {
OSCCON = 0b01101000; //4MHz
TRISA = 0b00101000; //Input(1)
TRISC = 0b00111000; //Input(1)
OPTION_REG = 0b00000000; //MSB WPUENn
WPUA = 0b00101000; //PupOn(1)
INTCON = 0b00000000;
LATA = 0b00010000;
LATC = 0b00000000;
ANSELA = 0b00000000;
ANSELC = 0b00000000;
}
void blk_led1(void) {
for (uint8_t lp = 0; lp < 100; lp++) {
LED1_ON;
LED_WAIT;
LED1_OFF;
LED_WAIT;
}
}
void blk_led2(void) {
for (uint8_t lp = 0; lp < 100; lp++) {
LED2_ON;
LED_WAIT;
LED2_OFF;
LED_WAIT;
}
}
void blk_led3(void) {
for (uint8_t lp = 0; lp < 100; lp++) {
LED3_ON;
LED_WAIT;
LED3_OFF;
LED_WAIT;
}
}
void blk_led4(void) {
for (uint8_t lp = 0; lp < 100; lp++) {
LED4_ON;
LED_WAIT;
LED4_OFF;
LED_WAIT;
}
}
void blk_led5(void) {
for (uint8_t lp = 0; lp < 100; lp++) {
LED5_ON;
LED_WAIT;
LED5_OFF;
LED_WAIT;
}
}
void led_chk(void) {
blk_led1();
__delay_ms(200);
blk_led2();
__delay_ms(200);
blk_led3();
__delay_ms(200);
blk_led4();
__delay_ms(200);
blk_led5();
__delay_ms(200);
}
void i2c_st(void) {
I2C_SCK_HIGH;
I2C_SDA_HIGH;
__delay_us(10);
I2C_SDA_LOW;
__delay_us(6);
I2C_SCK_LOW;
__delay_us(1);
}
void i2c_sck(void) {
I2C_SCK_HIGH;
__delay_us(4);
I2C_SCK_LOW;
__delay_us(1);
}
void i2c_end(void) {
// Stop
I2C_SDA_LOW;
__delay_us(2);
I2C_SCK_HIGH;
__delay_us(6);
// Wait
I2C_SDA_HIGH;
__delay_us(20);
}
void i2c_rtn(void) {
I2C_SDA_HIGH;
__delay_us(6);
I2C_SCK_HIGH;
__delay_us(4);
I2C_SCK_LOW;
I2C_SDA_LOW;
__delay_us(20);
}
void i2c_ack(void) {
__delay_us(1);
I2C_SDA_LOW;
__delay_us(5);
I2C_SCK_HIGH;
__delay_us(4);
I2C_SCK_LOW;
I2C_SDA_LOW;
__delay_us(20);
}
void i2c_nak(void) {
__delay_us(1);
I2C_SDA_HIGH;
__delay_us(5);
I2C_SCK_HIGH;
__delay_us(4);
I2C_SCK_LOW;
I2C_SDA_LOW;
__delay_us(20);
}
void i2c_snd(uint8_t data) {
for (uint8_t lp = 0; lp < 8; lp++) {
if ((data & 0x80) == 0) {
I2C_SDA_LOW;
} else {
I2C_SDA_HIGH;
}
data = (data << 1) & 0xff;
__delay_us(2);
i2c_sck();
}
i2c_rtn();
}
uint8_t i2c_rcv_cnt() {
uint8_t data = 0;
I2C_SDA_READ;
for (uint8_t lp = 0; lp < 8; lp++) {
data = (data << 1) & 0xff;
__delay_us(2);
if (I2C_SDA_DATA == 1) {
data = data | 0x01;
}
i2c_sck();
}
i2c_ack();
return data;
}
uint8_t i2c_rcv_end() {
uint8_t data = 0;
I2C_SDA_READ;
for (uint8_t lp = 0; lp < 8; lp++) {
data = (data << 1) & 0xff;
__delay_us(2);
if (I2C_SDA_DATA == 1) {
data = data | 0x01;
}
i2c_sck();
}
i2c_nak();
return data;
}
uint8_t tun_rcv(void) {
uint8_t data;
uint8_t freq;
uint8_t seek;
uint8_t rssi;
i2c_st();
// read
data = (TUN_ADR & 0xFE) | 0x01;
i2c_snd(data);
// reg0A
data = i2c_rcv_cnt();
seek = (data & 0x40) >> 6;
//
data = i2c_rcv_cnt();
freq = data;
// reg0B
data = i2c_rcv_cnt();
rssi = data;
//
data = i2c_rcv_end();
i2c_end();
return freq;
}
void reg_set(uint8_t freq, uint8_t vol, uint8_t mode) {
uint8_t frq_h;
uint8_t frq_l;
uint8_t frq_r;
uint8_t data;
frq_r = (freq - 60);
frq_h = (frq_r >> 2);
frq_l = ((frq_r & 0x03) << 6) & 0xff;
i2c_st();
// write
data = (TUN_ADR & 0xFE);
i2c_snd(data);
// reg02
if (mode == M_SEQ_UP) {
data = FUP02_H;
} else if (mode == M_SEQ_DN) {
data = FDN02_H;
} else {
data = REG02_H;
}
i2c_snd(data);
//
data = REG02_L;
i2c_snd(data);
// reg03
if (mode == M_TUN_CHK) {
data = TFM03_H;
} else {
data = frq_h;
}
i2c_snd(data);
//
if (mode == M_TUN_CHK) {
data = TFM03_L;
} else if (mode == M_VOL_SET) {
data = (frq_l & 0xC0) | (REG03_L & 0x3F);
} else if (mode == M_SEQ_UP) {
data = (frq_l & 0xC0) | (REG03_L & 0x3F);
} else if (mode == M_SEQ_DN) {
data = (frq_l & 0xC0) | (REG03_L & 0x3F);
} else {
data = (frq_l & 0xC0) | (TUN03_L & 0x3F);
}
i2c_snd(data);
// reg04
data = REG04_H;
i2c_snd(data);
//
data = REG04_L;
i2c_snd(data);
// reg05
if (mode == M_SEQ_UP) {
data = TUN05_H;
} else if (mode == M_SEQ_DN) {
data = TUN05_H;
} else {
data = REG05_H;
}
i2c_snd(data);
//
if (mode == M_TUN_CHK) {
data = REG05_L;
} else {
data = (REG05_L & 0xF0) | (vol & 0x0F);
}
i2c_snd(data);
i2c_end();
}
void bcd_num(uint8_t num) {
uint8_t tim0[5], tim1[5];
if (num > 15) {
blk_led1();
blk_led5();
return;
}
for (uint8_t lp = 0; lp < 4; lp++) {
if (num & 0x08) {
tim0[lp] = BRIT0;
tim1[lp] = BRIT1;
} else {
tim0[lp] = DARK0;
tim1[lp] = DARK1;
}
num = (uint8_t) (num << 1);
}
for (uint8_t lp = 0; lp < 60; lp++) {
if ((num == 0) || (tim1[0] == BRIT1)) {
LED2_ON;
}
if (num != 0) {
for (uint8_t us = 0; us < tim1[0]; us++) {
LED_WAIT;
}
}
LED2_OFF;
for (uint8_t us = 0; us < tim0[0]; us++) {
LED_WAIT;
}
if ((num == 0) || (tim1[1] == BRIT1)) {
LED3_ON;
}
if (num != 0) {
for (uint8_t us = 0; us < tim1[1]; us++) {
LED_WAIT;
}
}
LED3_OFF;
for (uint8_t us = 0; us < tim0[1]; us++) {
LED_WAIT;
}
if ((num == 0) || (tim1[2] == BRIT1)) {
LED4_ON;
}
if (num != 0) {
for (uint8_t us = 0; us < tim1[2]; us++) {
LED_WAIT;
}
}
LED4_OFF;
for (uint8_t us = 0; us < tim0[2]; us++) {
LED_WAIT;
}
if ((num == 0) || (tim1[3] == BRIT1)) {
LED5_ON;
}
if (num != 0) {
for (uint8_t us = 0; us < tim1[3]; us++) {
LED_WAIT;
}
}
LED5_OFF;
for (uint8_t us = 0; us < tim0[3]; us++) {
LED_WAIT;
}
}
}
void frq_bcd_disp(uint8_t freq) {
uint8_t frq3 = 7;
uint8_t frq2 = 0;
uint8_t frq1 = 0;
while (freq > 99) {
frq3++;
freq = freq - 100;
}
if (frq3 > 9) {
frq3 = 5;
}
while (freq > 9) {
frq2++;
freq = freq - 10;
}
if (frq2 > 9) {
frq3 = 5;
}
while (freq > 0) {
frq1++;
freq = freq - 1;
}
if (frq1 > 9) {
frq3 = 5;
}
bcd_num(frq3);
//Wait
for (uint8_t lp = 0; lp < 4; lp++) {
if ((SW_UP == PUSH_ON) || (SW_DN == PUSH_ON) || (SW_FN == PUSH_ON)) {
return;
} else {
__delay_ms(50);
}
}
bcd_num(frq2);
//Wait
for (uint8_t lp = 0; lp < 4; lp++) {
if ((SW_UP == PUSH_ON) || (SW_DN == PUSH_ON) || (SW_FN == PUSH_ON)) {
return;
} else {
__delay_ms(50);
}
}
bcd_num(frq1);
//Wait
for (uint8_t lp = 0; lp < 6; lp++) {
if ((SW_UP == PUSH_ON) || (SW_DN == PUSH_ON) || (SW_FN == PUSH_ON)) {
return;
} else {
__delay_ms(50);
}
}
}
void main(void) {
uint8_t freq = SET_TFM;
uint8_t frq_seq = 0;
uint8_t vol = 5;
uint8_t disp_c = 3;
//Initialize
port_init();
//Hard check
led_chk();
//Test mode
while (SW_FN == PUSH_ON) {
reg_set(0, 0, M_TUN_CHK);
for (uint8_t lp = 0; lp < 3; lp++) {
blk_led1();
blk_led3();
blk_led5();
__delay_ms(100);
}
__delay_ms(250);
freq = SET_NHK;
for (uint8_t lp = 0; lp < 16; lp++) {
bcd_num(lp);
__delay_ms(250);
}
while (SW_DN == PUSH_ON) {
freq = SET_NAK;
blk_led2();
}
while (SW_UP == PUSH_ON) {
freq = SET_JWV;
blk_led4();
}
}
//Start
__delay_ms(50);
blk_led3();
reg_set(freq, vol, M_FRQ_SET);
__delay_ms(250);
__delay_ms(250);
//Loop
while (1) {
uint8_t frq_rd;
//Volume
if (SW_FN == PUSH_ON) {
frq_seq = 0;
disp_c = 0;
__delay_ms(100);
for (uint8_t lp = 0; lp < 10; lp++) {
blk_led3();
if (SW_UP == PUSH_ON) {
blk_led4();
if (vol < VOL_LMT_H) {
vol++;
lp = 0;
blk_led5();
}
reg_set(freq, vol, M_VOL_SET);
}
if (SW_DN == PUSH_ON) {
blk_led2();
if (vol > VOL_LMT_L) {
vol--;
lp = 0;
blk_led1();
}
reg_set(freq, vol, M_VOL_SET);
}
__delay_ms(200);
}
// exit vol set func
__delay_ms(250);
__delay_ms(250);
continue;
}
//Tuning
if ((frq_seq == 0) && (disp_c < 8) && (disp_c > 1)) {
//Frequency Up
if (SW_UP == PUSH_ON) {
disp_c = 2;
freq++;
if (freq > 250) {
blk_led1();
freq = 70;
}
for (uint8_t lp = 0; lp < 3; lp++) {
__delay_ms(200);
blk_led4();
}
//Step
if (SW_UP != PUSH_ON) {
reg_set(freq, vol, M_FRQ_SET);
for (uint8_t lp = 0; lp < 2; lp++) {
__delay_ms(200);
blk_led4();
}
//Seek
} else {
reg_set(freq, vol, M_SEQ_UP);
frq_seq = 1;
for (uint8_t lp = 0; lp < 5; lp++) {
__delay_ms(200);
blk_led5();
}
}
continue;
}
//Frequency Down
if (SW_DN == PUSH_ON) {
disp_c = 2;
freq--;
if (freq < 70) {
blk_led5();
freq = 250;
}
for (uint8_t lp = 0; lp < 3; lp++) {
__delay_ms(200);
blk_led2();
}
//Step
blk_led2();
if (SW_DN != PUSH_ON) {
reg_set(freq, vol, M_FRQ_SET);
for (uint8_t lp = 0; lp < 2; lp++) {
__delay_ms(200);
blk_led2();
}
//Seek
} else {
reg_set(freq, vol, M_SEQ_DN);
frq_seq = 1;
for (uint8_t lp = 0; lp < 5; lp++) {
__delay_ms(200);
blk_led1();
}
}
continue;
}
}
//Wait
for (uint8_t lp = 0; lp < 10; lp++) {
__delay_ms(50);
if ((SW_UP == PUSH_ON) || (SW_DN == PUSH_ON) || (SW_FN == PUSH_ON)) {
if (disp_c > 7) {
blk_led1();
blk_led5();
disp_c = 0;
}
break;
}
}
frq_seq = 0;
//Display
disp_c++;
if (disp_c > 120) {
disp_c = 6;
} else if (disp_c > 7) {
__delay_ms(100);
continue;
} else if (disp_c < 3) {
__delay_ms(100);
continue;
}
//active counter 3,4,5,6,7
frq_rd = tun_rcv();
if (frq_rd > 190) {
blk_led2();
blk_led4();
freq = 40;
} else {
freq = (frq_rd + 60);
}
//sleep break
frq_bcd_disp(freq);
if ((SW_UP == PUSH_ON) || (SW_DN == PUSH_ON)) {
if (disp_c > 7) {
blk_led1();
blk_led5();
disp_c = 0;
}
continue;
} else {
__delay_ms(100);
}
}
}
|
jlaine/quant
|
lib/src/loop.h
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <stdint.h>
#include <quant/quant.h>
#include "conn.h"
#include "quic.h" // IWYU pragma: keep
typedef void (*func_ptr)(void);
extern func_ptr api_func;
extern void * api_conn;
extern void * api_strm;
extern void loop_init(void);
extern uint64_t loop_now(void);
extern void loop_break(void);
extern void __attribute__((nonnull(1))) loop_run(struct w_engine * const w,
const func_ptr f,
struct q_conn * const c,
struct q_stream * const s);
// see https://stackoverflow.com/a/45600545/2240756
//
#define OVERLOADED_MACRO(M, ...) OVR(M, CNT_ARGS(__VA_ARGS__))(__VA_ARGS__)
#define OVR(macro_name, nargs) OVR_EXPAND(macro_name, nargs)
#define OVR_EXPAND(macro_name, nargs) macro_name##nargs
#define CNT_ARGS(...) ARG_MATCH(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define ARG_MATCH(_1, _2, _3, _4, _5, _6, _7, _8, _9, N, ...) N
#define maybe_api_return(...) \
__extension__(OVERLOADED_MACRO(maybe_api_return, __VA_ARGS__))
#ifdef DEBUG_EXTRA
#define DEBUG_EXTRA_warn warn
#else
#define DEBUG_EXTRA_warn(...)
#endif
/// If current API function and argument match @p func and @p arg - and @p strm
/// if it is non-zero - exit the event loop.
///
/// @param func The API function to potentially return to.
/// @param conn The connection to check API activity on.
/// @param strm The stream to check API activity on.
///
/// @return True if the event loop was exited.
///
#define maybe_api_return3(func, conn, strm) \
__extension__({ \
if (unlikely(api_func == (func_ptr)(&(func)) && api_conn == (conn) && \
((strm) == 0 || api_strm == (strm)))) { \
loop_break(); \
DEBUG_EXTRA_warn(DBG, #func "(" #conn ", " #strm \
") done, exiting event loop"); \
} \
api_func == 0; \
})
/// If current API argument matches @p arg - and @p strm if it is non-zero -
/// exit the event loop (for any active API function).
///
/// @param conn The connection to check API activity on.
/// @param strm The stream to check API activity on.
///
/// @return True if the event loop was exited.
///
#define maybe_api_return2(conn, strm) \
__extension__({ \
if (unlikely(api_conn == (conn) && \
((strm) == 0 || api_strm == (strm)))) { \
loop_break(); \
DEBUG_EXTRA_warn(DBG, "<any>(" #conn ", " #strm \
") done, exiting event loop"); \
} \
api_func == 0; \
})
|
jlaine/quant
|
lib/src/marshall.c
|
<reponame>jlaine/quant
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <quant/quant.h>
#include "marshall.h"
// #define VARINT1_MAX 0x3f
// #define VARINT2_MAX UINT16_C(0x3FFF)
// #define VARINT4_MAX UINT32_C(0x3fffffff)
// #define VARINT8_MAX UINT64_C(0x3fffffffffffffff)
// #define VARINT_MAX VARINT8_MAX
#define VARINT_MASK UINT64_C(0xc000000000000000)
#define VARINT_MASK8 UINT64_C(0x3fffffffc0000000)
#define VARINT_MASK4 UINT64_C(0x000000003fffc000)
#define VARINT_MASK2 UINT64_C(0x0000000000003fc0)
/// Computes number of bytes need to enccode @p v in QUIC varint encoding.
///
/// @param[in] val Value to check.
///
/// @return Number of bytes needed in varint encoding (1, 2, 4 or 8).
///
uint8_t varint_size(const uint64_t val)
{
ensure((val & VARINT_MASK) == 0, "value overflow: %" PRIu64, val);
if ((val & VARINT_MASK8) != 0)
return 8;
if ((val & VARINT_MASK4) != 0)
return 4;
if ((val & VARINT_MASK2) != 0)
return 2;
return 1;
}
void enc1(uint8_t ** pos, const uint8_t * const end, const uint8_t val)
{
ensure(*pos + sizeof(val) <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
**pos = val;
*pos += sizeof(val);
}
void enc2(uint8_t ** pos, const uint8_t * const end, const uint16_t val)
{
ensure(*pos + sizeof(val) <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
const uint16_t v = bswap16(val);
memcpy(*pos, &v, sizeof(v));
*pos += sizeof(val);
}
void enc3(uint8_t ** pos, const uint8_t * const end, const uint32_t val)
{
ensure(*pos + 3 <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
const uint32_t v = bswap32(val << 8);
memcpy(*pos, &v, 3);
*pos += 3;
}
void enc4(uint8_t ** pos, const uint8_t * const end, const uint32_t val)
{
ensure(*pos + sizeof(val) <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
const uint32_t v = bswap32(val);
memcpy(*pos, &v, sizeof(v));
*pos += sizeof(val);
}
void enc8(uint8_t ** pos, const uint8_t * const end, const uint64_t val)
{
ensure(*pos + sizeof(val) <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
const uint64_t v = bswap64(val);
memcpy(*pos, &v, sizeof(v));
*pos += sizeof(val);
}
void encv(uint8_t ** pos, const uint8_t * const end, const uint64_t val)
{
ensure((val & VARINT_MASK) == 0, "value overflow: %" PRIu64, val);
if ((val & VARINT_MASK8) != 0) {
ensure(*pos + 8 <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
*(*pos + 0) = ((val >> 56) & 0x3f) + 0xc0;
*(*pos + 1) = (val >> 48) & 0xff;
*(*pos + 2) = (val >> 40) & 0xff;
*(*pos + 3) = (val >> 32) & 0xff;
*(*pos + 4) = (val >> 24) & 0xff;
*(*pos + 5) = (val >> 16) & 0xff;
*(*pos + 6) = (val >> 8) & 0xff;
*(*pos + 7) = val & 0xff;
*pos += 8;
return;
}
if ((val & VARINT_MASK4) != 0) {
ensure(*pos + 4 <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
*(*pos + 0) = ((val >> 24) & 0x3f) + 0x80;
*(*pos + 1) = (val >> 16) & 0xff;
*(*pos + 2) = (val >> 8) & 0xff;
*(*pos + 3) = val & 0xff;
*pos += 4;
return;
}
if ((val & VARINT_MASK2) != 0) {
ensure(*pos + 2 <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
*(*pos + 0) = ((val >> 8) & 0x3f) + 0x40;
*(*pos + 1) = val & 0xff;
*pos += 2;
return;
}
ensure(*pos + 1 <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
**pos = val & 0x3f;
*pos += 1;
}
void encvl(uint8_t ** pos,
const uint8_t * const end,
const uint64_t val,
const uint8_t len)
{
const uint8_t len_needed = varint_size(val);
ensure(len_needed <= len, "value/len mismatch");
if (len_needed == len) {
encv(pos, end, val);
return;
}
if (len == 2) {
enc1(pos, end, 0x40);
enc1(pos, end, (uint8_t)val);
return;
}
if (len == 4) {
enc1(pos, end, 0x80);
enc1(pos, end, 0x00);
enc2(pos, end, (uint16_t)val);
return;
}
if (len == 8) {
enc1(pos, end, 0xC0);
enc1(pos, end, 0x00);
enc2(pos, end, 0x00);
enc4(pos, end, (uint32_t)val);
return;
}
}
void encb(uint8_t ** pos,
const uint8_t * const end,
const uint8_t * const val,
const uint16_t len)
{
ensure(*pos + len <= end, "buffer overflow: %lu",
(unsigned long)(end - *pos));
memcpy(*pos, val, len);
*pos += len;
}
bool dec1(uint8_t * const val,
const uint8_t ** const pos,
const uint8_t * const end)
{
if (unlikely(*pos + sizeof(*val) > end))
return false;
*val = **pos;
*pos += sizeof(*val);
return true;
}
bool dec2(uint16_t * const val,
const uint8_t ** const pos,
const uint8_t * const end)
{
if (unlikely(*pos + sizeof(*val) > end))
return false;
memcpy(val, *pos, sizeof(*val));
*val = bswap16(*val);
*pos += sizeof(*val);
return true;
}
bool dec3(uint32_t * const val,
const uint8_t ** const pos,
const uint8_t * const end)
{
if (unlikely(*pos + 3 > end))
return false;
memcpy(val, *pos, 3);
*val = bswap32(*val << 8);
*pos += 3;
return true;
}
bool dec4(uint32_t * const val,
const uint8_t ** const pos,
const uint8_t * const end)
{
if (unlikely(*pos + sizeof(*val) > end))
return false;
memcpy(val, *pos, sizeof(*val));
*val = bswap32(*val);
*pos += sizeof(*val);
return true;
}
bool dec8(uint64_t * const val,
const uint8_t ** const pos,
const uint8_t * const end)
{
if (unlikely(*pos + sizeof(*val) > end))
return false;
memcpy(val, *pos, sizeof(*val));
*val = bswap64(*val);
*pos += sizeof(*val);
return true;
}
bool decv(uint64_t * const val,
const uint8_t ** const pos,
const uint8_t * const end)
{
switch (**pos & 0xc0) {
case 0xc0:
if (unlikely(*pos + 8 > end))
return false;
#ifndef HAVE_64BIT
return false;
#else
*val =
((uint64_t)(*(*pos + 0) & 0x3f) << 56) +
((uint64_t)(*(*pos + 1)) << 48) + ((uint64_t)(*(*pos + 1)) << 48) +
((uint64_t)(*(*pos + 2)) << 40) + ((uint64_t)(*(*pos + 3)) << 32) +
((uint64_t)(*(*pos + 4)) << 24) + ((uint64_t)(*(*pos + 5)) << 16) +
((uint64_t)(*(*pos + 6)) << 8) + ((uint64_t)(*(*pos + 7)) << 0);
*pos += 8;
return true;
#endif
case 0x80:
if (unlikely(*pos + 4 > end))
return false;
*val = ((uint64_t)(*(*pos + 0) & 0x3f) << 24) +
((uint64_t)(*(*pos + 1)) << 16) +
((uint64_t)(*(*pos + 2)) << 8) + ((uint64_t)(*(*pos + 3)) << 0);
*pos += 4;
return true;
case 0x40:
if (unlikely(*pos + 2 > end))
return false;
*val = ((uint64_t)(*(*pos + 0) & 0x3f) << 8) + (uint64_t)(*(*pos + 1));
*pos += 2;
return true;
case 0x00:
if (unlikely(*pos + 1 > end))
return false;
*val = (**pos) & 0x3f;
*pos += 1;
return true;
}
return false;
}
bool decb(uint8_t * const val,
const uint8_t ** const pos,
const uint8_t * const end,
const uint16_t len)
{
if (unlikely(*pos + len > end))
return false;
memcpy(val, *pos, len);
*pos += len;
return true;
}
|
jlaine/quant
|
lib/src/quic.c
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <inttypes.h>
#include <netdb.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
// IWYU pragma: no_include <picotls/../picotls.h>
#include <picotls.h> // IWYU pragma: keep
#include <quant/quant.h>
#include <timeout.h>
#ifdef HAVE_ASAN
#include <sanitizer/asan_interface.h>
#else
#define ASAN_POISON_MEMORY_REGION(x, y)
#define ASAN_UNPOISON_MEMORY_REGION(x, y)
#endif
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
#include <errno.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "conn.h"
#include "loop.h"
#include "pkt.h"
#include "pn.h"
#include "qlog.h"
#include "quic.h"
#include "recovery.h"
#include "stream.h"
#include "tls.h"
// TODO: many of these globals should move to a per-engine struct
/// QUIC version supported by this implementation in order of preference.
const uint32_t ok_vers[] = {
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
0xbabababa, // reserved version to trigger negotiation, TODO: randomize
#endif
0x45474700 + DRAFT_VERSION, // quant private version -xx
0xff000000 + DRAFT_VERSION, // draft-ietf-quic-transport-xx
};
/// Length of the @p ok_vers array.
const uint8_t ok_vers_len = sizeof(ok_vers) / sizeof(ok_vers[0]);
struct q_conn_conf default_conn_conf = {.idle_timeout = 10,
.enable_udp_zero_checksums = true,
.tls_key_update_frequency = 3,
.enable_spinbit =
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
true
#else
false
#endif
};
struct q_conn_sl accept_queue = sl_head_initializer(accept_queue);
static struct timeout api_alarm = TIMEOUT_INITIALIZER(0);
static uint32_t num_bufs = 0;
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
int corpus_pkt_dir, corpus_frm_dir;
#endif
void alloc_off(struct w_engine * const w,
struct w_iov_sq * const q,
const uint32_t len,
const uint16_t off)
{
w_alloc_len(w, q, len, MAX_PKT_LEN - AEAD_LEN - off, off);
struct w_iov * v = 0;
sq_foreach (v, q, next) {
struct pkt_meta * const m = &meta(v);
ASAN_UNPOISON_MEMORY_REGION(m, sizeof(*m));
m->strm_data_pos = off;
#ifdef DEBUG_BUFFERS
warn(DBG, "idx %" PRIu32 " (avail %" PRIu ") len %u", w_iov_idx(v),
sq_len(&w->iov), v->len);
#endif
}
}
void free_iov(struct w_iov * const v, struct pkt_meta * const m)
{
#ifdef DEBUG_BUFFERS
warn(DBG, "idx %" PRIu32 " (avail %" PRIu ") %cX'ed %s pkt nr=%" PRIu,
w_iov_idx(v), sq_len(&v->w->iov) + 1, m->txed ? 'T' : 'R',
pkt_type_str(m->hdr.flags, &m->hdr.vers),
has_pkt_nr(m->hdr.flags, m->hdr.vers) ? m->hdr.nr : 0);
#endif
if (m->txed) {
if (m->acked == false && m->lost == false &&
m->pn->abandoned == false) {
m->strm = 0;
on_pkt_lost(m, false);
}
struct pkt_meta * m_rtx = sl_first(&m->rtx);
if (unlikely(m_rtx)) {
// this pkt has prior or later RTXs
if (m->has_rtx) {
// this pkt has an RTX
#ifdef DEBUG_BUFFERS
warn(DBG, "pkt nr=%" PRIu " has RTX %" PRIu,
has_pkt_nr(m->hdr.flags, m->hdr.vers) ? m->hdr.nr : 0,
has_pkt_nr(m_rtx->hdr.flags, m_rtx->hdr.vers)
? m_rtx->hdr.nr
: 0);
#endif
sl_remove(&m_rtx->rtx, m, pkt_meta, rtx_next);
} else {
// this is the last ("real") RTX of a packet
while (m_rtx) {
#ifdef DEBUG_BUFFERS
warn(DBG, "pkt nr=%" PRIu " was also TX'ed as %" PRIu,
has_pkt_nr(m->hdr.flags, m->hdr.vers) ? m->hdr.nr : 0,
has_pkt_nr(m_rtx->hdr.flags, m_rtx->hdr.vers)
? m_rtx->hdr.nr
: 0);
#endif
m_rtx->strm = 0;
ensure(m_rtx->has_rtx, "was RTX'ed");
sl_remove_head(&m->rtx, rtx_next);
sl_remove_head(&m_rtx->rtx, rtx_next);
m_rtx = sl_next(m_rtx, rtx_next);
}
}
}
}
memset(m, 0, sizeof(*m));
ASAN_POISON_MEMORY_REGION(m, sizeof(*m));
w_free_iov(v);
}
struct w_iov * alloc_iov(struct w_engine * const w,
const uint16_t len,
const uint16_t off,
struct pkt_meta ** const m)
{
struct w_iov * const v = w_alloc_iov(w, len, off);
ensure(v, "w_alloc_iov failed");
*m = &meta(v);
ASAN_UNPOISON_MEMORY_REGION(*m, sizeof(**m));
(*m)->strm_data_pos = off;
#ifdef DEBUG_BUFFERS
warn(DBG, "alloc_iov idx %" PRIu32 " (avail %" PRIu ") len %u off %u",
w_iov_idx(v), sq_len(&w->iov), v->len, off);
#endif
return v;
}
struct w_iov * w_iov_dup(const struct w_iov * const v,
struct pkt_meta ** const mdup,
const uint16_t off)
{
struct w_iov * const vdup = w_alloc_iov(v->w, v->len - off, 0);
ensure(vdup, "w_alloc_iov failed");
#ifdef DEBUG_BUFFERS
warn(DBG, "w_alloc_iov idx %" PRIu32 " (avail %" PRIu ") len %u",
w_iov_idx(vdup), sq_len(&v->w->iov), vdup->len);
#endif
if (mdup) {
*mdup = &meta(vdup);
ASAN_UNPOISON_MEMORY_REGION(*mdup, sizeof(**mdup));
}
memcpy(vdup->buf, v->buf + off, v->len - off);
memcpy(&vdup->addr, &v->addr, sizeof(v->addr));
vdup->flags = v->flags;
return vdup;
}
void q_alloc(struct w_engine * const w,
struct w_iov_sq * const q,
const size_t len)
{
ensure(len <= UINT32_MAX, "len %zu too long", len);
alloc_off(w, q, (uint32_t)len, DATA_OFFSET);
}
void q_free(struct w_iov_sq * const q)
{
while (!sq_empty(q)) {
struct w_iov * const v = sq_first(q);
sq_remove_head(q, next);
free_iov(v, &meta(v));
}
}
static void __attribute__((nonnull)) mark_fin(struct w_iov_sq * const q)
{
struct w_iov * const last = sq_last(q, w_iov, next);
ensure(last, "got last buffer");
meta(last).is_fin = true;
}
struct q_conn * q_connect(struct w_engine * const w,
const struct sockaddr * const peer,
const char * const peer_name,
struct w_iov_sq * const early_data,
struct q_stream ** const early_data_stream,
const bool fin,
const char * const alpn,
const struct q_conn_conf * const conf)
{
// make new connection
const uint vers = ok_vers[0];
struct q_conn * const c = new_conn(w, vers, 0, 0, peer, peer_name, 0, conf);
// init TLS
init_tls(c, alpn);
init_tp(c);
// if we have no early data, we're not trying 0-RTT
c->try_0rtt &= early_data && early_data_stream;
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char ip[NI_MAXHOST];
char port[NI_MAXSERV];
const int err = getnameinfo(peer, sizeof(*peer), ip, sizeof(ip), port,
sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV);
ensure(err == 0, "getnameinfo %d", err);
mk_cid_str(WRN, c->scid, scid_str);
warn(WRN, "new %u-RTT %s conn %s to %s:%s, %" PRIu " byte%s queued for TX",
c->try_0rtt ? 0 : 1, conn_type(c), scid_str, ip, port,
early_data ? w_iov_sq_len(early_data) : 0,
plural(early_data ? w_iov_sq_len(early_data) : 0));
#endif
restart_idle_alarm(c);
w_connect(c->sock, peer);
// start TLS handshake
tls_io(c->cstrms[ep_init], 0);
if (early_data && !sq_empty(early_data)) {
ensure(early_data_stream, "early data without stream pointer");
// queue up early data
if (fin)
mark_fin(early_data);
*early_data_stream = new_stream(c, c->next_sid_bidi);
concat_out(*early_data_stream, early_data);
} else if (early_data_stream)
*early_data_stream = 0;
timeouts_add(ped(w)->wheel, &c->tx_w, 0);
warn(DBG, "waiting for connect on %s conn %s to %s:%s", conn_type(c),
scid_str, ip, port);
conn_to_state(c, conn_opng);
loop_run(w, (func_ptr)q_connect, c, 0);
if (fin && early_data_stream && *early_data_stream)
strm_to_state(*early_data_stream,
(*early_data_stream)->state == strm_hcrm ? strm_clsd
: strm_hclo);
if (c->state != conn_estb) {
warn(WRN, "%s conn %s not connected", conn_type(c), scid_str);
return 0;
}
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
struct pn_data * const pnd = &c->pns[pn_data].data;
warn(WRN, "%s conn %s connected%s, cipher %s", conn_type(c), scid_str,
c->did_0rtt ? " after 0-RTT" : "",
pnd->out_1rtt[pnd->out_kyph].aead->algo->name);
#endif
return c;
}
bool q_write(struct q_stream * const s,
struct w_iov_sq * const q,
const bool fin)
{
struct q_conn * const c = s->c;
mk_cid_str(ERR, c->scid, scid_str);
if (unlikely(c->state == conn_qlse || c->state == conn_drng ||
c->state == conn_clsd)) {
warn(ERR, "%s conn %s is in state %s, can't write", conn_type(c),
scid_str, conn_state_str[c->state]);
return false;
}
if (unlikely(s->state == strm_hclo || s->state == strm_clsd)) {
warn(ERR, "%s conn %s strm " FMT_SID " is in state %s, can't write",
conn_type(c), scid_str, s->id, strm_state_str[s->state]);
return false;
}
// add to stream
if (fin) {
if (sq_empty(q))
alloc_off(c->w, q, 1, DATA_OFFSET);
mark_fin(q);
// strm_to_state(s, s->state == strm_hcrm ? strm_clsd : strm_hclo);
}
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
const uint_t qlen = w_iov_sq_len(q);
const uint_t qcnt = w_iov_sq_cnt(q);
warn(WRN,
"writing %" PRIu " byte%s %sin %" PRIu
" buf%s on %s conn %s strm " FMT_SID,
qlen, plural(qlen), fin ? "(and FIN) " : "", qcnt, plural(qcnt),
conn_type(c), scid_str, s->id);
#endif
concat_out(s, q);
// kick TX watcher
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
return true;
}
struct q_stream *
q_read(struct q_conn * const c, struct w_iov_sq * const q, const bool all)
{
struct q_stream * s = 0;
do {
kh_foreach_value(&c->strms_by_id, s, {
if (!sq_empty(&s->in) || s->state == strm_clsd)
// we found a stream with queued data
break;
});
if (s == 0 && all) {
// no data queued on any stream, wait for new data
mk_cid_str(WRN, c->scid, scid_str);
warn(WRN, "waiting to read on any strm on %s conn %s", conn_type(c),
scid_str);
loop_run(c->w, (func_ptr)q_read, c, 0);
}
} while (s == 0 && all);
if (s && s->state != strm_clsd)
q_read_stream(s, q, false);
return s;
}
bool q_read_stream(struct q_stream * const s,
struct w_iov_sq * const q,
const bool all)
{
struct q_conn * const c = s->c;
if (unlikely(c->state != conn_estb))
return 0;
mk_cid_str(WRN, c->scid, scid_str);
if (q_peer_closed_stream(s) == false && all) {
warn(WRN, "reading all on %s conn %s strm " FMT_SID, conn_type(c),
scid_str, s->id);
again:
loop_run(c->w, (func_ptr)q_read_stream, c, s);
}
if (sq_empty(&s->in))
return false;
struct w_iov * const last = sq_last(&s->in, w_iov, next);
const struct pkt_meta * const m_last = &meta(last);
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
const uint_t qlen = w_iov_sq_len(&s->in);
const uint_t qcnt = w_iov_sq_cnt(&s->in);
warn(WRN,
"read %" PRIu " new byte%s %sin %" PRIu " buf%s on %s "
"conn %s strm " FMT_SID,
qlen, plural(qlen), m_last->is_fin ? "(and FIN) " : "", qcnt,
plural(qcnt), conn_type(c), scid_str, s->id);
#endif
sq_concat(q, &s->in);
if (all && m_last->is_fin == false)
goto again;
return true;
}
struct q_conn * q_bind(struct w_engine * const w, const uint16_t port)
{
// bind socket and create new embryonic server connection
struct q_conn * const c = new_conn(w, 0, 0, 0, 0, 0, bswap16(port), 0);
if (likely(c))
warn(INF, "bound %s socket to port %u", conn_type(c), port);
return c;
}
static void cancel_api_call(struct w_engine * const w)
{
#ifdef DEBUG_EXTRA
warn(DBG, "canceling API call");
#endif
timeouts_del(ped(w)->wheel, &api_alarm);
maybe_api_return(q_accept, 0, 0);
maybe_api_return(q_ready, 0, 0);
}
static void __attribute__((nonnull))
restart_api_alarm(struct w_engine * const w, const uint64_t nsec)
{
#ifdef DEBUG_TIMERS
warn(DBG, "next API alarm in %f sec", nsec / (double)NS_PER_S);
#endif
timeouts_add(ped(w)->wheel, &api_alarm, nsec);
}
struct q_conn * q_accept(struct w_engine * const w,
const struct q_conn_conf * const conf)
{
if (sl_first(&accept_queue))
goto accept;
const uint_t idle_to = get_conf(conf, idle_timeout);
warn(WRN, "waiting for conn on any serv sock (timeout %" PRIu " ms)",
idle_to);
if (idle_to)
restart_api_alarm(w, idle_to * NS_PER_MS);
loop_run(w, (func_ptr)q_accept, 0, 0);
if (sl_empty(&accept_queue)) {
warn(ERR, "no conn ready for accept");
return 0;
}
accept:;
struct q_conn * const c = sl_first(&accept_queue);
sl_remove_head(&accept_queue, node_aq);
restart_idle_alarm(c);
c->needs_accept = false;
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char ip[NI_MAXHOST];
char port[NI_MAXSERV];
ensure(getnameinfo((struct sockaddr *)&c->peer, sizeof(c->peer), ip,
sizeof(ip), port, sizeof(port),
NI_NUMERICHOST | NI_NUMERICSERV) == 0,
"getnameinfo");
struct pn_data * const pnd = &c->pns[pn_data].data;
mk_cid_str(WRN, c->scid, scid_str);
warn(WRN, "%s conn %s accepted from clnt %s:%s%s, cipher %s", conn_type(c),
scid_str, ip, port, c->did_0rtt ? " after 0-RTT" : "",
pnd->out_1rtt[pnd->out_kyph].aead->algo->name);
#endif
update_conf(c, conf);
return c;
}
struct q_stream * q_rsv_stream(struct q_conn * const c, const bool bidi)
{
if (unlikely(c->state == conn_drng || c->state == conn_clsd))
return 0;
const uint_t * const max_streams =
bidi ? &c->tp_out.max_strms_bidi : &c->tp_out.max_strms_uni;
if (unlikely(*max_streams == 0))
warn(WRN, "peer hasn't allowed %s streams", bidi ? "bi" : "uni");
dint_t * const next_sid = bidi ? &c->next_sid_bidi : &c->next_sid_uni;
const uint_t next = (uint_t)(*next_sid >> 2);
if (unlikely(next >= *max_streams)) {
// we hit the max stream limit, wait for MAX_STREAMS frame
warn(WRN, "need %s MAX_STREAMS increase (%" PRIu " >= %" PRIu ")",
bidi ? "bi" : "uni", next, *max_streams);
if (bidi)
c->sid_blocked_bidi = true;
else
c->sid_blocked_uni = true;
loop_run(c->w, (func_ptr)q_rsv_stream, c, 0);
}
// stream blocking is handled by new_stream
return new_stream(c, *next_sid);
}
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
static int __attribute__((nonnull))
mk_or_open_dir(const char * const path, mode_t mode)
{
int fd = mkdir(path, mode);
ensure(fd == 0 || (fd == -1 && errno == EEXIST), "mkdir %s", path);
fd = open(path, O_RDONLY | O_CLOEXEC);
ensure(fd != -1, "open %s", path);
return fd;
}
#endif
struct w_engine * q_init(const char * const ifname,
const struct q_conf * const conf)
{
if (conf && conf->conn_conf) {
// update default connection configuration
default_conn_conf.idle_timeout =
get_conf(conf->conn_conf, idle_timeout);
default_conn_conf.tls_key_update_frequency =
get_conf(conf->conn_conf, tls_key_update_frequency);
default_conn_conf.enable_spinbit =
get_conf_uncond(conf->conn_conf, enable_spinbit);
default_conn_conf.enable_udp_zero_checksums =
get_conf_uncond(conf->conn_conf, enable_udp_zero_checksums);
default_conn_conf.enable_tls_key_updates =
get_conf_uncond(conf->conn_conf, enable_tls_key_updates);
default_conn_conf.disable_migration =
get_conf_uncond(conf->conn_conf, disable_migration);
default_conn_conf.enable_zero_len_cid =
get_conf_uncond(conf->conn_conf, enable_zero_len_cid);
}
// initialize warpcore on the given interface
num_bufs = conf && conf->num_bufs ? conf->num_bufs : 10000;
struct w_engine * const w = w_init(ifname, 0, num_bufs);
const uint_t num_bufs_ok = sq_len(&w->iov);
if (num_bufs_ok < num_bufs)
warn(WRN, "only allocated %" PRIu "/%" PRIu32 " warpcore buffers ",
num_bufs_ok, num_bufs);
w->data = calloc(1, sizeof(struct per_engine_data));
ensure(w->data, "could not calloc");
ped(w)->pkt_meta = calloc(num_bufs, sizeof(*ped(w)->pkt_meta));
ensure(ped(w)->pkt_meta, "could not calloc");
ASAN_POISON_MEMORY_REGION(ped(w)->pkt_meta,
num_bufs * sizeof(*ped(w)->pkt_meta));
// initialize the event loop
loop_init();
int err;
ped(w)->wheel = timeouts_open(TIMEOUT_nHZ, &err);
timeouts_update(ped(w)->wheel, loop_now());
timeout_setcb(&api_alarm, cancel_api_call, w);
warn(INF, "%s/%s (%s) %s/%s ready", quant_name, w->backend_name,
w->backend_variant, quant_version, QUANT_COMMIT_HASH_ABBREV_STR);
#ifndef PARTICLE
warn(INF, "submit bug reports at https://github.com/NTAP/quant/issues");
#endif
// initialize TLS context
init_tls_ctx(conf, &ped(w)->tls_ctx);
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
#ifdef FUZZING
warn(CRT, "%s compiled for fuzzing - will not communicate", quant_name);
#else
// create the directories for exporting fuzzer corpus data
warn(NTE, "debug build, storing fuzzer corpus data");
corpus_pkt_dir = mk_or_open_dir("../corpus_pkt", 0755);
corpus_frm_dir = mk_or_open_dir("../corpus_frm", 0755);
#endif
#endif
#ifndef NO_QLOG
if (conf && conf->qlog && *conf->qlog) {
qlog = fopen(conf->qlog, "we");
ensure(qlog, "fopen %s", conf->qlog);
}
#endif
return w;
}
void q_close_stream(struct q_stream * const s)
{
mk_cid_str(WRN, s->c->scid, scid_str);
warn(WRN, "closing strm " FMT_SID " on %s conn %s", s->id, conn_type(s->c),
scid_str);
struct w_iov_sq q = w_iov_sq_initializer(q);
q_write(s, &q, true);
}
void q_free_stream(struct q_stream * const s)
{
free_stream(s);
}
void q_stream_get_written(struct q_stream * const s, struct w_iov_sq * const q)
{
if (s->out_una == 0) {
sq_concat(q, &s->out);
return;
}
struct w_iov * v = sq_first(&s->out);
while (v != s->out_una) {
sq_remove_head(&s->out, next);
sq_insert_tail(q, v, next);
v = sq_first(&s->out);
}
}
void q_close(struct q_conn * const c,
const uint64_t code,
const char * const reason)
{
mk_cid_str(WRN, c->scid, scid_str);
if (c->scid)
warn(WRN,
"closing %s conn %s on port %u w/err %s0x%" PRIx64 "%s%s%s" NRM,
conn_type(c), scid_str, bswap16(get_sport(c->sock)),
code ? RED : NRM, code, reason ? " (" : "", reason ? reason : "",
reason ? ")" : "");
c->err_code = (uint_t)code;
#ifndef NO_ERR_REASONS
if (reason) {
strncpy(c->err_reason, reason, MAX_ERR_REASON_LEN);
c->err_reason_len = (uint8_t)strnlen(reason, MAX_ERR_REASON_LEN);
}
#endif
if (c->state == conn_idle || c->state == conn_clsd ||
(!c->is_clnt && c->holds_sock))
// we don't need to do the closing dance in these cases
goto done;
if (c->state != conn_drng) {
conn_to_state(c, conn_qlse);
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
}
loop_run(c->w, (func_ptr)q_close, c, 0);
done:
if (c->scid && c->i.pkts_in_valid > 0) {
conn_info_populate(c);
warn(INF, "%s conn %s stats:", conn_type(c), scid_str);
warn(INF, "\tpkts_in_valid = %s%" PRIu NRM,
c->i.pkts_in_valid ? NRM : BLD RED, c->i.pkts_in_valid);
warn(INF, "\tpkts_in_invalid = %s%" PRIu NRM,
c->i.pkts_in_invalid ? BLD RED : NRM, c->i.pkts_in_invalid);
warn(INF, "\tpkts_out = %" PRIu, c->i.pkts_out);
warn(INF, "\tpkts_out_lost = %" PRIu, c->i.pkts_out_lost);
warn(INF, "\tpkts_out_rtx = %" PRIu, c->i.pkts_out_rtx);
warn(INF, "\trtt = %.3f", c->i.rtt / (float)NS_PER_S);
warn(INF, "\trttvar = %.3f", c->i.rttvar / (float)NS_PER_S);
warn(INF, "\tcwnd = %" PRIu, c->i.cwnd);
warn(INF, "\tssthresh = %" PRIu, c->i.ssthresh);
warn(INF, "\tpto_cnt = %" PRIu, c->i.pto_cnt);
}
free_conn(c);
#ifndef NO_QLOG
fflush(qlog);
#endif
}
void q_cleanup(struct w_engine * const w)
{
// close all connections
struct q_conn * c;
kh_foreach_value(&conns_by_id, c, { q_close(c, 0, 0); });
kh_foreach_value(&conns_by_ipnp, c, { q_close(c, 0, 0); });
kh_foreach_value(&conns_by_srt, c, { q_close(c, 0, 0); });
// stop the event loop
timeouts_close(ped(w)->wheel);
#ifndef NO_OOO_0RTT
// free 0-RTT reordering cache
while (!splay_empty(&ooo_0rtt_by_cid)) {
struct ooo_0rtt * const zo =
splay_min(ooo_0rtt_by_cid, &ooo_0rtt_by_cid);
ensure(splay_remove(ooo_0rtt_by_cid, &ooo_0rtt_by_cid, zo), "removed");
free(zo);
}
#endif
#ifdef HAVE_ASAN
for (uint_t i = 0; i < num_bufs; i++) {
struct pkt_meta * const m = &ped(w)->pkt_meta[i];
if (__asan_address_is_poisoned(m) == false) {
warn(DBG, "buffer %" PRIu " still in use for %cX'ed %s pkt %" PRIu,
i, m->txed ? 'T' : 'R',
pkt_type_str(m->hdr.flags, &m->hdr.vers),
has_pkt_nr(m->hdr.flags, m->hdr.vers) ? m->hdr.nr : 0);
}
}
#endif
kh_release(conns_by_id, &conns_by_id);
kh_release(conns_by_ipnp, &conns_by_ipnp);
kh_release(conns_by_srt, &conns_by_srt);
free_tls_ctx(&ped(w)->tls_ctx);
free(ped(w)->pkt_meta);
free(w->data);
w_cleanup(w);
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
close(corpus_pkt_dir);
close(corpus_frm_dir);
#endif
qlog_close();
}
const char *
q_cid(struct q_conn * const c, char * const buf, const size_t buf_len)
{
ensure(buf_len >= hex_str_len(CID_LEN_MAX),
"buf too short (need at least %lu)",
(unsigned long)hex_str_len(CID_LEN_MAX));
if (likely(c->scid))
hex2str(c->scid->id, c->scid->len, buf, buf_len);
else
*buf = 0;
return buf;
}
uint_t q_sid(const struct q_stream * const s)
{
return (uint_t)s->id;
}
bool q_is_stream_closed(const struct q_stream * const s)
{
return s->state == strm_clsd;
}
bool q_peer_closed_stream(const struct q_stream * const s)
{
return s->state == strm_hcrm || s->state == strm_clsd;
}
bool q_is_conn_closed(const struct q_conn * const c)
{
return c->state == conn_clsd;
}
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
void write_to_corpus(const int dir, const void * const data, const size_t len)
{
const uint64_t rand = w_rand64();
char file[MAXPATHLEN];
hex2str((const uint8_t *)&rand, sizeof(rand), file, sizeof(file));
const int fd =
openat(dir, file, O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0644);
if (fd == -1) {
warn(ERR, "cannot open corpus file %s", file);
goto done;
}
if (write(fd, data, len) == -1) {
warn(ERR, "cannot write corpus file %s", file);
goto done;
}
done:
close(fd);
}
#endif
bool q_ready(struct w_engine * const w,
const uint64_t nsec,
struct q_conn ** const ready)
{
if (sl_empty(&c_ready)) {
if (nsec)
restart_api_alarm(w, nsec);
#ifdef DEBUG_EXTRA
warn(WRN, "waiting for conn to get ready");
#endif
loop_run(w, (func_ptr)q_ready, 0, 0);
}
struct q_conn * const c = sl_first(&c_ready);
if (c) {
sl_remove_head(&c_ready, node_rx_ext);
c->have_new_data = c->in_c_ready = false;
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && defined(DEBUG_EXTRA)
char * op = "rx";
if (c->needs_accept)
op = "accept";
else if (c->state == conn_clsd)
op = "close";
mk_cid_str(WRN, c->scid, scid_str);
warn(WRN, "%s conn %s ready to %s", conn_type(c), scid_str, op);
} else {
warn(WRN, "no conn ready to rx");
#endif
}
if (ready)
*ready = c;
return kh_size(&conns_by_srt);
}
bool q_is_new_serv_conn(const struct q_conn * const c)
{
return c->needs_accept;
}
#ifndef NO_MIGRATION
void q_rebind_sock(struct q_conn * const c, const bool use_new_dcid)
{
ensure(c->is_clnt, "can only rebind w_sock on client");
struct w_sock * const new_sock = w_bind(c->w, 0, &c->sockopt);
if (new_sock == 0)
// could not open new w_sock, can't rebind
return;
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char old_ip[NI_MAXHOST];
char old_port[NI_MAXSERV];
const struct sockaddr * src = w_get_addr(c->sock, true);
ensure(getnameinfo(src, sizeof(*src), old_ip, sizeof(old_ip), old_port,
sizeof(old_port), NI_NUMERICHOST | NI_NUMERICSERV) == 0,
"getnameinfo");
#endif
// close the current w_sock
if (c->scid == 0)
conns_by_ipnp_del(c);
w_close(c->sock);
c->sock = new_sock;
w_connect(c->sock, (struct sockaddr *)&c->peer);
if (c->scid == 0)
conns_by_ipnp_ins(c);
if (use_new_dcid)
// switch to new dcid
use_next_dcid(c);
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char new_ip[NI_MAXHOST];
char new_port[NI_MAXSERV];
src = w_get_addr(c->sock, true);
ensure(getnameinfo(src, sizeof(*src), new_ip, sizeof(new_ip), new_port,
sizeof(new_port), NI_NUMERICHOST | NI_NUMERICSERV) == 0,
"getnameinfo");
mk_cid_str(NTE, c->scid, scid_str);
warn(NTE, "simulated %s for %s conn %s from %s:%s to %s:%s",
use_new_dcid ? "conn migration" : "NAT rebinding", conn_type(c),
scid_str, old_ip, old_port, new_ip, new_port);
#endif
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
}
#endif
void q_info(struct q_conn * const c, struct q_conn_info * const ci)
{
conn_info_populate(c);
memcpy(ci, &c->i, sizeof(*ci));
}
char * hex2str(const uint8_t * const src,
const size_t len_src,
char * const dst,
const size_t len_dst)
{
ensure(len_dst >= hex_str_len(len_src), "overflow %lu < %lu",
(unsigned long)len_dst, (unsigned long)hex_str_len(len_src));
static const char hex[] = "0123456789abcdef";
size_t i;
for (i = 0; i < len_src; i++) {
dst[i * 2] = hex[(src[i] >> 4) & 0x0f];
dst[i * 2 + 1] = hex[src[i] & 0x0f];
}
dst[i * 2] = 0;
return dst;
}
|
jlaine/quant
|
lib/src/qlog.c
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef NO_QLOG
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <quant/quant.h>
#include <warpcore/warpcore.h>
#include "bitset.h"
#include "frame.h"
#include "loop.h"
#include "marshall.h"
#include "pkt.h"
#include "qlog.h"
#include "quic.h"
#include "recovery.h"
#include "stream.h"
FILE * qlog = 0;
static bool prev_event = false;
static uint64_t qlog_ref_t = 0;
static const char * __attribute__((const, nonnull))
qlog_pkt_type_str(const uint8_t flags, const void * const vers)
{
if (is_lh(flags)) {
if (((const uint8_t * const)vers)[0] == 0 &&
((const uint8_t * const)vers)[1] == 0 &&
((const uint8_t * const)vers)[2] == 0 &&
((const uint8_t * const)vers)[3] == 0)
return "VERSION_NEGOTIATION";
switch (pkt_type(flags)) {
case LH_INIT:
return "INITIAL";
case LH_RTRY:
return "RETRY";
case LH_HSHK:
return "HANDSHAKE";
case LH_0RTT:
return "ZERORTT";
}
} else if (pkt_type(flags) == SH)
return "ONERTT";
return "UNKOWN";
}
static uint64_t __attribute__((const)) to_usec(const uint64_t t)
{
return t / NS_PER_US;
}
static bool qlog_common(const struct cid * const gid)
{
if (qlog_ref_t == 0)
return false;
char cid_str[hex_str_len(CID_LEN_MAX)];
hex2str(gid->id, gid->len, cid_str, sizeof(cid_str));
fprintf(qlog, "%s[%" PRIu64 ",\"%s\"", likely(prev_event) ? "," : "",
to_usec(loop_now() - qlog_ref_t), cid_str);
return true;
}
void qlog_init(const struct q_conn * const c)
{
if (qlog && qlog_ref_t == 0) {
qlog_ref_t = loop_now();
fprintf(qlog,
"{"
"\"qlog_version\":\"draft-00\","
"\"title\":\"%s %s qlog\","
"\"traces\":[{"
"\"vantage_point\":{\"type\":\"%s\"},"
"\"configuration\":{\"time_units\":\"us\"},\"common_fields\":{"
"\"protocol_type\":\"QUIC_HTTP3\",\"reference_time\":%" PRIu64
"},"
"\"event_fields\":[\"relative_time\",\"group_id\",\"CATEGORY\","
"\"EVENT_TYPE\","
"\"TRIGGER\",\"DATA\"],\"events\":[",
quant_name, quant_version, c->is_clnt ? "CLIENT" : "SERVER",
to_usec(qlog_ref_t));
}
}
void qlog_close(void)
{
if (qlog) {
fputs("]}]}", qlog);
fclose(qlog);
}
}
void qlog_transport(const qlog_pkt_evt_t evt,
const char * const trg,
struct w_iov * const v,
const struct pkt_meta * const m,
const struct cid * const gid)
{
if (qlog_common(gid) == false)
return;
static const char * const evt_str[] = {[pkt_tx] = "PACKET_SENT",
[pkt_rx] = "PACKET_RECEIVED",
[pkt_dp] = "PACKET_DROPPED"};
fprintf(qlog,
",\"TRANSPORT\",\"%s\",\"%s\",{\"packet_type\":\"%"
"s\",\"header\":{\"packet_size\":%u",
evt_str[evt], trg, qlog_pkt_type_str(m->hdr.flags, &m->hdr.vers),
m->udp_len);
if (is_lh(m->hdr.flags) == false || (m->hdr.vers && m->hdr.type != LH_RTRY))
fprintf(qlog, ",\"packet_number\":%" PRIu, m->hdr.nr);
fputs("}", qlog);
if (evt == pkt_dp)
goto done;
static const struct frames qlog_frm =
bitset_t_initializer(1 << FRM_ACK | 1 << FRM_STR);
if (bit_overlap(FRM_MAX, &m->frms, &qlog_frm) == false)
goto done;
fputs(",\"frames\":[", qlog);
int prev_frame = 0;
if (has_frm(m->frms, FRM_STR)) {
prev_frame = fprintf(qlog,
"%s{\"frame_type\": \"STREAM\",\"id\": %" PRId
",\"length\": %u,\"offset\": %" PRIu,
prev_frame ? "," : "", m->strm->id,
m->strm_data_len, m->strm_off);
if (m->is_fin)
fputs(",\"fin\":true", qlog);
fputs("}", qlog);
}
if (has_frm(m->frms, FRM_ACK)) {
adj_iov_to_start(v, m);
const uint8_t * pos = v->buf + m->ack_frm_pos;
const uint8_t * const end = v->buf + v->len;
uint64_t lg_ack = 0;
decv(&lg_ack, &pos, end);
uint64_t ack_delay = 0;
decv(&ack_delay, &pos, end);
uint64_t ack_rng_cnt = 0;
decv(&ack_rng_cnt, &pos, end);
// prev_frame =
fprintf(qlog,
"%s{\"frame_type\": \"ACK\",\"ack_delay\": %" PRIu64
",\"acked_ranges\":[",
prev_frame ? "," : "", ack_delay);
// this is a similar loop as in dec_ack_frame() - keep changes in sync
for (uint64_t n = ack_rng_cnt + 1; n > 0; n--) {
uint64_t ack_rng = 0;
decv(&ack_rng, &pos, end);
fprintf(qlog, "%s[%" PRIu64 ",%" PRIu64 "]",
(n <= ack_rng_cnt ? "," : ""), lg_ack - ack_rng, lg_ack);
if (n > 1) {
uint64_t gap = 0;
decv(&gap, &pos, end);
lg_ack -= ack_rng + gap + 2;
}
}
adj_iov_to_data(v, m);
fputs("]}", qlog);
}
fputs("]", qlog);
done:
fputs("}]", qlog);
prev_event = true;
}
void qlog_recovery(const qlog_rec_evt_t evt,
const char * const trg,
const struct q_conn * const c,
const struct cid * const gid)
{
if (qlog_common(gid) == false)
return;
static const char * const evt_str[] = {[rec_mu] = "METRIC_UPDATE"};
fprintf(qlog, ",\"RECOVERY\",\"%s\",\"%s\",{", evt_str[evt], trg);
int prev_metric = 0;
if (c->rec.cur.in_flight != c->rec.prev.in_flight)
prev_metric = fprintf(qlog, "%s\"bytes_in_flight\":%" PRIu,
prev_metric ? "," : "", c->rec.cur.in_flight);
if (c->rec.cur.cwnd != c->rec.prev.cwnd)
prev_metric = fprintf(qlog, "%s\"cwnd\":%" PRIu, prev_metric ? "," : "",
c->rec.cur.cwnd);
if (c->rec.cur.ssthresh != UINT_T_MAX &&
c->rec.cur.ssthresh != c->rec.prev.ssthresh)
prev_metric = fprintf(qlog, "%s\"ssthresh\":%" PRIu,
prev_metric ? "," : "", c->rec.cur.ssthresh);
if (c->rec.cur.srtt != c->rec.prev.srtt)
prev_metric = fprintf(qlog, "%s\"smoothed_rtt\":%" PRIu64,
prev_metric ? "," : "", to_usec(c->rec.cur.srtt));
if (c->rec.cur.min_rtt < UINT_T_MAX &&
c->rec.cur.min_rtt != c->rec.prev.min_rtt)
prev_metric =
fprintf(qlog, "%s\"min_rtt\":%" PRIu64, prev_metric ? "," : "",
to_usec(c->rec.cur.min_rtt));
if (c->rec.cur.latest_rtt != c->rec.prev.latest_rtt)
prev_metric =
fprintf(qlog, "%s\"latest_rtt\":%" PRIu64, prev_metric ? "," : "",
to_usec(c->rec.cur.latest_rtt));
if (c->rec.cur.rttvar != c->rec.prev.rttvar)
// prev_metric =
fprintf(qlog, "%s\"rtt_variance\":%" PRIu64, prev_metric ? "," : "",
to_usec(c->rec.cur.rttvar));
fputs("}]", qlog);
prev_event = true;
}
#else
static void * _unused __attribute__((unused));
#endif
|
jlaine/quant
|
lib/src/frame.h
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <warpcore/warpcore.h>
#include "bitset.h"
struct pn_space;
struct q_conn;
struct q_stream;
struct cid;
#define FRM_PAD 0x00 ///< PADDING
#define FRM_PNG 0x01 ///< PING
#define FRM_ACK 0x02 ///< ACK (only type encoded in the frames bitstr_t)
#define FRM_ACE 0x03 ///< ACK w/ECN
#define FRM_RST 0x04 ///< RESET_STREAM
#define FRM_STP 0x05 ///< STOP_SENDING
#define FRM_CRY 0x06 ///< CRYPTO
#define FRM_TOK 0x07 ///< NEW_TOKEN
#define FRM_STR 0x08 ///< STREAM (only type encoded in the frames bitstr_t)
#define FRM_STR_09 0x09
#define FRM_STR_0a 0x0a
#define FRM_STR_0b 0x0b
#define FRM_STR_0c 0x0c
#define FRM_STR_0d 0x0d
#define FRM_STR_0e 0x0e
#define FRM_STR_0f 0x0f
#define FRM_STR_MAX FRM_STR_0f
#define FRM_MCD 0x10 ///< MAX_DATA (connection)
#define FRM_MSD 0x11 ///< MAX_STREAM_DATA
#define FRM_MSB 0x12 ///< MAX_STREAMS (bidirectional)
#define FRM_MSU 0x13 ///< MAX_STREAMS (unidirectional)
#define FRM_CDB 0x14 ///< (connection) DATA_BLOCKED
#define FRM_SDB 0x15 ///< STREAM_DATA_BLOCKED
#define FRM_SBB 0x16 ///< STREAMS_BLOCKED (bidirectional)
#define FRM_SBU 0x17 ///< STREAMS_BLOCKED (unidirectional)
#define FRM_CID 0x18 ///< NEW_CONNECTION_ID
#define FRM_RTR 0x19 ///< RETIRE_CONNECTION_ID
#define FRM_PCL 0x1a ///< PATH_CHALLENGE
#define FRM_PRP 0x1b ///< PATH_RESPONSE
#define FRM_CLQ 0x1c ///< CONNECTION_CLOSE (QUIC layer)
#define FRM_CLA 0x1d ///< CONNECTION_CLOSE (application)
#define FRM_MAX (FRM_CLA + 1)
bitset_define(frames, FRM_MAX);
#define F_STREAM_FIN 0x01
#define F_STREAM_LEN 0x02
#define F_STREAM_OFF 0x04
#define FRAM_IN BLD BLU
#define FRAM_OUT BLD GRN
#define has_frm(frames, type) bit_isset(FRM_MAX, (type), &(frames))
struct pkt_meta;
#if defined(NDEBUG) && !defined(NDEBUG_WITH_DLOG)
#define log_stream_or_crypto_frame(...)
#else
extern void __attribute__((nonnull(2)))
log_stream_or_crypto_frame(const bool is_rtx,
const struct pkt_meta * const m,
const uint8_t fl,
const dint_t sid,
const bool in,
const char * const kind);
#endif
extern bool __attribute__((nonnull))
dec_frames(struct q_conn * const c, struct w_iov ** vv, struct pkt_meta ** mm);
extern uint16_t __attribute__((const)) max_frame_len(const uint8_t type);
extern void __attribute__((nonnull))
enc_padding_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
const uint16_t len);
extern void __attribute__((nonnull)) enc_ack_frame(uint8_t ** pos,
const uint8_t * const start,
const uint8_t * const end,
struct pkt_meta * const m,
struct pn_space * const pn);
extern void __attribute__((nonnull))
calc_lens_of_stream_or_crypto_frame(const struct pkt_meta * const m,
const struct w_iov * const v,
const struct q_stream * const s,
uint16_t * const hlen,
uint16_t * const dlen);
extern void __attribute__((nonnull))
enc_stream_or_crypto_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct w_iov * const v,
struct q_stream * const s,
const uint16_t dlen);
extern void __attribute__((nonnull)) enc_close_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
extern void __attribute__((nonnull))
enc_path_response_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
extern void __attribute__((nonnull))
enc_max_strm_data_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct q_stream * const s);
extern void __attribute__((nonnull))
enc_max_data_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
extern void __attribute__((nonnull))
enc_max_strms_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
const bool bidi);
extern void __attribute__((nonnull))
enc_strm_data_blocked_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct q_stream * const s);
extern void __attribute__((nonnull))
enc_data_blocked_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
extern void __attribute__((nonnull))
enc_streams_blocked_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
const bool bidi);
extern void __attribute__((nonnull))
enc_path_challenge_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
extern void __attribute__((nonnull))
enc_new_cid_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
extern void __attribute__((nonnull))
enc_new_token_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
extern void __attribute__((nonnull))
enc_retire_cid_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct cid * const dcid);
extern void __attribute__((nonnull)) enc_ping_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m);
static inline bool __attribute__((nonnull))
is_ack_eliciting(const struct frames * const f)
{
static const struct frames ack_or_pad =
bitset_t_initializer(1 << FRM_ACK | 1 << FRM_PAD);
struct frames not_ack_or_pad = bitset_t_initializer(0);
bit_nand2(FRM_MAX, ¬_ack_or_pad, f, &ack_or_pad);
return !bit_empty(FRM_MAX, ¬_ack_or_pad);
}
|
jlaine/quant
|
bin/client.c
|
<reponame>jlaine/quant<filename>bin/client.c
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <math.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <time.h>
#include <unistd.h>
#define klib_unused
#include <http_parser.h>
#include <picoquic/h3zero.h> // IWYU pragma: keep
#include <picoquic/picoquic.h> // IWYU pragma: keep
#include <picoquic/democlient.h>
#include <quant/quant.h>
#define timespec_to_double(diff) \
((double)(diff).tv_sec + (double)(diff).tv_nsec / NS_PER_S)
#define bps(bytes, secs) \
__extension__({ \
static char _str[32]; \
const double _bps = \
(bytes) && (fpclassify(secs) != FP_ZERO) ? (bytes)*8 / (secs) : 0; \
if (_bps > NS_PER_S) \
snprintf(_str, sizeof(_str), "%.3f Gb/s", _bps / NS_PER_S); \
else if (_bps > US_PER_S) \
snprintf(_str, sizeof(_str), "%.3f Mb/s", _bps / US_PER_S); \
else if (_bps > MS_PER_S) \
snprintf(_str, sizeof(_str), "%.3f Kb/s", _bps / MS_PER_S); \
else \
snprintf(_str, sizeof(_str), "%.3f b/s", _bps); \
_str; \
})
struct conn_cache_entry {
struct sockaddr_in dst;
struct q_conn * c;
#ifndef NO_MIGRATION
bool rebound;
uint8_t _unused[7];
#endif
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
KHASH_MAP_INIT_INT64(conn_cache, struct conn_cache_entry *)
#pragma clang diagnostic pop
static uint32_t timeout = 10;
static uint32_t num_bufs = 100000;
static uint32_t reps = 1;
static bool do_h3 = false;
static bool flip_keys = false;
static bool zlen_cids = false;
static bool write_files = false;
#ifndef NO_MIGRATION
static bool rebind = false;
static bool migrate = false;
#endif
struct stream_entry {
sl_entry(stream_entry) next;
struct q_conn * c;
struct q_stream * s;
char * url;
struct timespec req_t;
struct timespec rep_t;
struct w_iov_sq req;
struct w_iov_sq rep;
};
static sl_head(stream_list, stream_entry) sl = sl_head_initializer(sl);
static inline uint64_t __attribute__((nonnull))
conn_cache_key(const struct sockaddr * const sock)
{
const struct sockaddr_in * const sock4 =
(const struct sockaddr_in *)(const void *)sock;
return ((uint64_t)sock4->sin_addr.s_addr
<< sizeof(sock4->sin_addr.s_addr) * 8) |
(uint64_t)sock4->sin_port;
}
static void __attribute__((noreturn, nonnull)) usage(const char * const name,
const char * const ifname,
const char * const cache,
const char * const tls_log,
const char * const qlog,
const bool verify_certs)
{
printf("%s [options] URL [URL...]\n", name);
printf("\t[-i interface]\tinterface to run over; default %s\n", ifname);
printf("\t[-q log]\twrite qlog events to file; default %s\n", qlog);
printf("\t[-s cache]\tTLS 0-RTT state cache; default %s\n", cache);
printf("\t[-l log]\tlog file for TLS keys; default %s\n", tls_log);
printf("\t[-t timeout]\tidle timeout in seconds; default %u\n", timeout);
printf("\t[-c]\t\tverify TLS certificates; default %s\n",
verify_certs ? "true" : "false");
printf("\t[-u]\t\tupdate TLS keys; default %s\n",
flip_keys ? "true" : "false");
printf("\t[-3]\t\tsend a static H3 request; default %s\n",
do_h3 ? "true" : "false");
printf("\t[-z]\t\tuse zero-length source connection IDs; default %s\n",
zlen_cids ? "true" : "false");
printf("\t[-w]\t\twrite retrieved objects to disk; default %s\n",
write_files ? "true" : "false");
printf("\t[-r reps]\trepetitions for all URLs; default %u\n", reps);
printf("\t[-b bufs]\tnumber of network buffers to allocate; default %u\n",
num_bufs);
#ifndef NO_MIGRATION
printf("\t[-n]\t\tsimulate NAT rebind (use twice for \"real\" migration); "
"default %s\n",
rebind ? "true" : "false");
#endif
#ifndef NDEBUG
printf("\t[-v verbosity]\tverbosity level (0-%d, default %d)\n", DLEVEL,
util_dlevel);
#endif
exit(0);
}
static void __attribute__((nonnull))
set_from_url(char * const var,
const size_t len,
const char * const url,
const struct http_parser_url * const u,
const enum http_parser_url_fields f,
const char * const def)
{
if ((u->field_set & (1 << f)) == 0) {
strncpy(var, def, len);
var[len - 1] = 0;
} else {
strncpy(var, &url[u->field_data[f].off], u->field_data[f].len);
var[u->field_data[f].len] = 0;
}
}
static struct q_conn * __attribute__((nonnull))
get(char * const url, struct w_engine * const w, khash_t(conn_cache) * cc)
{
// parse and verify the URIs passed on the command line
struct http_parser_url u = {0};
if (http_parser_parse_url(url, strlen(url), 0, &u)) {
warn(ERR, "http_parser_parse_url: %s",
http_errno_description((enum http_errno)errno));
return 0;
}
ensure((u.field_set & (1 << UF_USERINFO)) == 0 &&
(u.field_set & (1 << UF_QUERY)) == 0 &&
(u.field_set & (1 << UF_FRAGMENT)) == 0,
"unsupported URL components");
// extract relevant info from URL
char dest[1024];
char port[64];
char path[2048];
set_from_url(dest, sizeof(dest), url, &u, UF_HOST, "localhost");
set_from_url(port, sizeof(port), url, &u, UF_PORT, "4433");
set_from_url(path, sizeof(path), url, &u, UF_PATH, "/index.html");
struct addrinfo * peer;
const struct addrinfo hints = {.ai_family = PF_INET,
.ai_socktype = SOCK_DGRAM,
.ai_protocol = IPPROTO_UDP};
const int err = getaddrinfo(dest, port, &hints, &peer);
if (err) {
warn(ERR, "getaddrinfo: %s", gai_strerror(err));
freeaddrinfo(peer);
return 0;
}
// add to stream list
struct stream_entry * se = calloc(1, sizeof(*se));
ensure(se, "calloc failed");
sq_init(&se->rep);
sl_insert_head(&sl, se, next);
sq_init(&se->req);
if (do_h3) {
q_alloc(w, &se->req, 1024);
struct w_iov * const v = sq_first(&se->req);
size_t consumed;
h3zero_client_create_stream_request(v->buf, v->len, (uint8_t *)path,
strlen(path), 0, dest, &consumed);
v->len = (uint16_t)consumed;
} else {
// assemble an HTTP/0.9 request
char req_str[MAXPATHLEN + 6];
const int req_str_len =
snprintf(req_str, sizeof(req_str), "GET %s\r\n", path);
q_chunk_str(w, req_str, (uint32_t)req_str_len, &se->req);
}
// do we have a connection open to this peer?
khiter_t k = kh_get(conn_cache, cc, conn_cache_key(peer->ai_addr));
struct conn_cache_entry * cce =
(k == kh_end(cc) ? 0 : kh_val(cc, k)); // NOLINT
const bool opened_new = cce == 0;
if (cce == 0) {
clock_gettime(CLOCK_MONOTONIC, &se->req_t);
// no, open a new connection
struct q_conn * const c = q_connect(
w, peer->ai_addr, dest,
#ifndef NO_MIGRATION
rebind ? 0 : &se->req, rebind ? 0 : &se->s,
#else
0, 0,
#endif
true,
do_h3 ? "h3-" DRAFT_VERSION_STRING : "hq-" DRAFT_VERSION_STRING, 0);
if (c == 0) {
freeaddrinfo(peer);
return 0;
}
if (do_h3) {
// we need to open a uni stream for an empty H/3 SETTINGS frame
struct q_stream * const ss = q_rsv_stream(c, false);
if (ss == 0)
return 0;
static const uint8_t h3_empty_settings[] = {0x04, 0x00};
// XXX lsquic doesn't like a FIN on this stream
q_write_str(w, ss, (const char *)h3_empty_settings,
sizeof(h3_empty_settings), false);
}
cce = calloc(1, sizeof(*cce));
ensure(cce, "calloc failed");
cce->c = c;
// insert into connection cache
cce->dst = *(struct sockaddr_in *)&peer->ai_addr;
int ret;
k = kh_put(conn_cache, cc, conn_cache_key(peer->ai_addr), &ret);
ensure(ret >= 1, "inserted returned %d", ret);
kh_val(cc, k) = cce;
}
if (opened_new == false
#ifndef NO_MIGRATION
|| (rebind && cce->rebound == false)
#endif
) {
se->s = q_rsv_stream(cce->c, true);
if (se->s) {
clock_gettime(CLOCK_MONOTONIC, &se->req_t);
q_write(se->s, &se->req, true);
#ifndef NO_MIGRATION
if (rebind && cce->rebound == false) {
q_rebind_sock(cce->c, migrate);
cce->rebound = true; // only rebind once
}
#endif
}
}
se->c = cce->c;
se->url = url;
freeaddrinfo(peer);
return cce->c; // NOLINT
}
static void __attribute__((nonnull)) free_cc(khash_t(conn_cache) * cc)
{
struct conn_cache_entry * cce;
kh_foreach_value(cc, cce, { free(cce); });
kh_destroy(conn_cache, cc);
}
static void free_se(struct stream_entry * const se)
{
q_free(&se->req);
q_free(&se->rep);
free(se);
}
static void free_sl_head(void)
{
struct stream_entry * const se = sl_first(&sl);
sl_remove_head(&sl, next);
free_se(se);
}
static void free_sl(void)
{
while (sl_empty(&sl) == false)
free_sl_head();
}
static void __attribute__((nonnull))
write_object(struct stream_entry * const se)
{
char * const slash = strrchr(se->url, '/');
if (slash && *(slash + 1) == 0)
// this URL ends in a slash, so strip that to name the file
*slash = 0;
const int fd =
open(*basename(se->url) == 0 ? "index.html" : basename(se->url),
O_CREAT | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP);
ensure(fd != -1, "cannot open %s", basename(se->url));
struct iovec vec[IOV_MAX];
struct w_iov * v = sq_first(&se->rep);
int i = 0;
while (v) {
vec[i].iov_base = v->buf;
vec[i].iov_len = v->len;
if (++i == IOV_MAX || sq_next(v, next) == 0) {
ensure(writev(fd, vec, i) != -1, "cannot writev");
i = 0;
}
v = sq_next(v, next);
}
close(fd);
}
int main(int argc, char * argv[])
{
#ifndef NDEBUG
util_dlevel = DLEVEL; // default to maximum compiled-in verbosity
#endif
char ifname[IFNAMSIZ] = "lo"
#ifndef __linux__
"0"
#endif
;
int ch;
char cache[MAXPATHLEN] = "/tmp/" QUANT "-session";
char tls_log[MAXPATHLEN] = "/tmp/" QUANT "-tlslog";
char qlog[MAXPATHLEN] = "/tmp/" QUANT "-client.qlog";
bool verify_certs = false;
int ret = 0;
while ((ch = getopt(argc, argv,
"hi:v:s:t:l:cu3zb:wr:q:"
#ifndef NO_MIGRATION
"n"
#endif
)) != -1) {
switch (ch) {
case 'i':
strncpy(ifname, optarg, sizeof(ifname) - 1);
break;
case 's':
strncpy(cache, optarg, sizeof(cache) - 1);
break;
case 'q':
strncpy(qlog, optarg, sizeof(qlog) - 1);
break;
case 't':
timeout = (uint32_t)MIN(600, strtoul(optarg, 0, 10)); // 10 min
break;
case 'b':
num_bufs =
(uint32_t)MAX(1000, MIN(strtoul(optarg, 0, 10), UINT32_MAX));
break;
case 'r':
reps = (uint32_t)MAX(1, MIN(strtoul(optarg, 0, 10), UINT32_MAX));
break;
case 'l':
strncpy(tls_log, optarg, sizeof(tls_log) - 1);
break;
case 'c':
verify_certs = true;
break;
case 'u':
flip_keys = true;
break;
case '3':
do_h3 = true;
break;
case 'z':
zlen_cids = true;
break;
case 'w':
write_files = true;
break;
#ifndef NO_MIGRATION
case 'n':
if (rebind)
migrate = true;
rebind = true;
break;
#endif
case 'v':
#ifndef NDEBUG
util_dlevel = (short)MIN(DLEVEL, strtoul(optarg, 0, 10));
#endif
break;
case 'h':
case '?':
default:
usage(basename(argv[0]), ifname, cache, tls_log, qlog,
verify_certs);
}
}
struct w_engine * const w = q_init(
ifname, &(const struct q_conf){
.conn_conf = &(
struct q_conn_conf){.enable_tls_key_updates = flip_keys,
.enable_spinbit = true,
.idle_timeout = timeout,
.enable_zero_len_cid = zlen_cids},
.qlog = qlog,
.num_bufs = num_bufs,
.ticket_store = cache,
.tls_log = tls_log,
.enable_tls_cert_verify = verify_certs});
khash_t(conn_cache) * cc = kh_init(conn_cache);
if (reps > 1)
puts("size\ttime\t\tbps\t\turl");
for (uint64_t r = 1; r <= reps; r++) {
int url_idx = optind;
while (url_idx < argc) {
// open a new connection, or get an open one
warn(INF, "%s retrieving %s", basename(argv[0]), argv[url_idx]);
get(argv[url_idx++], w, cc);
}
// collect the replies
bool all_closed;
do {
all_closed = true;
bool rxed_new = false;
struct stream_entry * se = 0;
struct stream_entry * tmp = 0;
sl_foreach_safe (se, &sl, next, tmp) {
if (se->c == 0 || se->s == 0 || q_is_conn_closed(se->c)) {
sl_remove(&sl, se, stream_entry, next);
free_se(se);
continue;
}
rxed_new |= q_read_stream(se->s, &se->rep, false);
const bool is_closed = q_peer_closed_stream(se->s);
all_closed &= is_closed;
if (is_closed)
clock_gettime(CLOCK_MONOTONIC, &se->rep_t);
}
if (rxed_new == false) {
struct q_conn * c;
q_ready(w, timeout * NS_PER_S, &c);
if (c == 0)
break;
}
} while (all_closed == false);
// print/save the replies
while (sl_empty(&sl) == false) {
struct stream_entry * const se = sl_first(&sl);
ret |= w_iov_sq_cnt(&se->rep) == 0;
struct timespec diff;
timespec_sub(&se->rep_t, &se->req_t, &diff);
const double elapsed = timespec_to_double(diff);
if (reps > 1)
printf("%" PRIu "\t%f\t\"%s\"\t%s\n", w_iov_sq_len(&se->rep),
elapsed, bps(w_iov_sq_len(&se->rep), elapsed), se->url);
#ifndef NDEBUG
char cid_str[64];
q_cid(se->c, cid_str, sizeof(cid_str));
warn(WRN,
"read %" PRIu
" byte%s in %.3f sec (%s) on conn %s strm %" PRIu,
w_iov_sq_len(&se->rep), plural(w_iov_sq_len(&se->rep)),
elapsed < 0 ? 0 : elapsed,
bps(w_iov_sq_len(&se->rep), elapsed), cid_str, q_sid(se->s));
#endif
// retrieve the TX'ed request
q_stream_get_written(se->s, &se->req);
if (write_files)
write_object(se);
// save the object, and print its first three packets to stdout
struct w_iov * v;
uint32_t n = 0;
sq_foreach (v, &se->rep, next) {
const bool is_last = v == sq_last(&se->rep, w_iov, next);
if (w_iov_sq_cnt(&se->rep) > 100 || reps > 1)
// don't print large responses, or repeated ones
continue;
// XXX the strnlen() test is super-hacky
if (do_h3 && n == 0 &&
(v->buf[0] != 0x01 && v->buf[0] != 0xff &&
strnlen((char *)v->buf, v->len) == v->len))
warn(WRN, "no h3 payload");
if (n < 4 || is_last) {
if (do_h3) {
#ifndef NDEBUG
if (util_dlevel == DBG)
hexdump(v->buf, v->len);
#endif
} else {
// don't print newlines to console log
for (uint16_t p = 0; p < v->len; p++)
if (v->buf[p] == '\n' || v->buf[p] == '\r')
v->buf[p] = ' ';
printf("%.*s%s", v->len, v->buf, is_last ? "\n" : "");
if (is_last)
fflush(stdout);
}
} else
printf(".");
n++;
}
q_free_stream(se->s);
free_sl_head();
}
}
q_cleanup(w);
free_cc(cc);
free_sl();
warn(DBG, "%s exiting", basename(argv[0]));
return ret;
}
|
jlaine/quant
|
bin/server.c
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <fcntl.h>
#include <libgen.h>
#include <net/if.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#ifndef __linux__
#include <sys/types.h>
#endif
#include <http_parser.h>
#include <quant/quant.h>
struct q_conn;
#ifndef NDEBUG
static bool __attribute__((const)) is_bench_obj(const uint_t len)
{
return len == 5000000 || len == 10000000;
}
#endif
static void __attribute__((noreturn)) usage(const char * const name,
const char * const ifname,
const char * const qlog,
const uint16_t port,
const char * const dir,
const char * const cert,
const char * const key,
const uint32_t timeout,
const uint32_t num_bufs)
{
printf("%s [options]\n", name);
printf("\t[-i interface]\tinterface to run over; default %s\n", ifname);
printf("\t[-p port]\tdestination port; default %d\n", port);
printf("\t[-q log]\twrite qlog events to file; default %s\n", qlog);
printf("\t[-d dir]\tserver root directory; default %s\n", dir);
printf("\t[-c cert]\tTLS certificate; default %s\n", cert);
printf("\t[-k key]\tTLS key; default %s\n", key);
printf("\t[-t timeout]\tidle timeout in seconds; default %u\n", timeout);
printf("\t[-b bufs]\tnumber of network buffers to allocate; default %u\n ",
num_bufs);
#ifndef NDEBUG
printf("\t[-v verbosity]\tverbosity level (0-%d, default %d)\n", DLEVEL,
util_dlevel);
#endif
exit(0);
}
struct cb_data {
struct q_stream * s;
struct q_conn * c;
struct w_engine * w;
int dir;
// short dlevel;
uint32_t _dummy;
};
static bool send_err(const struct cb_data * const d, const uint16_t code)
{
const char * msg;
bool close = false;
switch (code) {
case 400:
msg = "400 Bad Request";
close = true;
break;
case 403:
msg = "403 Forbidden";
break;
case 404:
msg = "404 Not Found";
break;
case 505:
msg = "505 HTTP Version Not Supported";
close = true;
break;
default:
msg = "500 Internal Server Error";
}
if (close)
q_close(d->c, 0x0003, msg);
else
q_write_str(d->w, d->s, msg, strlen(msg), true);
return close;
}
#ifndef NDEBUG
static uint32_t bench_cnt = 0;
#endif
static int serve_cb(http_parser * parser, const char * at, size_t len)
{
(void)parser;
const struct cb_data * const d = parser->data;
char cid_str[64];
q_cid(d->c, cid_str, sizeof(cid_str));
warn(INF, "conn %s str %" PRId " serving URL %.*s", cid_str, q_sid(d->s),
(int)len, at);
char path[MAXPATHLEN] = ".";
strncpy(&path[*at == '/' ? 1 : 0], at, MIN(len, sizeof(path) - 1));
// hacky way to prevent directory traversals
if (strstr(path, ".."))
return send_err(d, 403);
// check if this is a "GET /n" request for random data
const uint32_t n = (uint32_t)strtoul(&path[2], 0, 10);
if (n) {
struct w_iov_sq out = w_iov_sq_initializer(out);
q_alloc(d->w, &out, n);
// check whether we managed to allow enough buffers
if (w_iov_sq_len(&out) != n) {
warn(ERR, "could only allocate %" PRIu "/%u bytes of buffer",
w_iov_sq_len(&out), n);
q_free(&out);
return send_err(d, 500);
}
#ifndef NDEBUG
// randomize data
struct w_iov * v = 0;
uint8_t c = 'A' + (uint8_t)w_rand_uniform32(26);
sq_foreach (v, &out, next) {
memset(v->buf, c, v->len);
c = unlikely(c == 'Z') ? 'A' : c + 1;
}
// for the two "benchmark objects", reduce logging
if (is_bench_obj(n)) {
warn(NTE, "reducing log level for benchmark object transfer");
util_dlevel = WRN;
bench_cnt++;
}
#endif
q_write(d->s, &out, true);
return 0;
}
struct stat info;
if (fstatat(d->dir, path, &info, 0) == -1)
return send_err(d, 404);
// if this a directory, look up its index
if (info.st_mode & S_IFDIR) {
strncat(path, "/index.html", sizeof(path) - len - 1);
if (fstatat(d->dir, path, &info, 0) == -1)
return send_err(d, 404);
}
if ((info.st_mode & S_IFREG) == 0 || (info.st_mode & S_IFLNK) == 0)
return send_err(d, 403);
if (info.st_size >= UINT32_MAX)
return send_err(d, 500);
const int f = openat(d->dir, path, O_RDONLY | O_CLOEXEC);
ensure(f != -1, "could not open %s", path);
q_write_file(d->w, d->s, f, (uint32_t)info.st_size, true);
return 0;
}
#define MAXPORTS 16
int main(int argc, char * argv[])
{
uint32_t timeout = 10;
#ifndef NDEBUG
short ini_dlevel = util_dlevel =
DLEVEL; // default to maximum compiled-in verbosity
#endif
char ifname[IFNAMSIZ] = "lo"
#ifndef __linux__
"0"
#endif
;
char dir[MAXPATHLEN] = ".";
char cert[MAXPATHLEN] = "test/dummy.crt";
char key[MAXPATHLEN] = "test/dummy.key";
char qlog[MAXPATHLEN] = "/tmp/" QUANT "-server.qlog";
uint16_t port[MAXPORTS] = {4433, 4434};
size_t num_ports = 0;
uint32_t num_bufs = 100000;
int ch;
int ret = 0;
while ((ch = getopt(argc, argv, "hi:p:d:v:c:k:t:b:q:")) != -1) {
switch (ch) {
case 'q':
strncpy(qlog, optarg, sizeof(qlog) - 1);
break;
case 'i':
strncpy(ifname, optarg, sizeof(ifname) - 1);
break;
case 'd':
strncpy(dir, optarg, sizeof(dir) - 1);
break;
case 'c':
strncpy(cert, optarg, sizeof(cert) - 1);
break;
case 'k':
strncpy(key, optarg, sizeof(key) - 1);
break;
case 'p':
port[num_ports++] =
(uint16_t)MIN(UINT16_MAX, strtoul(optarg, 0, 10));
ensure(num_ports < MAXPORTS, "can only listen on at most %u ports",
MAXPORTS);
break;
case 't':
timeout =
MIN(600, (uint32_t)strtoul(optarg, 0, 10)); // 10 min = 600 sec
break;
case 'b':
num_bufs = MAX(1000, (uint32_t)strtoul(optarg, 0, 10));
break;
case 'v':
#ifndef NDEBUG
ini_dlevel = util_dlevel =
(short)MIN(DLEVEL, strtoul(optarg, 0, 10));
#endif
break;
case 'h':
case '?':
default:
usage(basename(argv[0]), ifname, qlog, port[0], dir, cert, key,
timeout, num_bufs);
}
}
if (num_ports == 0)
// if no -p args were given, we listen on two ports by default
num_ports = 2;
const int dir_fd = open(dir, O_RDONLY | O_CLOEXEC);
ensure(dir_fd != -1, "%s does not exist", dir);
struct w_engine * const w =
q_init(ifname, &(const struct q_conf){.conn_conf =
&(struct q_conn_conf){
.idle_timeout = timeout,
.enable_spinbit = true,
},
.qlog = qlog,
.num_bufs = num_bufs,
.tls_cert = cert,
.tls_key = key});
struct q_conn * conn[MAXPORTS];
for (size_t i = 0; i < num_ports; i++) {
conn[i] = q_bind(w, port[i]);
warn(DBG, "%s %s %s port %d", basename(argv[0]),
conn[i] ? "waiting on" : "failed to bind to", ifname, port[i]);
}
bool first_conn = true;
http_parser_settings settings = {.on_url = serve_cb};
while (1) {
struct q_conn * c;
const bool have_active =
q_ready(w, first_conn ? 0 : timeout * NS_PER_S, &c);
if (c == 0) {
if (have_active == false)
break;
continue;
}
first_conn = false;
// do we need to q_accept?
if (q_is_new_serv_conn(c))
q_accept(w, 0);
if (q_is_conn_closed(c)) {
q_close(c, 0, 0);
continue;
}
// do we need to handle a request?
struct cb_data d = {.c = c, .w = w, .dir = dir_fd};
http_parser parser = {.data = &d};
again:
http_parser_init(&parser, HTTP_REQUEST);
struct w_iov_sq q = w_iov_sq_initializer(q);
struct q_stream * s = q_read(c, &q, false);
if (sq_empty(&q)) {
if (s && q_is_stream_closed(s)) {
// retrieve the TX'ed request
q_stream_get_written(s, &q);
#ifndef NDEBUG
// if we wrote a "benchmark objects", increase logging
const uint_t len = w_iov_sq_len(&q);
if (is_bench_obj(len) && --bench_cnt == 0) {
util_dlevel = ini_dlevel;
warn(NTE, "increasing log level after benchmark object "
"transfer");
}
#endif
q_free_stream(s);
q_free(&q);
goto again;
}
continue;
}
if (q_is_uni_stream(s)) {
warn(NTE, "can't serve request on uni stream: %.*s",
sq_first(&q)->len, sq_first(&q)->buf);
} else {
d.s = s;
struct w_iov * v = 0;
sq_foreach (v, &q, next) {
if (v->len == 0)
// skip empty bufs (such as pure FINs)
continue;
const size_t parsed = http_parser_execute(
&parser, &settings, (char *)v->buf, v->len);
if (parsed != v->len) {
warn(ERR, "HTTP parser error: %.*s", (int)(v->len - parsed),
&v->buf[parsed]);
hexdump(v->buf, v->len);
// XXX the strnlen() test is super-hacky
if (strnlen((char *)v->buf, v->len) == v->len)
send_err(&d, 400);
else
send_err(&d, 505);
ret = 1;
}
goto again;
}
}
q_free(&q);
}
q_cleanup(w);
warn(DBG, "%s exiting", basename(argv[0]));
return ret;
}
|
jlaine/quant
|
lib/src/recovery.c
|
<reponame>jlaine/quant
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/param.h>
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
#include <stdio.h>
#endif
#include <quant/quant.h>
#include "bitset.h"
#include "conn.h"
#include "diet.h"
#include "frame.h"
#include "loop.h"
#include "marshall.h"
#include "pkt.h"
#include "pn.h"
#include "qlog.h"
#include "quic.h"
#include "recovery.h"
#include "stream.h"
#include "tls.h"
#define is_crypto_pkt(m) has_frm((m)->frms, FRM_CRY)
static inline bool __attribute__((nonnull))
in_cong_recovery(const struct q_conn * const c, const uint64_t sent_t)
{
// see InRecovery() pseudo code
return sent_t <= c->rec.rec_start_t;
}
static bool __attribute__((nonnull))
have_unacked_crypto_data(struct q_conn * const c)
{
return (c->cstrms[ep_init] &&
out_fully_acked(c->cstrms[ep_init]) == false) ||
out_fully_acked(c->cstrms[ep_hshk]) == false;
}
static bool __attribute__((nonnull))
have_keys(struct q_conn * const c, const pn_t t)
{
const struct pn_space * const pn = &c->pns[t];
switch (t) {
case pn_init:
case pn_hshk:
return pn->early.in.aead && pn->early.out.aead;
case pn_data:
return (pn->data.in_1rtt[0].aead && pn->data.out_1rtt[0].aead) ||
(pn->data.in_1rtt[1].aead && pn->data.out_1rtt[1].aead);
}
die("unhandled pn %s", pn_type_str(t));
#ifdef PARTICLE
return false; // old gcc doesn't seem to understand "noreturn" attribute
#endif
}
static void __attribute__((nonnull)) maybe_tx(struct q_conn * const c)
{
if (has_wnd(c, c->w->mtu) == false)
return;
c->no_wnd = false;
// don't set c->needs_tx = true, since it's not clear we must TX
c->tx_limit = 0;
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
}
static struct pn_space * __attribute__((nonnull))
earliest_loss_t_pn(struct q_conn * const c)
{
uint64_t loss_t = 0;
struct pn_space * pn = 0;
for (pn_t t = pn_init; t <= pn_data; t++) {
if (c->pns[t].abandoned)
continue;
if (is_ack_eliciting(&c->pns[t].tx_frames) == false)
// no ACK-eliciting frames outstanding
continue;
if (pn == 0 || (c->pns[t].loss_t && c->pns[t].loss_t < loss_t)) {
pn = &c->pns[t];
loss_t = pn->loss_t;
}
}
return pn;
}
void log_cc(struct q_conn * const c)
{
const uint_t ssthresh =
c->rec.cur.ssthresh == UINT_T_MAX ? 0 : c->rec.cur.ssthresh;
const dint_t delta_in_flight =
(dint_t)c->rec.cur.in_flight - (dint_t)c->rec.prev.in_flight;
const dint_t delta_cwnd =
(dint_t)c->rec.cur.cwnd - (dint_t)c->rec.prev.cwnd;
const dint_t delta_ssthresh =
(dint_t)ssthresh -
(dint_t)(c->rec.prev.ssthresh == UINT_T_MAX ? 0 : c->rec.prev.ssthresh);
const int64_t delta_srtt =
(int64_t)c->rec.cur.srtt - (int64_t)c->rec.prev.srtt;
const int64_t delta_rttvar =
(int64_t)c->rec.cur.rttvar - (int64_t)c->rec.prev.rttvar;
if (delta_in_flight || delta_cwnd || delta_ssthresh || delta_srtt ||
delta_rttvar) {
mk_cid_str(DBG, c->scid, scid_str);
warn(DBG,
"%s conn %s: in_flight=%" PRIu " (%s%+" PRId NRM "), cwnd" NRM
"=%" PRIu " (%s%+" PRId NRM "), ssthresh=%" PRIu " (%s%+" PRId NRM
"), srtt=%.3f (%s%+.3f" NRM "), rttvar=%.3f (%s%+.3f" NRM ")",
conn_type(c), scid_str, c->rec.cur.in_flight,
delta_in_flight > 0 ? GRN : delta_in_flight < 0 ? RED : "",
delta_in_flight, c->rec.cur.cwnd,
delta_cwnd > 0 ? GRN : delta_cwnd < 0 ? RED : "", delta_cwnd,
ssthresh, delta_ssthresh > 0 ? GRN : delta_ssthresh < 0 ? RED : "",
delta_ssthresh, c->rec.cur.srtt / (double)NS_PER_S,
delta_srtt > 0 ? GRN : delta_srtt < 0 ? RED : "",
delta_srtt / (double)NS_PER_S,
c->rec.cur.rttvar / (double)NS_PER_S,
delta_rttvar > 0 ? GRN : delta_rttvar < 0 ? RED : "",
delta_rttvar / (double)NS_PER_S);
}
qlog_recovery(rec_mu, "DEFAULT", c, &c->odcid);
c->rec.prev = c->rec.cur;
}
void set_ld_timer(struct q_conn * const c)
{
if (c->state == conn_idle || c->state == conn_clsg || c->state == conn_drng)
// don't do LD while idle or draining
return;
// see SetLossDetectionTimer() pseudo code
#ifdef DEBUG_TIMERS
const char * type = BLD RED "???" NRM;
mk_cid_str(DBG, c->scid, scid_str);
#endif
const struct pn_space * const pn = earliest_loss_t_pn(c);
if (pn && pn->loss_t) {
#ifdef DEBUG_TIMERS
type = "TT";
#endif
c->rec.ld_alarm_val = pn->loss_t;
goto set_to;
}
if (unlikely(have_unacked_crypto_data(c) ||
have_keys(c, pn_data) == false)) {
#ifdef DEBUG_TIMERS
type = "crypto RTX";
#endif
timeout_t to = 2 * (unlikely(c->rec.cur.srtt == 0) ? kInitialRtt
: c->rec.cur.srtt);
to = MAX(to, kGranularity) * (1 << c->rec.crypto_cnt);
c->rec.ld_alarm_val = c->rec.last_sent_crypto_t + to;
goto set_to;
}
// don't arm the alarm if there are no ack-eliciting packets in flight
if (unlikely(c->rec.ae_in_flight == 0)) {
#ifdef DEBUG_TIMERS
warn(DBG, "no RTX-able pkts in flight, stopping ld_alarm on %s conn %s",
conn_type(c), scid_str);
#endif
timeouts_del(ped(c->w)->wheel, &c->rec.ld_alarm);
return;
}
#ifdef DEBUG_TIMERS
type = "PTO";
#endif
timeout_t to = c->rec.cur.srtt + MAX(4 * c->rec.cur.rttvar, kGranularity) +
c->tp_out.max_ack_del * NS_PER_MS;
to *= 1 << c->rec.pto_cnt;
c->rec.ld_alarm_val = c->rec.last_sent_ack_elicit_t + to;
set_to:;
const uint64_t now = loop_now();
if (unlikely(c->rec.ld_alarm_val < now)) {
#ifdef DEBUG_TIMERS
warn(WRN, "%s alarm expired %f sec ago", type,
((int64_t)c->rec.ld_alarm_val - (int64_t)now) / (double)NS_PER_S);
#endif
c->rec.ld_alarm_val = 0;
} else
c->rec.ld_alarm_val -= now;
#ifdef DEBUG_TIMERS
warn(DBG, "%s alarm in %f sec on %s conn %s", type,
c->rec.ld_alarm_val / (double)NS_PER_S, conn_type(c), scid_str);
#endif
timeouts_add(ped(c->w)->wheel, &c->rec.ld_alarm,
c->rec.ld_alarm_val <= 0 ? 0 : c->rec.ld_alarm_val);
}
void congestion_event(struct q_conn * const c, const uint64_t sent_t)
{
// see CongestionEvent() pseudo code
if (in_cong_recovery(c, sent_t))
return;
c->rec.rec_start_t = loop_now();
c->rec.cur.cwnd /= kLossReductionDivisor;
c->rec.cur.ssthresh = c->rec.cur.cwnd =
MAX(c->rec.cur.cwnd, kMinimumWindow);
}
static bool __attribute__((nonnull))
in_persistent_cong(struct pn_space * const pn __attribute__((unused)),
const uint_t lg_lost __attribute__((unused)))
{
// struct q_conn * const c = pn->c;
// // see InPersistentCongestion() pseudo code
// const uint64_t cong_period =
// kPersistentCongestionThreshold *
// (c->rec.cur.srtt + MAX(4 * c->rec.cur.rttvar, kGranularity) +
// c->tp_out.max_ack_del * NS_PER_MS);
// const struct ival * const i = diet_find(&pn->lost, lg_lost);
// warn(DBG,
// "lg_lost_ival %" PRIu "-%" PRIu ", lg_lost %" PRIu ", period
// %f", i->lo, i->hi, lg_lost, cong_period);
// return i->lo + cong_period < lg_lost;
return false;
}
static void remove_from_in_flight(const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
ensure(c->rec.cur.in_flight >= m->udp_len, "in_flight underrun %" PRIu,
m->udp_len - c->rec.cur.in_flight);
c->rec.cur.in_flight -= m->udp_len;
if (m->ack_eliciting)
c->rec.ae_in_flight--;
}
void on_pkt_lost(struct pkt_meta * const m, const bool is_lost)
{
struct pn_space * const pn = m->pn;
struct q_conn * const c = pn->c;
if (m->in_flight)
remove_from_in_flight(m);
// rest of function is not from pseudo code
diet_insert(&pn->acked_or_lost, m->hdr.nr, 0);
if (is_lost) {
// if we lost connection or stream control frames, possibly RTX them
// static const struct frames conn_ctrl =
// bitset_t_initializer(1 << FRM_TOK | 1 << FRM_CDB | 1 << FRM_SBB |
// 1 << FRM_SBU | 1 << FRM_CID | 1 << FRM_RTR);
static const struct frames all_ctrl =
bitset_t_initializer(1 << FRM_RST | 1 << FRM_STP | 1 << FRM_TOK |
1 << FRM_CDB | 1 << FRM_SDB | 1 << FRM_SBB |
1 << FRM_SBU | 1 << FRM_CID | 1 << FRM_RTR);
if (bit_overlap(FRM_MAX, &all_ctrl, &m->frms))
for (uint8_t i = 0; i < FRM_MAX; i++)
if (has_frm(m->frms, i) && bit_isset(FRM_MAX, i, &all_ctrl)) {
warn(DBG, "%s pkt %" PRIu " CONTROL LOST: 0x%02x",
pkt_type_str(m->hdr.flags, &m->hdr.vers), m->hdr.nr,
i);
switch (i) {
case FRM_CID:
c->max_cid_seq_out = m->min_cid_seq - 1;
break;
case FRM_CDB:
case FRM_SDB:
// DATA_BLOCKED and STREAM_DATA_BLOCKED RTX'ed
// automatically
break;
default:
warn(CRT, "unhandled RTX of 0x%02x frame", i);
}
}
static const struct frames strm_ctrl =
// FRM_SDB is automatically RTX'ed XXX fix this mess
bitset_t_initializer(1 << FRM_RST |
1 << FRM_STP /*| 1 << FRM_SDB*/);
if (bit_overlap(FRM_MAX, &strm_ctrl, &m->frms))
need_ctrl_update(m->strm);
}
m->lost = true;
if (m->strm)
m->strm->lost_cnt++;
pm_by_nr_del(&pn->sent_pkts, m);
}
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG))
#define DEBUG_diet_insert diet_insert
#define DEBUG_ensure ensure
#else
#define DEBUG_diet_insert(...)
#define DEBUG_ensure(...)
#endif
static void __attribute__((nonnull))
detect_lost_pkts(struct pn_space * const pn, const bool do_cc)
{
if (unlikely(pn->abandoned))
return;
struct q_conn * const c = pn->c;
pn->loss_t = 0;
// Minimum time of kGranularity before packets are deemed lost.
const uint64_t loss_del =
MAX(kGranularity, 9 * MAX(c->rec.cur.latest_rtt, c->rec.cur.srtt) / 8);
// Packets sent before this time are deemed lost.
const uint64_t lost_send_t = loop_now() - loss_del;
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG))
struct diet lost = diet_initializer(lost);
#endif
uint_t lg_lost = UINT_T_MAX;
uint64_t lg_lost_tx_t = 0;
bool in_flight_lost = false;
struct pkt_meta * m;
kh_foreach_value(&pn->sent_pkts, m, {
// TODO these ensures should not execute for release builds
DEBUG_ensure(m->acked == false,
"%s ACKed %s pkt %" PRIu " in sent_pkts", conn_type(c),
pkt_type_str(m->hdr.flags, &m->hdr.vers), m->hdr.nr);
DEBUG_ensure(m->lost == false, "%s lost %s pkt %" PRIu " in sent_pkts",
conn_type(c), pkt_type_str(m->hdr.flags, &m->hdr.vers),
m->hdr.nr);
if (m->hdr.nr > pn->lg_acked)
continue;
// Mark packet as lost, or set time when it should be marked.
if (m->t <= lost_send_t ||
pn->lg_acked >= m->hdr.nr + kPacketThreshold) {
m->lost = true;
in_flight_lost |= m->in_flight;
c->i.pkts_out_lost++;
if (unlikely(lg_lost == UINT_T_MAX) || m->hdr.nr > lg_lost) {
// cppcheck-suppress unreadVariable
lg_lost = m->hdr.nr;
lg_lost_tx_t = m->t;
}
} else {
if (unlikely(!pn->loss_t))
pn->loss_t = m->t + loss_del;
else
pn->loss_t = MIN(pn->loss_t, m->t + loss_del);
}
// OnPacketsLost
if (m->lost) {
DEBUG_diet_insert(&lost, m->hdr.nr, 0);
on_pkt_lost(m, true);
if (m->strm == 0 || m->has_rtx)
free_iov(w_iov(c->w, pm_idx(c->w, m)), m);
}
});
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG))
char buf[512];
int pos = 0;
struct ival * i = 0;
diet_foreach (i, diet, &lost) {
if ((size_t)pos >= sizeof(buf)) {
buf[sizeof(buf) - 2] = buf[sizeof(buf) - 3] = buf[sizeof(buf) - 4] =
'.';
buf[sizeof(buf) - 1] = 0;
break;
}
if (i->lo == i->hi)
pos +=
snprintf(&buf[pos], sizeof(buf) - (size_t)pos, FMT_PNR_OUT "%s",
i->lo, splay_next(diet, &lost, i) ? ", " : "");
else
pos += snprintf(&buf[pos], sizeof(buf) - (size_t)pos,
FMT_PNR_OUT ".." FMT_PNR_OUT "%s", i->lo, i->hi,
splay_next(diet, &lost, i) ? ", " : "");
}
diet_free(&lost);
if (pos)
warn(DBG, "%s %s lost: %s", conn_type(c), pn_type_str(pn->type), buf);
#endif
// OnPacketsLost
if (do_cc && in_flight_lost) {
congestion_event(c, lg_lost_tx_t);
if (in_persistent_cong(pn, lg_lost))
c->rec.cur.cwnd = kMinimumWindow;
}
log_cc(c);
maybe_tx(c);
}
static void __attribute__((nonnull)) on_ld_timeout(struct q_conn * const c)
{
// timeouts_del(ped(c->w)->wheel, &c->rec.ld_alarm);
// see OnLossDetectionTimeout pseudo code
struct pn_space * const pn = earliest_loss_t_pn(c);
mk_cid_str(NTE, c->scid, scid_str);
if (pn && pn->loss_t) {
#ifdef DEBUG_TIMERS
warn(DBG, "%s TT alarm on %s conn %s", pn_type_str(pn->type),
conn_type(c), scid_str);
#endif
detect_lost_pkts(pn, true);
goto set_timer; // otherwise no PTO will happen
} else if (have_unacked_crypto_data(c)) {
#ifdef DEBUG_TIMERS
warn(DBG, "crypto RTX #%u on %s conn %s", c->rec.crypto_cnt + 1,
conn_type(c), scid_str);
#endif
detect_lost_pkts(&c->pns[pn_init], false);
detect_lost_pkts(&c->pns[pn_hshk], false);
detect_lost_pkts(&c->pns[pn_data], false);
if (c->rec.crypto_cnt++ >= 2 && c->sockopt.enable_ecn) {
warn(NTE, "turning off ECN for %s conn %s", conn_type(c), scid_str);
c->sockopt.enable_ecn = false;
w_set_sockopt(c->sock, &c->sockopt);
}
c->tx_limit = 0;
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
c->i.pto_cnt++;
} else if (have_keys(c, pn_data) == false) {
#ifdef DEBUG_TIMERS
warn(DBG, "anti-deadlock RTX #%u on %s conn %s", c->rec.crypto_cnt + 1,
conn_type(c), scid_str);
#endif
c->tx_limit = have_keys(c, pn_hshk) ? 1 : 2;
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
c->rec.crypto_cnt++;
} else {
#ifdef DEBUG_TIMERS
warn(DBG, "PTO alarm #%u on %s conn %s", c->rec.pto_cnt, conn_type(c),
scid_str);
#endif
c->rec.pto_cnt++;
c->i.pto_cnt++;
c->tx_limit = 2;
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
}
if (timeout_expired(&c->rec.ld_alarm))
set_timer:
set_ld_timer(c);
}
static void __attribute__((nonnull))
track_acked_pkts(struct w_iov * const v, struct pkt_meta * const m)
{
adj_iov_to_start(v, m);
const uint8_t * pos = v->buf + m->ack_frm_pos;
const uint8_t * const end = v->buf + v->len;
uint64_t lg_ack = 0;
decv(&lg_ack, &pos, end);
uint64_t ack_delay = 0;
decv(&ack_delay, &pos, end);
uint64_t ack_rng_cnt = 0;
decv(&ack_rng_cnt, &pos, end);
// this is a similar loop as in dec_ack_frame() - keep changes in sync
for (uint64_t n = ack_rng_cnt + 1; n > 0; n--) {
uint64_t ack_rng = 0;
decv(&ack_rng, &pos, end);
diet_remove_ival(&m->pn->recv,
&(const struct ival){.lo = (uint_t)(lg_ack - ack_rng),
.hi = (uint_t)lg_ack});
if (n > 1) {
uint64_t gap = 0;
decv(&gap, &pos, end);
lg_ack -= ack_rng + gap + 2;
}
}
adj_iov_to_data(v, m);
}
void on_pkt_sent(struct pkt_meta * const m)
{
m->txed = true;
// see OnPacketSent() pseudo code
const uint64_t now = loop_now();
pm_by_nr_ins(&m->pn->sent_pkts, m);
// nr is set in enc_pkt()
m->t = now;
// ack_eliciting is set in enc_pkt()
m->in_flight = m->ack_eliciting || has_frm(m->frms, FRM_PAD);
// size is set in enc_pkt()
struct q_conn * const c = m->pn->c;
if (likely(m->in_flight)) {
if (unlikely(is_crypto_pkt(m)))
c->rec.last_sent_crypto_t = now;
if (likely(m->ack_eliciting)) {
c->rec.last_sent_ack_elicit_t = now;
c->rec.ae_in_flight++;
}
// OnPacketSentCC
c->rec.cur.in_flight += m->udp_len;
}
// we call set_ld_timer(c) once for a TX'ed burst in do_tx() instead of here
}
static void __attribute__((nonnull))
update_rtt(struct q_conn * const c, uint_t ack_del)
{
// see UpdateRtt() pseudo code
if (unlikely(c->rec.cur.srtt == 0)) {
c->rec.cur.min_rtt = c->rec.cur.srtt = c->rec.cur.latest_rtt;
c->rec.cur.rttvar = c->rec.cur.latest_rtt / 2;
return;
}
c->rec.cur.min_rtt = MIN(c->rec.cur.min_rtt, c->rec.cur.latest_rtt);
ack_del = MIN(ack_del, c->tp_out.max_ack_del) * NS_PER_MS;
const uint_t adj_rtt = c->rec.cur.latest_rtt > c->rec.cur.min_rtt + ack_del
? c->rec.cur.latest_rtt - ack_del
: c->rec.cur.latest_rtt;
c->rec.cur.rttvar = 3 * c->rec.cur.rttvar / 4 +
(uint_t)
#ifdef HAVE_64BIT
llabs
#else
labs
#endif
((dint_t)c->rec.cur.srtt - (dint_t)adj_rtt) /
4;
c->rec.cur.srtt = (7 * c->rec.cur.srtt / 8) + adj_rtt / 8;
}
void on_ack_received_1(struct pkt_meta * const lg_ack, const uint_t ack_del)
{
// see OnAckReceived() pseudo code
struct pn_space * const pn = lg_ack->pn;
struct q_conn * const c = pn->c;
pn->lg_acked = unlikely(pn->lg_acked == UINT_T_MAX)
? lg_ack->hdr.nr
: MAX(pn->lg_acked, lg_ack->hdr.nr);
if (is_ack_eliciting(&lg_ack->pn->tx_frames)) {
c->rec.cur.latest_rtt = loop_now() - lg_ack->t;
update_rtt(c, likely(pn->type == pn_data) ? ack_del : 0);
}
// ProcessECN() is done in dec_ack_frame()
}
void on_ack_received_2(struct pn_space * const pn)
{
// see OnAckReceived() pseudo code
struct q_conn * const c = pn->c;
detect_lost_pkts(pn, true);
c->rec.crypto_cnt = c->rec.pto_cnt = 0;
set_ld_timer(c);
}
static void __attribute__((nonnull))
on_pkt_acked_cc(const struct pkt_meta * const m)
{
// OnPacketAckedCC
remove_from_in_flight(m);
struct q_conn * const c = m->pn->c;
if (in_cong_recovery(c, m->t))
return;
// TODO: IsAppLimited check
if (c->rec.cur.cwnd < c->rec.cur.ssthresh)
c->rec.cur.cwnd += m->udp_len;
else
c->rec.cur.cwnd += (kMaxDatagramSize * m->udp_len) / c->rec.cur.cwnd;
}
void on_pkt_acked(struct w_iov * const v, struct pkt_meta * m)
{
// see OnPacketAcked() pseudo code
struct pn_space * const pn = m->pn;
struct q_conn * const c = pn->c;
if (m->in_flight && m->lost == false)
on_pkt_acked_cc(m);
diet_insert(&pn->acked_or_lost, m->hdr.nr, 0);
pm_by_nr_del(&pn->sent_pkts, m);
// rest of function is not from pseudo code
// stop ACK'ing packets contained in the ACK frame of this packet
if (has_frm(m->frms, FRM_ACK))
track_acked_pkts(v, m);
struct pkt_meta * const m_rtx = sl_first(&m->rtx);
if (unlikely(m_rtx)) {
// this ACKs a pkt with prior or later RTXs
if (m->has_rtx) {
// this ACKs a pkt that was since (again) RTX'ed
warn(DBG, "%s %s pkt " FMT_PNR_OUT " was RTX'ed as " FMT_PNR_OUT,
conn_type(c), pkt_type_str(m->hdr.flags, &m->hdr.vers),
m->hdr.nr, m_rtx->hdr.nr);
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG))
ensure(sl_next(m_rtx, rtx_next) == 0, "RTX chain corrupt");
#endif
if (m_rtx->acked == false) {
// treat RTX'ed data as ACK'ed; use stand-in w_iov for RTX info
const uint_t acked_nr = m->hdr.nr;
pm_by_nr_del(&pn->sent_pkts, m_rtx);
m->hdr.nr = m_rtx->hdr.nr;
m_rtx->hdr.nr = acked_nr;
const uint16_t acked_udp_len = m->udp_len;
m->udp_len = m_rtx->udp_len;
m_rtx->udp_len = acked_udp_len;
pm_by_nr_ins(&pn->sent_pkts, m);
m = m_rtx;
// XXX caller will not be aware that we mucked around with m!
}
} else {
// this ACKs the last ("real") RTX of a packet
warn(CRT, "pkt nr=%" PRIu " was earlier TX'ed as %" PRIu,
has_pkt_nr(m->hdr.flags, m->hdr.vers) ? m->hdr.nr : 0,
has_pkt_nr(m_rtx->hdr.flags, m_rtx->hdr.vers) ? m_rtx->hdr.nr
: 0);
}
}
m->acked = true;
struct q_stream * const s = m->strm;
if (s && m->has_rtx == false) {
// if this ACKs its stream's out_una, move that forward
struct w_iov * tmp;
sq_foreach_from_safe (s->out_una, &s->out, next, tmp) {
struct pkt_meta * const mou = &meta(s->out_una);
if (mou->acked == false)
break;
// if this ACKs a crypto packet, we can free it
if (unlikely(s->id < 0 && mou->lost == false)) {
sq_remove(&s->out, s->out_una, w_iov, next);
free_iov(s->out_una, mou);
}
}
if (s->id >= 0 && s->out_una == 0) {
if (unlikely(m->is_fin || c->did_0rtt)) {
// this ACKs a FIN
c->have_new_data = true;
strm_to_state(s, s->state == strm_hcrm ? strm_clsd : strm_hclo);
}
if (c->did_0rtt)
maybe_api_return(q_connect, c, 0);
}
} else
free_iov(v, m);
}
void init_rec(struct q_conn * const c)
{
if (timeout_pending(&c->rec.ld_alarm))
timeouts_del(ped(c->w)->wheel, &c->rec.ld_alarm);
c->rec.cur = (struct cc_state){
.cwnd = kInitialWindow, .ssthresh = UINT_T_MAX, .min_rtt = UINT_T_MAX};
c->rec.prev = c->rec.cur;
timeout_setcb(&c->rec.ld_alarm, on_ld_timeout, c);
}
|
jlaine/quant
|
lib/src/stream.c
|
<reponame>jlaine/quant
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <quant/quant.h>
#include "conn.h"
#include "diet.h"
#include "pkt.h"
#include "quic.h"
#include "stream.h"
#ifndef NO_OOO_DATA
SPLAY_GENERATE(ooo_by_off, pkt_meta, off_node, ooo_by_off_cmp)
#endif
#undef STRM_STATE
#define STRM_STATE(k, v) [v] = #k
const char * const strm_state_str[] = {STRM_STATES};
struct q_stream * get_stream(struct q_conn * const c, const dint_t id)
{
const khiter_t k = kh_get(strms_by_id, &c->strms_by_id, (khint64_t)id);
if (unlikely(k == kh_end(&c->strms_by_id)))
return 0;
return kh_val(&c->strms_by_id, k);
}
dint_t max_sid(const dint_t sid, const struct q_conn * const c)
{
const uint_t max =
is_srv_ini(sid) == c->is_clnt
? (is_uni(sid) ? c->tp_in.max_strms_uni : c->tp_in.max_strms_bidi)
: (is_uni(sid) ? c->tp_out.max_strms_uni
: c->tp_out.max_strms_bidi);
return unlikely(max == 0)
? 0
: (dint_t)((max - 1) << 2) | ((STRM_FL_SRV | STRM_FL_UNI) & sid);
}
void apply_stream_limits(struct q_stream * const s)
{
struct q_conn * const c = s->c;
s->in_data_max = is_srv_ini(s->id) == c->is_clnt
? (is_uni(s->id) ? c->tp_in.max_strm_data_uni
: c->tp_in.max_strm_data_bidi_remote)
: (is_uni(s->id) ? c->tp_in.max_strm_data_uni
: c->tp_in.max_strm_data_bidi_local);
s->out_data_max =
is_srv_ini(s->id) == c->is_clnt
? (is_uni(s->id) ? c->tp_out.max_strm_data_uni
: c->tp_out.max_strm_data_bidi_remote)
: (is_uni(s->id) ? c->tp_out.max_strm_data_uni
: c->tp_out.max_strm_data_bidi_local);
if (s->id >= 0)
do_stream_fc(s, 0);
}
struct q_stream * new_stream(struct q_conn * const c, const dint_t id)
{
struct q_stream * const s = calloc(1, sizeof(*s));
ensure(s, "could not calloc q_stream");
sq_init(&s->out);
sq_init(&s->in);
s->c = c;
s->id = id;
strm_to_state(s, strm_open);
if (unlikely(id < 0)) {
c->cstrms[strm_epoch(s)] = s;
return s;
}
int ret;
const khiter_t k =
kh_put(strms_by_id, &c->strms_by_id, (khint64_t)id, &ret);
ensure(ret >= 1, "inserted");
kh_val(&c->strms_by_id, k) = s;
apply_stream_limits(s);
const bool is_local = (is_srv_ini(id) != c->is_clnt);
const uint_t cnt = (uint_t)((id >> 2) + 1);
if (is_local) {
if (is_uni(id)) {
c->cnt_uni = MAX(cnt, c->cnt_uni);
c->next_sid_uni += 4;
} else {
c->next_sid_bidi += 4;
c->cnt_bidi = MAX(cnt, c->cnt_bidi);
}
}
do_stream_id_fc(c, cnt, !is_uni(id), is_local);
return s;
}
void free_stream(struct q_stream * const s)
{
struct q_conn * const c = s->c;
if (likely(s->id >= 0)) {
#ifndef FUZZING
mk_cid_str(DBG, c->scid, scid_str);
warn(DBG, "freeing strm " FMT_SID " on %s conn %s", s->id, conn_type(c),
scid_str);
#endif
diet_insert(&c->clsd_strms, (uint_t)s->id, 0);
const khiter_t k =
kh_get(strms_by_id, &c->strms_by_id, (khint64_t)s->id);
ensure(k != kh_end(&c->strms_by_id), "found");
kh_del(strms_by_id, &c->strms_by_id, k);
} else
s->c->cstrms[strm_epoch(s)] = 0;
#ifndef NO_OOO_DATA
while (!splay_empty(&s->in_ooo)) {
struct pkt_meta * const p = splay_min(ooo_by_off, &s->in_ooo);
ensure(splay_remove(ooo_by_off, &s->in_ooo, p), "removed");
free_iov(w_iov(c->w, pm_idx(c->w, p)), p);
}
#endif
q_free(&s->out);
q_free(&s->in);
free(s);
}
void track_bytes_in(struct q_stream * const s, const uint_t n)
{
if (likely(s->id >= 0))
// crypto "streams" don't count
s->c->in_data_str += n;
s->in_data += n;
}
void track_bytes_out(struct q_stream * const s, const uint_t n)
{
if (likely(s->id >= 0))
// crypto "streams" don't count
s->c->out_data_str += n;
s->out_data += n;
}
void reset_stream(struct q_stream * const s, const bool forget)
{
#ifdef DEBUG_STREAMS
mk_cid_str(DBG, s->c->scid, scid_str);
warn(DBG, "reset strm %u " FMT_SID " on %s conn %s", forget, s->id,
conn_type(s->c), scid_str);
#endif
// reset stream offsets and other data
s->lost_cnt = s->in_data_off = s->in_data = s->out_data = 0;
if (forget) {
s->out_una = 0;
q_free(&s->out);
q_free(&s->in);
return;
}
struct w_iov * v = s->out_una;
sq_foreach_from (v, &s->out, next) {
struct pkt_meta * const m = &meta(v);
if (m->pn)
// remove trailing padding
v->len = m->strm_data_len;
// don't reset stream-data-related fields
// TODO: redo this with offsetof magic
const bool fin = m->is_fin;
const uint16_t shp = m->strm_frm_pos;
const uint16_t sds = m->strm_data_pos;
const uint16_t sdl = m->strm_data_len;
memset(m, 0, sizeof(*m));
m->is_fin = fin;
m->strm_frm_pos = shp;
m->strm_data_pos = sds;
m->strm_data_len = sdl;
}
}
void do_stream_fc(struct q_stream * const s, const uint16_t len)
{
s->blocked = (s->out_data + len + MAX_PKT_LEN > s->out_data_max);
if (s->in_data * 2 > s->in_data_max) {
s->tx_max_strm_data = true;
s->in_data_max *= 2;
}
need_ctrl_update(s);
}
void do_stream_id_fc(struct q_conn * const c,
const uint_t cnt,
const bool bidi,
const bool local)
{
if (local) {
// this is a local stream
if (bidi)
c->sid_blocked_bidi = (cnt == c->tp_out.max_strms_bidi);
else
c->sid_blocked_uni =
(c->tp_out.max_strms_uni && cnt == c->tp_out.max_strms_uni);
return;
}
// this is a remote stream
if (bidi) {
if (cnt == c->tp_in.max_strms_bidi) {
c->tx_max_sid_bidi = true;
c->tp_in.max_strms_bidi *= 2;
}
} else {
if (cnt == c->tp_in.max_strms_uni) {
c->tx_max_sid_uni = true;
c->tp_in.max_strms_uni *= 2;
}
}
}
void concat_out(struct q_stream * const s, struct w_iov_sq * const q)
{
if (s->out_una == 0)
s->out_una = sq_first(q);
sq_concat(&s->out, q);
}
bool q_is_uni_stream(const struct q_stream * const s)
{
return is_uni(s->id);
}
|
jlaine/quant
|
lib/src/conn.c
|
<gh_stars>0
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <inttypes.h>
#include <netdb.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#ifndef NO_ERR_REASONS
#include <stdarg.h>
#endif
#ifndef PARTICLE
#include <netinet/in.h>
#include <netinet/ip.h>
#endif
// IWYU pragma: no_include <picotls/../picotls.h>
#include <picotls.h> // IWYU pragma: keep
#include <quant/quant.h>
#include <timeout.h>
#include "bitset.h"
#include "conn.h"
#include "diet.h"
#include "frame.h"
#include "loop.h"
#include "marshall.h"
#include "pkt.h"
#include "pn.h"
#include "qlog.h"
#include "quic.h"
#include "recovery.h"
#include "stream.h"
#include "tls.h"
#undef CONN_STATE
#define CONN_STATE(k, v) [v] = #k
const char * const conn_state_str[] = {CONN_STATES};
struct q_conn_sl c_ready = sl_head_initializer(c_ready);
khash_t(conns_by_ipnp) conns_by_ipnp = {0};
khash_t(conns_by_id) conns_by_id = {0};
khash_t(conns_by_srt) conns_by_srt = {0};
static inline __attribute__((const)) bool is_vneg_vers(const uint32_t vers)
{
return (vers & 0x0f0f0f0f) == 0x0a0a0a0a;
}
static inline __attribute__((const)) bool is_draft_vers(const uint32_t vers)
{
return (vers & 0xff000000) == 0xff000000;
}
static inline int __attribute__((nonnull))
sockaddr_cmp(const struct sockaddr * const a, const struct sockaddr * const b)
{
int diff = (a->sa_family > b->sa_family) - (a->sa_family < b->sa_family);
if (diff)
return diff;
switch (a->sa_family) {
case AF_INET:;
const struct sockaddr_in * const a4 =
(const struct sockaddr_in *)(const void *)a;
const struct sockaddr_in * const b4 =
(const struct sockaddr_in *)(const void *)b;
diff = (a4->sin_port > b4->sin_port) - (a4->sin_port < b4->sin_port);
if (diff)
return diff;
return (a4->sin_addr.s_addr > b4->sin_addr.s_addr) -
(a4->sin_addr.s_addr < b4->sin_addr.s_addr);
default:
#ifndef FUZZING
die("unsupported address family");
#ifdef PARTICLE
return 0; // old gcc doesn't seem to understand "noreturn" attribute
#endif
#else
return memcmp(a->sa_data, b->sa_data, sizeof(a->sa_data));
#endif
}
}
#ifndef NO_MIGRATION
SPLAY_GENERATE(cids_by_seq, cid, node_seq, cids_by_seq_cmp)
#endif
static bool __attribute__((const)) vers_supported(const uint32_t v)
{
if (is_vneg_vers(v))
return false;
for (uint8_t i = 0; i < ok_vers_len; i++)
if (v == ok_vers[i])
return true;
// we're out of matching candidates
warn(INF, "no vers in common");
return false;
}
static uint32_t __attribute__((nonnull))
clnt_vneg(const uint8_t * const pos, const uint8_t * const end)
{
for (uint8_t i = 0; i < ok_vers_len; i++) {
if (is_vneg_vers(ok_vers[i]))
continue;
const uint8_t * p = pos;
while (p + sizeof(ok_vers[0]) <= end) {
uint32_t vers = 0;
dec4(&vers, &p, end);
if (is_vneg_vers(vers))
continue;
#ifdef DEBUG_EXTRA
warn(DBG,
"serv prio %ld = 0x%0" PRIx32 "; our prio %u = 0x%0" PRIx32,
(unsigned long)(p - pos) / sizeof(vers), vers, i, ok_vers[i]);
#endif
if (ok_vers[i] == vers)
return vers;
}
}
// we're out of matching candidates
warn(INF, "no vers in common with serv");
return 0;
}
#ifndef NO_OOO_0RTT
struct ooo_0rtt_by_cid ooo_0rtt_by_cid = splay_initializer(&ooo_0rtt_by_cid);
SPLAY_GENERATE(ooo_0rtt_by_cid, ooo_0rtt, node, ooo_0rtt_by_cid_cmp)
#endif
static inline epoch_t __attribute__((nonnull))
epoch_in(const struct q_conn * const c)
{
const size_t epoch = ptls_get_read_epoch(c->tls.t);
ensure(epoch <= ep_data, "unhandled epoch %lu", (unsigned long)epoch);
return (epoch_t)epoch;
}
static struct q_conn * __attribute__((nonnull))
get_conn_by_ipnp(const struct sockaddr * const src,
const struct sockaddr * const dst)
{
const khiter_t k = kh_get(conns_by_ipnp, &conns_by_ipnp,
(khint64_t)conns_by_ipnp_key(src, dst));
if (unlikely(k == kh_end(&conns_by_ipnp)))
return 0;
return kh_val(&conns_by_ipnp, k);
}
static struct q_conn * __attribute__((nonnull))
get_conn_by_cid(struct cid * const scid)
{
const khiter_t k = kh_get(conns_by_id, &conns_by_id, scid);
if (unlikely(k == kh_end(&conns_by_id)))
return 0;
return kh_val(&conns_by_id, k);
}
struct q_conn * get_conn_by_srt(uint8_t * const srt)
{
const khiter_t k = kh_get(conns_by_srt, &conns_by_srt, srt);
if (unlikely(k == kh_end(&conns_by_srt)))
return 0;
return kh_val(&conns_by_srt, k);
}
#ifndef NO_MIGRATION
static inline void __attribute__((nonnull))
cids_by_id_ins(khash_t(cids_by_id) * const cbi, struct cid * const id)
{
int ret;
const khiter_t k = kh_put(cids_by_id, cbi, id, &ret);
ensure(ret >= 1, "inserted returned %d", ret);
kh_val(cbi, k) = id;
}
static inline void __attribute__((nonnull))
cids_by_id_del(khash_t(cids_by_id) * const cbi, struct cid * const id)
{
const khiter_t k = kh_get(cids_by_id, cbi, id);
ensure(k != kh_end(cbi), "found");
kh_del(cids_by_id, cbi, k);
}
static struct cid * __attribute__((nonnull))
get_cid_by_id(const khash_t(cids_by_id) * const cbi, struct cid * const id)
{
const khiter_t k = kh_get(cids_by_id, cbi, id);
if (unlikely(k == kh_end(cbi)))
return 0;
return kh_val(cbi, k);
}
void use_next_dcid(struct q_conn * const c)
{
struct cid * const dcid =
splay_next(cids_by_seq, &c->dcids_by_seq, c->dcid);
ensure(dcid, "can't switch from dcid %" PRIu, c->dcid->seq);
mk_cid_str(NTE, dcid, dcid_str_new);
mk_cid_str(NTE, c->dcid, dcid_str_prev);
warn(NTE, "migration to dcid %s for %s conn (was %s)", dcid_str_new,
conn_type(c), dcid_str_prev);
if (c->spin_enabled)
c->spin = 0; // need to reset spin value
c->tx_retire_cid = c->dcid->retired = true;
c->dcid = dcid;
}
#endif
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG))
static void __attribute__((nonnull)) log_sent_pkts(struct q_conn * const c)
{
for (pn_t t = pn_init; t <= pn_data; t++) {
struct pn_space * const pn = &c->pns[t];
if (pn->abandoned)
continue;
struct diet unacked = diet_initializer(unacked);
struct pkt_meta * m;
kh_foreach_value(&pn->sent_pkts, m,
diet_insert(&unacked, m->hdr.nr, 0));
#ifndef PARTICLE
char buf[512];
#else
char buf[64];
#endif
int pos = 0;
struct ival * i = 0;
diet_foreach (i, diet, &unacked) {
if ((size_t)pos >= sizeof(buf)) {
buf[sizeof(buf) - 2] = buf[sizeof(buf) - 3] =
buf[sizeof(buf) - 4] = '.';
buf[sizeof(buf) - 1] = 0;
break;
}
if (i->lo == i->hi)
pos += snprintf(&buf[pos], sizeof(buf) - (size_t)pos,
FMT_PNR_OUT "%s", i->lo,
splay_next(diet, &unacked, i) ? ", " : "");
else
pos += snprintf(&buf[pos], sizeof(buf) - (size_t)pos,
FMT_PNR_OUT ".." FMT_PNR_OUT "%s", i->lo, i->hi,
splay_next(diet, &unacked, i) ? ", " : "");
}
diet_free(&unacked);
if (pos)
warn(INF, "%s %s unacked: %s", conn_type(c), pn_type_str(t), buf);
}
}
#else
#define log_sent_pkts(...)
#endif
static void __attribute__((nonnull))
rtx_pkt(struct w_iov * const v, struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
c->i.pkts_out_rtx++;
if (m->lost)
// we don't need to do the steps below if the pkt is lost already
return;
// on RTX, remember orig pkt meta data
const uint16_t data_start = m->strm_data_pos;
struct pkt_meta * m_orig;
struct w_iov * const v_orig = alloc_iov(c->w, 0, data_start, &m_orig);
pm_cpy(m_orig, m, true);
memcpy(v_orig->buf - data_start, v->buf - data_start, data_start);
m_orig->has_rtx = true;
sl_insert_head(&m->rtx, m_orig, rtx_next);
sl_insert_head(&m_orig->rtx, m, rtx_next);
pm_by_nr_del(&m->pn->sent_pkts, m);
// we reinsert m with its new pkt nr in on_pkt_sent()
pm_by_nr_ins(&m_orig->pn->sent_pkts, m_orig);
}
static void __attribute__((nonnull)) mk_rand_cid(struct cid * const cid)
{
cid->len = 8 + (uint8_t)w_rand_uniform32(CID_LEN_MAX - 7);
rand_bytes(cid->id, sizeof(cid->id) + sizeof(cid->srt));
}
static void __attribute__((nonnull))
tx_vneg_resp(const struct w_sock * const ws,
const struct w_iov * const v,
struct pkt_meta * const m)
{
struct pkt_meta * mx;
struct w_iov * const xv = alloc_iov(ws->w, 0, 0, &mx);
struct w_iov_sq q = w_iov_sq_initializer(q);
sq_insert_head(&q, xv, next);
warn(INF, "sending vneg serv response");
mx->hdr.flags = HEAD_FORM | (uint8_t)w_rand_uniform32(UINT8_MAX);
uint8_t * pos = xv->buf;
const uint8_t * end = xv->buf + xv->len;
enc1(&pos, end, mx->hdr.flags);
enc4(&pos, end, mx->hdr.vers);
enc_lh_cids(&pos, end, mx, &m->hdr.scid, &m->hdr.dcid);
for (uint8_t j = 0; j < ok_vers_len; j++)
if (!is_vneg_vers(ok_vers[j]))
enc4(&pos, end, ok_vers[j]);
mx->udp_len = xv->len = (uint16_t)(pos - xv->buf);
xv->addr = v->addr;
xv->flags = v->flags;
log_pkt("TX", xv, (struct sockaddr *)&xv->addr, 0, 0, 0);
struct cid gid;
mk_rand_cid(&gid);
qlog_transport(pkt_tx, "DEFAULT", xv, mx, &gid);
#ifndef FUZZING
w_tx(ws, &q);
while (w_tx_pending(&q))
w_nic_tx(ws->w);
#endif
q_free(&q);
}
static void __attribute__((nonnull)) do_tx(struct q_conn * const c)
{
// do it here instead of in on_pkt_sent()
set_ld_timer(c);
log_cc(c);
c->needs_tx = false;
if (unlikely(sq_empty(&c->txq)))
return;
c->i.pkts_out += sq_len(&c->txq);
if (sq_len(&c->txq) > 1 && unlikely(is_lh(*sq_first(&c->txq)->buf)))
coalesce(&c->txq);
#ifndef FUZZING
// transmit encrypted/protected packets
w_tx(c->sock, &c->txq);
do
w_nic_tx(c->w);
while (w_tx_pending(&c->txq));
#endif
#if defined(DEBUG_BUFFERS) && (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG))
const uint_t avail = sq_len(&c->w->iov);
const uint_t sql = sq_len(&c->txq);
#endif
// txq was allocated straight from warpcore, no metadata needs to be freed
w_free(&c->txq);
#ifdef DEBUG_BUFFERS
warn(DBG, "w_free %" PRIu " (avail %" PRIu "->%" PRIu ")", sql, avail,
sq_len(&c->w->iov));
#endif
log_sent_pkts(c);
}
static void __attribute__((nonnull))
restart_key_flip_alarm(struct q_conn * const c)
{
const timeout_t t = c->tls_key_update_frequency * NS_PER_S;
#ifdef DEBUG_TIMERS
warn(DBG, "next key flip alarm in %f sec", t / (double)NS_PER_S);
#endif
timeouts_add(ped(c->w)->wheel, &c->key_flip_alarm, t);
}
void do_conn_fc(struct q_conn * const c, const uint16_t len)
{
if (unlikely(c->state == conn_clsg || c->state == conn_drng))
return;
if (len && c->out_data_str + len + MAX_PKT_LEN > c->tp_out.max_data)
c->blocked = true;
// check if we need to do connection-level flow control
if (c->in_data_str * 2 > c->tp_in.max_data) {
c->tx_max_data = true;
c->tp_in.max_data *= 2;
}
}
static void __attribute__((nonnull)) do_conn_mgmt(struct q_conn * const c)
{
if (c->state == conn_clsg || c->state == conn_drng)
return;
// do we need to make more stream IDs available?
if (likely(c->state == conn_estb)) {
do_stream_id_fc(c, c->cnt_uni, false, true);
do_stream_id_fc(c, c->cnt_bidi, true, true);
}
#ifndef NO_MIGRATION
if (likely(c->tp_out.disable_migration == false) &&
unlikely(c->do_migration == true) && c->scid) {
if (splay_count(&c->scids_by_seq) >= 2) {
// the peer has a CID for us that they can switch to
const struct cid * const dcid =
splay_max(cids_by_seq, &c->dcids_by_seq);
// if higher-numbered destination CIDs are available, switch to next
if (dcid && dcid->seq > c->dcid->seq) {
use_next_dcid(c);
// don't migrate again for a while
c->do_migration = false;
restart_key_flip_alarm(c);
}
}
// send new CIDs if the peer doesn't have sufficient remaining
c->tx_ncid = needs_more_ncids(c);
}
#endif
}
static bool __attribute__((nonnull)) tx_stream(struct q_stream * const s)
{
struct q_conn * const c = s->c;
const bool has_data = (sq_len(&s->out) && out_fully_acked(s) == false);
#ifdef DEBUG_STREAMS
warn(ERR,
"%s strm id=" FMT_SID ", cnt=%" PRIu
", has_data=%u, needs_ctrl=%u, blocked=%u, lost_cnt=%" PRIu
", fully_acked=%u, "
"limit=%" PRIu32,
conn_type(c), s->id, sq_len(&s->out), has_data, needs_ctrl(s),
s->blocked, s->lost_cnt, out_fully_acked(s), c->tx_limit);
#endif
// check if we should skip TX on this stream
if (has_data == false || (s->blocked && s->lost_cnt == 0) ||
// unless for 0-RTT, is this a regular stream during conn open?
unlikely(c->try_0rtt == false && s->id >= 0 && c->state != conn_estb)) {
#ifdef DEBUG_STREAMS
warn(ERR, "skip " FMT_SID " %u %u", s->id, c->try_0rtt, c->state);
#endif
return true;
}
#ifdef DEBUG_STREAMS
mk_cid_str(INF, c->scid, scid_str);
warn(INF, "TX on %s conn %s strm " FMT_SID " w/%" PRIu " pkt%s in queue ",
conn_type(c), scid_str, s->id, sq_len(&s->out),
plural(sq_len(&s->out)));
#endif
uint32_t encoded = 0;
struct w_iov * v = s->out_una;
sq_foreach_from (v, &s->out, next) {
struct pkt_meta * const m = &meta(v);
if (unlikely(has_wnd(c, v->len) == false && c->tx_limit == 0)) {
c->no_wnd = true;
break;
}
if (unlikely(m->acked)) {
#ifdef DEBUG_EXTRA
warn(INF, "skip ACK'ed pkt " FMT_PNR_OUT, m->hdr.nr);
#endif
continue;
}
if (c->tx_limit == 0 && m->txed && m->lost == false) {
#ifdef DEBUG_EXTRA
warn(INF, "skip non-lost TX'ed pkt " FMT_PNR_OUT, m->hdr.nr);
#endif
continue;
}
if (likely(c->state == conn_estb && s->id >= 0)) {
do_stream_fc(s, v->len);
do_conn_fc(c, v->len);
}
const bool do_rtx = m->lost || (c->tx_limit && m->txed);
if (unlikely(do_rtx))
rtx_pkt(v, m);
if (unlikely(enc_pkt(s, do_rtx, true, c->tx_limit > 0, v, m) == false))
continue;
encoded++;
if (unlikely(s->blocked || c->blocked))
break;
if (unlikely(c->tx_limit && encoded == c->tx_limit)) {
#ifdef DEBUG_STREAMS
warn(INF, "tx limit %" PRIu32 " reached", c->tx_limit);
#endif
break;
}
}
return (unlikely(c->tx_limit) && encoded == c->tx_limit) ||
c->no_wnd == false;
}
static bool __attribute__((nonnull))
tx_ack(struct q_conn * const c, const epoch_t e, const bool tx_ack_eliciting)
{
do_conn_mgmt(c);
if (unlikely(c->cstrms[e] == 0))
return false;
struct pkt_meta * m;
struct w_iov * const v = alloc_iov(c->w, 0, 0, &m);
return enc_pkt(c->cstrms[e], false, false, tx_ack_eliciting, v, m);
}
void tx(struct q_conn * const c)
{
timeouts_del(ped(c->w)->wheel, &c->tx_w);
if (unlikely(c->state == conn_drng))
return;
if (unlikely(c->state == conn_qlse)) {
enter_closing(c);
tx_ack(c, epoch_in(c), false);
goto done;
}
if (unlikely(c->tx_rtry)) {
tx_ack(c, ep_init, false);
goto done;
}
if (unlikely(c->state == conn_opng) && c->is_clnt && c->try_0rtt &&
c->pns[pn_data].data.out_0rtt.aead == 0) {
// if we have no 0-rtt keys here, the ticket didn't have any - disable
warn(NTE, "TLS ticket w/o 0-RTT keys, disabling 0-RTT");
c->try_0rtt = false;
}
if (unlikely(c->blocked))
goto done;
do_conn_mgmt(c);
if (likely(c->state != conn_clsg))
for (epoch_t e = ep_init; e <= ep_data; e++) {
if (c->cstrms[e] == 0)
continue;
if (tx_stream(c->cstrms[e]) == false)
goto done;
}
struct q_stream * s;
kh_foreach_value(&c->strms_by_id, s, {
if (tx_stream(s) == false)
break;
});
done:;
// make sure we sent enough packets when we have a TX limit
uint_t sent = sq_len(&c->txq);
while ((unlikely(c->tx_limit) && sent < c->tx_limit) ||
(c->needs_tx && sent == 0)) {
if (likely(tx_ack(c, epoch_in(c), c->tx_limit && sent < c->tx_limit)))
sent++;
else {
warn(WRN, "no ACK sent");
break;
}
}
if (likely(sent))
do_tx(c);
}
void conns_by_srt_ins(struct q_conn * const c, uint8_t * const srt)
{
int ret;
const khiter_t k = kh_put(conns_by_srt, &conns_by_srt, srt, &ret);
if (unlikely(ret == 0)) {
if (kh_val(&conns_by_srt, k) != c)
die("srt already in use by different conn ");
else {
mk_srt_str(WRN, srt, srt_str);
warn(WRN, "srt %s already used for conn", srt_str);
return;
}
}
kh_val(&conns_by_srt, k) = c;
}
static inline void __attribute__((nonnull))
conns_by_srt_del(uint8_t * const srt)
{
const khiter_t k = kh_get(conns_by_srt, &conns_by_srt, srt);
if (likely(k != kh_end(&conns_by_srt)))
// if peer is reusing SRTs w/different CIDs, it may already be deleted
kh_del(conns_by_srt, &conns_by_srt, k);
}
static inline void __attribute__((nonnull))
conns_by_id_ins(struct q_conn * const c, struct cid * const id)
{
int ret;
const khiter_t k = kh_put(conns_by_id, &conns_by_id, id, &ret);
ensure(ret >= 1, "inserted returned %d", ret);
kh_val(&conns_by_id, k) = c;
}
static inline void __attribute__((nonnull))
conns_by_id_del(struct cid * const id)
{
const khiter_t k = kh_get(conns_by_id, &conns_by_id, id);
ensure(k != kh_end(&conns_by_id), "found");
kh_del(conns_by_id, &conns_by_id, k);
}
static void __attribute__((nonnull)) update_act_scid(struct q_conn * const c)
{
// server picks a new random cid
struct cid nscid = {.len = SCID_LEN_SERV, .has_srt = true};
rand_bytes(nscid.id, sizeof(nscid.id) + sizeof(nscid.srt));
cid_cpy(&c->odcid, c->scid);
mk_cid_str(NTE, &nscid, nscid_str);
mk_cid_str(NTE, c->scid, scid_str);
warn(NTE, "hshk switch to scid %s for %s %s conn (was %s)", nscid_str,
conn_state_str[c->state], conn_type(c), scid_str);
conns_by_id_del(c->scid);
#ifndef NO_MIGRATION
cids_by_id_del(&c->scids_by_id, c->scid);
#endif
cid_cpy(c->scid, &nscid);
#ifndef NO_MIGRATION
cids_by_id_ins(&c->scids_by_id, c->scid);
#endif
conns_by_id_ins(c, c->scid);
// we need to keep accepting the client-chosen odcid for 0-RTT pkts
#ifndef NO_MIGRATION
cids_by_id_ins(&c->scids_by_id, &c->odcid);
#endif
conns_by_id_ins(c, &c->odcid);
}
void add_scid(struct q_conn * const c, struct cid * const id)
{
struct cid * const scid = calloc(1, sizeof(*scid));
ensure(scid, "could not calloc");
cid_cpy(scid, id);
#ifndef NO_MIGRATION
ensure(splay_insert(cids_by_seq, &c->scids_by_seq, scid) == 0, "inserted");
cids_by_id_ins(&c->scids_by_id, scid);
#endif
if (c->scid == 0)
c->scid = scid;
conns_by_id_ins(c, scid);
}
void add_dcid(struct q_conn * const c, const struct cid * const id)
{
struct cid * dcid =
#ifndef NO_MIGRATION
splay_find(cids_by_seq, &c->dcids_by_seq, id);
#else
c->dcid;
#endif
if (dcid == 0) {
dcid = calloc(1, sizeof(*dcid));
ensure(dcid, "could not calloc");
if (c->dcid == 0)
c->dcid = dcid;
} else {
mk_cid_str(NTE, id, dcid_str_new);
mk_cid_str(NTE, c->dcid, dcid_str_prev);
warn(NTE, "hshk switch to dcid %s for %s conn (was %s)", dcid_str_new,
conn_type(c), dcid_str_prev);
#ifndef NO_MIGRATION
ensure(splay_remove(cids_by_seq, &c->dcids_by_seq, dcid), "removed");
#endif
if (dcid->has_srt)
conns_by_srt_del(dcid->srt);
}
cid_cpy(dcid, id);
if (id->has_srt)
conns_by_srt_ins(c, dcid->srt);
#ifndef NO_MIGRATION
ensure(splay_insert(cids_by_seq, &c->dcids_by_seq, dcid) == 0, "inserted");
#endif
}
static void __attribute__((nonnull))
rx_crypto(struct q_conn * const c, const struct pkt_meta * const m_cur)
{
struct q_stream * const s = c->cstrms[epoch_in(c)];
while (!sq_empty(&s->in)) {
// take the data out of the crypto stream
struct w_iov * const v = sq_first(&s->in);
sq_remove_head(&s->in, next);
// ooo crypto pkts have stream cleared by dec_stream_or_crypto_frame()
struct pkt_meta * const m = &meta(v);
const bool free_ooo = m->strm == 0;
// mark this (potential in-order) pkt for freeing in rx_pkts()
m->strm = 0;
const int ret = tls_io(s, v);
if (free_ooo && m != m_cur)
free_iov(v, m);
if (ret)
continue;
if (c->state == conn_idle || c->state == conn_opng) {
conn_to_state(c, conn_estb);
if (c->is_clnt)
maybe_api_return(q_connect, c, 0);
else {
// TODO: find a better way to send NEW_TOKEN
make_rtry_tok(c);
if (c->needs_accept == false) {
sl_insert_head(&accept_queue, c, node_aq);
c->needs_accept = true;
}
maybe_api_return(q_accept, 0, 0);
}
}
}
}
static void __attribute__((nonnull)) free_cids(struct q_conn * const c)
{
if (c->is_clnt == false && c->odcid.len) {
// TODO: we should stop accepting pkts on the client odcid earlier
#ifndef NO_MIGRATION
cids_by_id_del(&c->scids_by_id, &c->odcid);
#endif
conns_by_id_del(&c->odcid);
}
if (c->scid == 0)
conns_by_ipnp_del(c);
#ifndef NO_MIGRATION
while (!splay_empty(&c->scids_by_seq)) {
struct cid * const id = splay_min(cids_by_seq, &c->scids_by_seq);
free_scid(c, id);
}
while (!splay_empty(&c->dcids_by_seq)) {
struct cid * const id = splay_min(cids_by_seq, &c->dcids_by_seq);
free_dcid(c, id);
}
#else
if (c->scid)
free_scid(c, c->scid);
if (c->dcid)
free_dcid(c, c->dcid);
#endif
c->scid = c->dcid = 0;
}
static void __attribute__((nonnull(1))) new_cids(struct q_conn * const c,
const bool zero_len_scid,
const struct cid * const dcid,
const struct cid * const scid)
{
// init dcid
if (c->is_clnt) {
struct cid ndcid;
mk_rand_cid(&ndcid);
cid_cpy(&c->odcid, &ndcid);
add_dcid(c, &ndcid);
} else if (dcid)
add_dcid(c, dcid);
// init scid and add connection to global data structures
struct cid nscid = {0};
if (c->is_clnt) {
nscid.len = zero_len_scid ? 0 : SCID_LEN_CLNT;
if (nscid.len)
rand_bytes(nscid.id, sizeof(nscid.id) + sizeof(nscid.srt));
} else if (scid) {
cid_cpy(&nscid, scid);
if (nscid.has_srt == false) {
rand_bytes(nscid.srt, sizeof(nscid.srt));
nscid.has_srt = true;
}
}
if (nscid.len)
add_scid(c, &nscid);
else if (c->scid == 0)
conns_by_ipnp_ins(c);
}
static void __attribute__((nonnull))
vneg_or_rtry_resp(struct q_conn * const c, const bool is_vneg)
{
// reset FC state
c->in_data_str = c->out_data_str = 0;
for (epoch_t e = ep_init; e <= ep_data; e++)
if (c->cstrms[e])
reset_stream(c->cstrms[e], true);
struct q_stream * s;
kh_foreach_value(&c->strms_by_id, s, reset_stream(s, false));
// reset packet number spaces
for (pn_t t = pn_init; t <= pn_data; t++)
reset_pn(&c->pns[t]);
if (is_vneg) {
// reset CIDs
const bool zero_len_scid = c->scid == 0;
free_cids(c); // this zeros c->scid
new_cids(c, zero_len_scid, 0, 0);
}
// reset CC state
init_rec(c);
// reset TLS state and create new CH
const bool should_try_0rtt = c->try_0rtt;
init_tls(c, (char *)c->tls.alpn.base);
c->try_0rtt = should_try_0rtt;
tls_io(c->cstrms[ep_init], 0);
}
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
static bool __attribute__((const))
pkt_ok_for_epoch(const uint8_t flags, const epoch_t epoch)
{
switch (epoch) {
case ep_init:
return pkt_type(flags) == LH_INIT || pkt_type(flags) == LH_RTRY;
case ep_0rtt:
case ep_hshk:
return is_lh(flags);
case ep_data:
return true;
}
#ifdef PARTICLE
return false; // old gcc doesn't seem to understand "noreturn" attribute
#endif
}
#endif
static bool __attribute__((nonnull)) rx_pkt(const struct w_sock * const ws,
struct w_iov * v,
struct pkt_meta * m,
struct w_iov_sq * const x
#ifdef NO_OOO_0RTT
__attribute__((unused))
#endif
,
const struct cid * const odcid
#if defined(NDEBUG) && !defined(NDEBUG_WITH_DLOG)
__attribute__((unused))
#endif
,
const uint8_t * const tok,
const uint16_t tok_len)
{
struct q_conn * const c = m->pn->c;
bool ok = false;
log_pkt("RX", v, (struct sockaddr *)&v->addr, odcid, tok, tok_len);
c->in_data += m->udp_len;
switch (c->state) {
case conn_idle:
// this is a new connection
c->vers = m->hdr.vers;
// TODO: remove this interop hack eventually
if (bswap16(get_sport(ws)) == 4434) {
if (m->hdr.type == LH_INIT && tok_len) {
if (verify_rtry_tok(c, tok, tok_len) == false) {
warn(ERR, "retry token verification failed");
enter_closing(c);
goto done;
}
} else {
if (c->tx_rtry) {
warn(DBG, "already tx'ing retry, ignoring");
goto done;
}
warn(INF, "sending retry");
// send a RETRY
make_rtry_tok(c);
ok = true;
c->needs_tx = c->tx_rtry = true;
update_act_scid(c);
goto done;
}
}
#ifdef DEBUG_EXTRA
warn(INF, "supporting clnt-requested vers 0x%0" PRIx32, c->vers);
#endif
if (dec_frames(c, &v, &m) == false)
goto done;
// if the CH doesn't include any crypto frames, bail
if (has_frm(m->frms, FRM_CRY) == false) {
warn(ERR, "initial pkt w/o crypto frames");
enter_closing(c);
goto done;
}
init_tp(c);
#ifndef NO_OOO_0RTT
// check if any reordered 0-RTT packets are cached for this CID
const struct ooo_0rtt which = {.cid = m->hdr.dcid};
struct ooo_0rtt * const zo =
splay_find(ooo_0rtt_by_cid, &ooo_0rtt_by_cid, &which);
if (zo) {
mk_cid_str(INF, c->scid, scid_str);
warn(INF, "have reordered 0-RTT pkt for %s conn %s", conn_type(c),
scid_str);
ensure(splay_remove(ooo_0rtt_by_cid, &ooo_0rtt_by_cid, zo),
"removed");
sq_insert_head(x, zo->v, next);
free(zo);
}
#endif
conn_to_state(c, conn_opng);
// server limits response to 3x incoming pkt
c->path_val_win = 3 * m->udp_len;
// server picks a new random cid
update_act_scid(c);
ok = true;
break;
case conn_opng:
// this state is currently only in effect on the client
if (m->hdr.vers == 0) {
// this is a vneg pkt
m->hdr.nr = UINT_T_MAX;
if (c->vers != ok_vers[0]) {
// we must have already reacted to a prior vneg pkt
warn(INF, "ignoring spurious vneg response");
goto done;
}
// check that the rx'ed CIDs match our tx'ed CIDs
const bool rx_scid_ok = !cid_cmp(&m->hdr.scid, c->dcid);
const bool rxed_dcid_ok =
m->hdr.dcid.len == 0 || !cid_cmp(&m->hdr.dcid, c->scid);
if (rx_scid_ok == false || rxed_dcid_ok == false) {
mk_cid_str(INF, rx_scid_ok ? &m->hdr.dcid : &m->hdr.scid,
cid_str1);
mk_cid_str(INF, rx_scid_ok ? c->scid : c->dcid, cid_str2);
warn(INF, "vneg %ccid mismatch: rx %s != %s",
rx_scid_ok ? 'd' : 's', cid_str1, cid_str2);
enter_closing(c);
goto done;
}
// only do vneg for draft and vneg versions
if (is_vneg_vers(c->vers) == false &&
is_draft_vers(c->vers) == false) {
err_close(c, ERR_PROTOCOL_VIOLATION, 0,
"must not vneg for tx vers 0x%0" PRIx32, c->vers);
goto done;
}
// handle an incoming vneg packet
const uint32_t try_vers =
clnt_vneg(v->buf + m->hdr.hdr_len, v->buf + v->len);
if (try_vers == 0) {
// no version in common with serv
enter_closing(c);
goto done;
}
vneg_or_rtry_resp(c, true);
c->vers = try_vers;
warn(INF,
"serv didn't like vers 0x%0" PRIx32
", retrying with 0x%0" PRIx32 "",
c->vers_initial, c->vers);
ok = true;
goto done;
}
if (unlikely(m->hdr.vers != c->vers)) {
warn(ERR,
"serv response w/vers 0x%0" PRIx32 " to CI w/vers 0x%0" PRIx32
", ignoring",
m->hdr.vers, c->vers);
goto done;
}
if (m->hdr.type == LH_RTRY) {
m->hdr.nr = UINT_T_MAX;
if (c->tok_len) {
// we already had an earlier RETRY on this connection
warn(INF, "already handled a retry, ignoring");
goto done;
}
// handle an incoming retry packet
c->tok_len = tok_len;
memcpy(c->tok, tok, c->tok_len);
vneg_or_rtry_resp(c, false);
mk_tok_str(INF, c->tok, c->tok_len, tok_str);
warn(INF, "handling serv retry w/tok %s", tok_str);
ok = true;
goto done;
}
// server accepted version -
// if we get here, this should be a regular server-hello
ok = dec_frames(c, &v, &m);
break;
case conn_estb:
case conn_qlse:
case conn_clsg:
case conn_drng:
if (is_lh(m->hdr.flags) && m->hdr.vers == 0) {
// we shouldn't get another vneg packet here, ignore
warn(NTE, "ignoring spurious vneg response");
goto done;
}
// ignore 0-RTT packets if we're not doing 0-RTT
if (c->did_0rtt == false && m->hdr.type == LH_0RTT) {
warn(NTE, "ignoring 0-RTT pkt");
goto done;
}
if (dec_frames(c, &v, &m) == false)
goto done;
ok = true;
break;
case conn_clsd:
warn(NTE, "ignoring pkt for closed %s conn", conn_type(c));
break;
}
done:
if (unlikely(ok == false))
return false;
if (likely(m->hdr.nr != UINT_T_MAX)) {
struct pn_space * const pn = pn_for_pkt_type(c, m->hdr.type);
// update ECN info
switch (v->flags & IPTOS_ECN_MASK) {
case IPTOS_ECN_ECT1:
pn->ect1_cnt++;
break;
case IPTOS_ECN_ECT0:
pn->ect0_cnt++;
break;
case IPTOS_ECN_CE:
pn->ce_cnt++;
break;
}
pn->pkts_rxed_since_last_ack_tx++;
}
#ifndef NO_QLOG
// if pkt has STREAM or CRYPTO frame but no strm pointer, it's a dup
static const struct frames qlog_dup_chk =
bitset_t_initializer(1 << FRM_CRY | 1 << FRM_STR);
const bool dup_strm =
bit_overlap(FRM_MAX, &m->frms, &qlog_dup_chk) && m->strm == 0;
qlog_transport(dup_strm ? pkt_dp : pkt_rx, "DEFAULT", v, m, &c->odcid);
#endif
return true;
}
#ifdef FUZZING
void
#else
static void __attribute__((nonnull))
#endif
rx_pkts(struct w_iov_sq * const x,
struct q_conn_sl * const crx,
const struct w_sock * const ws)
{
struct cid outer_dcid = {0};
while (!sq_empty(x)) {
struct w_iov * const xv = sq_first(x);
sq_remove_head(x, next);
#ifdef DEBUG_BUFFERS
warn(DBG, "rx idx %" PRIu32 " (avail %" PRIu ") len %u type 0x%02x",
w_iov_idx(xv), sq_len(&xv->w->iov), xv->len, *xv->buf);
#endif
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
// when called from the fuzzer, v->addr.ss_family is zero
if (xv->addr.ss_family)
write_to_corpus(corpus_pkt_dir, xv->buf, xv->len);
#endif
// allocate new w_iov for the (eventual) unencrypted data and meta-data
struct pkt_meta * m;
struct w_iov * const v = alloc_iov(ws->w, 0, 0, &m);
v->addr = xv->addr;
v->flags = xv->flags;
v->len = xv->len; // this is just so that log_pkt can show the rx len
m->t = loop_now();
bool pkt_valid = false;
const bool is_clnt = w_connected(ws);
struct q_conn * c = 0;
struct q_conn * const c_ipnp = // only our client can use zero-len cids
is_clnt ? get_conn_by_ipnp(w_get_addr(ws, true),
(struct sockaddr *)&v->addr)
: 0;
struct cid odcid = {.len = 0};
uint8_t tok[MAX_TOK_LEN];
uint16_t tok_len = 0;
if (unlikely(!dec_pkt_hdr_beginning(
xv, v, m, is_clnt, &odcid, tok, &tok_len,
is_clnt ? (c_ipnp ? 0 : SCID_LEN_CLNT) : SCID_LEN_SERV))) {
// we might still need to send a vneg packet
if (w_connected(ws) == false) {
if (m->hdr.scid.len == 0 || m->hdr.scid.len >= 4) {
warn(ERR, "received invalid %u-byte %s pkt, sending vneg",
v->len, pkt_type_str(m->hdr.flags, &m->hdr.vers));
tx_vneg_resp(ws, v, m);
} else {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
warn(ERR,
"received invalid %u-byte %s pkt w/invalid scid len "
"%u, ignoring",
v->len, pkt_type_str(m->hdr.flags, &m->hdr.vers),
m->hdr.scid.len);
goto drop;
}
} else
warn(ERR, "received invalid %u-byte %s pkt), ignoring", v->len,
pkt_type_str(m->hdr.flags, &m->hdr.vers));
// can't log packet, because it may be too short for log_pkt()
goto drop;
}
c = get_conn_by_cid(&m->hdr.dcid);
if (c == 0 && m->hdr.dcid.len == 0)
c = c_ipnp;
if (likely(is_lh(m->hdr.flags)) && !is_clnt) {
if (c && m->hdr.type == LH_0RTT) {
mk_cid_str(WRN, c->scid, scid_str);
mk_cid_str(WRN, &m->hdr.dcid, dcid_str);
if (c->did_0rtt)
warn(INF,
"got 0-RTT pkt for orig cid %s, new is %s, "
"accepting",
dcid_str, scid_str);
else {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
warn(WRN,
"got 0-RTT pkt for orig cid %s, new is %s, "
"but rejected 0-RTT, ignoring",
dcid_str, scid_str);
goto drop;
}
} else if (m->hdr.type == LH_INIT && c == 0) {
// validate minimum packet size
if (xv->len < MIN_INI_LEN) {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
warn(ERR, "%u-byte Initial pkt too short (< %u)", xv->len,
MIN_INI_LEN);
goto drop;
}
if (vers_supported(m->hdr.vers) == false ||
is_vneg_vers(m->hdr.vers)) {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
warn(WRN,
"clnt-requested vers 0x%0" PRIx32 " not supported",
m->hdr.vers);
tx_vneg_resp(ws, v, m);
goto drop;
}
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char ip[NI_MAXHOST];
char port[NI_MAXSERV];
ensure(getnameinfo((struct sockaddr *)&v->addr, sizeof(v->addr),
ip, sizeof(ip), port, sizeof(port),
NI_NUMERICHOST | NI_NUMERICSERV) == 0,
"getnameinfo");
mk_cid_str(NTE, &m->hdr.dcid, dcid_str);
warn(NTE, "new serv conn on port %u from %s:%s w/cid=%s",
bswap16(get_sport(ws)), ip, port, dcid_str);
#endif
c = new_conn(w_engine(ws), m->hdr.vers, &m->hdr.scid,
&m->hdr.dcid, (struct sockaddr *)&v->addr, 0,
get_sport(ws), 0);
init_tls(c, 0);
}
}
if (likely(c)) {
if (m->hdr.scid.len && cid_cmp(&m->hdr.scid, c->dcid) != 0) {
if (m->hdr.vers && m->hdr.type == LH_RTRY &&
cid_cmp(&odcid, c->dcid) != 0) {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
mk_cid_str(ERR, &odcid, odcid_str);
mk_cid_str(ERR, c->dcid, dcid_str);
warn(ERR, "retry dcid mismatch %s != %s, ignoring pkt",
odcid_str, dcid_str);
goto drop;
}
if (c->state == conn_opng)
add_dcid(c, &m->hdr.scid);
}
if (m->hdr.dcid.len && cid_cmp(&m->hdr.dcid, c->scid) != 0) {
struct cid * const scid =
#ifndef NO_MIGRATION
get_cid_by_id(&c->scids_by_id, &m->hdr.dcid);
#else
c->scid;
#endif
if (unlikely(scid == 0)) {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
mk_cid_str(ERR, &m->hdr.dcid, dcid_str);
warn(ERR, "unknown scid %s, ignoring pkt", dcid_str);
goto drop;
}
mk_cid_str(DBG, scid, scid_str_new);
if (scid->seq <= c->scid->seq)
warn(DBG, "pkt has prev scid %s, accepting", scid_str_new);
else {
mk_cid_str(NTE, c->scid, scid_str_prev);
warn(NTE, "migration to scid %s for %s conn (was %s)",
scid_str_new, conn_type(c), scid_str_prev);
c->scid = scid;
}
}
} else {
#if !defined(FUZZING) && !defined(NO_OOO_0RTT)
// if this is a 0-RTT pkt, track it (may be reordered)
if (m->hdr.type == LH_0RTT && m->hdr.vers) {
struct ooo_0rtt * const zo = calloc(1, sizeof(*zo));
ensure(zo, "could not calloc");
cid_cpy(&zo->cid, &m->hdr.dcid);
zo->v = v;
ensure(splay_insert(ooo_0rtt_by_cid, &ooo_0rtt_by_cid, zo) == 0,
"inserted");
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
mk_cid_str(INF, &m->hdr.dcid, dcid_str);
warn(INF, "caching 0-RTT pkt for unknown conn %s", dcid_str);
goto next;
}
#endif
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok, tok_len);
if (is_srt(xv, m)) {
mk_srt_str(INF, &xv->buf[xv->len - SRT_LEN], srt_str);
warn(INF, BLU BLD "STATELESS RESET" NRM " token=%s", srt_str);
goto next;
}
mk_cid_str(INF, &m->hdr.dcid, dcid_str);
warn(INF, "cannot find conn %s for %u-byte %s pkt, ignoring",
dcid_str, v->len, pkt_type_str(m->hdr.flags, &m->hdr.vers));
// hexdump(v->buf, v->len);
goto drop;
}
if (likely(has_pkt_nr(m->hdr.flags, m->hdr.vers))) {
bool decoal;
if (unlikely(m->hdr.type == LH_INIT && c->cstrms[ep_init] == 0)) {
// we already abandoned Initial pkt processing, ignore
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
warn(INF, "ignoring %u-byte %s pkt due to abandoned processing",
v->len, pkt_type_str(m->hdr.flags, &m->hdr.vers));
goto drop;
} else if (unlikely(dec_pkt_hdr_remainder(xv, v, m, c, x,
&decoal) == false)) {
v->len = xv->len;
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
if (m->is_reset) {
mk_srt_str(INF, &xv->buf[xv->len - SRT_LEN], srt_str);
warn(INF, BLU BLD "STATELESS RESET" NRM " token=%s",
srt_str);
} else
warn(ERR, "%s %u-byte %s pkt, ignoring",
pkt_ok_for_epoch(m->hdr.flags, epoch_in(c))
? "crypto fail on"
: "rx invalid",
v->len, pkt_type_str(m->hdr.flags, &m->hdr.vers));
goto drop;
}
// that dcid in split-out coalesced pkt matches outer pkt
if (unlikely(decoal) && outer_dcid.len == 0) {
// save outer dcid for checking
cid_cpy(&outer_dcid, &m->hdr.dcid);
goto decoal_done;
}
if (unlikely(outer_dcid.len) &&
cid_cmp(&outer_dcid, &m->hdr.dcid) != 0) {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
mk_cid_str(ERR, &m->hdr.dcid, dcid_str);
mk_cid_str(ERR, &outer_dcid, outer_dcid_str);
warn(ERR,
"outer dcid %s != inner dcid %s during "
"decoalescing, ignoring %s pkt",
outer_dcid_str, dcid_str,
pkt_type_str(m->hdr.flags, &m->hdr.vers));
goto drop;
}
if (likely(decoal == false))
// forget outer dcid
outer_dcid.len = 0;
// check if this pkt came from a new source IP and/or port
if (sockaddr_cmp((struct sockaddr *)&c->peer,
(struct sockaddr *)&v->addr) != 0 &&
(c->tx_path_chlg == false ||
sockaddr_cmp((struct sockaddr *)&c->migr_peer,
(struct sockaddr *)&v->addr) != 0)) {
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char ip[NI_MAXHOST];
char port[NI_MAXSERV];
ensure(getnameinfo((struct sockaddr *)&v->addr, sizeof(v->addr),
ip, sizeof(ip), port, sizeof(port),
NI_NUMERICHOST | NI_NUMERICSERV) == 0,
"getnameinfo");
#endif
struct pn_space * const pn = &c->pns[pn_data];
if (m->hdr.nr <= diet_max(&pn->recv_all)) {
log_pkt("RX", v, (struct sockaddr *)&v->addr, &odcid, tok,
tok_len);
warn(NTE,
"pkt from new peer %s:%s, nr " FMT_PNR_IN
" <= max " FMT_PNR_IN ", ignoring",
ip, port, m->hdr.nr, diet_max(&pn->recv_all));
goto drop;
}
warn(NTE,
"pkt from new peer %s:%s, nr " FMT_PNR_IN
" > max " FMT_PNR_IN ", probing",
ip, port, m->hdr.nr, diet_max(&pn->recv_all));
rand_bytes(&c->path_chlg_out, sizeof(c->path_chlg_out));
c->migr_peer = v->addr;
c->needs_tx = c->tx_path_chlg = true;
}
} else
// this is a vneg or rtry pkt, dec_pkt_hdr_remainder not called
m->pn = &c->pns[pn_init];
decoal_done:
if (likely(rx_pkt(ws, v, m, x, &odcid, tok, tok_len))) {
rx_crypto(c, m);
c->min_rx_epoch = c->had_rx ? MIN(c->min_rx_epoch,
epoch_for_pkt_type(m->hdr.type))
: epoch_for_pkt_type(m->hdr.type);
if (likely(has_pkt_nr(m->hdr.flags, m->hdr.vers))) {
struct pn_space * const pn = pn_for_pkt_type(c, m->hdr.type);
diet_insert(&pn->recv, m->hdr.nr, m->t);
diet_insert(&pn->recv_all, m->hdr.nr, 0);
}
pkt_valid = true;
// remember that we had a RX event on this connection
if (unlikely(!c->had_rx)) {
c->had_rx = true;
sl_insert_head(crx, c, node_rx_int);
}
}
if (m->strm == 0)
// we didn't place this pkt in any stream - bye!
goto drop;
else if (unlikely(m->strm->state == strm_clsd &&
sq_empty(&m->strm->in)))
free_stream(m->strm);
goto next;
drop:
if (pkt_valid == false)
qlog_transport(pkt_dp, "DEFAULT", v, m, &m->hdr.dcid);
free_iov(v, m);
next:
if (likely(c)) {
if (likely(pkt_valid))
c->i.pkts_in_valid++;
else
c->i.pkts_in_invalid++;
}
#ifdef DEBUG_BUFFERS
warn(DBG, "w_free_iov idx %" PRIu32 " (avail %" PRIu ")", w_iov_idx(xv),
sq_len(&xv->w->iov) + 1);
#endif
w_free_iov(xv);
}
}
void restart_idle_alarm(struct q_conn * const c)
{
const timeout_t t =
MAX((timeout_t)c->tp_in.idle_to * NS_PER_MS, 3 * c->rec.ld_alarm_val);
#ifdef DEBUG_TIMERS
warn(DBG, "next idle alarm in %f sec", t / (double)NS_PER_S);
#endif
timeouts_add(ped(c->w)->wheel, &c->idle_alarm, t);
}
static void __attribute__((nonnull)) restart_ack_alarm(struct q_conn * const c)
{
const timeout_t t = c->tp_out.max_ack_del * NS_PER_MS;
#ifdef DEBUG_TIMERS
warn(DBG, "next ACK alarm in %f sec", t / (double)NS_PER_S);
#endif
timeouts_add(ped(c->w)->wheel, &c->ack_alarm, t);
}
void rx(struct w_sock * const ws)
{
struct w_iov_sq x = w_iov_sq_initializer(x);
struct q_conn_sl crx = sl_head_initializer(crx);
w_rx(ws, &x);
rx_pkts(&x, &crx, ws);
// for all connections that had RX events
while (!sl_empty(&crx)) {
struct q_conn * const c = sl_first(&crx);
sl_remove_head(&crx, node_rx_int);
// clear the helper flags set above
c->had_rx = false;
if (unlikely(c->state == conn_drng))
continue;
// reset idle timeout
if (likely(c->pns[pn_data].data.out_kyph ==
c->pns[pn_data].data.in_kyph))
restart_idle_alarm(c);
// is a TX needed for this connection?
if (c->needs_tx) {
c->tx_limit = 0;
tx(c); // clears c->needs_tx if we TX'ed
}
for (epoch_t e = c->min_rx_epoch; e <= ep_data; e++) {
if (c->cstrms[e] == 0 || e == ep_0rtt)
// don't ACK abandoned and 0rtt pn spaces
continue;
struct pn_space * const pn = pn_for_epoch(c, e);
switch (needs_ack(pn)) {
case imm_ack:
// TODO: find a way to push this from the RX to TX path
tx_ack(c, e, false);
do_tx(c);
break;
case del_ack:
if (likely(c->state != conn_clsg))
restart_ack_alarm(c);
break;
case no_ack:
case grat_ack:
break;
}
}
if (unlikely(c->tx_rtry))
// if we sent a retry, forget the entire connection existed
free_conn(c);
else if (c->have_new_data) {
if (!c->in_c_ready) {
sl_insert_head(&c_ready, c, node_rx_ext);
c->in_c_ready = true;
maybe_api_return(q_ready, 0, 0);
}
}
}
}
void
#ifndef NO_ERR_REASONS
err_close
#else
err_close_noreason
#endif
(struct q_conn * const c,
const uint_t code,
const uint8_t frm
#ifndef NO_ERR_REASONS
,
const char * const fmt,
...
#endif
)
{
#ifndef FUZZING
if (unlikely(c->err_code)) {
#ifndef NO_ERR_REASONS
warn(WRN,
"ignoring new err 0x%" PRIx "; existing err is 0x%" PRIx " (%s) ",
code, c->err_code, c->err_reason);
#endif
return;
}
#endif
#ifndef NO_ERR_REASONS
va_list ap;
va_start(ap, fmt);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
const int ret = vsnprintf(c->err_reason, sizeof(c->err_reason), fmt, ap);
ensure(ret >= 0, "vsnprintf() failed");
va_end(ap);
warn(ERR, "%s", c->err_reason);
c->err_reason_len =
(uint8_t)MIN((unsigned long)ret + 1, sizeof(c->err_reason));
#endif
conn_to_state(c, conn_qlse);
c->err_code = code;
c->err_frm = frm;
c->needs_tx = true;
enter_closing(c);
}
static void __attribute__((nonnull)) key_flip(struct q_conn * const c)
{
c->do_key_flip = c->key_flips_enabled;
#ifndef NO_MIGRATION
// XXX we borrow the key flip timer for this
c->do_migration = !c->tp_out.disable_migration;
#endif
}
static void __attribute__((nonnull)) stop_all_alarms(struct q_conn * const c)
{
timeouts_del(ped(c->w)->wheel, &c->rec.ld_alarm);
timeouts_del(ped(c->w)->wheel, &c->idle_alarm);
timeouts_del(ped(c->w)->wheel, &c->key_flip_alarm);
timeouts_del(ped(c->w)->wheel, &c->ack_alarm);
timeouts_del(ped(c->w)->wheel, &c->closing_alarm);
}
static void __attribute__((nonnull)) enter_closed(struct q_conn * const c)
{
conn_to_state(c, conn_clsd);
stop_all_alarms(c);
if (!c->in_c_ready) {
sl_insert_head(&c_ready, c, node_rx_ext);
c->in_c_ready = true;
}
// terminate whatever API call is currently active
maybe_api_return(c, 0);
maybe_api_return(q_ready, 0, 0);
}
void enter_closing(struct q_conn * const c)
{
if (c->state == conn_clsg)
return;
stop_all_alarms(c);
#ifndef FUZZING
if ((c->state == conn_idle || c->state == conn_opng) && c->err_code == 0) {
#endif
// no need to go closing->draining in these cases
timeouts_add(ped(c->w)->wheel, &c->closing_alarm, 0);
return;
#ifndef FUZZING
}
#endif
#ifndef FUZZING
// if we're going closing->draining, don't start the timer again
if (timeout_pending(&c->closing_alarm) == false) {
// start closing/draining alarm (3 * RTO)
const timeout_t dur =
3 * (c->rec.cur.srtt == 0 ? kInitialRtt : c->rec.cur.srtt) +
4 * c->rec.cur.rttvar;
timeouts_add(ped(c->w)->wheel, &c->closing_alarm, dur);
#ifdef DEBUG_TIMERS
mk_cid_str(DBG, c->scid, scid_str);
warn(DBG, "closing/draining alarm in %f sec on %s conn %s",
dur / (double)NS_PER_S, conn_type(c), scid_str);
#endif
}
#endif
if (c->state != conn_drng) {
c->needs_tx = true;
conn_to_state(c, conn_clsg);
timeouts_add(ped(c->w)->wheel, &c->tx_w, 0);
}
}
static void __attribute__((nonnull)) idle_alarm(struct q_conn * const c)
{
#ifdef DEBUG_TIMERS
mk_cid_str(DBG, c->scid, scid_str);
warn(DBG, "idle timeout on %s conn %s", conn_type(c), scid_str);
#endif
enter_closing(c);
}
static void __attribute__((nonnull)) ack_alarm(struct q_conn * const c)
{
#ifdef DEBUG_TIMERS
mk_cid_str(DBG, c->scid, scid_str);
warn(DBG, "ACK timer fired on %s conn %s", conn_type(c), scid_str);
#endif
if (needs_ack(&c->pns[pn_data]) != no_ack)
if (tx_ack(c, ep_data, false))
do_tx(c);
}
void update_conf(struct q_conn * const c, const struct q_conn_conf * const conf)
{
c->spin_enabled = get_conf_uncond(conf, enable_spinbit);
// (re)set idle alarm
c->tp_in.idle_to = get_conf(conf, idle_timeout) * MS_PER_S;
restart_idle_alarm(c);
c->tp_in.disable_migration =
#ifndef NO_MIGRATION
get_conf_uncond(conf, disable_migration);
#else
true;
#endif
c->key_flips_enabled = get_conf_uncond(conf, enable_tls_key_updates);
if (c->tp_out.disable_migration == false || c->key_flips_enabled) {
c->tls_key_update_frequency = get_conf(conf, tls_key_update_frequency);
restart_key_flip_alarm(c);
}
c->sockopt.enable_udp_zero_checksums =
get_conf_uncond(conf, enable_udp_zero_checksums);
w_set_sockopt(c->sock, &c->sockopt);
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
// XXX for testing, do a key flip and a migration ASAP (if enabled)
c->do_key_flip = c->key_flips_enabled;
#ifndef NO_MIGRATION
c->do_migration = !c->tp_out.disable_migration;
#endif
#endif
}
struct q_conn * new_conn(struct w_engine * const w,
const uint32_t vers,
const struct cid * const dcid,
const struct cid * const scid,
const struct sockaddr * const peer,
const char * const peer_name,
const uint16_t port,
const struct q_conn_conf * const conf)
{
struct q_conn * const c = calloc(1, sizeof(*c));
ensure(c, "could not calloc");
if (peer)
memcpy(&c->peer, peer, sizeof(*peer));
if (peer_name) {
c->is_clnt = true;
ensure(c->peer_name = strdup(peer_name), "could not dup peer_name");
}
// initialize socket
c->w = w;
const struct sockaddr_in * const addr4 =
(const struct sockaddr_in *)(const void *)peer;
c->sock = w_get_sock(w, w->ip, port,
c->is_clnt && addr4 ? addr4->sin_addr.s_addr : 0,
c->is_clnt && addr4 ? addr4->sin_port : 0);
if (c->sock == 0) {
c->sockopt.enable_ecn = true;
c->sockopt.enable_udp_zero_checksums =
get_conf_uncond(conf, enable_udp_zero_checksums);
c->sock = w_bind(w, port, &c->sockopt);
if (unlikely(c->sock == 0))
goto fail;
c->holds_sock = true;
} else if (unlikely(peer == 0))
goto fail;
// init CIDs
c->next_sid_bidi = c->is_clnt ? 0 : STRM_FL_SRV;
c->next_sid_uni = c->is_clnt ? STRM_FL_UNI : STRM_FL_UNI | STRM_FL_SRV;
#ifndef NO_MIGRATION
splay_init(&c->dcids_by_seq);
splay_init(&c->scids_by_seq);
#endif
const bool zero_len_scid = get_conf(conf, enable_zero_len_cid);
new_cids(c, zero_len_scid, dcid, scid);
c->vers = c->vers_initial = vers;
diet_init(&c->clsd_strms);
sq_init(&c->txq);
// initialize idle timeout
timeout_setcb(&c->idle_alarm, idle_alarm, c);
// initialize closing alarm
timeout_setcb(&c->closing_alarm, enter_closed, c);
// initialize key flip alarm (XXX also abused for migration)
timeout_setcb(&c->key_flip_alarm, key_flip, c);
// initialize ACK timeout
timeout_setcb(&c->ack_alarm, ack_alarm, c);
// initialize recovery state
init_rec(c);
if (c->is_clnt)
c->path_val_win = UINT_T_MAX;
// start a TX watcher
timeout_init(&c->tx_w, TIMEOUT_ABS);
timeout_setcb(&c->tx_w, tx, c);
if (likely(c->is_clnt || c->holds_sock == false))
update_conf(c, conf);
// TODO most of these should become configurable via q_conn_conf
c->tp_in.max_pkt = w_mtu(c->w);
c->tp_in.ack_del_exp = c->tp_out.ack_del_exp = DEF_ACK_DEL_EXP;
c->tp_in.max_ack_del = c->tp_out.max_ack_del = DEF_MAX_ACK_DEL;
c->tp_in.max_strm_data_uni = c->is_clnt ? INIT_STRM_DATA_UNI : 0;
c->tp_in.max_strms_uni = c->is_clnt ? INIT_MAX_UNI_STREAMS : 0;
c->tp_in.max_strms_bidi =
c->is_clnt ? INIT_MAX_BIDI_STREAMS * 2 : INIT_MAX_BIDI_STREAMS;
c->tp_in.max_strm_data_bidi_local = c->tp_in.max_strm_data_bidi_remote =
c->is_clnt ? INIT_STRM_DATA_BIDI : INIT_STRM_DATA_BIDI / 2;
c->tp_in.max_data =
c->tp_in.max_strms_bidi * c->tp_in.max_strm_data_bidi_local;
c->tp_in.act_cid_lim =
c->tp_in.disable_migration ? 0 : (c->is_clnt ? 4 : 2);
// initialize packet number spaces
for (pn_t t = pn_init; t <= pn_data; t++)
init_pn(&c->pns[t], c, t);
// create crypto streams
for (epoch_t e = ep_init; e <= ep_data; e++)
if (e != ep_0rtt)
new_stream(c, crpt_strm_id(e));
if (c->scid) {
// FIXME: first connection sets the type for all future connections
qlog_init(c);
mk_cid_str(DBG, c->scid, scid_str);
warn(DBG, "%s conn %s on port %u created", conn_type(c), scid_str,
bswap16(get_sport(c->sock)));
}
conn_to_state(c, conn_idle);
return c;
fail:
free(c);
return 0;
}
void free_scid(struct q_conn * const c
#ifdef NO_MIGRATION
__attribute__((unused))
#endif
,
struct cid * const id)
{
#ifndef NO_MIGRATION
ensure(splay_remove(cids_by_seq, &c->scids_by_seq, id), "removed");
cids_by_id_del(&c->scids_by_id, id);
#endif
conns_by_id_del(id);
free(id);
}
void free_dcid(struct q_conn * const c
#ifdef NO_MIGRATION
__attribute__((unused))
#endif
,
struct cid * const id)
{
if (id->has_srt)
conns_by_srt_del(id->srt);
#ifndef NO_MIGRATION
ensure(splay_remove(cids_by_seq, &c->dcids_by_seq, id), "removed");
#endif
free(id);
}
void free_conn(struct q_conn * const c)
{
// exit any active API call on the connection
maybe_api_return(c, 0);
stop_all_alarms(c);
struct q_stream * s;
kh_foreach_value(&c->strms_by_id, s, { free_stream(s); });
kh_release(strms_by_id, &c->strms_by_id);
// free crypto streams
for (epoch_t e = ep_init; e <= ep_data; e++)
if (c->cstrms[e])
free_stream(c->cstrms[e]);
free_tls(c, false);
// free packet number spaces
for (pn_t t = pn_init; t <= pn_data; t++)
free_pn(&c->pns[t]);
timeouts_del(ped(c->w)->wheel, &c->tx_w);
diet_free(&c->clsd_strms);
free(c->peer_name);
// remove connection from global lists and free CIDs
free_cids(c);
#ifndef NO_MIGRATION
kh_release(cids_by_id, &c->scids_by_id);
#endif
if (c->holds_sock)
// only close the socket for the final server connection
w_close(c->sock);
if (c->in_c_ready)
sl_remove(&c_ready, c, q_conn, node_rx_ext);
if (c->needs_accept)
sl_remove(&accept_queue, c, q_conn, node_aq);
free(c);
}
void conn_info_populate(struct q_conn * const c)
{
// fill some q_conn_info fields based on other conn fields
c->i.cwnd = c->rec.cur.cwnd;
c->i.ssthresh = c->rec.cur.ssthresh;
c->i.rtt = c->rec.cur.srtt;
c->i.rttvar = c->rec.cur.rttvar;
}
|
jlaine/quant
|
lib/src/recovery.h
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <quant/quant.h>
#include <timeout.h>
#include "pn.h"
#include "quic.h"
struct q_conn;
struct pn_space;
struct cc_state {
uint_t latest_rtt; // latest_rtt
uint_t min_rtt; // min_rtt
uint_t rttvar; // rttvar
uint_t srtt; // smoothed_rtt
uint_t ae_in_flight; // nr of ACK-eliciting pkts inflight
uint_t cwnd; // congestion_window
uint_t in_flight; // bytes_in_flight
uint_t ssthresh; // sshtresh
};
struct recovery {
struct timeout ld_alarm; // loss_detection_timer
timeout_t ld_alarm_val;
// LD state
uint64_t last_sent_ack_elicit_t; // time_of_last_sent_ack_eliciting_packet
uint64_t last_sent_crypto_t; // time_of_last_sent_crypto_packet
uint16_t crypto_cnt; // crypto_count
uint16_t pto_cnt; // pto_count
// largest_sent_packet -> pn->lg_sent
// largest_acked_packet -> pn->lg_acked
// max_ack_delay -> c->tp_out.max_ack_del
#ifdef HAVE_64BIT
uint8_t _unused[4];
#endif
// CC state
uint64_t rec_start_t; // recovery_start_time
uint_t ae_in_flight; // nr of ACK-eliciting pkts inflight
struct cc_state cur;
struct cc_state prev;
#ifndef HAVE_64BIT
uint8_t _unused[4];
#endif
};
extern void __attribute__((nonnull)) log_cc(struct q_conn * const c);
extern void __attribute__((nonnull)) init_rec(struct q_conn * const c);
extern void __attribute__((nonnull)) on_pkt_sent(struct pkt_meta * const m);
extern void __attribute__((nonnull))
on_ack_received_1(struct pkt_meta * const lg_ack, const uint_t ack_del);
extern void __attribute__((nonnull))
on_ack_received_2(struct pn_space * const pn);
extern void __attribute__((nonnull))
on_pkt_acked(struct w_iov * const v, struct pkt_meta * m);
extern void __attribute__((nonnull))
congestion_event(struct q_conn * const c, const uint64_t sent_t);
extern void __attribute__((nonnull)) set_ld_timer(struct q_conn * const c);
extern void __attribute__((nonnull))
on_pkt_lost(struct pkt_meta * const m, const bool is_lost);
|
jlaine/quant
|
lib/src/frame.c
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <netdb.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#ifndef PARTICLE
#include <netinet/ip.h>
#endif
// IWYU pragma: no_include <picotls/../picotls.h>
#include <picotls.h> // IWYU pragma: keep
#include <quant/quant.h>
#include <timeout.h>
#include <warpcore/warpcore.h>
#include "bitset.h"
#include "conn.h"
#include "diet.h"
#include "frame.h"
#include "loop.h"
#include "marshall.h"
#include "pkt.h"
#include "pn.h"
#include "quic.h"
#include "recovery.h"
#include "stream.h"
#include "tls.h"
// TODO: check error conditions and codes more thoroughly
#define track_frame(m, ft) bit_set(FRM_MAX, (ft), &(m)->frms)
#define err_close_return(c, code, ...) \
do { \
err_close((c), (code), __VA_ARGS__); \
return false; \
} while (0)
#define dec1_chk(val, pos, end, c, type) \
do { \
if (unlikely(dec1((val), (pos), (end)) == false)) \
err_close_return((c), ERR_FRAME_ENC, (type), "dec1 %s in %s:%u", \
#val, __FILE__, __LINE__); \
} while (0)
#define decv_chk(val, pos, end, c, type) \
do { \
uint64_t _v; \
if (unlikely(decv(&_v, (pos), (end)) == false)) \
err_close_return((c), ERR_FRAME_ENC, (type), "decv %s in %s:%u", \
#val, __FILE__, __LINE__); \
*(val) = (uint_t)_v; \
} while (0)
#define decb_chk(val, pos, end, len, c, type) \
do { \
if (unlikely(decb((val), (pos), (end), (len)) == false)) \
err_close_return((c), ERR_FRAME_ENC, (type), "decb %s in %s:%u", \
#val, __FILE__, __LINE__); \
} while (0)
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
void log_stream_or_crypto_frame(const bool rtx,
const struct pkt_meta * const m,
const uint8_t fl,
const dint_t sid,
const bool in,
const char * kind)
{
// if (util_dlevel != INF && util_dlevel != DBG)
// return;
const struct q_conn * const c = m->pn->c;
const struct q_stream * const s = m->strm;
if (kind == 0)
kind = BLD RED "invalid" NRM;
if (sid >= 0)
warn(INF,
"%sSTREAM" NRM " 0x%02x=%s%s%s%s%s id=" FMT_SID "/%" PRIu
" off=%" PRIu "/%" PRIu " len=%u coff=%" PRIu "/%" PRIu
" %s%s%s%s",
in ? FRAM_IN : FRAM_OUT, fl, is_set(F_STREAM_FIN, fl) ? "FIN" : "",
is_set(F_STREAM_FIN, fl) &&
(is_set(F_STREAM_LEN, fl) || is_set(F_STREAM_OFF, fl))
? "|"
: "",
is_set(F_STREAM_LEN, fl) ? "LEN" : "",
is_set(F_STREAM_LEN, fl) && is_set(F_STREAM_OFF, fl) ? "|" : "",
is_set(F_STREAM_OFF, fl) ? "OFF" : "", sid, max_sid(sid, c),
m->strm_off,
in ? (s ? s->in_data_max : 0) : (s ? s->out_data_max : 0),
m->strm_data_len, in ? c->in_data_str : c->out_data_str,
in ? c->tp_in.max_data : c->tp_out.max_data,
rtx ? REV BLD GRN "[RTX]" NRM " " : "", in ? "[" : "", kind,
in ? "]" : "");
else
warn(INF, "%sCRYPTO" NRM " off=%" PRIu " len=%u %s%s%s%s",
in ? FRAM_IN : FRAM_OUT, m->strm_off, m->strm_data_len,
rtx ? REV BLD GRN "[RTX]" NRM " " : "", in ? "[" : "", kind,
in ? "]" : "");
}
#endif
static void __attribute__((nonnull)) trim_frame(struct pkt_meta * const p)
{
const uint_t diff = p->strm->in_data_off - p->strm_off;
p->strm_off += diff;
p->strm_data_pos += diff;
p->strm_data_len -= diff;
}
static struct q_stream * __attribute__((nonnull))
get_and_validate_strm(struct q_conn * const c,
const dint_t sid,
const uint8_t type,
const bool ok_when_writer)
{
if (is_uni(sid) && unlikely(is_srv_ini(sid) ==
(ok_when_writer ? c->is_clnt : !c->is_clnt)))
err_close(c, ERR_STREAM_STATE, type,
"got frame 0x%02x for uni sid %" PRId " but am %s", type, sid,
conn_type(c));
else {
struct q_stream * s = get_stream(c, sid);
if (unlikely(s == 0)) {
if (unlikely(diet_find(&c->clsd_strms, (uint_t)sid))) {
mk_cid_str(NTE, c->scid, scid_str);
warn(NTE,
"ignoring 0x%02x frame for closed strm " FMT_SID
" on %s conn %s",
type, sid, conn_type(c), scid_str);
} else if (type == FRM_MSD || type == FRM_STP)
// we are supposed to open closed streams on RX of these frames
s = new_stream(c, sid);
else
err_close(c, ERR_STREAM_STATE, type, "unknown strm %" PRId,
sid);
}
return s;
}
return 0;
}
static bool __attribute__((nonnull))
dec_stream_or_crypto_frame(const uint8_t type,
const uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct w_iov * const v)
{
struct pn_space * const pn = m->pn;
if (unlikely(pn == 0))
return false;
struct q_conn * const c = pn->c;
m->strm_frm_pos = (uint16_t)(*pos - v->buf) - 1;
dint_t sid = 0;
if (unlikely(type == FRM_CRY)) {
const epoch_t e = epoch_for_pkt_type(m->hdr.type);
if (unlikely(c->cstrms[e] == 0))
err_close_return(c, ERR_STREAM_STATE, type,
"epoch %u pkt processing abandoned", e);
sid = crpt_strm_id(e);
m->strm = c->cstrms[e];
} else {
m->is_fin = is_set(F_STREAM_FIN, type);
decv_chk((uint_t *)&sid, pos, end, c, type);
m->strm = get_stream(c, sid);
}
if (is_set(F_STREAM_OFF, type) || unlikely(type == FRM_CRY))
decv_chk(&m->strm_off, pos, end, c, type);
else
m->strm_off = 0;
uint_t l = 0;
if (is_set(F_STREAM_LEN, type) || unlikely(type == FRM_CRY)) {
decv_chk(&l, pos, end, c, type);
if (unlikely(*pos + l > end))
err_close_return(c, ERR_FRAME_ENC, type, "illegal strm len");
} else
// stream data extends to end of packet
l = (uint16_t)(end - *pos);
const dint_t max = max_sid(sid, c);
if (unlikely(sid > max)) {
log_stream_or_crypto_frame(false, m, type, sid, true, 0);
err_close_return(c, ERR_STREAM_ID, type, "sid %" PRId " > max %" PRId,
sid, max);
}
m->strm_data_pos = (uint16_t)(*pos - v->buf);
m->strm_data_len = (uint16_t)l;
// deliver data into stream
bool ignore = false;
const char * kind = 0;
if (unlikely(m->strm_data_len == 0 && !is_set(F_STREAM_FIN, type))) {
#ifdef DEBUG_EXTRA
warn(WRN, "zero-len strm/crypt frame on sid " FMT_SID ", ignoring",
sid);
#endif
ignore = true;
kind = "ign";
goto done;
}
mk_cid_str(NTE, c->scid, scid_str);
if (unlikely(m->strm == 0)) {
if (unlikely(diet_find(&c->clsd_strms, (uint_t)sid))) {
#ifdef DEBUG_STREAMS
warn(NTE,
"ignoring STREAM frame for closed strm " FMT_SID
" on %s conn %s",
sid, conn_type(c), scid_str);
#endif
ignore = true;
kind = "ign";
goto done;
}
if (unlikely(is_srv_ini(sid) != c->is_clnt)) {
log_stream_or_crypto_frame(false, m, type, sid, true, 0);
err_close_return(c, ERR_STREAM_STATE, type,
"got sid %" PRId " but am %s", sid, conn_type(c));
}
m->strm = new_stream(c, sid);
}
// best case: new in-order data
if (m->strm->in_data_off >= m->strm_off &&
m->strm->in_data_off <=
m->strm_off + m->strm_data_len - (m->strm_data_len ? 1 : 0)) {
kind = "seq";
if (unlikely(m->strm->state == strm_hcrm ||
m->strm->state == strm_clsd)) {
warn(NTE,
"ignoring STREAM frame for %s strm " FMT_SID " on %s conn %s",
strm_state_str[m->strm->state], sid, conn_type(c), scid_str);
ignore = true;
goto done;
}
if (unlikely(m->strm->in_data_off > m->strm_off))
// already-received data at the beginning of the frame, trim
trim_frame(m);
track_bytes_in(m->strm, m->strm_data_len);
m->strm->in_data_off += m->strm_data_len;
sq_insert_tail(&m->strm->in, v, next);
#ifndef NO_OOO_DATA
// check if a hole has been filled that lets us dequeue ooo data
struct pkt_meta * p = splay_min(ooo_by_off, &m->strm->in_ooo);
while (p) {
struct pkt_meta * const nxt =
splay_next(ooo_by_off, &m->strm->in_ooo, p);
if (unlikely(p->strm_off + p->strm_data_len <
m->strm->in_data_off)) {
// right edge of p < left edge of stream
warn(WRN, "drop stale frame [%" PRIu "..%" PRIu "]",
p->strm_off, p->strm_off + p->strm_data_len);
ensure(splay_remove(ooo_by_off, &m->strm->in_ooo, p),
"removed");
p = nxt;
continue;
}
// right edge of p >= left edge of stream
if (p->strm_off > m->strm->in_data_off)
// also left edge of p > left edge of stream: still a gap
break;
// left edge of p <= left edge of stream: overlap, trim & enqueue
if (unlikely(p->strm->in_data_off > p->strm_off))
trim_frame(p);
sq_insert_tail(&m->strm->in, w_iov(c->w, pm_idx(c->w, p)), next);
m->strm->in_data_off += p->strm_data_len;
ensure(splay_remove(ooo_by_off, &m->strm->in_ooo, p), "removed");
// mark ooo crypto data for freeing by rx_crypto()
if (p->strm->id < 0)
p->strm = 0;
p = nxt;
}
#else
ignore = true;
#endif
// check if we have delivered a FIN, and act on it if we did
struct w_iov * const last = sq_last(&m->strm->in, w_iov, next);
if (last) {
const struct pkt_meta * const m_last = &meta(last);
if (unlikely(v != last))
adj_iov_to_start(last, m_last);
if (m_last->is_fin) {
m->pn->imm_ack = true;
strm_to_state(m->strm, m->strm->state <= strm_hcrm ? strm_hcrm
: strm_clsd);
}
if (unlikely(v != last))
adj_iov_to_data(last, m_last);
}
if (type != FRM_CRY) {
do_stream_fc(m->strm, 0);
do_conn_fc(c, 0);
c->have_new_data = true;
maybe_api_return(q_read, c, 0);
maybe_api_return(q_read_stream, c, m->strm);
}
goto done;
}
// data is a complete duplicate
if (m->strm_off + m->strm_data_len <= m->strm->in_data_off) {
kind = RED "dup" NRM;
ignore = true;
goto done;
}
#ifndef NO_OOO_DATA
// data is out of order - check if it overlaps with already stored ooo data
kind = YEL "ooo" NRM;
if (unlikely(m->strm->state == strm_hcrm || m->strm->state == strm_clsd)) {
warn(NTE, "ignoring STREAM frame for %s strm " FMT_SID " on %s conn %s",
strm_state_str[m->strm->state], sid, conn_type(c), scid_str);
ignore = true;
kind = "ign";
goto done;
}
struct pkt_meta * p = splay_min(ooo_by_off, &m->strm->in_ooo);
while (p && p->strm_off + p->strm_data_len - 1 < m->strm_off)
p = splay_next(ooo_by_off, &m->strm->in_ooo, p);
// right edge of p >= left edge of v
if (p && p->strm_off <= m->strm_off + m->strm_data_len - 1) {
// left edge of p <= right edge of v
warn(ERR,
"[%" PRIu "..%" PRIu "] have existing overlapping ooo data [%" PRIu
"..%" PRIu "]",
m->strm_off, m->strm_off + m->strm_data_len, p->strm_off,
p->strm_off + p->strm_data_len - 1);
ignore = true;
kind = "ign";
goto done;
}
// this ooo data doesn't overlap with anything
track_bytes_in(m->strm, m->strm_data_len);
ensure(splay_insert(ooo_by_off, &m->strm->in_ooo, m) == 0, "inserted");
#endif
done:
log_stream_or_crypto_frame(false, m, type, sid, true, kind);
if (m->strm && type != FRM_CRY &&
m->strm_off + m->strm_data_len > m->strm->in_data_max)
err_close_return(c, ERR_FLOW_CONTROL, type,
"stream %" PRIu " off %" PRIu " >= in_data_max %" PRIu,
m->strm->id, m->strm_off + m->strm_data_len - 1,
m->strm->in_data_max);
if (ignore)
// this indicates to callers that the w_iov was not placed in a stream
m->strm = 0;
*pos = &v->buf[m->strm_data_pos + m->strm_data_len];
return true;
}
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
static uint_t __attribute__((const))
shorten_ack_nr(const uint_t ack, const uint_t diff)
{
if (unlikely(diff == 0))
return ack;
static const uint_t divs[] = {
// clang-format off
UINT_C(1), UINT_C(10), UINT_C(10), UINT_C(10), UINT_C(100), UINT_C(100),
UINT_C(100), UINT_C(1000), UINT_C(1000), UINT_C(1000), UINT_C(10000),
UINT_C(10000), UINT_C(10000), UINT_C(10000), UINT_C(100000),
UINT_C(100000), UINT_C(100000), UINT_C(1000000), UINT_C(1000000),
UINT_C(1000000), UINT_C(10000000), UINT_C(10000000), UINT_C(10000000),
UINT_C(10000000), UINT_C(100000000), UINT_C(100000000),
UINT_C(100000000), UINT_C(1000000000), UINT_C(1000000000),
UINT_C(1000000000),
#ifdef HAVE_64BIT
UINT_C(10000000000), UINT_C(10000000000),
UINT_C(10000000000), UINT_C(10000000000), UINT_C(100000000000),
UINT_C(100000000000), UINT_C(100000000000), UINT_C(1000000000000),
UINT_C(1000000000000), UINT_C(1000000000000), UINT_C(10000000000000),
UINT_C(10000000000000), UINT_C(10000000000000), UINT_C(10000000000000),
UINT_C(100000000000000), UINT_C(100000000000000),
UINT_C(100000000000000), UINT_C(1000000000000000),
UINT_C(1000000000000000), UINT_C(1000000000000000),
UINT_C(10000000000000000), UINT_C(10000000000000000),
UINT_C(10000000000000000), UINT_C(10000000000000000),
UINT_C(100000000000000000), UINT_C(100000000000000000),
UINT_C(100000000000000000), UINT_C(1000000000000000000),
UINT_C(1000000000000000000), UINT_C(1000000000000000000),
UINT_C(10000000000000000000), UINT_C(10000000000000000000),
UINT_C(10000000000000000000), UINT_C(10000000000000000000)
#endif
// clang-format on
};
return ack % divs[sizeof(divs[0]) * 8 - (size_t)(
#ifdef HAVE_64BIT
__builtin_clzll(diff)
#else
__builtin_clzl(diff)
#endif
)];
}
#endif
static bool __attribute__((nonnull)) dec_ack_frame(const uint8_t type,
const uint8_t ** pos,
const uint8_t * const start,
const uint8_t * const end,
struct pkt_meta * const m)
{
if (unlikely(m->ack_frm_pos))
warn(WRN, "packet contains multiple ACK frames");
else
m->ack_frm_pos = (uint16_t)(*pos - start);
struct pn_space * const pn = m->pn;
if (unlikely(pn == 0))
return false;
struct q_conn * const c = pn->c;
uint_t lg_ack_in_frm = 0;
decv_chk(&lg_ack_in_frm, pos, end, c, type);
uint_t ack_delay_raw = 0;
decv_chk(&ack_delay_raw, pos, end, c, type);
// TODO: figure out a better way to handle huge ACK delays
if (unlikely(ack_delay_raw > UINT32_MAX))
err_close_return(c, ERR_FRAME_ENC, type, "ACK delay raw %" PRIu,
ack_delay_raw);
// handshake pkts always use the default ACK delay exponent
const uint_t ade = m->hdr.type == LH_INIT || m->hdr.type == LH_HSHK
? DEF_ACK_DEL_EXP
: c->tp_in.ack_del_exp;
const uint_t ack_delay = ack_delay_raw << ade;
uint_t ack_rng_cnt = 0;
decv_chk(&ack_rng_cnt, pos, end, c, type);
const struct ival * const cum_ack_ival = diet_min_ival(&pn->acked_or_lost);
const uint_t cum_ack = cum_ack_ival ? cum_ack_ival->hi : UINT_T_MAX;
uint_t lg_ack = lg_ack_in_frm;
uint64_t lg_ack_in_frm_t = 0;
bool got_new_ack = false;
for (uint_t n = ack_rng_cnt + 1; n > 0; n--) {
uint_t gap = 0;
uint_t ack_rng = 0;
decv_chk(&ack_rng, pos, end, c, type);
if (unlikely(ack_rng > (UINT16_MAX << 4)))
err_close_return(c, ERR_INTERNAL, type, "ACK rng len %" PRIu,
ack_rng);
if (unlikely(ack_rng > lg_ack))
err_close_return(c, ERR_FRAME_ENC, type, "ACK rng len %" PRIu,
" > lg_ack %" PRIu, ack_rng, lg_ack);
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
if (ack_rng == 0) {
if (n == ack_rng_cnt + 1)
warn(INF,
FRAM_IN "ACK" NRM " 0x%02x=%s lg=" FMT_PNR_OUT
" delay=%" PRIu " (%" PRIu " usec) cnt=%" PRIu
" rng=%" PRIu " [" FMT_PNR_OUT "]",
type, type == FRM_ACE ? "ECN" : "", lg_ack_in_frm,
ack_delay_raw, ack_delay, ack_rng_cnt, ack_rng,
lg_ack_in_frm);
else
warn(INF,
FRAM_IN "ACK" NRM " gap=%" PRIu " rng=%" PRIu
" [" FMT_PNR_OUT "]",
gap, ack_rng, lg_ack);
} else {
if (n == ack_rng_cnt + 1)
warn(INF,
FRAM_IN "ACK" NRM " 0x%02x=%s lg=" FMT_PNR_OUT
" delay=%" PRIu " (%" PRIu " usec) cnt=%" PRIu
" rng=%" PRIu " [" FMT_PNR_OUT ".." FMT_PNR_OUT
"]",
type, type == FRM_ACE ? "ECN" : "", lg_ack_in_frm,
ack_delay_raw, ack_delay, ack_rng_cnt, ack_rng,
lg_ack - ack_rng, shorten_ack_nr(lg_ack, ack_rng));
else
warn(INF,
FRAM_IN "ACK" NRM " gap=%" PRIu " rng=%" PRIu
" [" FMT_PNR_OUT ".." FMT_PNR_OUT "]",
gap, ack_rng, lg_ack - ack_rng,
shorten_ack_nr(lg_ack, ack_rng));
}
#endif
uint_t ack = lg_ack;
while (ack_rng >= lg_ack - ack) {
if (likely(cum_ack != UINT_T_MAX) && ack <= cum_ack)
// we can skip the remainder of this range entirely
goto next_rng;
if (diet_find(&pn->acked_or_lost, ack))
goto next_ack;
struct pkt_meta * m_acked;
struct w_iov * const acked = find_sent_pkt(pn, ack, &m_acked);
if (unlikely(acked == 0)) {
#ifndef FUZZING
// this is just way too noisy when fuzzing
err_close_return(c, ERR_PROTOCOL_VIOLATION, type,
"got ACK for %s pkt %" PRIu " never sent",
pn_type_str(pn->type), ack);
#endif
goto next_ack;
}
got_new_ack = true;
if (unlikely(ack == lg_ack_in_frm)) {
// call this only for the largest ACK in the frame
on_ack_received_1(m_acked, ack_delay);
lg_ack_in_frm_t = m_acked->t;
}
on_pkt_acked(acked, m_acked);
// if the ACK'ed pkt was sent with ECT, verify peer and path support
if (likely(c->sockopt.enable_ecn &&
is_set(IPTOS_ECN_ECT0, acked->flags)) &&
unlikely(type != FRM_ACE)) {
mk_cid_str(NTE, c->scid, scid_str);
warn(NTE, "ECN verification failed for %s conn %s",
conn_type(c), scid_str);
c->sockopt.enable_ecn = false;
w_set_sockopt(c->sock, &c->sockopt);
}
next_ack:
if (likely(ack > 0))
ack--;
else
break;
}
next_rng:
if (n > 1) {
decv_chk(&gap, pos, end, c, type);
if (unlikely((lg_ack - ack_rng) < gap + 2)) {
warn(DBG, "lg_ack=%" PRIu ", ack_rng=%" PRIu ", gap=%" PRIu,
lg_ack, ack_rng, -gap);
err_close_return(c, ERR_PROTOCOL_VIOLATION, type,
"illegal ACK frame");
}
lg_ack -= ack_rng + gap + 2;
}
}
if (type == FRM_ACE) {
// decode ECN
uint_t ect0_cnt = 0;
uint_t ect1_cnt = 0;
uint_t ce_cnt = 0;
decv_chk(&ect0_cnt, pos, end, c, type);
decv_chk(&ect1_cnt, pos, end, c, type);
decv_chk(&ce_cnt, pos, end, c, type);
warn(INF,
FRAM_IN "ECN" NRM " ect0=%s%" PRIu NRM " ect1=%s%" PRIu NRM
" ce=%s%" PRIu NRM,
ect0_cnt ? GRN : NRM, ect0_cnt, ect1_cnt ? GRN : NRM, ect1_cnt,
ce_cnt ? GRN : NRM, ce_cnt);
// TODO: add sanity check whether markings make sense
// ProcessECN
if (ce_cnt > pn->ce_cnt) {
pn->ce_cnt = ce_cnt;
congestion_event(c, lg_ack_in_frm_t);
}
}
if (got_new_ack)
on_ack_received_2(pn);
bit_zero(FRM_MAX, &pn->tx_frames);
return true;
}
static bool __attribute__((nonnull))
dec_close_frame(const uint8_t type,
const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct pn_space * const pn = m->pn;
if (unlikely(pn == 0))
return false;
struct q_conn * const c = pn->c;
uint_t err_code;
decv_chk(&err_code, pos, end, c, type);
uint_t frame_type = 0;
if (type == FRM_CLQ)
decv_chk(&frame_type, pos, end, c, type);
uint_t reas_len = 0;
decv_chk(&reas_len, pos, end, c, type);
const uint16_t act_reas_len =
(uint16_t)MIN(reas_len, (uint16_t)(end - *pos));
char reas_phr[2048]; // FIXME: should be limited by MTU (or something)
if (act_reas_len)
decb_chk((uint8_t *)reas_phr, pos, end, act_reas_len, c, type);
if (type == FRM_CLQ)
warn(INF,
FRAM_IN "CONNECTION_CLOSE" NRM " 0x%02x=quic err=%s0x%" PRIx NRM
" frame=0x%" PRIx " rlen=%" PRIu " reason=%s%.*s" NRM,
type, err_code ? RED : NRM, err_code, frame_type, reas_len,
err_code ? RED : NRM, (int)reas_len, reas_phr);
else
warn(INF,
FRAM_IN "CONNECTION_CLOSE" NRM " 0x%02x=app err=%s0x%" PRIx NRM
" rlen=%" PRIu " reason=%s%.*s" NRM,
type, err_code ? RED : NRM, err_code, reas_len,
err_code ? RED : NRM, (int)reas_len, reas_phr);
if (unlikely(reas_len != act_reas_len))
err_close_return(c, ERR_FRAME_ENC, type, "illegal reason len");
if (c->state == conn_drng)
timeouts_add(ped(c->w)->wheel, &c->closing_alarm, 0);
else {
if (c->is_clnt) {
conn_to_state(c, conn_drng);
timeouts_add(ped(c->w)->wheel, &c->closing_alarm, 0);
} else
enter_closing(c);
}
return true;
}
static bool __attribute__((nonnull))
dec_max_strm_data_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
dint_t sid = 0;
decv_chk((uint_t *)&sid, pos, end, c, FRM_MSD);
uint_t max = 0;
decv_chk(&max, pos, end, c, FRM_MSD);
warn(INF, FRAM_IN "MAX_STREAM_DATA" NRM " id=" FMT_SID " max=%" PRIu, sid,
max);
struct q_stream * const s = get_and_validate_strm(c, sid, FRM_MSD, true);
if (unlikely(s == 0))
return true;
if (max > s->out_data_max) {
s->out_data_max = max;
if (s->blocked) {
s->blocked = false;
c->needs_tx = true;
}
need_ctrl_update(s);
} else if (max < s->out_data_max)
warn(NTE, "MAX_STREAM_DATA %" PRIu " < current value %" PRIu, max,
s->out_data_max);
return true;
}
static bool __attribute__((nonnull))
dec_max_strms_frame(const uint8_t type,
const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
uint_t max = 0;
decv_chk(&max, pos, end, c, type);
warn(INF, FRAM_IN "MAX_STREAMS" NRM " 0x%02x=%s max=%" PRIu, type,
type == FRM_MSU ? "uni" : "bi", max);
uint_t * const max_streams =
type == FRM_MSU ? &c->tp_out.max_strms_uni : &c->tp_out.max_strms_bidi;
if (max > *max_streams) {
*max_streams = max;
maybe_api_return(q_rsv_stream, c, 0);
} else if (max < *max_streams)
warn(NTE, "RX'ed max_%s_streams %" PRIu " < current value %" PRIu,
type == FRM_MSU ? "uni" : "bidi", max, *max_streams);
return true;
}
static bool __attribute__((nonnull))
dec_max_data_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
uint_t max = 0;
decv_chk(&max, pos, end, c, FRM_MCD);
warn(INF, FRAM_IN "MAX_DATA" NRM " max=%" PRIu, max);
if (max > c->tp_out.max_data) {
c->tp_out.max_data = max;
c->blocked = false;
} else if (max < c->tp_out.max_data)
warn(NTE, "MAX_DATA %" PRIu " < current value %" PRIu, max,
c->tp_out.max_data);
return true;
}
static bool __attribute__((nonnull))
dec_strm_data_blocked_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
dint_t sid = 0;
decv_chk((uint_t *)&sid, pos, end, c, FRM_SDB);
uint_t off = 0;
decv_chk(&off, pos, end, c, FRM_SDB);
warn(INF, FRAM_IN "STREAM_DATA_BLOCKED" NRM " id=" FMT_SID " lim=%" PRIu,
sid, off);
struct q_stream * const s = get_and_validate_strm(c, sid, FRM_SDB, false);
if (unlikely(s == 0))
return true;
do_stream_fc(s, 0);
// because do_stream_fc() only sets this when increasing the FC window
s->tx_max_strm_data = true;
need_ctrl_update(s);
return true;
}
static bool __attribute__((nonnull))
dec_data_blocked_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
uint_t off = 0;
decv_chk(&off, pos, end, c, FRM_CDB);
warn(INF, FRAM_IN "DATA_BLOCKED" NRM " lim=%" PRIu, off);
do_conn_fc(c, 0);
// because do_conn_fc() only sets this when increasing the FC window
c->tx_max_data = true;
return true;
}
static bool __attribute__((nonnull))
dec_streams_blocked_frame(const uint8_t type,
const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
uint_t max = 0;
decv_chk(&max, pos, end, c, FRM_SBB);
warn(INF, FRAM_IN "STREAMS_BLOCKED" NRM " 0x%02x=%s max=%" PRIu, type,
type == FRM_SBB ? "bi" : "uni", max);
do_stream_id_fc(c, max, type == FRM_SBB, false);
return true;
}
static bool __attribute__((nonnull))
dec_stop_sending_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
dint_t sid = 0;
decv_chk((uint_t *)&sid, pos, end, c, FRM_STP);
uint_t err_code;
decv_chk(&err_code, pos, end, c, FRM_STP);
warn(INF, FRAM_IN "STOP_SENDING" NRM " id=" FMT_SID " err=%s0x%" PRIx NRM,
sid, err_code ? RED : NRM, err_code);
struct q_stream * const s = get_and_validate_strm(c, sid, FRM_STP, true);
if (unlikely(s == 0))
return true;
return true;
}
static bool __attribute__((nonnull))
dec_path_challenge_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
decb_chk(c->path_chlg_in, pos, end, PATH_CHLG_LEN, c, FRM_PCL);
mk_path_chlg_str(INF, c->path_chlg_in, pci_str);
warn(INF, FRAM_IN "PATH_CHALLENGE" NRM " data=%s", pci_str);
memcpy(c->path_resp_out, c->path_chlg_in, PATH_CHLG_LEN);
c->needs_tx = c->tx_path_resp = true;
return true;
}
static bool __attribute__((nonnull))
dec_path_response_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
decb_chk(c->path_resp_in, pos, end, PATH_CHLG_LEN, c, FRM_PRP);
mk_path_chlg_str(NTE, c->path_resp_in, pri_str);
warn(INF, FRAM_IN "PATH_RESPONSE" NRM " data=%s", pri_str);
if (unlikely(c->tx_path_chlg == false)) {
warn(NTE, "unexpected PATH_RESPONSE %s, ignoring", pri_str);
return true;
}
if (unlikely(c->path_resp_in != c->path_chlg_out)) {
mk_path_chlg_str(NTE, c->path_chlg_out, pco_str);
warn(NTE, "PATH_RESPONSE %s != %s, ignoring", pri_str, pco_str);
return true;
}
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char ip[NI_MAXHOST];
char port[NI_MAXSERV];
char migr_ip[NI_MAXHOST];
char migr_port[NI_MAXSERV];
ensure(getnameinfo((struct sockaddr *)&c->peer, sizeof(c->peer), ip,
sizeof(ip), port, sizeof(port),
NI_NUMERICHOST | NI_NUMERICSERV) == 0,
"getnameinfo");
ensure(getnameinfo((struct sockaddr *)&c->migr_peer, sizeof(c->migr_peer),
migr_ip, sizeof(migr_ip), migr_port, sizeof(migr_port),
NI_NUMERICHOST | NI_NUMERICSERV) == 0,
"getnameinfo");
warn(NTE, "migration from %s:%s to %s:%s complete", ip, port, migr_ip,
migr_port);
#endif
c->tx_path_chlg = false;
c->peer = c->migr_peer;
return true;
}
static bool __attribute__((nonnull))
dec_new_cid_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
struct cid dcid = {.seq = 0, .has_srt = true};
decv_chk(&dcid.seq, pos, end, c, FRM_CID);
decv_chk(&dcid.rpt, pos, end, c, FRM_CID);
dec1_chk(&dcid.len, pos, end, c, FRM_CID);
if (likely(dcid.len >= CID_LEN_MIN && dcid.len <= CID_LEN_MAX)) {
decb_chk(dcid.id, pos, end, dcid.len, c, FRM_CID);
decb_chk(dcid.srt, pos, end, sizeof(dcid.srt), c, FRM_CID);
}
const bool dup =
#ifndef NO_MIGRATION
splay_find(cids_by_seq, &c->dcids_by_seq, &dcid);
#else
false;
#endif
mk_srt_str(INF, dcid.srt, srt_str);
mk_cid_str(INF, &dcid, dcid_str);
warn(INF,
FRAM_IN "NEW_CONNECTION_ID" NRM " seq=%" PRIu " rpt=%" PRIu
" len=%u dcid=%s srt=%s%s",
dcid.seq, dcid.rpt, dcid.len, dcid_str, srt_str,
dup ? " [" RED "dup" NRM "]" : "");
#ifndef NO_MIGRATION
const uint_t max_act_cids =
c->tp_in.act_cid_lim + (c->tp_out.pref_addr.cid.len ? 1 : 0);
if (likely(dup == false) &&
unlikely(splay_count(&c->dcids_by_seq) > max_act_cids))
err_close_return(c, ERR_PROTOCOL_VIOLATION, FRM_CID,
"illegal seq %u (have %" PRIu "/%" PRIu ")", dcid.seq,
splay_count(&c->dcids_by_seq), max_act_cids);
if (unlikely(dcid.rpt > dcid.seq))
err_close_return(c, ERR_PROTOCOL_VIOLATION, FRM_CID, "illegal rpt %u",
dcid.rpt);
if (unlikely(dcid.len < CID_LEN_MIN || dcid.len > CID_LEN_MAX))
err_close_return(c, ERR_PROTOCOL_VIOLATION, FRM_CID, "illegal len %u",
dcid.len);
if (dup == false)
add_dcid(c, &dcid);
// FIXME: retire cids
#else
err_close_return(c, ERR_PROTOCOL_VIOLATION, FRM_CID,
"migration disabled but got NEW_CONNECTION_ID");
#endif
return true;
}
static bool __attribute__((nonnull))
dec_reset_stream_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
dint_t sid = 0;
decv_chk((uint_t *)&sid, pos, end, c, FRM_RST);
uint_t err_code;
decv_chk(&err_code, pos, end, c, FRM_RST);
uint_t off = 0;
decv_chk(&off, pos, end, c, FRM_RST);
warn(INF,
FRAM_IN "RESET_STREAM" NRM " id=" FMT_SID " err=%s0x%" PRIx NRM
" off=%" PRIu,
sid, err_code ? RED : NRM, err_code, off);
struct q_stream * const s = get_and_validate_strm(c, sid, FRM_RST, false);
if (unlikely(s == 0))
return true;
strm_to_state(s, strm_clsd);
return true;
}
static bool __attribute__((nonnull))
dec_retire_cid_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
struct cid which = {.seq = 0};
decv_chk(&which.seq, pos, end, c, FRM_RTR);
warn(INF, FRAM_IN "RETIRE_CONNECTION_ID" NRM " seq=%" PRIu, which.seq);
#ifndef NO_MIGRATION
struct cid * const scid = splay_find(cids_by_seq, &c->scids_by_seq, &which);
if (unlikely(scid == 0))
err_close_return(c, ERR_PROTOCOL_VIOLATION, FRM_RTR,
"no cid seq %" PRIu, which.seq);
else if (c->scid->seq == scid->seq) {
struct cid * const next_scid =
splay_next(cids_by_seq, &c->scids_by_seq, scid);
if (unlikely(next_scid == 0))
err_close_return(c, ERR_INTERNAL, FRM_RTR, "no next scid");
c->scid = next_scid;
}
free_scid(c, scid);
// rx of RETIRE_CONNECTION_ID means we should send more
c->tx_ncid = true;
#endif
return true;
}
static bool __attribute__((nonnull))
dec_new_token_frame(const uint8_t ** pos,
const uint8_t * const end,
const struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
uint_t tok_len = 0;
decv_chk(&tok_len, pos, end, c, FRM_TOK);
const uint_t act_tok_len = MIN(tok_len, (uint_t)(end - *pos));
uint8_t tok[MAX_TOK_LEN];
decb_chk(tok, pos, end, (uint16_t)act_tok_len, c, FRM_TOK);
mk_tok_str(INF, tok, tok_len, tok_str);
warn(INF, FRAM_IN "NEW_TOKEN" NRM " len=%" PRIu " tok=%s", tok_len,
tok_str);
if (unlikely(tok_len != act_tok_len))
err_close_return(c, ERR_FRAME_ENC, FRM_TOK, "illegal tok len");
// TODO: actually do something with the token
return true;
}
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
static void log_pad(const uint16_t len)
{
warn(INF, FRAM_IN "PADDING" NRM " len=%u", len);
}
#else
#define log_pad(...) \
do { \
} while (0)
#endif
bool dec_frames(struct q_conn * const c,
struct w_iov ** vv,
struct pkt_meta ** mm)
{
struct w_iov * v = *vv;
struct pkt_meta * m = *mm;
const uint8_t * pos = v->buf + m->hdr.hdr_len;
const uint8_t * start = v->buf;
const uint8_t * end = v->buf + v->len;
const uint8_t * pad_start = 0;
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
// when called from the fuzzer, v->addr.ss_family is zero
if (v->addr.ss_family)
write_to_corpus(corpus_frm_dir, pos, (size_t)(end - pos));
#endif
while (likely(pos < end)) {
uint8_t type;
dec1_chk(&type, &pos, end, c, 0);
// special-case for optimized parsing of padding ranges
if (type == FRM_PAD) {
if (unlikely(pad_start == 0)) {
pad_start = pos;
track_frame(m, FRM_PAD);
}
continue;
}
if (pad_start) {
log_pad((uint16_t)(pos - pad_start + 1));
pad_start = 0;
}
// check that frame type is allowed in this pkt type
static const struct frames lh_ok =
bitset_t_initializer(1 << FRM_CRY | 1 << FRM_ACK | 1 << FRM_ACE |
1 << FRM_PAD | 1 << FRM_CLQ | 1 << FRM_CLA);
if (unlikely((m->hdr.type == LH_INIT || m->hdr.type == LH_HSHK) &&
type < FRM_MAX &&
bit_isset(FRM_MAX, type, &lh_ok) == false))
err_close_return(c, ERR_PROTOCOL_VIOLATION, type,
"0x%02x frame not allowed in %s pkt", type,
pkt_type_str(m->hdr.flags, &m->hdr.vers));
bool ok;
switch (type) {
case FRM_CRY:
case FRM_STR:
case FRM_STR_09:
case FRM_STR_0a:
case FRM_STR_0b:
case FRM_STR_0c:
case FRM_STR_0d:
case FRM_STR_0e:
case FRM_STR_0f:;
static const struct frames cry_or_str =
bitset_t_initializer(1 << FRM_CRY | 1 << FRM_STR);
if (unlikely(bit_overlap(FRM_MAX, &m->frms, &cry_or_str)) &&
m->strm) {
// already had at least one stream or crypto frame in this
// packet with non-duplicate data, so generate (another) copy
#ifdef DEBUG_EXTRA
warn(DBG, "addtl stream or crypto frame, copy");
#endif
const uint16_t off = (uint16_t)(pos - v->buf - 1);
struct pkt_meta * mdup;
struct w_iov * const vdup = w_iov_dup(v, &mdup, off);
pm_cpy(mdup, m, false);
// adjust w_iov start and len to stream frame data
v->buf += m->strm_data_pos;
v->len = m->strm_data_len;
// continue parsing in the copied w_iov
v = *vv = vdup;
m = *mm = mdup;
pos = v->buf + 1;
start = v->buf;
end = v->buf + v->len;
}
ok = dec_stream_or_crypto_frame(type, &pos, end, m, v);
type = type == FRM_CRY ? FRM_CRY : FRM_STR;
break;
case FRM_ACE:
case FRM_ACK:
ok = dec_ack_frame(type, &pos, start, end, m);
type = FRM_ACK; // only enc FRM_ACK in bitstr_t
break;
case FRM_RST:
ok = dec_reset_stream_frame(&pos, end, m);
break;
case FRM_CLQ:
case FRM_CLA:
ok = dec_close_frame(type, &pos, end, m);
break;
case FRM_PNG:
warn(INF, FRAM_IN "PING" NRM);
ok = true;
break;
case FRM_MSD:
ok = dec_max_strm_data_frame(&pos, end, m);
break;
case FRM_MSB:
case FRM_MSU:
ok = dec_max_strms_frame(type, &pos, end, m);
break;
case FRM_MCD:
ok = dec_max_data_frame(&pos, end, m);
break;
case FRM_SDB:
ok = dec_strm_data_blocked_frame(&pos, end, m);
break;
case FRM_CDB:
ok = dec_data_blocked_frame(&pos, end, m);
break;
case FRM_SBB:
case FRM_SBU:
ok = dec_streams_blocked_frame(type, &pos, end, m);
break;
case FRM_STP:
ok = dec_stop_sending_frame(&pos, end, m);
break;
case FRM_PCL:
ok = dec_path_challenge_frame(&pos, end, m);
break;
case FRM_PRP:
ok = dec_path_response_frame(&pos, end, m);
break;
case FRM_CID:
ok = dec_new_cid_frame(&pos, end, m);
break;
case FRM_TOK:
ok = dec_new_token_frame(&pos, end, m);
break;
case FRM_RTR:
ok = dec_retire_cid_frame(&pos, end, m);
break;
default:
err_close_return(c, ERR_FRAME_ENC, type,
"unknown 0x%02x frame at pos %u", type,
pos - v->buf);
}
if (unlikely(ok == false))
// there was an error parsing a frame
err_close_return(c, ERR_FRAME_ENC, type,
"error parsing 0x%02x frame at pos %lu", type,
pos - v->buf);
// record this frame type in the meta data
track_frame(m, type);
}
if (pad_start)
log_pad((uint16_t)(pos - pad_start + 1));
if (m->strm_data_pos) {
// adjust w_iov start and len to stream frame data
v->buf += m->strm_data_pos;
v->len = m->strm_data_len;
}
// track outstanding frame types in the pn space
struct pn_space * const pn = pn_for_pkt_type(c, m->hdr.type);
bit_or(FRM_MAX, &pn->rx_frames, &m->frms);
return true;
}
uint16_t max_frame_len(const uint8_t type)
{
// return max len needed to encode the given frame type
uint16_t len = sizeof(uint8_t); // type
switch (type) {
case FRM_PAD:
case FRM_PNG:
break;
// these are always first, so assume there is enough space
// case FRM_ACE:
// case FRM_ACK:
case FRM_RST:
len += sizeof(uint_t) + sizeof(uint16_t) + sizeof(uint_t);
break;
// these two are never combined with stream frames, so no need to
// check case FRM_CLQ: case FRM_CLA:
case FRM_STP:
len += sizeof(uint_t) + sizeof(uint16_t);
break;
// these two don't need to be length-checked
// case FRM_STR:
// case FRM_CRY:
case FRM_TOK:
// only true on TX; update when make_rtry_tok() changes
len += sizeof(uint_t) + PTLS_MAX_DIGEST_SIZE + CID_LEN_MAX;
break;
case FRM_MCD:
case FRM_MSB:
case FRM_MSU:
case FRM_CDB:
case FRM_SBB:
case FRM_SBU:
case FRM_RTR:
case FRM_PCL:
case FRM_PRP:
len += sizeof(uint_t);
break;
case FRM_MSD:
case FRM_SDB:
len += sizeof(uint_t) + sizeof(uint_t);
break;
case FRM_CID:
len += sizeof(uint_t) + sizeof(uint8_t) + CID_LEN_MAX + SRT_LEN;
break;
default:
die("unhandled 0x%02x frame", type);
}
return len;
}
void enc_padding_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
const uint16_t len)
{
if (unlikely(len == 0))
return;
ensure(*pos + len <= end, "buffer overflow w/len %u", len);
memset(*pos, FRM_PAD, len);
*pos += len;
warn(INF, FRAM_OUT "PADDING" NRM " len=%u", len);
track_frame(m, FRM_PAD);
}
void enc_ack_frame(uint8_t ** pos,
const uint8_t * const start,
const uint8_t * const end,
struct pkt_meta * const m,
struct pn_space * const pn)
{
const uint8_t type =
likely(pn->ect0_cnt || pn->ect1_cnt || pn->ce_cnt) ? FRM_ACE : FRM_ACK;
enc1(pos, end, type);
m->ack_frm_pos = (uint16_t)(*pos - start);
const struct ival * const first_rng = diet_max_ival(&pn->recv);
ensure(first_rng, "nothing to ACK");
encv(pos, end, first_rng->hi);
// handshake pkts always use the default ACK delay exponent
struct q_conn * const c = pn->c;
const uint_t ade = m->hdr.type == LH_INIT || m->hdr.type == LH_HSHK
? DEF_ACK_DEL_EXP
: c->tp_out.ack_del_exp;
const uint_t ack_delay =
NS_TO_MS(loop_now() - diet_timestamp(first_rng)) >> ade;
encv(pos, end, ack_delay);
const uint_t ack_rng_cnt = diet_cnt(&pn->recv) - 1;
encv(pos, end, ack_rng_cnt);
uint_t prev_lo = 0;
struct ival * b;
diet_foreach_rev (b, diet, &pn->recv) {
uint_t gap = 0;
if (prev_lo) {
gap = prev_lo - b->hi - 2;
encv(pos, end, gap);
}
const uint_t ack_rng = b->hi - b->lo;
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
if (ack_rng) {
if (prev_lo)
warn(INF,
FRAM_OUT "ACK" NRM " gap=%" PRIu " rng=%" PRIu
" [" FMT_PNR_IN ".." FMT_PNR_IN "]",
gap, ack_rng, b->lo, shorten_ack_nr(b->hi, ack_rng));
else
warn(INF,
FRAM_OUT "ACK" NRM " 0x%02x=%s lg=" FMT_PNR_IN
" delay=%" PRIu " (%" PRIu " usec) cnt=%" PRIu
" rng=%" PRIu " [" FMT_PNR_IN ".." FMT_PNR_IN "]",
type, type == FRM_ACE ? "ECN" : "", first_rng->hi,
ack_delay, ack_delay << ade, ack_rng_cnt, ack_rng, b->lo,
shorten_ack_nr(b->hi, ack_rng));
} else {
if (prev_lo)
warn(INF,
FRAM_OUT "ACK" NRM " gap=%" PRIu " rng=%" PRIu
" [" FMT_PNR_IN "]",
gap, ack_rng, b->hi);
else
warn(INF,
FRAM_OUT "ACK" NRM " 0x%02x=%s lg=" FMT_PNR_IN
" delay=%" PRIu " (%" PRIu " usec) cnt=%" PRIu
" rng=%" PRIu " [" FMT_PNR_IN "]",
type, type == FRM_ACE ? "ECN" : "", first_rng->hi,
ack_delay, ack_delay << ade, ack_rng_cnt, ack_rng,
first_rng->hi);
}
#endif
encv(pos, end, ack_rng);
prev_lo = b->lo;
}
if (type == FRM_ACE) {
// encode ECN
encv(pos, end, pn->ect0_cnt);
encv(pos, end, pn->ect1_cnt);
encv(pos, end, pn->ce_cnt);
warn(INF,
FRAM_OUT "ECN" NRM " ect0=%s%" PRIu NRM " ect1=%s%" PRIu NRM
" ce=%s%" PRIu NRM,
pn->ect0_cnt ? BLU : NRM, pn->ect0_cnt, pn->ect1_cnt ? BLU : NRM,
pn->ect1_cnt, pn->ce_cnt ? BLU : NRM, pn->ce_cnt);
}
timeouts_del(ped(c->w)->wheel, &c->ack_alarm);
bit_zero(FRM_MAX, &pn->rx_frames);
pn->pkts_rxed_since_last_ack_tx = 0;
pn->imm_ack = false;
track_frame(m, FRM_ACK);
}
void calc_lens_of_stream_or_crypto_frame(const struct pkt_meta * const m,
const struct w_iov * const v,
const struct q_stream * const s,
uint16_t * const hlen,
uint16_t * const dlen)
{
const uint16_t strm_data_len = (uint16_t)(v->len - m->strm_data_pos);
const bool enc_strm = s->id >= 0;
*hlen = 1; // type byte
if (likely(enc_strm))
*hlen += varint_size((uint_t)s->id);
if (likely(s->out_data || !enc_strm))
*hlen += varint_size(s->out_data);
*dlen = likely(enc_strm) &&
strm_data_len == MAX_PKT_LEN - AEAD_LEN - DATA_OFFSET
? 0
: strm_data_len;
if (*dlen)
*hlen += varint_size(*dlen);
}
void enc_stream_or_crypto_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct w_iov * const v,
struct q_stream * const s,
const uint16_t dlen)
{
const bool enc_strm = s->id >= 0;
uint8_t type = likely(enc_strm) ? FRM_STR : FRM_CRY;
m->strm = s;
m->strm_data_len = v->len - m->strm_data_pos;
m->strm_off = s->out_data;
m->strm_frm_pos = (uint16_t)(*pos - v->buf);
(*pos)++;
if (likely(enc_strm))
encv(pos, end, (uint_t)s->id);
if (m->strm_off || unlikely(!enc_strm)) {
if (likely(enc_strm))
type |= F_STREAM_OFF;
encv(pos, end, m->strm_off);
}
if (dlen) {
if (likely(enc_strm))
type |= F_STREAM_LEN;
encv(pos, end, dlen);
}
if (likely(enc_strm) && unlikely(m->is_fin))
type |= F_STREAM_FIN;
*pos = v->buf + m->strm_frm_pos;
enc1(pos, end, type);
*pos = v->buf + m->strm_data_pos + m->strm_data_len;
log_stream_or_crypto_frame(false, m, type, s->id, false, "");
track_bytes_out(s, m->strm_data_len);
ensure(!enc_strm || m->strm_off < s->out_data_max, "exceeded fc window");
track_frame(m, type == FRM_CRY ? FRM_CRY : FRM_STR);
}
void enc_close_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
const struct q_conn * const c = m->pn->c;
const uint8_t type = c->err_frm == 0 ? FRM_CLA : FRM_CLQ;
enc1(pos, end, type);
encv(pos, end, c->err_code);
if (type == FRM_CLQ)
enc1(pos, end, c->err_frm);
#ifndef NO_ERR_REASONS
const uint8_t err_reason_len = c->err_reason_len;
const char * const err_reason = c->err_reason;
#else
const uint8_t err_reason_len = 0;
const char err_reason[] = "";
#endif
encv(pos, end, err_reason_len);
if (err_reason_len)
encb(pos, end, (const uint8_t *)err_reason, err_reason_len);
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
if (type == FRM_CLQ)
warn(INF,
FRAM_OUT "CONNECTION_CLOSE" NRM " 0x%02x=quic err=%s0x%" PRIx NRM
" frame=0x%02x rlen=%u reason=%s%.*s" NRM,
type, c->err_code ? RED : NRM, c->err_code, c->err_frm,
err_reason_len, c->err_code ? RED : NRM, (int)err_reason_len,
err_reason);
else
warn(INF,
FRAM_OUT "CONNECTION_CLOSE" NRM " 0x%02x=app err=%s0x%" PRIx NRM
" rlen=%u reason=%s%.*s" NRM,
type, c->err_code ? RED : NRM, c->err_code, err_reason_len,
c->err_code ? RED : NRM, (int)err_reason_len, err_reason);
#endif
track_frame(m, type);
}
void enc_max_strm_data_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct q_stream * const s)
{
enc1(pos, end, FRM_MSD);
encv(pos, end, (uint_t)s->id);
encv(pos, end, s->in_data_max);
warn(INF, FRAM_OUT "MAX_STREAM_DATA" NRM " id=" FMT_SID " max=%" PRIu,
s->id, s->in_data_max);
m->max_strm_data_sid = s->id;
m->max_strm_data = s->in_data_max;
s->tx_max_strm_data = false;
track_frame(m, FRM_MSD);
}
void enc_max_data_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
enc1(pos, end, FRM_MCD);
encv(pos, end, c->tp_in.max_data);
warn(INF, FRAM_OUT "MAX_DATA" NRM " max=%" PRIu, c->tp_in.max_data);
m->max_data = c->tp_in.max_data;
c->tx_max_data = false;
track_frame(m, FRM_MCD);
}
void enc_max_strms_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
const bool bidi)
{
struct q_conn * const c = m->pn->c;
const uint8_t type = bidi ? FRM_MSB : FRM_MSU;
enc1(pos, end, type);
const uint_t max = bidi ? c->tp_in.max_strms_bidi : c->tp_in.max_strms_uni;
encv(pos, end, max);
warn(INF, FRAM_OUT "MAX_STREAMS" NRM " 0x%02x=%s max=%" PRIu, type,
bidi ? "bi" : "uni", max);
if (bidi)
c->tx_max_sid_bidi = false;
else
c->tx_max_sid_uni = false;
track_frame(m, type);
}
void enc_strm_data_blocked_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct q_stream * const s)
{
enc1(pos, end, FRM_SDB);
encv(pos, end, (uint_t)s->id);
m->strm_data_blocked = s->out_data_max;
encv(pos, end, m->strm_data_blocked);
warn(INF, FRAM_OUT "STREAM_DATA_BLOCKED" NRM " id=" FMT_SID " lim=%" PRIu,
s->id, m->strm_data_blocked);
track_frame(m, FRM_SDB);
}
void enc_data_blocked_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
enc1(pos, end, FRM_CDB);
m->data_blocked = m->pn->c->tp_out.max_data + m->strm_data_len;
encv(pos, end, m->data_blocked);
warn(INF, FRAM_OUT "DATA_BLOCKED" NRM " lim=%" PRIu, m->data_blocked);
track_frame(m, FRM_CDB);
}
void enc_streams_blocked_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
const bool bidi)
{
struct q_conn * const c = m->pn->c;
const uint8_t type = bidi ? FRM_SBB : FRM_SBU;
enc1(pos, end, type);
const uint_t lim =
bidi ? c->tp_out.max_strms_bidi : c->tp_out.max_strms_uni;
encv(pos, end, lim);
warn(INF, FRAM_OUT "STREAMS_BLOCKED" NRM " 0x%02x=%s lim=%" PRIu, type,
type == FRM_SBB ? "bi" : "uni", lim);
if (bidi)
c->sid_blocked_bidi = false;
else
c->sid_blocked_uni = false;
track_frame(m, type);
}
void enc_path_response_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
const struct q_conn * const c = m->pn->c;
enc1(pos, end, FRM_PRP);
encb(pos, end, c->path_resp_out, sizeof(c->path_resp_out));
mk_path_chlg_str(INF, c->path_resp_out, pro_str);
warn(INF, FRAM_OUT "PATH_RESPONSE" NRM " data=%s", pro_str);
track_frame(m, FRM_PRP);
}
void enc_path_challenge_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
const struct q_conn * const c = m->pn->c;
enc1(pos, end, FRM_PCL);
encb(pos, end, c->path_chlg_out, sizeof(c->path_chlg_out));
mk_path_chlg_str(INF, c->path_resp_out, pco_str);
warn(INF, FRAM_OUT "PATH_CHALLENGE" NRM " data=%s", pco_str);
track_frame(m, FRM_PCL);
}
#ifndef NO_MIGRATION
void enc_new_cid_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
struct q_conn * const c = m->pn->c;
const struct cid * const max_scid =
splay_max(cids_by_seq, &c->scids_by_seq);
const struct cid * const min_scid =
splay_min(cids_by_seq, &c->scids_by_seq);
c->max_cid_seq_out = MAX(min_scid->seq, c->max_cid_seq_out + 1);
struct cid ncid = {.seq = c->max_cid_seq_out,
.len = c->is_clnt ? SCID_LEN_CLNT : SCID_LEN_SERV};
// FIXME: add rpt
struct cid * enc_cid = &ncid;
if (max_scid && ncid.seq <= max_scid->seq) {
enc_cid = splay_find(cids_by_seq, &c->scids_by_seq, &ncid);
ensure(enc_cid, "max_scid->seq %" PRIu " ncid.seq %" PRIu,
max_scid->seq, ncid.seq);
} else {
rand_bytes(ncid.id, sizeof(ncid.id) + sizeof(ncid.srt));
add_scid(c, &ncid);
}
m->min_cid_seq = m->min_cid_seq == 0 ? enc_cid->seq : m->min_cid_seq;
enc1(pos, end, FRM_CID);
encv(pos, end, enc_cid->seq);
encv(pos, end, enc_cid->rpt);
enc1(pos, end, enc_cid->len);
encb(pos, end, enc_cid->id, enc_cid->len);
encb(pos, end, enc_cid->srt, sizeof(enc_cid->srt));
mk_srt_str(INF, enc_cid->srt, srt_str);
mk_cid_str(INF, enc_cid, enc_cid_str);
warn(INF,
FRAM_OUT "NEW_CONNECTION_ID" NRM " seq=%" PRIu " rpt=%" PRIu
" len=%u cid=%s srt=%s %s",
enc_cid->seq, enc_cid->rpt, enc_cid->len, enc_cid_str, srt_str,
enc_cid == &ncid ? "" : BLD REV GRN "[RTX]" NRM);
track_frame(m, FRM_CID);
}
#endif
void enc_new_token_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
const struct q_conn * const c = m->pn->c;
enc1(pos, end, FRM_TOK);
encv(pos, end, c->tok_len);
encb(pos, end, c->tok, c->tok_len);
mk_tok_str(INF, c->tok, c->tok_len, tok_str);
warn(INF, FRAM_OUT "NEW_TOKEN" NRM " len=%u tok=%s", c->tok_len, tok_str);
track_frame(m, FRM_TOK);
}
void enc_retire_cid_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m,
struct cid * const dcid)
{
enc1(pos, end, FRM_RTR);
encv(pos, end, dcid->seq);
warn(INF, FRAM_OUT "RETIRE_CONNECTION_ID" NRM " seq=%" PRIu, dcid->seq);
m->pn->c->tx_retire_cid = false;
track_frame(m, FRM_RTR);
}
void enc_ping_frame(uint8_t ** pos,
const uint8_t * const end,
struct pkt_meta * const m)
{
enc1(pos, end, FRM_PNG);
warn(INF, FRAM_OUT "PING" NRM);
track_frame(m, FRM_PNG);
}
|
jlaine/quant
|
lib/src/tls.c
|
<gh_stars>0
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <assert.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/types.h>
#ifndef NO_TLS_TICKETS
#include <unistd.h>
#endif
#ifndef NO_TLS_LOG
#include <stdarg.h>
#endif
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
#include <netdb.h>
#endif
#ifdef PARTICLE
#include <rng_hal.h>
#include <uECC.h>
#define gai_strerror(x) ""
void ptls_minicrypto_random_bytes(void * buf, size_t len)
{
while (len >= sizeof(uint32_t)) {
*((uint32_t *)buf) = HAL_RNG_GetRandomNumber();
buf += sizeof(uint32_t);
len -= sizeof(uint32_t);
}
while (len > 0) {
*((uint8_t *)buf) = HAL_RNG_GetRandomNumber();
buf += sizeof(uint8_t);
len -= sizeof(uint8_t);
}
}
static int uecc_rng(uint8_t * dest, unsigned size)
{
ptls_minicrypto_random_bytes(dest, size);
return 1;
}
#endif
#ifdef WITH_OPENSSL
#include <openssl/evp.h>
#include <openssl/ossl_typ.h>
#include <openssl/pem.h>
#include <picotls/openssl.h>
#define cipher_suite ptls_openssl_cipher_suites
#define aes128gcmsha256 ptls_openssl_aes128gcmsha256
#define secp256r1 ptls_openssl_secp256r1
#define x25519 ptls_openssl_x25519
#define sign_certificate_t ptls_openssl_sign_certificate_t
#else
#include <picotls/minicrypto.h>
#ifndef PARTICLE
#define cipher_suite ptls_minicrypto_cipher_suites
#else
static const ptls_cipher_suite_t * cipher_suite[] = {
&ptls_minicrypto_aes128gcmsha256, 0};
#endif
#define aes128gcmsha256 ptls_minicrypto_aes128gcmsha256
#define secp256r1 ptls_minicrypto_secp256r1
#define x25519 ptls_minicrypto_x25519
#endif
#include <quant/quant.h>
#include "bitset.h"
#include "conn.h"
#include "frame.h"
#include "marshall.h"
#include "pkt.h"
#include "pn.h"
#include "quic.h"
#include "stream.h"
#include "tls.h"
#ifndef NO_TLS_TICKETS
struct tls_ticket {
char * sni;
char * alpn;
uint8_t * ticket;
size_t ticket_len;
struct transport_params tp;
uint32_t vers;
uint8_t _unused[4];
splay_entry(tls_ticket) node;
};
struct tickets_by_peer {
splay_head(, tls_ticket);
char file_name[MAXPATHLEN];
};
static int __attribute__((nonnull))
tls_ticket_cmp(const struct tls_ticket * const a,
const struct tls_ticket * const b)
{
int diff = strcmp(a->sni, b->sni);
if (diff)
return diff;
diff = strcmp(a->alpn, b->alpn);
return diff;
}
SPLAY_PROTOTYPE(tickets_by_peer, tls_ticket, node, tls_ticket_cmp)
SPLAY_GENERATE(tickets_by_peer, tls_ticket, node, tls_ticket_cmp)
static struct tickets_by_peer tickets = {splay_initializer(tickets), {"\0"}};
#endif
#ifndef NO_TLS_LOG
static FILE * tls_log_file;
#endif
#ifdef WITH_OPENSSL
static sign_certificate_t sign_cert = {0};
static ptls_openssl_verify_certificate_t verifier = {0};
#endif
// first entry is client default, if not otherwise specified
// last entry should be h3-, since we ignore that in on_ch
static const ptls_iovec_t alpn[] = {{(uint8_t *)"hq-" DRAFT_VERSION_STRING, 5},
{(uint8_t *)"h3-" DRAFT_VERSION_STRING, 5}};
static const size_t alpn_cnt = sizeof(alpn) / sizeof(alpn[0]);
#ifndef NO_TLS_TICKETS
static struct cipher_ctx dec_tckt;
static struct cipher_ctx enc_tckt;
#endif
#define QUIC_TP 0xffa5
#define TP_OCID 0x00 ///< original_connection_id
#define TP_IDTO 0x01 ///< idle_timeout
#define TP_SRT 0x02 ///< stateless_reset_token
#define TP_MPS 0x03 ///< max_packet_size
#define TP_IMD 0x04 ///< initial_max_data
#define TP_IMSD_BL 0x05 ///< initial_max_stream_data_bidi_local
#define TP_IMSD_BR 0x06 ///< initial_max_stream_data_bidi_remote
#define TP_IMSD_U 0x07 ///< initial_max_stream_data_uni
#define TP_IMSB 0x08 ///< initial_max_streams_bidi
#define TP_IMSU 0x09 ///< initial_max_streams_uni
#define TP_ADE 0x0a ///< ack_delay_exponent
#define TP_MAD 0x0b ///< max_ack_delay
#define TP_DMIG 0x0c ///< disable_migration
#define TP_PRFA 0x0d ///< preferred_address
#define TP_ACIL 0x0e ///< active_connection_id_limit
#define TP_MAX (TP_ACIL + 1)
// quicly shim
#define AEAD_BASE_LABEL PTLS_HKDF_EXPAND_LABEL_PREFIX "quic "
#define st_quicly_cipher_context_t cipher_ctx
// from quicly
void dispose_cipher(struct st_quicly_cipher_context_t * ctx)
{
if (ctx->aead) {
ptls_aead_free(ctx->aead);
ctx->aead = 0;
}
if (ctx->header_protection) {
ptls_cipher_free(ctx->header_protection);
ctx->header_protection = 0;
}
}
// from quicly (with mods for key update)
static int setup_cipher(ptls_cipher_context_t ** hp_ctx,
ptls_aead_context_t ** aead_ctx,
ptls_aead_algorithm_t * aead,
ptls_hash_algorithm_t * hash,
int is_enc,
const void * secret)
{
uint8_t hpkey[PTLS_MAX_SECRET_SIZE] = {0};
int ret;
// *hp_ctx = NULL;
// *aead_ctx = NULL;
if (hp_ctx) {
if ((ret = ptls_hkdf_expand_label(
hash, hpkey, aead->ctr_cipher->key_size,
ptls_iovec_init(secret, hash->digest_size), "quic hp",
ptls_iovec_init(NULL, 0), NULL)) != 0)
goto Exit;
if ((*hp_ctx = ptls_cipher_new(aead->ctr_cipher, is_enc, hpkey)) ==
NULL) {
ret = PTLS_ERROR_NO_MEMORY;
goto Exit;
}
}
if ((*aead_ctx = ptls_aead_new(aead, hash, is_enc, secret,
AEAD_BASE_LABEL)) == NULL) {
ret = PTLS_ERROR_NO_MEMORY;
goto Exit;
}
#ifdef DEBUG_PROT
char secret_str[hex_str_len(PTLS_MAX_DIGEST_SIZE)];
char hpkey_str[hex_str_len(PTLS_MAX_DIGEST_SIZE)];
hex2str(secret, hash->digest_size, secret_str, sizeof(secret_str));
hex2str(hpkey, aead->ctr_cipher->key_size, hpkey_str, sizeof(hpkey_str));
warn(NTE, "aead-secret: %s, hp-key: %s", secret_str, hpkey_str);
#endif
ret = 0;
Exit:
if (ret != 0) {
if (*aead_ctx != NULL) {
ptls_aead_free(*aead_ctx);
*aead_ctx = NULL;
}
if (hp_ctx && *hp_ctx != NULL) {
ptls_cipher_free(*hp_ctx);
*hp_ctx = NULL;
}
}
ptls_clear_memory(hpkey, sizeof(hpkey));
return ret;
}
// from quicly (with mods for key update)
static int setup_initial_key(struct st_quicly_cipher_context_t * ctx,
ptls_cipher_suite_t * cs,
const void * master_secret,
const char * label,
int is_enc,
void * new_secret)
{
uint8_t _aead_secret[PTLS_MAX_DIGEST_SIZE];
uint8_t * const aead_secret = new_secret ? new_secret : _aead_secret;
int ret;
if ((ret = ptls_hkdf_expand_label(
cs->hash, aead_secret, cs->hash->digest_size,
ptls_iovec_init(master_secret, cs->hash->digest_size), label,
ptls_iovec_init(NULL, 0), NULL)) != 0)
goto Exit;
if ((ret =
setup_cipher(new_secret ? 0 : &ctx->header_protection, &ctx->aead,
cs->aead, cs->hash, is_enc, aead_secret)) != 0)
goto Exit;
Exit:
ptls_clear_memory(aead_secret, sizeof(aead_secret));
return ret;
}
// from quicly (with mods to the setup_initial_key call)
static int setup_initial_encryption(struct st_quicly_cipher_context_t * ingress,
struct st_quicly_cipher_context_t * egress,
ptls_cipher_suite_t ** cipher_suites,
ptls_iovec_t cid,
int is_client)
{
static const uint8_t salt[] = {0x7f, 0xbc, 0xdb, 0x0e, 0x7c, 0x66, 0xbb,
0xe9, 0x19, 0x3a, 0x96, 0xcd, 0x21, 0x51,
0x9e, 0xbd, 0x7a, 0x02, 0x64, 0x4a};
static const char * labels[2] = {"client in", "server in"};
ptls_cipher_suite_t ** cs;
uint8_t secret[PTLS_MAX_DIGEST_SIZE];
int ret;
/* find aes128gcm cipher */
for (cs = cipher_suites;; ++cs) {
assert(cs != NULL);
if ((*cs)->id == PTLS_CIPHER_SUITE_AES_128_GCM_SHA256)
break;
}
/* extract master secret */
if ((ret = ptls_hkdf_extract((*cs)->hash, secret,
ptls_iovec_init(salt, sizeof(salt)), cid)) !=
0)
goto Exit;
/* create aead contexts */
if ((ret = setup_initial_key(ingress, *cs, secret, labels[is_client], 0,
0)) != 0)
goto Exit;
if ((ret = setup_initial_key(egress, *cs, secret, labels[!is_client], 1,
0)) != 0)
goto Exit;
Exit:
ptls_clear_memory(secret, sizeof(secret));
return ret;
}
static int __attribute__((nonnull))
on_ch(ptls_on_client_hello_t * const self __attribute__((unused)),
ptls_t * const tls,
ptls_on_client_hello_parameters_t * const params)
{
if (params->server_name.len) {
// TODO verify the SNI instead of accepting whatever the client sent
warn(INF, "\tSNI = %.*s", (int)params->server_name.len,
params->server_name.base);
ensure(ptls_set_server_name(tls, (const char *)params->server_name.base,
params->server_name.len) == 0,
"ptls_set_server_name");
} else
warn(INF, "\tSNI = ");
if (params->negotiated_protocols.count == 0) {
warn(WRN, "\tALPN = ");
return 0;
}
size_t j;
for (j = 0; j < alpn_cnt - 1; j++)
for (size_t i = 0; i < params->negotiated_protocols.count; i++)
if (memcmp(params->negotiated_protocols.list[i].base, alpn[j].base,
MIN(params->negotiated_protocols.list[i].len,
alpn[j].len)) == 0)
goto done;
if (j == alpn_cnt - 1) {
warn(WRN, RED "\tALPN = %.*s (and maybe others, none supported)" NRM,
(int)params->negotiated_protocols.list[0].len,
params->negotiated_protocols.list[0].base);
return PTLS_ALERT_NO_APPLICATION_PROTOCOL;
}
done:
// mark this ALPN as negotiated
ptls_set_negotiated_protocol(tls, (char *)alpn[j].base, alpn[j].len);
warn(INF, "\tALPN = %.*s", (int)alpn[j].len, alpn[j].base);
return 0;
}
static int filter_tp(ptls_t * tls __attribute__((unused)),
struct st_ptls_handshake_properties_t * properties
__attribute__((unused)),
uint16_t type)
{
return type == QUIC_TP;
}
static bool __attribute__((nonnull))
dec_tp(uint_t * const val, const uint8_t ** pos, const uint8_t * const end)
{
uint16_t len;
if (dec2(&len, pos, end) == false)
return false;
if (len) {
uint64_t v = 0;
decv(&v, pos, end);
*val = (uint_t)v;
}
return true;
}
static int chk_tp(ptls_t * tls __attribute__((unused)),
ptls_handshake_properties_t * properties,
ptls_raw_extension_t * slots)
{
ensure(slots[0].type == QUIC_TP, "have tp");
ensure(slots[1].type == UINT16_MAX, "have end");
// get connection based on properties pointer
struct q_conn * const c =
(void *)((char *)properties - offsetof(struct tls, tls_hshk_prop) -
offsetof(struct q_conn, tls));
// set up parsing
const uint8_t * pos = (const uint8_t *)slots[0].data.base;
const uint8_t * const end = pos + slots[0].data.len;
uint16_t tpl;
if (dec2(&tpl, &pos, end) == false)
return 1;
if (tpl != slots[0].data.len - sizeof(tpl)) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY, "tp len %u incorrect",
tpl);
return 1;
}
// keep track of which transport parameters we've seen before
bitset_define(tp_list, TP_MAX);
struct tp_list tp_list = bitset_t_initializer(0);
while (pos < end) {
uint16_t tp;
if (dec2(&tp, &pos, end) == false)
return 1;
// skip unknown TPs
if (tp >= TP_MAX) {
uint16_t unknown_len;
if (dec2(&unknown_len, &pos, end) == false)
return 1;
char hex[hex_str_len(sizeof(c->tls.tp_buf))];
hex2str(pos, unknown_len, hex, sizeof(hex));
warn(WRN, "\t" BLD "%s tp" NRM " (0x%04x w/len %u) = %s",
(tp & 0xff00) == 0xff00 ? YEL "private" : RED "unknown", tp,
unknown_len, hex);
pos += unknown_len;
continue;
}
// check if this transport parameter is a duplicate
if (bit_isset(TP_MAX, tp, &tp_list)) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"duplicate tp 0x%04x", tp);
return 1;
}
bit_set(TP_MAX, tp, &tp_list);
switch (tp) {
case TP_IMSD_U:
if (dec_tp(&c->tp_out.max_strm_data_uni, &pos, end) == false)
return 1;
warn(INF, "\tinitial_max_stream_data_uni = %" PRIu " [bytes]",
c->tp_out.max_strm_data_uni);
break;
case TP_IMSD_BL:
if (dec_tp(&c->tp_out.max_strm_data_bidi_remote, &pos, end) ==
false)
return 1;
warn(INF,
"\tinitial_max_stream_data_bidi_local = %" PRIu " [bytes]",
c->tp_out.max_strm_data_bidi_remote);
break;
case TP_IMSD_BR:
// this is RX'ed as _remote, but applies to streams we open, so:
if (dec_tp(&c->tp_out.max_strm_data_bidi_local, &pos, end) == false)
return 1;
warn(INF,
"\tinitial_max_stream_data_bidi_remote = %" PRIu " [bytes]",
c->tp_out.max_strm_data_bidi_local);
break;
case TP_IMD:
if (dec_tp(&c->tp_out.max_data, &pos, end) == false)
return 1;
warn(INF, "\tinitial_max_data = %" PRIu " [bytes]",
c->tp_out.max_data);
break;
case TP_IMSB:
if (dec_tp(&c->tp_out.max_strms_bidi, &pos, end) == false)
return 1;
warn(INF, "\tinitial_max_streams_bidi = %" PRIu,
c->tp_out.max_strms_bidi);
break;
case TP_IMSU:
if (dec_tp(&c->tp_out.max_strms_uni, &pos, end) == false)
return 1;
warn(INF, "\tinitial_max_streams_uni = %" PRIu,
c->tp_out.max_strms_uni);
break;
case TP_IDTO:
if (dec_tp(&c->tp_out.idle_to, &pos, end) == false)
return 1;
warn(INF, "\tidle_timeout = %" PRIu " [ms]", c->tp_out.idle_to);
break;
case TP_MPS:
if (dec_tp(&c->tp_out.max_pkt, &pos, end) == false)
return 1;
warn(INF, "\tmax_packet_size = %" PRIu " [bytes]",
c->tp_out.max_pkt);
if (c->tp_out.max_pkt < 1200) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"tp_out.max_pkt %" PRIu " invalid (< 1200)",
c->tp_out.max_pkt);
return 1;
}
break;
case TP_ADE:;
uint_t ade = DEF_ACK_DEL_EXP;
if (dec_tp(&ade, &pos, end) == false)
return 1;
warn(INF, "\tack_delay_exponent = %" PRIu, ade);
if (ade > 20) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"ack_delay_exponent %" PRIu " invalid", ade);
return 1;
}
c->tp_out.ack_del_exp = (uint8_t)ade;
break;
case TP_MAD:
if (dec_tp(&c->tp_out.max_ack_del, &pos, end) == false)
return 1;
warn(INF, "\tmax_ack_delay = %" PRIu " [ms]",
c->tp_out.max_ack_del);
if (c->tp_out.max_ack_del > (1 << 14)) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"max_ack_delay %" PRIu " invalid",
c->tp_out.max_ack_del);
return 1;
}
break;
case TP_OCID:
if (c->is_clnt == false) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"rx original_connection_id tp at serv");
return 1;
}
uint16_t len;
if (dec2(&len, &pos, end) == false)
return 1;
if (len) {
decb(c->tp_out.orig_cid.id, &pos, end, len);
c->tp_out.orig_cid.len = (uint8_t)len;
}
mk_cid_str(INF, &c->tp_out.orig_cid, orig_cid_str);
warn(INF, "\toriginal_connection_id = %s", orig_cid_str);
break;
case TP_DMIG:;
uint_t dmig;
if (dec_tp(&dmig, &pos, end) == false)
return 1;
warn(INF, "\tdisable_migration = true");
c->tp_out.disable_migration = true;
break;
case TP_SRT:
if (c->is_clnt == false) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"rx stateless_reset_token tp at serv");
return 1;
}
uint16_t l;
if (dec2(&l, &pos, end) == false)
return 1;
struct cid * const dcid = c->dcid;
if (l != sizeof(dcid->srt)) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"illegal srt len %u", l);
return 1;
}
memcpy(dcid->srt, pos, sizeof(dcid->srt));
dcid->has_srt = true;
{
mk_srt_str(INF, dcid->srt, srt_str);
warn(INF, "\tstateless_reset_token = %s", srt_str);
}
conns_by_srt_ins(c, dcid->srt);
pos += sizeof(dcid->srt);
break;
case TP_PRFA:
if (dec2(&l, &pos, end) == false)
return 1;
struct pref_addr * const pa = &c->tp_out.pref_addr;
struct sockaddr_in * const pa4 =
(struct sockaddr_in *)&c->tp_out.pref_addr.addr4;
struct sockaddr_in6 * const pa6 =
(struct sockaddr_in6 *)&c->tp_out.pref_addr.addr6;
pa4->sin_family = AF_INET;
memcpy(&pa4->sin_addr, pos, sizeof(pa4->sin_addr));
pos += sizeof(pa4->sin_addr);
memcpy(&pa4->sin_port, pos, sizeof(pa4->sin_port));
pos += sizeof(pa4->sin_port);
pa6->sin6_family = AF_INET6;
memcpy(&pa6->sin6_addr, pos, sizeof(pa6->sin6_addr));
pos += sizeof(pa6->sin6_addr);
memcpy(&pa6->sin6_port, pos, sizeof(pa6->sin6_port));
pos += sizeof(pa6->sin6_port);
dec1(&pa->cid.len, &pos, end);
memcpy(pa->cid.id, pos, pa->cid.len);
pos += pa->cid.len;
pa->cid.seq = 1;
memcpy(pa->cid.srt, pos, sizeof(pa->cid.srt));
add_dcid(c, &pa->cid);
pos += sizeof(pa->cid.srt);
#if !defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)
char ip4[NI_MAXHOST];
char port4[NI_MAXSERV];
int err = getnameinfo((struct sockaddr *)pa4, sizeof(*pa4), ip4,
sizeof(ip4), port4, sizeof(port4),
NI_NUMERICHOST | NI_NUMERICSERV);
if (unlikely(err)) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY, "%s",
gai_strerror(err));
return 1;
}
char ip6[NI_MAXHOST];
char port6[NI_MAXSERV];
err = getnameinfo((struct sockaddr *)pa6, sizeof(*pa6), ip6,
sizeof(ip6), port6, sizeof(port6),
NI_NUMERICHOST | NI_NUMERICSERV);
if (unlikely(err)) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY, "%s",
gai_strerror(err));
return 1;
}
mk_cid_str(INF, &pa->cid, cid_str);
mk_srt_str(INF, pa->cid.srt, srt_str);
warn(INF,
"\tpreferred_address = IPv4=%s:%s IPv6=[%s]:%s cid=%s srt=%s",
ip4, port4, ip6, port6, cid_str, srt_str);
#endif
break;
case TP_ACIL:
if (dec_tp(&c->tp_out.act_cid_lim, &pos, end) == false)
return 1;
warn(INF, "\tactive_connection_id_limit = %" PRIu,
c->tp_out.act_cid_lim);
break;
default:
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"unsupported tp 0x%04x", tp);
return 1;
}
}
// if we did a RETRY, check that we got orig_cid and it matches
if (c->is_clnt && c->tok_len) {
if (c->tp_out.orig_cid.len == 0) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"no original_connection_id tp received");
return 1;
}
if (cid_cmp(&c->tp_out.orig_cid, &c->odcid)) {
err_close(c, ERR_TRANSPORT_PARAMETER, FRM_CRY,
"cid/odcid mismatch");
return 1;
}
}
// apply these parameter to all current non-crypto streams
struct q_stream * s;
kh_foreach_value(&c->strms_by_id, s, apply_stream_limits(s));
return 0;
}
static void __attribute__((nonnull)) enc_tp(uint8_t ** pos,
const uint8_t * const end,
const uint16_t tp,
const uint_t val)
{
enc2(pos, end, tp);
enc2(pos, end, varint_size(val));
encv(pos, end, val);
}
static void __attribute__((nonnull)) encb_tp(uint8_t ** pos,
const uint8_t * const end,
const uint16_t tp,
const uint8_t * const val,
const uint16_t len)
{
enc2(pos, end, tp);
enc2(pos, end, len);
if (len)
encb(pos, end, val, len);
}
void init_tp(struct q_conn * const c)
{
uint8_t * pos = c->tls.tp_buf + sizeof(uint16_t);
const uint8_t * end = &c->tls.tp_buf[sizeof(c->tls.tp_buf)];
// add a grease tp
uint8_t grease[18];
rand_bytes(&grease, sizeof(grease));
const uint16_t grease_type = 0xff00 + grease[0];
const uint16_t grease_len = grease[1] & 0x0f;
uint16_t tp_order[TP_MAX + 1] = {
TP_OCID, TP_IDTO, TP_SRT, TP_MPS, TP_IMD, TP_IMSD_BL,
TP_IMSD_BR, TP_IMSD_U, TP_IMSB, TP_IMSU, TP_ADE, TP_MAD,
TP_DMIG, TP_PRFA, TP_ACIL, grease_type};
// modern version of Fisher-Yates
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
for (size_t j = TP_MAX; j >= 1; j--) {
const size_t r = w_rand_uniform32((uint32_t)j);
const uint16_t tmp = tp_order[r];
tp_order[r] = tp_order[j];
tp_order[j] = tmp;
}
for (size_t j = 0; j <= TP_MAX; j++)
switch (tp_order[j]) {
case TP_IMSU:
if (c->tp_in.max_strms_uni)
enc_tp(&pos, end, TP_IMSU, c->tp_in.max_strms_uni);
break;
case TP_IMSD_U:
if (c->tp_in.max_strm_data_uni) {
enc_tp(&pos, end, TP_IMSD_U, c->tp_in.max_strm_data_uni);
#ifdef DEBUG_EXTRA
warn(INF, "\tinitial_max_stream_data_uni = %" PRIu " [bytes]",
c->tp_in.max_strm_data_uni);
#endif
}
break;
case TP_SRT:
if (!c->is_clnt) {
encb_tp(&pos, end, TP_SRT, c->scid->srt, sizeof(c->scid->srt));
#ifdef DEBUG_EXTRA
mk_srt_str(INF, c->scid->srt, srt_str);
warn(INF, "\tstateless_reset_token = %s", srt_str);
#endif
}
break;
case TP_OCID:
if (!c->is_clnt && c->odcid.len) {
encb_tp(&pos, end, TP_OCID, c->odcid.id, c->odcid.len);
#ifdef DEBUG_EXTRA
mk_cid_str(INF, &c->tp_in.orig_cid, orig_cid_str);
warn(INF, "\toriginal_connection_id = %s", orig_cid_str);
#endif
}
break;
case TP_IMSB:
enc_tp(&pos, end, TP_IMSB, c->tp_in.max_strms_bidi);
#ifdef DEBUG_EXTRA
warn(INF, "\tinitial_max_streams_bidi = %" PRIu,
c->tp_in.max_strms_bidi);
#endif
break;
case TP_IDTO:
enc_tp(&pos, end, TP_IDTO, c->tp_in.idle_to);
#ifdef DEBUG_EXTRA
warn(INF, "\tidle_timeout = %" PRIu " [ms]", c->tp_in.idle_to);
#endif
break;
case TP_IMSD_BR:
enc_tp(&pos, end, TP_IMSD_BR, c->tp_in.max_strm_data_bidi_remote);
#ifdef DEBUG_EXTRA
warn(INF,
"\tinitial_max_stream_data_bidi_remote = %" PRIu " [bytes]",
c->tp_in.max_strm_data_bidi_remote);
#endif
break;
case TP_IMSD_BL:
enc_tp(&pos, end, TP_IMSD_BL, c->tp_in.max_strm_data_bidi_local);
#ifdef DEBUG_EXTRA
warn(INF,
"\tinitial_max_stream_data_bidi_local = %" PRIu " [bytes]",
c->tp_in.max_strm_data_bidi_remote);
#endif
break;
case TP_IMD:
enc_tp(&pos, end, TP_IMD, c->tp_in.max_data);
#ifdef DEBUG_EXTRA
warn(INF, "\tinitial_max_data = %" PRIu " [bytes]",
c->tp_in.max_data);
#endif
break;
case TP_ADE:
enc_tp(&pos, end, TP_ADE, c->tp_in.ack_del_exp);
#ifdef DEBUG_EXTRA
warn(INF, "\tack_delay_exponent = %u", c->tp_in.ack_del_exp);
#endif
break;
case TP_MAD:
enc_tp(&pos, end, TP_MAD, c->tp_in.max_ack_del);
#ifdef DEBUG_EXTRA
warn(INF, "\tmax_ack_delay = %" PRIu " [ms]", c->tp_in.max_ack_del);
#endif
break;
case TP_MPS:
enc_tp(&pos, end, TP_MPS, c->tp_in.max_pkt);
#ifdef DEBUG_EXTRA
warn(INF, "\tmax_packet_size = %" PRIu " [bytes]",
c->tp_in.max_pkt);
#endif
break;
case TP_ACIL:
if (c->tp_in.disable_migration == false) {
enc_tp(&pos, end, TP_ACIL, c->tp_in.act_cid_lim);
#ifdef DEBUG_EXTRA
warn(INF, "\tactive_connection_id_limit = %" PRIu,
c->tp_in.act_cid_lim);
#endif
}
break;
case TP_PRFA:
// TODO: unhandled
break;
case TP_DMIG:
if (c->tp_in.disable_migration) {
enc_tp(&pos, end, TP_DMIG, c->tp_in.disable_migration);
#ifdef DEBUG_EXTRA
warn(INF, "\tdisable_migration = true");
#endif
}
break;
default:
if (tp_order[j] == grease_type) {
encb_tp(&pos, end, grease_type, &grease[2], grease_len);
#ifdef DEBUG_EXTRA
char grease_str[hex_str_len(sizeof(c->tls.tp_buf))];
hex2str(&grease[2], grease_len, grease_str, sizeof(grease_str));
warn(WRN, "\t" BLD "%s tp" NRM " (0x%04x w/len %u) = %s",
(grease_type & 0xff00) == 0xff00 ? YEL "private"
: RED "unknown",
grease_type, grease_len, grease_str);
#endif
} else
die("unknown tp 0x%04x", tp_order[j]);
break;
}
// encode length of all transport parameters
const uint16_t enc_len = (uint16_t)(pos - c->tls.tp_buf) - sizeof(uint16_t);
pos = c->tls.tp_buf;
enc2(&pos, end, enc_len);
c->tls.tp_ext[0] = (ptls_raw_extension_t){
QUIC_TP, {c->tls.tp_buf, enc_len + sizeof(uint16_t)}};
c->tls.tp_ext[1] = (ptls_raw_extension_t){UINT16_MAX};
}
#ifndef NO_TLS_TICKETS
static void init_ticket_prot(void)
{
const ptls_cipher_suite_t * const cs = &aes128gcmsha256;
uint8_t output[PTLS_MAX_SECRET_SIZE] = {0};
memcpy(output, quant_commit_hash,
MIN(quant_commit_hash_len, sizeof(output)));
setup_cipher(&dec_tckt.header_protection, &dec_tckt.aead, cs->aead,
cs->hash, 0, output);
setup_cipher(&enc_tckt.header_protection, &enc_tckt.aead, cs->aead,
cs->hash, 1, output);
ptls_clear_memory(output, sizeof(output));
}
static int encrypt_ticket_cb(ptls_encrypt_ticket_t * self
__attribute__((unused)),
ptls_t * tls,
int is_encrypt,
ptls_buffer_t * dst,
ptls_iovec_t src)
{
struct q_conn * const c = *ptls_get_data_ptr(tls);
uint64_t tid;
if (ptls_buffer_reserve(dst, src.len + quant_commit_hash_len + sizeof(tid) +
enc_tckt.aead->algo->tag_size))
return -1;
mk_cid_str(WRN, c->scid, scid_str);
if (is_encrypt) {
warn(INF, "creating new 0-RTT session ticket for %s conn %s (%s %s)",
conn_type(c), scid_str, ptls_get_server_name(tls),
ptls_get_negotiated_protocol(tls));
// prepend git commit hash
memcpy(dst->base + dst->off, quant_commit_hash, quant_commit_hash_len);
dst->off += quant_commit_hash_len;
// prepend ticket id
rand_bytes(&tid, sizeof(tid));
memcpy(dst->base + dst->off, &tid, sizeof(tid));
dst->off += sizeof(tid);
// now encrypt ticket
dst->off += ptls_aead_encrypt(enc_tckt.aead, dst->base + dst->off,
src.base, src.len, tid, 0, 0);
} else {
if (src.len < quant_commit_hash_len + sizeof(tid) +
dec_tckt.aead->algo->tag_size ||
memcmp(src.base, quant_commit_hash, quant_commit_hash_len) != 0) {
warn(WRN,
"could not verify 0-RTT session ticket for %s conn %s (%s "
"%s)",
conn_type(c), scid_str, ptls_get_server_name(tls),
ptls_get_negotiated_protocol(tls));
c->did_0rtt = false;
return -1;
}
uint8_t * src_base = src.base + quant_commit_hash_len;
size_t src_len = src.len - quant_commit_hash_len;
memcpy(&tid, src_base, sizeof(tid));
src_base += sizeof(tid);
src_len -= sizeof(tid);
const size_t n = ptls_aead_decrypt(dec_tckt.aead, dst->base + dst->off,
src_base, src_len, tid, 0, 0);
if (n > src_len) {
warn(WRN,
"could not decrypt 0-RTT session ticket for %s conn %s "
"(%s %s)",
conn_type(c), scid_str, ptls_get_server_name(tls),
ptls_get_negotiated_protocol(tls));
c->did_0rtt = false;
return -1;
}
dst->off += n;
warn(INF, "verified 0-RTT session ticket for %s conn %s (%s %s)",
conn_type(c), scid_str, ptls_get_server_name(tls),
ptls_get_negotiated_protocol(tls));
c->did_0rtt = true;
}
return 0;
}
static int save_ticket_cb(ptls_save_ticket_t * self __attribute__((unused)),
ptls_t * tls,
ptls_iovec_t src)
{
struct q_conn * const c = *ptls_get_data_ptr(tls);
warn(NTE, "saving TLS tickets to %s", tickets.file_name);
FILE * const fp = fopen(tickets.file_name, "wbe");
ensure(fp, "could not open ticket file %s", tickets.file_name);
// write git hash
ensure(fwrite(&quant_commit_hash_len, sizeof(quant_commit_hash_len), 1, fp),
"fwrite");
ensure(fwrite(quant_commit_hash, quant_commit_hash_len, 1, fp), "fwrite");
char * s = 0;
if (ptls_get_server_name(tls))
s = strdup(ptls_get_server_name(tls));
else
s = calloc(1, sizeof(char));
char * a = 0;
if (ptls_get_negotiated_protocol(tls))
a = strdup(ptls_get_negotiated_protocol(tls));
else
a = calloc(1, sizeof(char));
const struct tls_ticket which = {.sni = s, .alpn = a};
struct tls_ticket * t = splay_find(tickets_by_peer, &tickets, &which);
if (t == 0) {
// create new ticket
t = calloc(1, sizeof(*t));
ensure(t, "calloc");
t->sni = s;
t->alpn = a;
ensure(splay_insert(tickets_by_peer, &tickets, t) == 0, "inserted");
} else {
// update current ticket
free(t->ticket);
free(s);
free(a);
}
memcpy(&t->tp, &c->tp_out, sizeof(t->tp));
t->vers = c->vers;
t->ticket_len = src.len;
t->ticket = calloc(1, t->ticket_len);
ensure(t->ticket, "calloc");
memcpy(t->ticket, src.base, src.len);
// write all tickets
// FIXME this currently dumps the entire cache to file on each connection!
mk_cid_str(INF, c->scid, scid_str);
splay_foreach (t, tickets_by_peer, &tickets) {
warn(INF, "writing TLS ticket for %s conn %s (%s %s)", conn_type(c),
scid_str, t->sni, t->alpn);
size_t len = strlen(t->sni) + 1;
ensure(fwrite(&len, sizeof(len), 1, fp), "fwrite");
ensure(fwrite(t->sni, sizeof(*t->sni), len, fp), "fwrite");
len = strlen(t->alpn) + 1;
ensure(fwrite(&len, sizeof(len), 1, fp), "fwrite");
ensure(fwrite(t->alpn, sizeof(*t->alpn), len, fp), "fwrite");
ensure(fwrite(&t->tp, sizeof(t->tp), 1, fp), "fwrite");
ensure(fwrite(&t->vers, sizeof(t->vers), 1, fp), "fwrite");
ensure(fwrite(&t->ticket_len, sizeof(t->ticket_len), 1, fp), "fwrite");
ensure(fwrite(t->ticket, sizeof(*t->ticket), t->ticket_len, fp),
"fwrite");
}
fclose(fp);
return 0;
}
static ptls_save_ticket_t save_ticket = {.cb = save_ticket_cb};
static ptls_encrypt_ticket_t encrypt_ticket = {.cb = encrypt_ticket_cb};
#endif
void init_tls(struct q_conn * const c, const char * const clnt_alpn)
{
if (c->tls.t)
// we are re-initializing during version negotiation
free_tls(c, true);
ensure((c->tls.t = ptls_new(&ped(c->w)->tls_ctx, !c->is_clnt)) != 0,
"ptls_new");
*ptls_get_data_ptr(c->tls.t) = c;
if (c->is_clnt)
ensure(ptls_set_server_name(c->tls.t, c->peer_name, 0) == 0,
"ptls_set_server_name");
ptls_handshake_properties_t * const hshk_prop = &c->tls.tls_hshk_prop;
hshk_prop->additional_extensions = c->tls.tp_ext;
hshk_prop->collect_extension = filter_tp;
hshk_prop->collected_extensions = chk_tp;
if (c->is_clnt) {
if (clnt_alpn == 0 || *clnt_alpn == 0) {
c->tls.alpn = alpn[0];
warn(NTE, "using default ALPN %.*s", (int)c->tls.alpn.len,
c->tls.alpn.base);
} else if (clnt_alpn != (char *)c->tls.alpn.base) {
free(c->tls.alpn.base);
c->tls.alpn = ptls_iovec_init(strdup(clnt_alpn), strlen(clnt_alpn));
}
hshk_prop->client.negotiated_protocols.list = &c->tls.alpn;
hshk_prop->client.negotiated_protocols.count = 1;
hshk_prop->client.max_early_data_size = &c->tls.max_early_data;
#ifndef NO_TLS_TICKETS
// try to find an existing session ticket
struct tls_ticket which = {.sni = c->peer_name,
// this works, because of strdup() allocation
.alpn = (char *)c->tls.alpn.base};
struct tls_ticket * t = splay_find(tickets_by_peer, &tickets, &which);
if (t == 0) {
// if we couldn't find a ticket, try without an alpn
which.alpn = "";
t = splay_find(tickets_by_peer, &tickets, &which);
}
if (t) {
hshk_prop->client.session_ticket =
ptls_iovec_init(t->ticket, t->ticket_len);
memcpy(&c->tp_out, &t->tp, sizeof(t->tp));
c->vers_initial = c->vers = t->vers;
c->try_0rtt = true;
}
#endif
}
init_prot(c);
}
static void __attribute__((nonnull)) free_prot(struct q_conn * const c)
{
dispose_cipher(&c->pns[pn_init].early.in);
dispose_cipher(&c->pns[pn_init].early.out);
dispose_cipher(&c->pns[pn_hshk].early.in);
dispose_cipher(&c->pns[pn_hshk].early.out);
dispose_cipher(&c->pns[pn_data].data.in_0rtt);
dispose_cipher(&c->pns[pn_data].data.out_0rtt);
dispose_cipher(&c->pns[pn_data].data.in_1rtt[0]);
dispose_cipher(&c->pns[pn_data].data.out_1rtt[0]);
dispose_cipher(&c->pns[pn_data].data.in_1rtt[1]);
dispose_cipher(&c->pns[pn_data].data.out_1rtt[1]);
}
void free_tls(struct q_conn * const c, const bool keep_alpn)
{
if (c->tls.t)
ptls_free(c->tls.t);
ptls_clear_memory(c->tls.secret, sizeof(c->tls.secret));
free_prot(c);
if (keep_alpn == false && c->tls.alpn.base != alpn[0].base)
free(c->tls.alpn.base);
}
void init_prot(struct q_conn * const c)
{
struct cid * const scid = c->scid;
struct cid * const dcid = c->dcid;
const ptls_iovec_t cid = {
.base = (uint8_t *)(c->is_clnt ? &dcid->id : &scid->id),
.len = c->is_clnt ? dcid->len : scid->len};
ptls_cipher_suite_t * cs = &aes128gcmsha256;
struct pn_space * const pn = &c->pns[pn_init];
setup_initial_encryption(&pn->early.in, &pn->early.out, &cs, cid,
c->is_clnt);
}
int tls_io(struct q_stream * const s, struct w_iov * const iv)
{
struct q_conn * const c = s->c;
const size_t in_len = iv ? iv->len : 0;
const epoch_t ep_in = strm_epoch(s);
size_t epoch_off[5] = {0};
ptls_buffer_t tls_io;
uint8_t tls_io_buf[4096];
ptls_buffer_init(&tls_io, tls_io_buf, sizeof(tls_io_buf));
const int ret =
ptls_handle_message(c->tls.t, &tls_io, epoch_off, ep_in,
iv ? iv->buf : 0, in_len, &c->tls.tls_hshk_prop);
#ifdef DEBUG_PROT
warn(DBG,
"epoch %u, in %lu (off %" PRIu
"), gen %lu (%lu-%lu-%lu-%lu-%lu), ret %d, left %lu",
ep_in, (unsigned long)(iv ? iv->len : 0), iv ? meta(iv).strm_off : 0,
(unsigned long)tls_io.off, (unsigned long)epoch_off[0],
(unsigned long)epoch_off[1], (unsigned long)epoch_off[2],
(unsigned long)epoch_off[3], (unsigned long)epoch_off[4], ret,
(unsigned long)(iv ? iv->len - in_len : 0));
#endif
if (ret == 0 && c->state != conn_estb) {
if (ptls_is_psk_handshake(c->tls.t) && c->is_clnt)
c->did_0rtt = c->try_0rtt &&
(c->tls.tls_hshk_prop.client.early_data_acceptance ==
PTLS_EARLY_DATA_ACCEPTED);
} else if (ret != 0 && ret != PTLS_ERROR_IN_PROGRESS &&
ret != PTLS_ERROR_STATELESS_RETRY) {
err_close(c, ERR_TLS(PTLS_ERROR_TO_ALERT(ret)), FRM_CRY, "TLS error %u",
ret);
return ret;
}
if (tls_io.off == 0)
return ret;
// enqueue for TX
for (epoch_t e = ep_init; e <= ep_data; e++) {
const size_t out_len = epoch_off[e + 1] - epoch_off[e];
if (out_len == 0)
continue;
#ifdef DEBUG_PROT
warn(DBG, "epoch %u: off %lu len %lu", e, (unsigned long)epoch_off[e],
(unsigned long)out_len);
#endif
struct w_iov_sq o = w_iov_sq_initializer(o);
alloc_off(w_engine(c->sock), &o, (uint32_t)out_len,
DATA_OFFSET + c->tok_len);
const uint8_t * data = tls_io.base + epoch_off[e];
struct w_iov * ov = 0;
sq_foreach (ov, &o, next) {
memcpy(ov->buf, data, ov->len);
data += ov->len;
}
concat_out(c->cstrms[e], &o);
c->needs_tx = true;
}
return ret;
}
#ifndef NO_TLS_TICKETS
static void __attribute__((nonnull)) free_ticket(struct tls_ticket * const t)
{
if (t->sni)
free(t->sni);
if (t->alpn)
free(t->alpn);
if (t->ticket)
free(t->ticket);
free(t);
}
static void read_tickets()
{
FILE * const fp = fopen(tickets.file_name, "rbe");
if (fp == 0) {
warn(WRN, "could not read TLS tickets from %s", tickets.file_name);
return;
}
warn(INF, "reading TLS tickets from %s", tickets.file_name);
// read and verify git hash
size_t hash_len;
if (fread(&hash_len, sizeof(quant_commit_hash_len), 1, fp) != 1)
goto done;
uint8_t buf[8192];
if (fread(buf, sizeof(uint8_t), hash_len, fp) != hash_len)
goto done;
if (hash_len != quant_commit_hash_len ||
memcmp(buf, quant_commit_hash, hash_len) != 0) {
warn(WRN, "TLS tickets were stored by different %s version, removing",
quant_name);
ensure(unlink(tickets.file_name) == 0, "unlink");
goto done;
}
for (;;) {
// try and read the SNI len
size_t len;
if (fread(&len, sizeof(len), 1, fp) != 1)
// we read all the tickets
break;
ensure(len <= 256, "SNI len %lu too long", len);
struct tls_ticket * const t = calloc(1, sizeof(*t));
ensure(t, "calloc");
t->sni = calloc(1, len);
ensure(t->sni, "calloc");
if (fread(t->sni, sizeof(*t->sni), len, fp) != len)
goto abort;
if (fread(&len, sizeof(len), 1, fp) != 1)
goto abort;
ensure(len <= 256, "ALPN len %lu too long", len);
t->alpn = calloc(1, len);
ensure(t->alpn, "calloc");
if (fread(t->alpn, sizeof(*t->alpn), len, fp) != len)
goto abort;
if (fread(&t->tp, sizeof(t->tp), 1, fp) != 1)
goto abort;
if (fread(&t->vers, sizeof(t->vers), 1, fp) != 1)
goto abort;
if (fread(&len, sizeof(len), 1, fp) != 1)
goto abort;
ensure(len <= 8192, "ticket_len %lu too long", len);
t->ticket_len = len;
t->ticket = calloc(len, sizeof(*t->ticket));
ensure(t->ticket, "calloc");
if (fread(t->ticket, sizeof(*t->ticket), len, fp) != len)
goto abort;
ensure(splay_insert(tickets_by_peer, &tickets, t) == 0, "inserted");
warn(INF, "got TLS ticket %s %s", t->sni, t->alpn);
continue;
abort:
free_ticket(t);
break;
}
done:
fclose(fp);
}
#endif
#ifndef NO_TLS_LOG
static void __attribute__((format(printf, 4, 5)))
log_event_cb(ptls_log_event_t * const self __attribute__((unused)),
ptls_t * const tls,
const char * const type,
const char * fmt,
...)
{
char output[hex_str_len(PTLS_HELLO_RANDOM_SIZE)];
hex2str(ptls_get_client_random(tls).base, PTLS_HELLO_RANDOM_SIZE, output,
sizeof(output));
fprintf(tls_log_file, "%s %s ", type, output);
va_list args;
va_start(args, fmt);
vfprintf(tls_log_file, fmt, args);
va_end(args);
fprintf(tls_log_file, "\n");
fflush(tls_log_file);
}
#endif
static int update_traffic_key_cb(ptls_update_traffic_key_t * const self
__attribute__((unused)),
ptls_t * const tls,
const int is_enc,
const size_t epoch,
const void * const secret)
{
#ifdef DEBUG_PROT
warn(CRT, "update_traffic_key %s %lu", is_enc ? "tx" : "rx",
(unsigned long)epoch);
#endif
struct q_conn * const c = *ptls_get_data_ptr(tls);
ptls_cipher_suite_t * const cipher = ptls_get_cipher(c->tls.t);
struct pn_space * const pn = pn_for_epoch(c, (epoch_t)epoch);
struct cipher_ctx * ctx = 0;
switch (epoch) {
case ep_0rtt:
ctx = is_enc ? &pn->data.out_0rtt : &pn->data.in_0rtt;
break;
case ep_hshk:
ctx = is_enc ? &pn->early.out : &pn->early.in;
break;
case ep_data:
memcpy(c->tls.secret[is_enc], secret, cipher->hash->digest_size);
ctx = is_enc ? &pn->data.out_1rtt[pn->data.out_kyph]
: &pn->data.in_1rtt[pn->data.in_kyph];
break;
default:
die("epoch %lu unknown", (unsigned long)epoch);
}
if (ped(c->w)->tls_ctx.log_event) {
static const char * const log_labels[2][4] = {
{0, "CLIENT_EARLY_TRAFFIC_SECRET",
"CLIENT_HANDSHAKE_TRAFFIC_SECRET", "CLIENT_TRAFFIC_SECRET_0"},
{0, 0, "SERVER_HANDSHAKE_TRAFFIC_SECRET",
"SERVER_TRAFFIC_SECRET_0"}};
char secret_str[hex_str_len(PTLS_MAX_DIGEST_SIZE)];
hex2str(secret, cipher->hash->digest_size, secret_str,
sizeof(secret_str));
ped(c->w)->tls_ctx.log_event->cb(
ped(c->w)->tls_ctx.log_event, tls,
log_labels[ptls_is_server(tls) == is_enc][epoch], "%s", secret_str);
}
return setup_cipher(&ctx->header_protection, &ctx->aead, cipher->aead,
cipher->hash, is_enc, secret);
}
void init_tls_ctx(const struct q_conf * const conf,
ptls_context_t * const tls_ctx)
{
#ifdef PARTICLE
// the picotls minicrypto backend depends on this
uECC_set_rng(uecc_rng);
#endif
if (conf && conf->tls_key) {
#ifdef WITH_OPENSSL
FILE * const fp = fopen(conf->tls_key, "rbe");
ensure(fp, "could not open key %s", conf->tls_key);
EVP_PKEY * const pkey = PEM_read_PrivateKey(fp, 0, 0, 0);
fclose(fp);
ensure(pkey, "failed to load private key");
ptls_openssl_init_sign_certificate(&sign_cert, pkey);
EVP_PKEY_free(pkey);
#elif !defined(PARTICLE)
// XXX ptls_minicrypto_load_private_key() only works for ECDSA keys
const int ret =
ptls_minicrypto_load_private_key(tls_ctx, conf->tls_key);
ensure(ret == 0, "could not open key %s", conf->tls_key);
#endif
}
#ifdef WITH_OPENSSL
ensure(ptls_openssl_init_verify_certificate(&verifier, 0) == 0,
"ptls_openssl_init_verify_certificate");
#endif
#ifndef PARTICLE
if (conf && conf->tls_cert) {
const int ret = ptls_load_certificates(tls_ctx, conf->tls_cert);
ensure(ret == 0, "ptls_load_certificates");
}
#endif
if (conf && conf->ticket_store) {
#ifndef NO_TLS_TICKETS
strncpy(tickets.file_name, conf->ticket_store,
sizeof(tickets.file_name));
tls_ctx->save_ticket = &save_ticket;
read_tickets();
#endif
} else {
#ifndef NO_TLS_TICKETS
tls_ctx->encrypt_ticket = &encrypt_ticket;
#endif
tls_ctx->max_early_data_size = 0xffffffff;
tls_ctx->ticket_lifetime = 60 * 60 * 24;
tls_ctx->require_dhe_on_psk = 0;
}
#ifndef NO_TLS_LOG
if (conf && conf->tls_log) {
tls_log_file = fopen(conf->tls_log, "abe");
ensure(tls_log_file, "could not open TLS log %s", conf->tls_log);
}
static ptls_log_event_t log_event = {log_event_cb};
if (conf && conf->tls_log)
tls_ctx->log_event = &log_event;
#endif
static ptls_key_exchange_algorithm_t * key_exchanges[] = {&secp256r1,
#ifndef PARTICLE
&x25519,
#endif
0};
static ptls_on_client_hello_t on_client_hello = {on_ch};
static ptls_update_traffic_key_t update_traffic_key = {
update_traffic_key_cb};
tls_ctx->omit_end_of_early_data = true;
tls_ctx->get_time = &ptls_get_time; // needs to be absolute time
tls_ctx->cipher_suites = cipher_suite;
tls_ctx->key_exchanges = key_exchanges;
tls_ctx->on_client_hello = &on_client_hello;
tls_ctx->update_traffic_key = &update_traffic_key;
tls_ctx->random_bytes = rand_bytes;
#ifdef WITH_OPENSSL
tls_ctx->sign_certificate = &sign_cert.super;
if (conf && conf->enable_tls_cert_verify)
tls_ctx->verify_certificate = &verifier.super;
#endif
#ifndef NO_TLS_TICKETS
init_ticket_prot();
#endif
}
void free_tls_ctx(ptls_context_t * const tls_ctx)
{
#ifndef NO_TLS_TICKETS
dispose_cipher(&dec_tckt);
dispose_cipher(&enc_tckt);
// free ticket cache
struct tls_ticket * t;
struct tls_ticket * tmp;
for (t = splay_min(tickets_by_peer, &tickets); t != 0; t = tmp) {
tmp = splay_next(tickets_by_peer, &tickets, t);
ensure(splay_remove(tickets_by_peer, &tickets, t), "removed");
free_ticket(t);
}
#endif
for (size_t i = 0; i < tls_ctx->certificates.count; i++)
free(tls_ctx->certificates.list[i].base);
free(tls_ctx->certificates.list);
}
static inline const struct cipher_ctx * __attribute__((nonnull))
which_cipher_ctx_out(const struct pkt_meta * const m, const bool kyph)
{
switch (m->hdr.type) {
case LH_INIT:
case LH_RTRY:
case LH_HSHK:
return &m->pn->early.out;
case LH_0RTT:
return &m->pn->data.out_0rtt;
default:
return &m->pn->data.out_1rtt[kyph ? is_set(SH_KYPH, m->hdr.flags) : 0];
}
}
uint16_t dec_aead(const struct w_iov * const xv,
const struct w_iov * const v,
const struct pkt_meta * const m,
const uint16_t len,
const struct cipher_ctx * const ctx)
{
const uint16_t hdr_len = m->hdr.hdr_len;
if (unlikely(hdr_len == 0 || hdr_len > len))
return 0;
const size_t ret =
ptls_aead_decrypt(ctx->aead, &v->buf[hdr_len], &xv->buf[hdr_len],
len - hdr_len, m->hdr.nr, xv->buf, hdr_len);
if (unlikely(ret == SIZE_MAX))
return 0;
memcpy(v->buf, xv->buf, hdr_len);
#ifdef DEBUG_PROT
warn(DBG, "dec %s AEAD over [%u..%u] in [%u..%u]",
pkt_type_str(m->hdr.flags, &m->hdr.vers), hdr_len, len - AEAD_LEN - 1,
len - AEAD_LEN, len - 1);
#endif
return hdr_len + len;
}
uint16_t enc_aead(const struct w_iov * const v,
const struct pkt_meta * const m,
struct w_iov * const xv,
const uint16_t pkt_nr_pos)
{
const struct cipher_ctx * ctx = which_cipher_ctx_out(m, true);
if (unlikely(ctx == 0 || ctx->aead == 0)) {
warn(NTE, "no %s crypto context",
pkt_type_str(m->hdr.flags, &m->hdr.vers));
return 0;
}
const uint16_t hdr_len = m->hdr.hdr_len;
memcpy(xv->buf, v->buf, hdr_len); // copy pkt header
const uint16_t plen = v->len - hdr_len + AEAD_LEN;
xv->len = hdr_len + (uint16_t)ptls_aead_encrypt(
ctx->aead, &xv->buf[hdr_len], &v->buf[hdr_len],
plen - AEAD_LEN, m->hdr.nr, v->buf, hdr_len);
// apply packet protection
ctx = which_cipher_ctx_out(m, false);
if (likely(pkt_nr_pos) &&
unlikely(xor_hp(xv, m, ctx, pkt_nr_pos, true) == false))
return 0;
#ifdef DEBUG_PROT
warn(DBG, "enc %s AEAD over [%u..%u] in [%u..%u]",
pkt_type_str(m->hdr.flags, &m->hdr.vers), hdr_len,
hdr_len + plen - AEAD_LEN - 1, hdr_len + plen - AEAD_LEN,
hdr_len + plen - 1);
#endif
return xv->len;
}
static ptls_hash_context_t * __attribute__((nonnull))
prep_hash_ctx(const struct q_conn * const c,
const ptls_cipher_suite_t * const cs)
{
// create hash context
ptls_hash_context_t * const hc = cs->hash->create();
ensure(hc, "could not create hash context");
// hash our git commit hash and the peer IP address
hc->update(hc, quant_commit_hash, quant_commit_hash_len);
hc->update(hc, &c->peer, sizeof(c->peer));
return hc;
}
void make_rtry_tok(struct q_conn * const c)
{
const ptls_cipher_suite_t * const cs = &aes128gcmsha256;
ptls_hash_context_t * const hc = prep_hash_ctx(c, cs);
// hash current scid
struct cid * const scid = c->scid;
hc->update(hc, scid->id, scid->len);
hc->final(hc, c->tok, PTLS_HASH_FINAL_MODE_FREE);
// append scid to hashed token
memcpy(&c->tok[cs->hash->digest_size], scid->id, scid->len);
// update max_frame_len() when this changes:
c->tok_len = (uint16_t)cs->hash->digest_size + scid->len;
}
bool verify_rtry_tok(struct q_conn * const c,
const uint8_t * const tok,
const uint16_t tok_len)
{
const ptls_cipher_suite_t * const cs = &aes128gcmsha256;
ptls_hash_context_t * const hc = prep_hash_ctx(c, cs);
// hash current cid included in token
hc->update(hc, tok + cs->hash->digest_size,
tok_len - cs->hash->digest_size);
uint8_t buf[PTLS_MAX_DIGEST_SIZE + CID_LEN_MAX];
hc->final(hc, buf, PTLS_HASH_FINAL_MODE_FREE);
if (memcmp(buf, tok, cs->hash->digest_size) == 0) {
c->odcid.len = (uint8_t)(tok_len - cs->hash->digest_size);
memcpy(&c->odcid.id, tok + cs->hash->digest_size, c->odcid.len);
return true;
}
return false;
}
void flip_keys(struct q_conn * const c, const bool out)
{
struct pn_data * const pnd = &c->pns[pn_data].data;
const bool new_kyph = !(out ? pnd->out_kyph : pnd->in_kyph);
#ifdef DEBUG_PROT
warn(DBG, "flip %s kyph %u -> %u", out ? "out" : "in",
out ? pnd->out_kyph : pnd->in_kyph, new_kyph);
#endif
const ptls_cipher_suite_t * const cs = ptls_get_cipher(c->tls.t);
if (unlikely(cs == 0)) {
warn(ERR, "cannot obtain cipher suite");
return;
}
uint8_t new_secret[PTLS_MAX_DIGEST_SIZE];
static const char flip_label[] = "traffic upd";
if (pnd->in_1rtt[new_kyph].aead)
ptls_aead_free(pnd->in_1rtt[new_kyph].aead);
if (setup_initial_key(&pnd->in_1rtt[new_kyph], cs, c->tls.secret[0],
flip_label, 0, new_secret))
return;
memcpy(c->tls.secret[0], new_secret, cs->hash->digest_size);
if (pnd->out_1rtt[new_kyph].aead)
ptls_aead_free(pnd->out_1rtt[new_kyph].aead);
if (setup_initial_key(&pnd->out_1rtt[new_kyph], cs, c->tls.secret[1],
flip_label, 1, new_secret) != 0)
return;
memcpy(c->tls.secret[1], new_secret, cs->hash->digest_size);
if (out == false)
pnd->in_kyph = new_kyph;
pnd->out_kyph = new_kyph;
}
void maybe_flip_keys(struct q_conn * const c, const bool out)
{
if (c->key_flips_enabled == false || likely(c->do_key_flip == false))
return;
struct pn_data * const pnd = &c->pns[pn_data].data;
if (pnd->out_kyph != pnd->in_kyph)
return;
flip_keys(c, out);
c->do_key_flip = false;
}
|
jlaine/quant
|
lib/src/conn.h
|
<reponame>jlaine/quant
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <quant/quant.h>
#include <timeout.h>
#include "diet.h"
#include "pn.h" // IWYU pragma: keep
#include "quic.h"
#include "recovery.h"
#include "tls.h"
KHASH_MAP_INIT_INT64(strms_by_id, struct q_stream *)
KHASH_MAP_INIT_INT64(conns_by_ipnp, struct q_conn *)
static inline khint_t __attribute__((nonnull))
hash_cid(const struct cid * const id)
{
return fnv1a_32(id->id, id->len);
}
static inline int __attribute__((nonnull))
cid_cmp(const struct cid * const a, const struct cid * const b)
{
// if the lengths are different, memcmp will fail on the first byte
return memcmp(&a->len, &b->len, a->len + sizeof(a->len));
}
static inline int __attribute__((nonnull))
kh_cid_cmp(const struct cid * const a, const struct cid * const b)
{
return cid_cmp(a, b) == 0;
}
KHASH_INIT(conns_by_id, struct cid *, struct q_conn *, 1, hash_cid, kh_cid_cmp)
static inline khint_t __attribute__((nonnull))
hash_srt(const uint8_t * const srt)
{
return fnv1a_32(srt, SRT_LEN);
}
static inline int __attribute__((nonnull))
kh_srt_cmp(const uint8_t * const a, const uint8_t * const b)
{
return memcmp(a, b, SRT_LEN) == 0;
}
KHASH_INIT(conns_by_srt, uint8_t *, struct q_conn *, 1, hash_srt, kh_srt_cmp)
extern khash_t(conns_by_ipnp) conns_by_ipnp;
extern khash_t(conns_by_id) conns_by_id;
extern khash_t(conns_by_srt) conns_by_srt;
struct pref_addr {
struct sockaddr_storage addr4;
struct sockaddr_storage addr6;
struct cid cid;
};
struct transport_params {
uint_t max_strm_data_uni;
uint_t max_strm_data_bidi_local;
uint_t max_strm_data_bidi_remote;
uint_t max_data;
uint_t max_strms_uni;
uint_t max_strms_bidi;
uint_t idle_to;
uint_t max_ack_del;
uint_t max_pkt;
uint_t act_cid_lim;
struct pref_addr pref_addr;
struct cid orig_cid;
uint8_t ack_del_exp;
bool disable_migration;
uint8_t _unused[6];
};
sl_head(q_conn_sl, q_conn);
#define CONN_STATE(k, v) k = v
#define CONN_STATES \
CONN_STATE(conn_clsd, 0), CONN_STATE(conn_idle, 1), \
CONN_STATE(conn_opng, 2), CONN_STATE(conn_estb, 3), \
CONN_STATE(conn_qlse, 4), CONN_STATE(conn_clsg, 5), \
CONN_STATE(conn_drng, 6),
/// Define connection states.
/// \dotfile conn-states.dot "Connection state diagram."
typedef enum { CONN_STATES } conn_state_t;
extern const char * const conn_state_str[];
#define MAX_TOK_LEN 160
#define MAX_ERR_REASON_LEN 32 // keep < 256, since err_reason_len is uint8_t
#define DEF_ACK_DEL_EXP 3
#define DEF_MAX_ACK_DEL 25 // ms
#ifndef NO_MIGRATION
splay_head(cids_by_seq, cid);
KHASH_INIT(cids_by_id, struct cid *, struct cid *, 1, hash_cid, kh_cid_cmp)
#endif
/// A QUIC connection.
struct q_conn {
sl_entry(q_conn) node_rx_int; ///< For maintaining the internal RX queue.
sl_entry(q_conn) node_rx_ext; ///< For maintaining the external RX queue.
sl_entry(q_conn) node_aq; ///< For maintaining the accept queue.
#ifndef NO_MIGRATION
struct cids_by_seq dcids_by_seq; ///< Destination CID hash by sequence.
struct cids_by_seq scids_by_seq; ///< Source CID hash by sequence.
khash_t(cids_by_id) scids_by_id; ///< Source CID hash by ID.
#endif
struct cid * dcid; ///< Active destination CID.
struct cid * scid; ///< Active source CID.
uint32_t holds_sock : 1; ///< Connection manages a warpcore socket.
uint32_t is_clnt : 1; ///< We are the client on this connection.
uint32_t had_rx : 1; ///< We had an RX event on this connection.
uint32_t needs_tx : 1; ///< We have a pending TX on this connection.
uint32_t tx_max_data : 1; ///< Sent a MAX_DATA frame.
uint32_t blocked : 1; ///< We are receive-window-blocked.
uint32_t sid_blocked_bidi : 1; ///< We are out of bidi stream IDs.
uint32_t sid_blocked_uni : 1; ///< We are out of unidir stream IDs.
uint32_t tx_max_sid_bidi : 1; ///< Send MAX_STREAM_ID frame for bidi.
uint32_t tx_max_sid_uni : 1; ///< Send MAX_STREAM_ID frame for unidir.
uint32_t try_0rtt : 1; ///< Try 0-RTT handshake.
uint32_t did_0rtt : 1; ///< 0-RTT handshake succeeded;
uint32_t tx_path_resp : 1; ///< Send PATH_RESPONSE.
uint32_t tx_path_chlg : 1; ///< Send PATH_CHALLENGE.
uint32_t tx_ncid : 1; ///< Send NEW_CONNECTION_ID.
uint32_t tx_rtry : 1; ///< We need to send a RETRY.
uint32_t have_new_data : 1; ///< New stream data was enqueued.
uint32_t in_c_ready : 1; ///< Connection is listed in c_ready.
uint32_t needs_accept : 1; ///< Need to call q_accept() for connection.
uint32_t tx_retire_cid : 1; ///< Send RETIRE_CONNECTION_ID.
uint32_t do_migration : 1; ///< Perform a CID migration when possible.
uint32_t key_flips_enabled : 1; ///< Are TLS key updates enabled?
uint32_t do_key_flip : 1; ///< Perform a TLS key update.
uint32_t spin_enabled : 1; ///< Is the spinbit enabled?
uint32_t spin : 1; ///< Spin value to set on next packet sent.
uint32_t no_wnd : 1; ///< TX is stalled by lack of window.
uint32_t : 6;
conn_state_t state; ///< State of the connection.
struct w_engine * w; ///< Underlying warpcore engine.
struct timeout tx_w; ///< TX watcher.
uint32_t vers; ///< QUIC version in use for this connection.
uint32_t vers_initial; ///< QUIC version first negotiated.
struct pn_space pns[pn_data + 1];
struct timeout idle_alarm;
struct timeout closing_alarm;
struct timeout key_flip_alarm;
struct timeout ack_alarm;
struct sockaddr_storage peer; ///< Address of our peer.
struct sockaddr_storage migr_peer; ///< Peer's desired migration address.
char * peer_name;
struct q_stream * cstrms[ep_data + 1]; ///< Crypto "streams".
khash_t(strms_by_id) strms_by_id; ///< Regular streams.
struct diet clsd_strms;
sl_head(, q_stream) need_ctrl;
struct w_sock * sock; ///< File descriptor (socket) for the connection.
struct transport_params tp_in; ///< Transport parameters for RX.
struct transport_params tp_out; ///< Transport parameters for TX.
struct recovery rec; ///< Loss recovery state.
struct tls tls; ///< TLS state.
dint_t next_sid_bidi; ///< Next unidir stream ID to use on q_rsv_stream().
dint_t next_sid_uni; ///< Next bidi stream ID to use on q_rsv_stream().
uint_t cnt_bidi; ///< Number of unidir stream IDs in use.
uint_t cnt_uni; ///< Number of bidi stream IDs in use.
uint_t in_data_str; ///< Current inbound aggregate stream data.
uint_t out_data_str; ///< Current outbound aggregate stream data.
uint_t path_val_win; ///< Window for path validation.
uint_t in_data; ///< Current inbound connection data.
uint_t out_data; ///< Current outbound connection data.
epoch_t min_rx_epoch;
uint8_t path_chlg_in[PATH_CHLG_LEN];
uint8_t path_resp_out[PATH_CHLG_LEN];
uint8_t path_chlg_out[PATH_CHLG_LEN];
uint8_t path_resp_in[PATH_CHLG_LEN];
struct w_sockopt sockopt; ///< Socket options.
uint_t max_cid_seq_out;
struct cid odcid; ///< Original destination CID of first Initial.
struct w_iov_sq txq;
struct q_conn_info i;
uint_t err_code;
uint8_t err_frm;
#ifndef NO_ERR_REASONS
uint8_t err_reason_len;
char err_reason[MAX_ERR_REASON_LEN];
#else
uint8_t _unused;
#endif
uint16_t tok_len;
uint8_t tok[MAX_TOK_LEN]; // some stacks send ungodly large tokens
uint32_t tx_limit;
timeout_t tls_key_update_frequency;
};
extern struct q_conn_sl c_ready;
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && defined(DEBUG_EXTRA) && \
!defined(FUZZING)
#define conn_to_state(c, s) \
do { \
if ((c)->scid) { \
mk_cid_str(DBG, (c)->scid, _scid_str); \
warn(DBG, "%s%s conn %s state %s -> " RED "%s" NRM, \
(c)->state == (s) ? RED BLD "useless transition: " NRM : "", \
conn_type(c), _scid_str, conn_state_str[(c)->state], \
conn_state_str[(s)]); \
} \
(c)->state = (s); \
} while (0)
#else
#define conn_to_state(c, s) (c)->state = (s)
#endif
extern void __attribute__((nonnull)) tx(struct q_conn * const c);
#ifdef NO_ERR_REASONS
#define err_close(c, code, frm, ...) err_close_noreason(c, code, frm)
#endif
extern void __attribute__((nonnull))
#ifndef NO_ERR_REASONS
err_close
#else
err_close_noreason
#endif
(struct q_conn * const c,
const uint_t code,
const uint8_t frm
#ifndef NO_ERR_REASONS
,
const char * const fmt,
...
#endif
);
extern void __attribute__((nonnull)) enter_closing(struct q_conn * const c);
extern struct q_conn * new_conn(struct w_engine * const w,
const uint32_t vers,
const struct cid * const dcid,
const struct cid * const scid,
const struct sockaddr * const peer,
const char * const peer_name,
const uint16_t port,
const struct q_conn_conf * const conf);
extern void __attribute__((nonnull)) free_conn(struct q_conn * const c);
extern void __attribute__((nonnull))
add_scid(struct q_conn * const c, struct cid * const id);
extern void __attribute__((nonnull))
add_dcid(struct q_conn * const c, const struct cid * const id);
extern void __attribute__((nonnull))
do_conn_fc(struct q_conn * const c, const uint16_t len);
extern void __attribute__((nonnull))
free_scid(struct q_conn * const c, struct cid * const id);
extern void __attribute__((nonnull))
free_dcid(struct q_conn * const c, struct cid * const id);
extern void __attribute__((nonnull(1)))
update_conf(struct q_conn * const c, const struct q_conn_conf * const conf);
extern struct q_conn * __attribute__((nonnull))
get_conn_by_srt(uint8_t * const srt);
extern void __attribute__((nonnull))
conns_by_srt_ins(struct q_conn * const c, uint8_t * const srt);
extern void __attribute__((nonnull)) rx(struct w_sock * const ws);
extern void __attribute__((nonnull))
conn_info_populate(struct q_conn * const c);
extern void __attribute__((nonnull)) use_next_dcid(struct q_conn * const c);
extern void __attribute__((nonnull))
restart_idle_alarm(struct q_conn * const c);
#ifdef FUZZING
extern void __attribute__((nonnull)) rx_pkts(struct w_iov_sq * const x,
struct q_conn_sl * const crx,
const struct w_sock * const ws);
#endif
static inline struct pn_space * __attribute__((nonnull))
pn_for_epoch(struct q_conn * const c, const epoch_t e)
{
switch (e) {
case ep_init:
return &c->pns[pn_init];
case ep_hshk:
return &c->pns[pn_hshk];
case ep_0rtt:
case ep_data:
return &c->pns[pn_data];
}
die("unhandled epoch %u", e);
return 0;
}
static inline int __attribute__((nonnull))
cids_by_seq_cmp(const struct cid * const a, const struct cid * const b)
{
return (a->seq > b->seq) - (a->seq < b->seq);
}
#ifndef NO_MIGRATION
SPLAY_PROTOTYPE(cids_by_seq, cid, node_seq, cids_by_seq_cmp)
#endif
#ifndef NO_OOO_0RTT
struct ooo_0rtt {
splay_entry(ooo_0rtt) node;
struct cid cid; ///< CID of 0-RTT pkt
struct w_iov * v; ///< the buffer containing the 0-RTT pkt
};
extern splay_head(ooo_0rtt_by_cid, ooo_0rtt) ooo_0rtt_by_cid;
static inline int __attribute__((nonnull))
ooo_0rtt_by_cid_cmp(const struct ooo_0rtt * const a,
const struct ooo_0rtt * const b)
{
return cid_cmp(&a->cid, &b->cid);
}
SPLAY_PROTOTYPE(ooo_0rtt_by_cid, ooo_0rtt, node, ooo_0rtt_by_cid_cmp)
#endif
static inline __attribute__((nonnull)) const char *
conn_type(const struct q_conn * const c)
{
return c->is_clnt ? "clnt" : "serv";
}
static inline bool __attribute__((nonnull))
has_pval_wnd(const struct q_conn * const c, const uint16_t len)
{
if (unlikely(c->out_data + len >= c->path_val_win)) {
mk_cid_str(DBG, c->scid, scid_str);
warn(DBG, "%s conn %s path val lim reached: %" PRIu " + %u >= %" PRIu,
conn_type(c), scid_str, c->out_data, len, c->path_val_win);
return false;
}
return true;
}
static inline bool __attribute__((nonnull))
has_wnd(const struct q_conn * const c, const uint16_t len)
{
mk_cid_str(DBG, c->scid, scid_str);
if (unlikely(c->blocked)) {
warn(DBG, "%s conn %s is blocked", conn_type(c), scid_str);
return false;
}
if (unlikely(c->rec.cur.in_flight + len >= c->rec.cur.cwnd)) {
warn(DBG,
"%s conn %s cwnd lim reached: in_flight %" PRIu " + %u >= %" PRIu,
conn_type(c), scid_str, c->rec.cur.in_flight, len,
c->rec.cur.cwnd);
return false;
}
return has_pval_wnd(c, len);
}
static inline uint16_t __attribute__((nonnull))
get_sport(const struct w_sock * const sock)
{
return ((const struct sockaddr_in *)(const void *)w_get_addr(sock, true))
->sin_port;
}
static inline bool __attribute__((
#ifndef NO_MIGRATION
nonnull
#else
const
#endif
)) needs_more_ncids(struct q_conn * const c
#ifdef NO_MIGRATION
__attribute__((unused))
#endif
)
{
#ifndef NO_MIGRATION
const struct cid * const max_scid =
splay_max(cids_by_seq, &c->scids_by_seq);
return splay_count(&c->scids_by_seq) <
MIN(c->tp_out.act_cid_lim, c->tp_in.act_cid_lim) ||
(max_scid && c->max_cid_seq_out < max_scid->seq);
#else
return false;
#endif
}
static inline uint64_t __attribute__((nonnull))
conns_by_ipnp_key(const struct sockaddr * const src,
const struct sockaddr * const dst)
{
const struct sockaddr_in * const src4 =
(const struct sockaddr_in *)(const void *)src;
const struct sockaddr_in * const dst4 =
(const struct sockaddr_in *)(const void *)dst;
return ((uint64_t)dst4->sin_addr.s_addr
<< sizeof(dst4->sin_addr.s_addr) * 8) |
((uint64_t)src4->sin_port << sizeof(src4->sin_port) * 8) |
(uint64_t)dst4->sin_port;
}
static inline void __attribute__((nonnull))
conns_by_ipnp_ins(struct q_conn * const c)
{
int ret;
const khiter_t k =
kh_put(conns_by_ipnp, &conns_by_ipnp,
(khint64_t)conns_by_ipnp_key(w_get_addr(c->sock, true),
(struct sockaddr *)&c->peer),
&ret);
ensure(ret >= 1, "inserted returned %d", ret);
kh_val(&conns_by_ipnp, k) = c;
}
static inline void __attribute__((nonnull))
conns_by_ipnp_del(const struct q_conn * const c)
{
const khiter_t k =
kh_get(conns_by_ipnp, &conns_by_ipnp,
(khint64_t)conns_by_ipnp_key(w_get_addr(c->sock, true),
(const struct sockaddr *)&c->peer));
ensure(k != kh_end(&conns_by_ipnp), "found");
kh_del(conns_by_ipnp, &conns_by_ipnp, k);
}
|
jlaine/quant
|
lib/src/loop.c
|
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <stdbool.h>
#include <stdint.h>
#include <timeout.h>
#include "conn.h"
#include "loop.h"
func_ptr api_func = 0;
void * api_conn = 0;
void * api_strm = 0;
static uint64_t now = 0;
static bool break_loop = false;
void loop_break(void)
{
break_loop = true;
api_func = 0;
api_conn = api_strm = 0;
}
void loop_init(void)
{
now = w_now();
}
uint64_t loop_now(void)
{
return now;
}
void __attribute__((nonnull(1))) loop_run(struct w_engine * const w,
const func_ptr f,
struct q_conn * const c,
struct q_stream * const s)
{
ensure(api_func == 0, "other API call active");
api_func = f;
api_conn = c;
api_strm = s;
break_loop = false;
while (likely(break_loop == false)) {
now = w_now();
timeouts_update(ped(w)->wheel, now);
struct timeout * t;
TIMEOUTS_FOREACH (t, ped(w)->wheel, TIMEOUTS_EXPIRED)
(*t->callback.fn)(t->callback.arg);
if (break_loop)
break;
bool do_rx = w_nic_rx(w, (int64_t)timeouts_timeout(ped(w)->wheel));
now = w_now();
timeouts_update(ped(w)->wheel, now);
while (do_rx) {
struct w_sock_slist sl = w_sock_slist_initializer(sl);
do_rx = w_rx_ready(w, &sl) > 0;
if (do_rx == false)
break;
struct w_sock * ws;
sl_foreach (ws, &sl, next_rx)
rx(ws);
};
}
api_func = 0;
api_conn = api_strm = 0;
}
|
jlaine/quant
|
lib/src/quic.h
|
<gh_stars>0
// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2016-2019, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
// IWYU pragma: no_include <picotls/../picotls.h>
#include <picotls.h> // IWYU pragma: keep
#include <quant/quant.h>
#include "frame.h"
// #define DEBUG_BUFFERS ///< Set to log buffer use details.
// #define DEBUG_EXTRA ///< Set to log various extra details.
// #define DEBUG_STREAMS ///< Set to log stream scheduling details.
// #define DEBUG_TIMERS ///< Set to log timer details.
// #define DEBUG_PROT ///< Set to log packet protection/encryption details.
#define DATA_OFFSET 48 ///< Offsets of stream frame payload data we TX.
#define CID_LEN_MIN 4 ///< Minimum CID length allowed by spec.
#define CID_LEN_MAX 20 ///< Maximum CID length allowed by spec.
#define SCID_LEN_CLNT 4 ///< Default client source CID length.
#define SCID_LEN_SERV 8 ///< Default server source CID length.
#define SRT_LEN 16 ///< Stateless reset token length allowed by spec.
#define PATH_CHLG_LEN 8 ///< Length of a path challenge.
#ifdef PARTICLE
#define IPTOS_ECN_NOTECT 0x00 // not-ECT
#define IPTOS_ECN_ECT1 0x01 // ECN-capable transport (1)
#define IPTOS_ECN_ECT0 0x02 // ECN-capable transport (0)
#define IPTOS_ECN_CE 0x03 // congestion experienced
#define IPTOS_ECN_MASK 0x03 // ECN field mask
#define NI_MAXHOST 16
#define NI_MAXSERV 6
#define O_CLOEXEC 0
#endif
// Maximum reordering in packets before packet threshold loss detection
// considers a packet lost. The RECOMMENDED value is 3.
#define kPacketThreshold 3
// Maximum reordering in time before time threshold loss detection considers a
// packet lost. Specified as an RTT multiplier. The RECOMMENDED value is 9/8.
// #define kTimeThreshold 1.125
// Timer granularity. This is a system-dependent value. However, implementations
// SHOULD use a value no smaller than 1ms.
#define kGranularity 1 * NS_PER_MS
// The RTT used before an RTT sample is taken. The RECOMMENDED value is 100ms.
#define kInitialRtt 500 * NS_PER_MS
/// The sender's maximum payload size. Does not include UDP or IP overhead. The
/// max packet size is used for calculating initial and minimum congestion
/// windows.
#define kMaxDatagramSize 1200
/// Default limit on the initial amount of outstanding data in flight, in bytes.
/// Taken from [RFC6928]. The RECOMMENDED value is the minimum of 10 *
/// kMaxDatagramSize and max(2* kMaxDatagramSize, 14720)).
#define kInitialWindow \
MIN(10 * kMaxDatagramSize, MAX(2 * kMaxDatagramSize, 14720))
/// Minimum congestion window in bytes.
#define kMinimumWindow (2 * kMaxDatagramSize)
/// Reduction in congestion window when a new loss event is detected.
#define kLossReductionDivisor 2 // kLossReductionFactor
/// Number of consecutive PTOs after which network is considered to be
/// experiencing persistent congestion. The RECOMMENDED value for
/// kPersistentCongestionThreshold is 3, which is equivalent to having two TLPs
/// before an RTO in TCP.
#define kPersistentCongestionThreshold 3
#ifndef PARTICLE
#define NRM "\x1B[0m" ///< ANSI escape sequence: reset all to normal
#define BLD "\x1B[1m" ///< ANSI escape sequence: bold
// #define DIM "\x1B[2m" ///< ANSI escape sequence: dim
// #define ULN "\x1B[3m" ///< ANSI escape sequence: underline
// #define BLN "\x1B[5m" ///< ANSI escape sequence: blink
#define REV "\x1B[7m" ///< ANSI escape sequence: reverse
// #define HID "\x1B[8m" ///< ANSI escape sequence: hidden
// #define BLK "\x1B[30m" ///< ANSI escape sequence: black
#define RED "\x1B[31m" ///< ANSI escape sequence: red
#define GRN "\x1B[32m" ///< ANSI escape sequence: green
#define YEL "\x1B[33m" ///< ANSI escape sequence: yellow
#define BLU "\x1B[34m" ///< ANSI escape sequence: blue
#define MAG "\x1B[35m" ///< ANSI escape sequence: magenta
#define CYN "\x1B[36m" ///< ANSI escape sequence: cyan
// #define WHT "\x1B[37m" ///< ANSI escape sequence: white
#else
#define NRM ""
#define BLD ""
#define REV ""
#define RED ""
#define GRN ""
#define YEL ""
#define BLU ""
#define MAG ""
#define CYN ""
#endif
#define FMT_PNR_IN BLU "%" PRIu NRM
#define FMT_PNR_OUT GRN "%" PRIu NRM
#define FMT_SID BLD YEL "%" PRId NRM
struct cid {
splay_entry(cid) node_seq;
uint_t seq; ///< Connection ID sequence number
uint_t rpt; ///< Retire prior to
/// XXX len must precede id for cid_cmp() over both to work
uint8_t len; ///< Connection ID length
/// XXX id must precede srt for rand_bytes() over both to work
uint8_t id[CID_LEN_MAX]; ///< Connection ID
uint8_t srt[SRT_LEN]; ///< Stateless Reset Token
uint8_t retired : 1; ///< Did we retire this CID?
uint8_t has_srt : 1; ///< Is the SRT field valid?
uint8_t : 6;
uint8_t _unused[2];
};
struct pkt_hdr {
struct cid dcid; ///< Destination CID.
struct cid scid; ///< Source CID.
uint_t nr; ///< Packet number.
uint16_t len; ///< Content of length field in long header.
uint16_t hdr_len; ///< Length of entire QUIC header.
uint32_t vers; ///< QUIC version in long header.
uint8_t flags; ///< First (raw) byte of packet.
uint8_t type; ///< Parsed packet type.
// we do not store any token of LH packets in the metadata anymore
#ifdef HAVE_64BIT
uint8_t _unused[6];
#else
uint8_t _unused[2];
#endif
};
/// Packet meta-data information associated with w_iov buffers
struct pkt_meta {
// XXX need to potentially change pm_cpy() below if fields are reordered
splay_entry(pkt_meta) off_node;
sl_entry(pkt_meta) rtx_next;
sl_head(pm_sl, pkt_meta) rtx; ///< List of pkt_meta structs of previous TXs.
// pm_cpy(true) starts copying from here:
struct frames frms; ///< Frames present in pkt.
struct q_stream * strm; ///< Stream this data was written on.
uint_t strm_off; ///< Stream data offset.
uint16_t strm_frm_pos; ///< Offset of stream frame header.
uint16_t strm_data_pos; ///< Offset of first byte of stream frame data.
uint16_t strm_data_len; ///< Length of stream frame data.
uint16_t ack_frm_pos; ///< Offset of (first, on RX) ACK frame (+1 for type).
dint_t max_strm_data_sid; ///< MAX_STREAM_DATA sid, if sent.
uint_t max_strm_data; ///< MAX_STREAM_DATA limit, if sent.
uint_t max_data; ///< MAX_DATA limit, if sent.
dint_t max_strms_bidi; ///< MAX_STREAM_ID bidir limit, if sent.
dint_t max_strms_uni; ///< MAX_STREAM_ID unidir limit, if sent.
uint_t strm_data_blocked; ///< STREAM_DATA_BLOCKED value, if sent.
uint_t data_blocked; ///< DATA_BLOCKED value, if sent.
uint_t min_cid_seq; ///< Smallest NEW_CONNECTION_ID seq in pkt, if sent.
#ifndef HAVE_64BIT
uint8_t _unused[4];
#endif
// pm_cpy(false) starts copying from here:
struct pn_space * pn; ///< Packet number space.
struct pkt_hdr hdr; ///< Parsed packet header.
uint64_t t; ///< TX or RX timestamp.
uint16_t udp_len; ///< Length of protected UDP packet at TX/RX.
uint8_t has_rtx : 1; ///< Does the w_iov hold truncated data?
uint8_t is_reset : 1; ///< This packet is a stateless reset.
uint8_t is_fin : 1; ///< This packet has a stream FIN bit.
uint8_t in_flight : 1; ///< Does this pkt count towards in_flight?
uint8_t ack_eliciting : 1; ///< Is this packet ACK-eliciting?
uint8_t acked : 1; ///< Was this packet ACKed?
uint8_t lost : 1; ///< Have we marked this packet as lost?
uint8_t txed : 1; ///< Did we TX this pkt?
#ifdef HAVE_64BIT
uint8_t _unused2[5];
#else
uint8_t _unused2[1];
#endif
};
struct per_engine_data {
struct timeouts * wheel;
struct pkt_meta * pkt_meta;
ptls_context_t tls_ctx;
};
#define ped(w) ((struct per_engine_data *)((w)->data))
extern struct q_conn_sl accept_queue;
extern struct q_conn_conf default_conn_conf;
/// The versions of QUIC supported by this implementation
extern const uint32_t ok_vers[];
extern const uint8_t ok_vers_len;
extern void __attribute__((nonnull)) alloc_off(struct w_engine * const w,
struct w_iov_sq * const q,
const uint32_t len,
const uint16_t off);
extern void __attribute__((nonnull))
free_iov(struct w_iov * const v, struct pkt_meta * const m);
extern struct w_iov * __attribute__((nonnull))
alloc_iov(struct w_engine * const w,
const uint16_t len,
const uint16_t off,
struct pkt_meta ** const m);
extern struct w_iov * __attribute__((nonnull(1)))
w_iov_dup(const struct w_iov * const v,
struct pkt_meta ** const mdup,
const uint16_t off);
#if (!defined(NDEBUG) || defined(NDEBUG_WITH_DLOG)) && !defined(FUZZING) && \
!defined(NO_FUZZER_CORPUS_COLLECTION)
extern int corpus_pkt_dir, corpus_frm_dir;
extern void __attribute__((nonnull))
write_to_corpus(const int dir, const void * const data, const size_t len);
#endif
/// Is flag @p f set in flags variable @p v?
///
/// @param f Flag.
/// @param v Variable.
///
/// @return True if set, false otherwise.
///
#define is_set(f, v) (((v) & (f)) == (f))
/// Return the pkt_meta entry for a given w_iov.
///
/// @param v Pointer to a w_iov.
///
/// @return Pointer to the pkt_meta entry for the w_iov.
///
#define meta(v) ped((v)->w)->pkt_meta[w_iov_idx(v)]
/// Return the w_iov index of a given pkt_meta.
///
/// @param w Pointer to warpcore engine.
/// @param m Pointer to a pkt_meta entry.
///
/// @return Index of the struct w_iov the struct pkt_meta holds meta data
/// for.
///
#define pm_idx(w, m) (uint32_t)((m)-ped(w)->pkt_meta)
extern char * __attribute__((nonnull)) hex2str(const uint8_t * const src,
const size_t len_src,
char * const dst,
const size_t len_dst);
#define hex_str_len(x) ((x)*2 + 1)
#define mk_cid_str(lvl, cid, str) \
char str[DLEVEL >= (lvl) \
? hex_str_len(2 * sizeof((cid)->seq) + CID_LEN_MAX) \
: 1]; \
if (unlikely(DLEVEL >= (lvl)) && likely(cid)) { \
const int _n = snprintf(str, sizeof(str), "%" PRIu ":", (cid)->seq); \
hex2str((cid)->id, (cid)->len, &str[_n], sizeof(str) - (size_t)_n); \
}
#define mk_path_chlg_str(lvl, path_chlg, str) \
char str[DLEVEL >= (lvl) ? hex_str_len(PATH_CHLG_LEN) : 1]; \
if (unlikely(DLEVEL >= (lvl))) \
hex2str((path_chlg), sizeof(path_chlg), str, sizeof(str))
#define mk_srt_str(lvl, srt, str) \
char str[DLEVEL >= (lvl) ? hex_str_len(SRT_LEN) : 1]; \
if (unlikely(DLEVEL >= (lvl))) \
hex2str((srt), sizeof(srt), str, sizeof(str))
#define mk_tok_str(lvl, tok, tok_len, str) \
char str[DLEVEL >= (lvl) ? hex_str_len(MAX_TOK_LEN) : 1]; \
if (unlikely(DLEVEL >= (lvl)) && likely(tok)) { \
hex2str((tok), (tok_len), str, sizeof(str)); \
}
#define has_strm_data(p) (p)->strm_frm_pos
#define get_conf(conf, val) \
(conf) && (conf)->val ? (conf)->val : default_conn_conf.val
#define get_conf_uncond(conf, val) (conf) ? (conf)->val : default_conn_conf.val
static inline void __attribute__((nonnull))
cid_cpy(struct cid * const dst, const struct cid * const src)
{
memcpy((uint8_t *)dst + offsetof(struct cid, seq),
(const uint8_t *)src + offsetof(struct cid, seq),
sizeof(struct cid) - offsetof(struct cid, seq));
}
static inline void __attribute__((nonnull))
pm_cpy(struct pkt_meta * const dst,
const struct pkt_meta * const src,
const bool also_frame_info)
{
const size_t off = also_frame_info ? offsetof(struct pkt_meta, frms)
: offsetof(struct pkt_meta, pn);
memcpy((uint8_t *)dst + off, (const uint8_t *)src + off,
sizeof(*dst) - off);
}
static inline void __attribute__((nonnull))
adj_iov_to_start(struct w_iov * const v, const struct pkt_meta * const m)
{
v->buf -= m->strm_data_pos;
v->len += m->strm_data_pos;
}
static inline void __attribute__((nonnull))
adj_iov_to_data(struct w_iov * const v, const struct pkt_meta * const m)
{
v->buf += m->strm_data_pos;
v->len -= m->strm_data_pos;
}
|
danilw/vulkan-shadertoy-launcher
|
os_utils/wayland_utils.h
|
<filename>os_utils/wayland_utils.h<gh_stars>10-100
// from https://wayland-book.com/seat/example.html
// used stable xdg-shell
// Wayland does not have stable "decoration" support, xdg-decoration not supported
// zxdg_toplevel_decoration_v1 is unstable
// https://wayland-book.com/xdg-shell-in-depth/interactive.html
#include <linux/input.h>
static uint8_t local_k_map[0xff+1]={0}; //+1 to have 0xff index
static uint8_t get_ASCII_key(uint8_t key){return local_k_map[key];}
static void xdg_wm_base_ping(void *data, struct xdg_wm_base *shell, uint32_t serial)
{
xdg_wm_base_pong(shell, serial);
}
static const struct xdg_wm_base_listener xdg_wm_base_listener = {xdg_wm_base_ping,};
static void seatCapabilities(struct wl_seat *seat, uint32_t caps, struct app_os_window *os_window);
static void seatCapabilitiesCb(void *data, struct wl_seat *seat, uint32_t caps)
{
struct app_os_window *os_window = (struct app_os_window *) data;
seatCapabilities(seat, caps, os_window);
}
void registryGlobal(struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version, struct app_os_window *os_window)
{
if (strcmp(interface, "wl_compositor") == 0) {
os_window->compositor = (struct wl_compositor *) wl_registry_bind(registry, name, &wl_compositor_interface, 3);
}
else if (strcmp(interface, "xdg_wm_base") == 0)
{
os_window->shell = (struct xdg_wm_base *) wl_registry_bind(registry, name, &xdg_wm_base_interface, 1);
xdg_wm_base_add_listener(os_window->shell, &xdg_wm_base_listener, NULL);
}
else if (strcmp(interface, "wl_seat") == 0)
{
os_window->seat = (struct wl_seat *) wl_registry_bind(registry, name, &wl_seat_interface, 1);
static const struct wl_seat_listener seat_listener ={ seatCapabilitiesCb, };
wl_seat_add_listener(os_window->seat, &seat_listener, os_window);
}
}
static void setSize(int width, int height, struct app_os_window *os_window)
{
if (width <= 0 || height <= 0){
os_window->is_minimized = true;
}else
{
os_window->is_minimized = false;
if ((os_window->app_data.iResolution[0] != width) || (os_window->app_data.iResolution[1] != height)) {
os_window->is_minimized = false;
os_window->app_data.iResolution[0] = width;
os_window->app_data.iResolution[1] = height;
if((os_window->app_data.iResolution[0]<=1)||(os_window->app_data.iResolution[1]<=1)){
os_window->is_minimized = true;
}
}
}
}
static void xdg_surface_handle_configure(void *data, struct xdg_surface *surface, uint32_t serial)
{
struct app_os_window *os_window = (struct app_os_window *) data;
xdg_surface_ack_configure(surface, serial);
os_window->configured = true;
}
static const struct xdg_surface_listener xdg_surface_listener = {xdg_surface_handle_configure,};
static void xdg_toplevel_handle_configure(void *data, struct xdg_toplevel *toplevel, int32_t width, int32_t height, struct wl_array *states)
{
struct app_os_window *os_window = (struct app_os_window *) data;
setSize(width, height, os_window);
}
static void xdg_toplevel_handle_close(void *data, struct xdg_toplevel *xdg_toplevel)
{
struct app_os_window *os_window = (struct app_os_window *) data;
os_window->app_data.quit = true;
}
static const struct xdg_toplevel_listener xdg_toplevel_listener = {xdg_toplevel_handle_configure, xdg_toplevel_handle_close,};
static void registryGlobalCb(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version)
{
struct app_os_window *os_window = (struct app_os_window *) data;
registryGlobal(registry, name, interface, version, os_window);
}
static void pointerEnterCb(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx, wl_fixed_t sy){}
static void pointerLeaveCb(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface){}
static void pointerMotion(struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy, struct app_os_window *os_window)
{
os_window->app_data.iMouse[0]=wl_fixed_to_int(sx);
os_window->app_data.iMouse[1]=os_window->app_data.iResolution[1] - wl_fixed_to_int(sy);
}
static void pointerMotionCb(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy)
{
struct app_os_window *os_window = (struct app_os_window *) data;
pointerMotion(pointer, time, sx, sy, os_window);
}
static void pointerButton(struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state, struct app_os_window *os_window)
{
switch (button)
{
case BTN_LEFT:
os_window->app_data.iMouse_click[0] = state;
if(state){
os_window->app_data.iMouse_lclick[0] = os_window->app_data.iMouse[0];
os_window->app_data.iMouse_lclick[1] = os_window->app_data.iResolution[1] - os_window->app_data.iMouse[1];
}else{
os_window->app_data.iMouse_lclick[0] = -os_window->app_data.iMouse_lclick[0];
os_window->app_data.iMouse_lclick[1] = -os_window->app_data.iMouse_lclick[1];
}
break;
case BTN_MIDDLE:
break;
case BTN_RIGHT:
os_window->app_data.iMouse_click[1] = state;
if(state){
os_window->app_data.iMouse_rclick[0] = os_window->app_data.iMouse[0];
os_window->app_data.iMouse_rclick[1] = os_window->app_data.iResolution[1] - os_window->app_data.iMouse[1];
}else{
os_window->app_data.iMouse_rclick[0] = -os_window->app_data.iMouse_rclick[0];
os_window->app_data.iMouse_rclick[1] = -os_window->app_data.iMouse_rclick[1];
}
break;
}
}
static void pointerButtonCb(void *data, struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state)
{
struct app_os_window *os_window = (struct app_os_window *) data;
pointerButton(pointer, serial, time, button, state, os_window);
}
static void pointerAxis(struct wl_pointer *pointer, uint32_t time, uint32_t axis, wl_fixed_t value, struct app_os_window *os_window)
{
float d = wl_fixed_to_double(value);
switch (axis)
{
case REL_X:
//printf("mouse wheel %f\n",d);
break;
}
}
static void pointerAxisCb(void *data, struct wl_pointer *pointer, uint32_t time, uint32_t axis, wl_fixed_t value)
{
struct app_os_window *os_window = (struct app_os_window *) data;
pointerAxis(pointer, time, axis, value, os_window);
}
static void keyboardKeymapCb(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size){}
static void keyboardEnterCb(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys){}
static void keyboardLeaveCb(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface){}
static void keyboardKey(struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state, struct app_os_window *os_window)
{
uint8_t keyA=get_ASCII_key((uint8_t)key);
if(state) {
os_window->pause_refresh=true;
keyboard_need_update=true;
keyboard_draw=true;
update_key_map(keyA,2,!keyboard_map[keyA][2]);
update_key_map(keyA,1,true);
update_key_map(keyA,0,true);
}else {
os_window->pause_refresh=true;
keyboard_need_update=true;
keyboard_draw=true;
update_key_map(keyA,0,false);
}
}
static void keyboardKeyCb(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state)
{
struct app_os_window *os_window = (struct app_os_window *) data;
keyboardKey(keyboard, serial, time, key, state, os_window);
}
static void keyboardModifiersCb(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group){}
static void seatCapabilities(struct wl_seat *seat, uint32_t caps, struct app_os_window *os_window)
{
if ((caps & WL_SEAT_CAPABILITY_POINTER) && !os_window->pointer)
{
os_window->pointer = wl_seat_get_pointer(seat);
static const struct wl_pointer_listener pointer_listener ={ pointerEnterCb, pointerLeaveCb, pointerMotionCb, pointerButtonCb, pointerAxisCb, };
wl_pointer_add_listener(os_window->pointer, &pointer_listener, os_window);
}
else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && os_window->pointer)
{
wl_pointer_destroy(os_window->pointer);
os_window->pointer = NULL;
}
if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !os_window->keyboard)
{
os_window->keyboard = wl_seat_get_keyboard(seat);
static const struct wl_keyboard_listener keyboard_listener = { keyboardKeymapCb, keyboardEnterCb, keyboardLeaveCb, keyboardKeyCb, keyboardModifiersCb, };
wl_keyboard_add_listener(os_window->keyboard, &keyboard_listener, os_window);
}
else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && os_window->keyboard)
{
wl_keyboard_destroy(os_window->keyboard);
os_window->keyboard = NULL;
}
}
static void registryGlobalRemoveCb(void *data, struct wl_registry *registry, uint32_t name){}
void initWaylandConnection(struct app_os_window *os_window)
{
os_window->display = wl_display_connect(NULL);
if (!os_window->display)
{
printf("Could not connect to Wayland display!\n");
fflush(stdout);
exit(1);
}
os_window->registry = wl_display_get_registry(os_window->display);
if (!os_window->registry)
{
printf("Could not get Wayland registry!\n");
fflush(stdout);
exit(1);
}
static const struct wl_registry_listener registry_listener = { registryGlobalCb, registryGlobalRemoveCb };
wl_registry_add_listener(os_window->registry, ®istry_listener, os_window);
wl_display_dispatch(os_window->display);
wl_display_roundtrip(os_window->display);
if (!os_window->compositor || !os_window->shell || !os_window->seat)
{
printf("Could not bind Wayland protocols!\n");
fflush(stdout);
exit(1);
}
}
static void gen_key_map();
static void setupWindow(struct app_os_window *os_window)
{
os_window->surface = wl_compositor_create_surface(os_window->compositor);
os_window->xdg_surface = xdg_wm_base_get_xdg_surface(os_window->shell, os_window->surface);
xdg_surface_add_listener(os_window->xdg_surface, &xdg_surface_listener, os_window);
os_window->xdg_toplevel = xdg_surface_get_toplevel(os_window->xdg_surface);
xdg_toplevel_add_listener(os_window->xdg_toplevel, &xdg_toplevel_listener, os_window);
xdg_toplevel_set_title(os_window->xdg_toplevel, os_window->name);
wl_surface_commit(os_window->surface);
gen_key_map();
}
//shadertoy keys
static const uint8_t Key_Backspace = 8, Key_Tab = 9, Key_Enter = 13, Key_Shift = 16, Key_Space = 32,
Key_Ctrl = 17, Key_Alt = 18, Key_Pause = 19, Key_Caps = 20, Key_Escape = 27, Key_PageUp = 33, Key_PageDown = 34, Key_End = 35,
Key_Home = 36, Key_LeftArrow = 37, Key_UpArrow = 38, Key_RightArrow = 39, Key_DownArrow = 40, Key_Insert = 45,
Key_Delete = 46, Key_0 = 48, Key_1 = 49, Key_2 = 50, Key_3 = 51, Key_4 = 52,
Key_5 = 53, Key_6 = 54, Key_7 = 55, Key_8 = 56, Key_9 = 57, Key_A = 65, Key_B = 66,
Key_C = 67, Key_D = 68, Key_E = 69, Key_F = 70, Key_G = 71, Key_H = 72,
Key_I = 73, Key_J = 74, Key_K = 75, Key_L = 76, Key_M = 77, Key_N = 78, Key_O = 79, Key_P = 80, Key_Q = 81,
Key_R = 82, Key_S = 83, Key_T = 84, Key_U = 85,
Key_V = 86, Key_W = 87, Key_X = 88, Key_Y = 89, Key_Z = 90, Key_LeftWindow = 91, Key_RightWindows = 92,
Key_Select = 93, Key_Numpad0 = 96, Key_Numpad1 = 97, Key_Numpad2 = 98, Key_Numpad3 = 99,
Key_Numpad4 = 100, Key_Numpad5 = 101, Key_Numpad6 = 102, Key_Numpad7 = 103, Key_Numpad8 = 104, Key_Numpad9 = 105,
Key_NumpadMultiply = 106, Key_NumpadAdd = 107, Key_NumpadSubtract = 109, Key_NumpadPeriod = 110, Key_NumpadDivide = 111,
Key_F1 = 112, Key_F2 = 113, Key_F3 = 114, Key_F4 = 115, Key_F5 = 116, Key_F6 = 117, Key_F7 = 118, Key_F8 = 119, Key_F9 = 120,
Key_F10 = 121, Key_F11 = 122, Key_F12 = 123, Key_NumLock = 144, Key_ScrollLock = 145,
Key_SemiColon = 186, Key_Equal = 187, Key_Comma = 188, Key_Dash = 189, Key_Period = 190,
Key_ForwardSlash = 191, Key_GraveAccent = 192, Key_OpenBracket = 219, Key_BackSlash = 220, Key_CloseBraket = 221, Key_SingleQuote = 222;
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
static void gen_key_map(){
uint32_t keycode=0;
keycode=KEY_A;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_A;
keycode=KEY_B;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_B;
keycode=KEY_C;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_C;
keycode=KEY_D;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_D;
keycode=KEY_E;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_E;
keycode=KEY_F;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F;
keycode=KEY_G;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_G;
keycode=KEY_H;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_H;
keycode=KEY_I;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_I;
keycode=KEY_J;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_J;
keycode=KEY_K;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_K;
keycode=KEY_L;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_L;
keycode=KEY_M;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_M;
keycode=KEY_N;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_N;
keycode=KEY_O;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_O;
keycode=KEY_P;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_P;
keycode=KEY_Q;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Q;
keycode=KEY_R;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_R;
keycode=KEY_S;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_S;
keycode=KEY_T;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_T;
keycode=KEY_U;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_U;
keycode=KEY_V;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_V;
keycode=KEY_W;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_W;
keycode=KEY_X;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_X;
keycode=KEY_Y;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Y;
keycode=KEY_Z;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Z;
keycode=KEY_SPACE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Space;
keycode=KEY_0;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_0;
keycode=KEY_1;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_1;
keycode=KEY_2;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_2;
keycode=KEY_3;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_3;
keycode=KEY_4;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_4;
keycode=KEY_5;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_5;
keycode=KEY_6;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_6;
keycode=KEY_7;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_7;
keycode=KEY_8;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_8;
keycode=KEY_9;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_9;
keycode=KEY_ESC;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Escape;
keycode=KEY_LEFTCTRL;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Ctrl;
keycode=KEY_LEFTSHIFT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Shift;
keycode=KEY_LEFTALT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Alt;
//keycode=KEY_Super_L;
//local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_LeftWindow;
keycode=KEY_RIGHTCTRL;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Ctrl;
keycode=KEY_RIGHTSHIFT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Shift;
keycode=KEY_RIGHTALT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Alt;
//keycode=KEY_Super_R;
//local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_RightWindows;
keycode=KEY_BACKSPACE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Backspace;
keycode=KEY_TAB;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Tab;
keycode=KEY_ENTER;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Enter;
keycode=KEY_PAUSE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Pause;
keycode=KEY_CAPSLOCK;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Caps;
keycode=KEY_PAGEUP;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_PageUp;
keycode=KEY_PAGEDOWN;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_PageDown;
keycode=KEY_END;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_End;
keycode=KEY_HOME;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Home;
keycode=KEY_LEFT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_LeftArrow;
keycode=KEY_UP;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_UpArrow;
keycode=KEY_RIGHT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_RightArrow;
keycode=KEY_DOWN;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_DownArrow;
keycode=KEY_INSERT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Insert;
keycode=KEY_DELETE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Delete;
keycode=KEY_SELECT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Select;
keycode=KEY_KP0;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad0;
keycode=KEY_KP1;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad1;
keycode=KEY_KP2;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad2;
keycode=KEY_KP3;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad3;
keycode=KEY_KP4;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad4;
keycode=KEY_KP5;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad5;
keycode=KEY_KP6;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad6;
keycode=KEY_KP7;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad7;
keycode=KEY_KP8;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad8;
keycode=KEY_KP9;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Numpad9;
keycode=KEY_KPENTER;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Enter;
keycode=KEY_KPASTERISK;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_NumpadMultiply;
keycode=KEY_KPPLUS;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_NumpadAdd;
keycode=KEY_KPMINUS;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_NumpadSubtract;
keycode=<KEY>;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_NumpadPeriod;
keycode=KEY_KPSLASH;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_NumpadDivide;
keycode=KEY_F1;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F1;
keycode=KEY_F2;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F2;
keycode=KEY_F3;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F3;
keycode=KEY_F4;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F4;
keycode=KEY_F5;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F5;
keycode=KEY_F6;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F6;
keycode=KEY_F7;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F7;
keycode=KEY_F8;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F8;
keycode=KEY_F9;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F9;
keycode=KEY_F10;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F10;
keycode=KEY_F11;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F11;
keycode=KEY_F12;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_F12;
keycode=KEY_NUMLOCK;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_NumLock;
keycode=KEY_SCROLLLOCK;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_ScrollLock;
keycode=KEY_SEMICOLON;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_SemiColon;
keycode=KEY_EQUAL;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Equal;
keycode=KEY_COMMA;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Comma;
keycode=KEY_MINUS;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Dash;
keycode=KEY_DOT;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_Period;
keycode=KEY_SLASH;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_ForwardSlash;
keycode=KEY_GRAVE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_GraveAccent;
keycode=KEY_LEFTBRACE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_OpenBracket;
keycode=KEY_BACKSLASH;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_BackSlash;
keycode=KEY_RIGHTBRACE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_CloseBraket;
keycode=KEY_APOSTROPHE;
local_k_map[(uint8_t)max(min(keycode,0xff),0)]=Key_SingleQuote;
}
|
danilw/vulkan-shadertoy-launcher
|
build_scripts/yariv/yariv.h
|
// The latest version of this library is available on GitHub;
// https://github.com/sheredom/yari-v
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org/>
#ifndef SHEREDOM_YARIV_H_INCLUDED
#define SHEREDOM_YARIV_H_INCLUDED
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
enum yariv_encode_flags_e {
yariv_encode_flags_default = 0,
// enable the SPIR-V to be stripped of all non-essential information
yariv_encode_flags_strip = 0x1
};
#if defined(__clang__) || defined(__GNUC__)
#define yariv_nonnull __attribute__((nonnull))
#define yariv_weak __attribute__((weak))
#elif defined(_MSC_VER)
#define yariv_nonnull
#define yariv_weak __inline
#else
#error Non clang, non gcc, non MSVC compiler found!
#endif
yariv_nonnull yariv_weak size_t yariv_encode_size(uint32_t encode_flags,
const void *spirv,
size_t spirv_size);
yariv_nonnull yariv_weak int yariv_encode(uint32_t encode_flags,
void *out_yariv,
size_t out_yariv_size,
const void *spirv, size_t spirv_size);
yariv_nonnull yariv_weak size_t yariv_decode_size(const void *yariv,
size_t yariv_size);
yariv_nonnull yariv_weak int yariv_decode(void *out_spirv,
size_t out_spirv_size,
const void *yariv, size_t yariv_size);
yariv_weak size_t yariv_encode_signed_varint(int32_t i, uint8_t *out);
yariv_weak size_t yariv_decode_signed_varint(const uint8_t *in, int32_t *out);
yariv_weak size_t yariv_encode_unsigned_varint(uint32_t i, uint8_t *out);
yariv_weak size_t yariv_decode_unsigned_varint(const uint8_t *in,
uint32_t *out);
yariv_weak uint32_t yariv_shuffle_opcode(uint32_t opcode);
yariv_weak int yariv_opcode_has_word_count(uint32_t opcode,
uint32_t *word_count);
yariv_weak int yariv_opcode_has_id(uint32_t opcode);
yariv_weak int yariv_opcode_has_type_and_id(uint32_t opcode);
yariv_weak uint32_t yariv_opcode_maybe_split(uint32_t opcode,
const uint32_t *spirv,
uint32_t word_count);
yariv_weak uint32_t yariv_word_count_constant_part(uint32_t opcode);
yariv_weak uint32_t yariv_word_count_to_id_delta(uint32_t opcode,
uint32_t word_count);
#undef yariv_weak
#undef yariv_nonnull
enum YarivOpcode_s {
YarivOpNop = 0,
YarivOpUndef = 1,
YarivOpSourceContinued = 2,
YarivOpSource = 3,
YarivOpSourceExtension = 4,
YarivOpName = 5,
YarivOpMemberName = 6,
YarivOpString = 7,
YarivOpLine = 8,
YarivOp9 = 9, // There is a gap in the SPIR-V opcode numbering here
YarivOpExtension = 10,
YarivOpExtInstImport = 11,
YarivOpExtInst = 12,
YarivOp13 = 13, // There is a gap in the SPIR-V opcode numbering here
YarivOpMemoryModel = 14,
YarivOpEntryPoint = 15,
YarivOpExecutionMode = 16,
YarivOpCapability = 17,
YarivOp18 = 18, // There is a gap in the SPIR-V opcode numbering here
YarivOpTypeVoid = 19,
YarivOpTypeBool = 20,
YarivOpTypeInt = 21,
YarivOpTypeFloat = 22,
YarivOpTypeVector = 23,
YarivOpTypeMatrix = 24,
YarivOpTypeImage = 25,
YarivOpTypeSampler = 26,
YarivOpTypeSampledImage = 27,
YarivOpTypeArray = 28,
YarivOpTypeRuntimeArray = 29,
YarivOpTypeStruct = 30,
YarivOpTypeOpaque = 31,
YarivOpTypePointer = 32,
YarivOpTypeFunction = 33,
YarivOpTypeEvent = 34,
YarivOpTypeDeviceEvent = 35,
YarivOpTypeReserveId = 36,
YarivOpTypeQueue = 37,
YarivOpTypePipe = 38,
YarivOpTypeForwardPointer = 39,
YarivOp40 = 40, // There is a gap in the SPIR-V opcode numbering here
YarivOpConstantTrue = 41,
YarivOpConstantFalse = 42,
YarivOpConstant = 43,
YarivOpConstantComposite = 44,
YarivOpConstantSampler = 45,
YarivOpConstantNull = 46,
YarivOp47 = 47, // There is a gap in the SPIR-V opcode numbering here
YarivOpSpecConstantTrue = 48,
YarivOpSpecConstantFalse = 49,
YarivOpSpecConstant = 50,
YarivOpSpecConstantComposite = 51,
YarivOpSpecConstantOp = 52,
YarivOp53 = 53, // There is a gap in the SPIR-V opcode numbering here
YarivOpFunction = 54,
YarivOpFunctionParameter = 55,
YarivOpFunctionEnd = 56,
YarivOpFunctionCall = 57,
YarivOp58 = 58, // There is a gap in the SPIR-V opcode numbering here
YarivOpVariable = 59,
YarivOpImageTexelPointer = 60,
YarivOpLoad = 61,
YarivOpStore = 62,
YarivOpCopyMemory = 63,
YarivOpCopyMemorySized = 64,
YarivOpAccessChain = 65,
YarivOpInBoundsAccessChain = 66,
YarivOpPtrAccessChain = 67,
YarivOpArrayLength = 68,
YarivOpGenericPtrMemSemantics = 69,
YarivOpInBoundsPtrAccessChain = 70,
YarivOpDecorate = 71,
YarivOpMemberDecorate = 72,
YarivOpDecorationGroup = 73,
YarivOpGroupDecorate = 74,
YarivOpGroupMemberDecorate = 75,
YarivOp76 = 76, // There is a gap in the SPIR-V opcode numbering here
YarivOpVectorExtractDynamic = 77,
YarivOpVectorInsertDynamic = 78,
YarivOpVectorShuffle = 79,
YarivOpCompositeConstruct = 80,
YarivOpCompositeExtract = 81,
YarivOpCompositeInsert = 82,
YarivOpCopyObject = 83,
YarivOpTranspose = 84,
YarivOp85 = 85, // There is a gap in the SPIR-V opcode numbering here
YarivOpSampledImage = 86,
YarivOpImageSampleImplicitLod = 87,
YarivOpImageSampleExplicitLod = 88,
YarivOpImageSampleDrefImplicitLod = 89,
YarivOpImageSampleDrefExplicitLod = 90,
YarivOpImageSampleProjImplicitLod = 91,
YarivOpImageSampleProjExplicitLod = 92,
YarivOpImageSampleProjDrefImplicitLod = 93,
YarivOpImageSampleProjDrefExplicitLod = 94,
YarivOpImageFetch = 95,
YarivOpImageGather = 96,
YarivOpImageDrefGather = 97,
YarivOpImageRead = 98,
YarivOpImageWrite = 99,
YarivOpImage = 100,
YarivOpImageQueryFormat = 101,
YarivOpImageQueryOrder = 102,
YarivOpImageQuerySizeLod = 103,
YarivOpImageQuerySize = 104,
YarivOpImageQueryLod = 105,
YarivOpImageQueryLevels = 106,
YarivOpImageQuerySamples = 107,
YarivOp108 = 108, // There is a gap in the SPIR-V opcode numbering here
YarivOpConvertFToU = 109,
YarivOpConvertFToS = 110,
YarivOpConvertSToF = 111,
YarivOpConvertUToF = 112,
YarivOpUConvert = 113,
YarivOpSConvert = 114,
YarivOpFConvert = 115,
YarivOpQuantizeToF16 = 116,
YarivOpConvertPtrToU = 117,
YarivOpSatConvertSToU = 118,
YarivOpSatConvertUToS = 119,
YarivOpConvertUToPtr = 120,
YarivOpPtrCastToGeneric = 121,
YarivOpGenericCastToPtr = 122,
YarivOpGenericCastToPtrExplicit = 123,
YarivOpBitcast = 124,
YarivOp125 = 125, // There is a gap in the SPIR-V opcode numbering here
YarivOpSNegate = 126,
YarivOpFNegate = 127,
YarivOpIAdd = 128,
YarivOpFAdd = 129,
YarivOpISub = 130,
YarivOpFSub = 131,
YarivOpIMul = 132,
YarivOpFMul = 133,
YarivOpUDiv = 134,
YarivOpSDiv = 135,
YarivOpFDiv = 136,
YarivOpUMod = 137,
YarivOpSRem = 138,
YarivOpSMod = 139,
YarivOpFRem = 140,
YarivOpFMod = 141,
YarivOpVectorTimesScalar = 142,
YarivOpMatrixTimesScalar = 143,
YarivOpVectorTimesMatrix = 144,
YarivOpMatrixTimesVector = 145,
YarivOpMatrixTimesMatrix = 146,
YarivOpOuterProduct = 147,
YarivOpDot = 148,
YarivOpIAddCarry = 149,
YarivOpISubBorrow = 150,
YarivOpUMulExtended = 151,
YarivOpSMulExtended = 152,
YarivOpAny = 154,
YarivOpAll = 155,
YarivOpIsNan = 156,
YarivOpIsInf = 157,
YarivOpIsFinite = 158,
YarivOpIsNormal = 159,
YarivOpSignBitSet = 160,
YarivOpLessOrGreater = 161,
YarivOpOrdered = 162,
YarivOpUnordered = 163,
YarivOpLogicalEqual = 164,
YarivOpLogicalNotEqual = 165,
YarivOpLogicalOr = 166,
YarivOpLogicalAnd = 167,
YarivOpLogicalNot = 168,
YarivOpSelect = 169,
YarivOpIEqual = 170,
YarivOpINotEqual = 171,
YarivOpUGreaterThan = 172,
YarivOpSGreaterThan = 173,
YarivOpUGreaterThanEqual = 174,
YarivOpSGreaterThanEqual = 175,
YarivOpULessThan = 176,
YarivOpSLessThan = 177,
YarivOpULessThanEqual = 178,
YarivOpSLessThanEqual = 179,
YarivOpFOrdEqual = 180,
YarivOpFUnordEqual = 181,
YarivOpFOrdNotEqual = 182,
YarivOpFUnordNotEqual = 183,
YarivOpFOrdLessThan = 184,
YarivOpFUnordLessThan = 185,
YarivOpFOrdGreaterThan = 186,
YarivOpFUnordGreaterThan = 187,
YarivOpFOrdLessThanEqual = 188,
YarivOpFUnordLessThanEqual = 189,
YarivOpFOrdGreaterThanEqual = 190,
YarivOpFUnordGreaterThanEqual = 191,
YarivOpShiftRightLogical = 194,
YarivOpShiftRightArithmetic = 195,
YarivOpShiftLeftLogical = 196,
YarivOpBitwiseOr = 197,
YarivOpBitwiseXor = 198,
YarivOpBitwiseAnd = 199,
YarivOpNot = 200,
YarivOpBitFieldInsert = 201,
YarivOpBitFieldSExtract = 202,
YarivOpBitFieldUExtract = 203,
YarivOpBitReverse = 204,
YarivOpBitCount = 205,
YarivOpDPdx = 207,
YarivOpDPdy = 208,
YarivOpFwidth = 209,
YarivOpDPdxFine = 210,
YarivOpDPdyFine = 211,
YarivOpFwidthFine = 212,
YarivOpDPdxCoarse = 213,
YarivOpDPdyCoarse = 214,
YarivOpFwidthCoarse = 215,
YarivOpEmitVertex = 218,
YarivOpEndPrimitive = 219,
YarivOpEmitStreamVertex = 220,
YarivOpEndStreamPrimitive = 221,
YarivOpControlBarrier = 224,
YarivOpMemoryBarrier = 225,
YarivOpAtomicLoad = 227,
YarivOpAtomicStore = 228,
YarivOpAtomicExchange = 229,
YarivOpAtomicCompareExchange = 230,
YarivOpAtomicCompareExchangeWeak = 231,
YarivOpAtomicIIncrement = 232,
YarivOpAtomicIDecrement = 233,
YarivOpAtomicIAdd = 234,
YarivOpAtomicISub = 235,
YarivOpAtomicSMin = 236,
YarivOpAtomicUMin = 237,
YarivOpAtomicSMax = 238,
YarivOpAtomicUMax = 239,
YarivOpAtomicAnd = 240,
YarivOpAtomicOr = 241,
YarivOpAtomicXor = 242,
YarivOpPhi = 245,
YarivOpLoopMerge = 246,
YarivOpSelectionMerge = 247,
YarivOpLabel = 248,
YarivOpBranch = 249,
YarivOpBranchConditional = 250,
YarivOpSwitch = 251,
YarivOpKill = 252,
YarivOpReturn = 253,
YarivOpReturnValue = 254,
YarivOpUnreachable = 255,
YarivOpLifetimeStart = 256,
YarivOpLifetimeStop = 257,
YarivOpGroupAsyncCopy = 259,
YarivOpGroupWaitEvents = 260,
YarivOpGroupAll = 261,
YarivOpGroupAny = 262,
YarivOpGroupBroadcast = 263,
YarivOpGroupIAdd = 264,
YarivOpGroupFAdd = 265,
YarivOpGroupFMin = 266,
YarivOpGroupUMin = 267,
YarivOpGroupSMin = 268,
YarivOpGroupFMax = 269,
YarivOpGroupUMax = 270,
YarivOpGroupSMax = 271,
YarivOpReadPipe = 274,
YarivOpWritePipe = 275,
YarivOpReservedReadPipe = 276,
YarivOpReservedWritePipe = 277,
YarivOpReserveReadPipePackets = 278,
YarivOpReserveWritePipePackets = 279,
YarivOpCommitReadPipe = 280,
YarivOpCommitWritePipe = 281,
YarivOpIsValidReserveId = 282,
YarivOpGetNumPipePackets = 283,
YarivOpGetMaxPipePackets = 284,
YarivOpGroupReserveReadPipePackets = 285,
YarivOpGroupReserveWritePipePackets = 286,
YarivOpGroupCommitReadPipe = 287,
YarivOpGroupCommitWritePipe = 288,
YarivOpEnqueueMarker = 291,
YarivOpEnqueueKernel = 292,
YarivOpGetKernelNDrangeSubGroupCount = 293,
YarivOpGetKernelNDrangeMaxSubGroupSize = 294,
YarivOpGetKernelWorkGroupSize = 295,
YarivOpGetKernelPreferredWorkGroupSizeMultiple = 296,
YarivOpRetainEvent = 297,
YarivOpReleaseEvent = 298,
YarivOpCreateUserEvent = 299,
YarivOpIsValidEvent = 300,
YarivOpSetUserEventStatus = 301,
YarivOpCaptureEventProfilingInfo = 302,
YarivOpGetDefaultQueue = 303,
YarivOpBuildNDRange = 304,
YarivOpImageSparseSampleImplicitLod = 305,
YarivOpImageSparseSampleExplicitLod = 306,
YarivOpImageSparseSampleDrefImplicitLod = 307,
YarivOpImageSparseSampleDrefExplicitLod = 308,
YarivOpImageSparseSampleProjImplicitLod = 309,
YarivOpImageSparseSampleProjExplicitLod = 310,
YarivOpImageSparseSampleProjDrefImplicitLod = 311,
YarivOpImageSparseSampleProjDrefExplicitLod = 312,
YarivOpImageSparseFetch = 313,
YarivOpImageSparseGather = 314,
YarivOpImageSparseDrefGather = 315,
YarivOpImageSparseTexelsResident = 316,
YarivOpNoLine = 317,
YarivOpAtomicFlagTestAndSet = 318,
YarivOpAtomicFlagClear = 319,
YarivOpImageSparseRead = 320,
// the following are not actual SPIR-V opcodes, but I want to generate them
// and treat them as such in the encoder/decoder
YarivOpLoadWithMemoryAccess = 500,
YarivOpStoreWithMemoryAccess = 501,
YarivOpDecorateWithNoLiterals = 502,
YarivOpDecorateWithOneLiteral = 503,
YarivOpMemberDecorateWithNoLiterals = 504,
YarivOpMemberDecorateWithOneLiteral = 505,
YarivOpVariableWithInitializer = 506,
YarivOpConstantWithManyLiterals = 507,
YarivOpAccessChainWithOneIndex = 508,
YarivOpAccessChainWithTwoIndices = 509,
YarivOpAccessChainWithThreeIndices = 510,
YarivOpVectorShuffleTwoLiterals = 511,
YarivOpVectorShuffleThreeLiterals = 512,
YarivOpVectorShuffleFourLiterals = 513,
YarivOp514 = 514,
YarivOp515 = 515,
YarivOp516 = 516,
YarivOpVectorSwizzleTwoLiterals = 517,
YarivOpVectorSwizzleThreeLiterals = 518,
YarivOpVectorSwizzleFourLiterals = 519,
YarivOpCompositeExtractWithLiteralZero = 520,
YarivOpCompositeExtractWithLiteralOne = 521,
YarivOpCompositeExtractWithLiteralTwo = 522,
YarivOpCompositeExtractWithLiteralThree = 523,
YarivOpCompositeConstructOneConstituent = 524,
YarivOpCompositeConstructTwoConstituents = 525,
YarivOpCompositeConstructThreeConstituents = 526,
YarivOpDecorateRelaxedPrecision = 527,
YarivOpMemberDecorateOffset = 528,
YarivOpConstantWithOneFloatLiteral = 529,
YarivOpDecorateLocation = 530
};
#if defined(__cplusplus)
#define YARIV_CAST(type, x) (static_cast<type>(x))
#else
#define YARIV_CAST(type, x) ((type)(x))
#endif
size_t yariv_encode_size(uint32_t encode_flags, const void *spirv,
size_t spirv_size) {
size_t yariv_size = 0;
size_t i, e;
int32_t last_id = 1;
const uint32_t type_offset = 1;
// for the SPIR-V header
// * we skip encoding SPIR-V's magic number at the beginning of the binary
// * we use two bytes to encode the version number
yariv_size += 2;
// * we use varint encoding for the generators magic number
yariv_size +=
yariv_encode_unsigned_varint(YARIV_CAST(const uint32_t *, spirv)[2], 0);
// * we use varint encoding for the bound (maximum ID used)
yariv_size +=
yariv_encode_unsigned_varint(YARIV_CAST(const uint32_t *, spirv)[3], 0);
// * we skip encoding the instruction schema
// iterate through all the opcodes
for (i = 5, e = spirv_size / 4; i < e;) {
const uint32_t *from = YARIV_CAST(const uint32_t *, spirv) + i;
const uint32_t word_count = (*from) >> 16;
uint32_t opcode = (*from) & 0xFFFFu;
uint32_t k;
int32_t maybe_update_id = last_id;
// if we can strip opcodes
if (yariv_encode_flags_strip & encode_flags) {
switch (opcode) {
default:
break;
case YarivOpNop:
case YarivOpSourceContinued:
case YarivOpSource:
case YarivOpSourceExtension:
case YarivOpName:
case YarivOpMemberName:
case YarivOpString:
case YarivOpLine:
case YarivOpNoLine:
// all of these opcodes can be stripped, so we skip them!
i += word_count;
continue;
}
}
opcode = yariv_opcode_maybe_split(opcode, from, word_count);
// we encode the opcode first as a varint
yariv_size += yariv_encode_unsigned_varint(yariv_shuffle_opcode(opcode), 0);
// followed by the word_count as a varint
if (!yariv_opcode_has_word_count(opcode, 0)) {
// we encode word count minus the constant part of the word count (derived
// from the opcode)
yariv_size += yariv_encode_unsigned_varint(
word_count - yariv_word_count_constant_part(opcode), 0);
}
// by default, we use unsigned varint encoding from the word immediately
// following the opcode/word-count word
k = 1;
if (yariv_opcode_has_id(opcode)) {
// if our opcode has an id, we want to use signed varint encoding
// relative to the last id we used
const int32_t id = YARIV_CAST(const int32_t *, spirv)[i + 1];
yariv_size += yariv_encode_signed_varint(id - last_id, 0);
maybe_update_id = id;
// and since we have already encoded the first word, k should skip
// another word for the remaining unsigned varint encoding
k += 1;
} else if (yariv_opcode_has_type_and_id(opcode)) {
// if our opcode has a type and id, we want to use signed varint
// encoding for the id relative to the last id we used
const uint32_t type = YARIV_CAST(const uint32_t *, spirv)[i + 1];
const int32_t id = YARIV_CAST(const int32_t *, spirv)[i + 2];
yariv_size += yariv_encode_unsigned_varint(type - type_offset, 0);
yariv_size += yariv_encode_signed_varint(id - last_id, 0);
maybe_update_id = id;
// and since we have already encoded the first two words, k should skip
// another two words for the remaining unsigned varint encoding
k += 2;
}
switch (opcode) {
default:
// then we encode some words as signed varints
for (; k < yariv_word_count_to_id_delta(opcode, word_count); k++) {
const int32_t id = YARIV_CAST(const int32_t *, spirv)[i + k];
yariv_size += yariv_encode_signed_varint(id - last_id, 0);
}
// then we encode the remaining words as unsigned varints
for (; k < word_count; k++) {
yariv_size += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k], 0);
}
break;
case YarivOpExtInstImport:
// our literal string can just be memcpy'ed over
yariv_size += sizeof(uint32_t) * (word_count - k);
break;
case YarivOpVectorShuffleTwoLiterals:
case YarivOpVectorShuffleThreeLiterals:
case YarivOpVectorShuffleFourLiterals: {
const int32_t vecid1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t vecid2 = YARIV_CAST(const int32_t *, spirv)[i + k++];
// we use the signed varint encoding relative to last id for the two
// vectors we are shuffling (but we don't update last id crucially)
yariv_size += yariv_encode_signed_varint(vecid1 - last_id, 0);
yariv_size += yariv_encode_signed_varint(vecid2 - last_id, 0);
// our literals are at most 3 bits each, and we have n of them
if (YarivOpVectorShuffleTwoLiterals == opcode) {
yariv_size += sizeof(uint8_t);
} else {
yariv_size += sizeof(uint8_t) * 2;
}
} break;
case YarivOpVectorSwizzleTwoLiterals:
case YarivOpVectorSwizzleThreeLiterals:
case YarivOpVectorSwizzleFourLiterals: {
// both our IDs are the same, so we output it only once
const int32_t vecid1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
// skip the ID that is the same
k++;
// we use the signed varint encoding relative to last id for the two
// vectors we are shuffling (but we don't update last id crucially)
yariv_size += yariv_encode_signed_varint(vecid1 - last_id, 0);
// our literals are at most 2 bits each, and we have n of them
yariv_size += sizeof(uint8_t);
} break;
case YarivOpCompositeExtractWithLiteralZero:
case YarivOpCompositeExtractWithLiteralOne:
case YarivOpCompositeExtractWithLiteralTwo:
case YarivOpCompositeExtractWithLiteralThree: {
// the id of the composite we are extracting from
const int32_t composite = YARIV_CAST(const int32_t *, spirv)[i + k++];
// we use the signed varint encoding relative to last id for the two
// vectors we are shuffling (but we don't update last id crucially)
yariv_size += yariv_encode_signed_varint(composite - last_id, 0);
// skip the literal that we are not going to encode
k++;
} break;
case YarivOpDecorateRelaxedPrecision:
// skip the decoration for relaxed precision that we are not going to
// encode
k++;
break;
case YarivOpMemberDecorateOffset:
// encode the member literal as a varint
yariv_size += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k++], 0);
// skip the decoration for offset that we are not going to encode
k++;
// encode the byte offset as a varint
yariv_size += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k++], 0);
break;
case YarivOpConstantWithOneFloatLiteral:
// our literal is a float, so we just encode it using 4 bytes
yariv_size += sizeof(uint32_t);
break;
case YarivOpDecorateLocation:
// skip the decoration for location that we are not going to encode
k++;
// encode the location as a varint
yariv_size += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k++], 0);
break;
}
// bump i along
i += word_count;
// set last id to be the one we (might) have set
last_id = maybe_update_id;
}
return yariv_size;
}
int yariv_encode(uint32_t encode_flags, void *out_yariv, size_t out_yariv_size,
const void *spirv, size_t spirv_size) {
size_t i, e;
int32_t last_id = 1;
const uint32_t type_offset = 1;
uint8_t *yariv = YARIV_CAST(uint8_t *, out_yariv);
// FIXME: I should really check as I go that we don't try and write into
// our_yariv beyond out_yariv_size!
(void)out_yariv_size;
// for the SPIR-V header
// * encode the two bytes of the version number
*yariv++ =
YARIV_CAST(uint8_t, (YARIV_CAST(const uint32_t *, spirv)[1] >> 16));
*yariv++ = YARIV_CAST(uint8_t, (YARIV_CAST(const uint32_t *, spirv)[1] >> 8));
// * encode the varint for the generators magic number
yariv += yariv_encode_unsigned_varint(YARIV_CAST(const uint32_t *, spirv)[2],
yariv);
// * encode the varint for the bound
yariv += yariv_encode_unsigned_varint(YARIV_CAST(const uint32_t *, spirv)[3],
yariv);
// iterate through all the opcodes
for (i = 5, e = spirv_size / 4; i < e;) {
const uint32_t *from = YARIV_CAST(const uint32_t *, spirv) + i;
const uint32_t word_count = (*from) >> 16;
uint32_t opcode = (*from) & 0xFFFFu;
uint32_t k;
int32_t maybe_update_id = last_id;
// if we can strip opcodes
if (yariv_encode_flags_strip & encode_flags) {
switch (opcode) {
default:
break;
case YarivOpNop:
case YarivOpSourceContinued:
case YarivOpSource:
case YarivOpSourceExtension:
case YarivOpName:
case YarivOpMemberName:
case YarivOpString:
case YarivOpLine:
case YarivOpNoLine:
// all of these opcodes can be stripped, so we skip them!
i += word_count;
continue;
}
}
opcode = yariv_opcode_maybe_split(opcode, from, word_count);
// for all opcodes we encode the opcode first as a varint
yariv += yariv_encode_unsigned_varint(yariv_shuffle_opcode(opcode), yariv);
if (!yariv_opcode_has_word_count(opcode, 0)) {
// followed by the word count as a varint (removing the known constant
// part of word count)
yariv += yariv_encode_unsigned_varint(
word_count - yariv_word_count_constant_part(opcode), yariv);
}
// by default, we use unsigned varint encoding from the word immediately
// following the opcode/word-count word
k = 1;
if (yariv_opcode_has_id(opcode)) {
// if our opcode has an id, we want to use signed varint encoding
// relative to the last id we used
const int32_t id = YARIV_CAST(const int32_t *, spirv)[i + 1];
yariv += yariv_encode_signed_varint(id - last_id, yariv);
maybe_update_id = id;
// and since we have already encoded the first word, k should skip
// another word for the remaining unsigned varint encoding
k += 1;
} else if (yariv_opcode_has_type_and_id(opcode)) {
// if our opcode has a type and id, we want to use signed varint
// encoding for the id relative to the last id we used
const uint32_t type = YARIV_CAST(const uint32_t *, spirv)[i + 1];
const int32_t id = YARIV_CAST(const int32_t *, spirv)[i + 2];
yariv += yariv_encode_unsigned_varint(type - type_offset, yariv);
yariv += yariv_encode_signed_varint(id - last_id, yariv);
maybe_update_id = id;
// and since we have already encoded the first two words, k should skip
// another two words for the remaining unsigned varint encoding
k += 2;
}
switch (opcode) {
default:
// then we encode some words as signed varints
for (; k < yariv_word_count_to_id_delta(opcode, word_count); k++) {
const int32_t id = YARIV_CAST(const int32_t *, spirv)[i + k];
yariv += yariv_encode_signed_varint(id - last_id, yariv);
}
// then we encode the remaining words as unsigned varints
for (; k < word_count; k++) {
yariv += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k], yariv);
}
break;
case YarivOpExtInstImport:
// our literal string can just be memcpy'ed over
memcpy(yariv, YARIV_CAST(const uint32_t *, spirv) + i + k,
sizeof(uint32_t) * (word_count - k));
yariv += sizeof(uint32_t) * (word_count - k);
break;
case YarivOpVectorShuffleTwoLiterals:
case YarivOpVectorShuffleThreeLiterals:
case YarivOpVectorShuffleFourLiterals: {
const int32_t vecid1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t vecid2 = YARIV_CAST(const int32_t *, spirv)[i + k++];
// we use the signed varint encoding relative to last id for the two
// vectors we are shuffling (but we don't update last id crucially)
yariv += yariv_encode_signed_varint(vecid1 - last_id, yariv);
yariv += yariv_encode_signed_varint(vecid2 - last_id, yariv);
// our literals are at most 3 bits each, and we have n of them
if (YarivOpVectorShuffleTwoLiterals == opcode) {
const int32_t component0 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
*yariv++ = YARIV_CAST(uint8_t, ((component0 << 3) | component1) & 0xFF);
} else if (YarivOpVectorShuffleThreeLiterals == opcode) {
const int32_t component0 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component2 = YARIV_CAST(const int32_t *, spirv)[i + k++];
*yariv++ = YARIV_CAST(uint8_t, ((component0 << 3) | component1) & 0xFF);
*yariv++ = YARIV_CAST(uint8_t, (component2)&0xFF);
} else if (YarivOpVectorShuffleFourLiterals == opcode) {
const int32_t component0 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component2 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component3 = YARIV_CAST(const int32_t *, spirv)[i + k++];
*yariv++ = YARIV_CAST(uint8_t, ((component0 << 3) | component1) & 0xFF);
*yariv++ = YARIV_CAST(uint8_t, ((component2 << 3) | component3) & 0xFF);
}
} break;
case YarivOpVectorSwizzleTwoLiterals:
case YarivOpVectorSwizzleThreeLiterals:
case YarivOpVectorSwizzleFourLiterals: {
// both our IDs are the same, so we output it only once
const int32_t vecid1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
// skip the ID that is the same
k++;
// we use the signed varint encoding relative to last id for the one
// vector we are shuffling (but we don't update last id crucially)
yariv += yariv_encode_signed_varint(vecid1 - last_id, yariv);
// our literals are at most 2 bits each, and we have n of them
if (YarivOpVectorSwizzleTwoLiterals == opcode) {
const int32_t component0 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
*yariv++ = YARIV_CAST(uint8_t, ((component0 << 2) | component1) & 0xFF);
} else if (YarivOpVectorSwizzleThreeLiterals == opcode) {
const int32_t component0 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component2 = YARIV_CAST(const int32_t *, spirv)[i + k++];
*yariv++ = YARIV_CAST(
uint8_t,
((component0 << 4) | (component1 << 2) | component2) & 0xFF);
} else if (YarivOpVectorSwizzleFourLiterals == opcode) {
const int32_t component0 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component1 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component2 = YARIV_CAST(const int32_t *, spirv)[i + k++];
const int32_t component3 = YARIV_CAST(const int32_t *, spirv)[i + k++];
*yariv++ = YARIV_CAST(uint8_t, ((component0 << 6) | (component1 << 4) |
(component2 << 2) | component3) &
0xFF);
}
} break;
case YarivOpCompositeExtractWithLiteralZero:
case YarivOpCompositeExtractWithLiteralOne:
case YarivOpCompositeExtractWithLiteralTwo:
case YarivOpCompositeExtractWithLiteralThree: {
// the id of the composite we are extracting from
const int32_t composite = YARIV_CAST(const int32_t *, spirv)[i + k++];
// we use the signed varint encoding relative to last id for the two
// vectors we are shuffling (but we don't update last id crucially)
yariv += yariv_encode_signed_varint(composite - last_id, yariv);
// skip the literal that we are not going to encode
k++;
} break;
case YarivOpDecorateRelaxedPrecision:
// skip the decoration for relaxed precision that we are not going to
// encode
k++;
break;
case YarivOpMemberDecorateOffset:
// encode the member literal as a varint
yariv += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k++], yariv);
// skip the decoration for offset that we are not going to encode
k++;
// encode the byte offset as a varint
yariv += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k++], yariv);
break;
case YarivOpConstantWithOneFloatLiteral:
// our literal is a float, so we just encode it using 4 bytes
memcpy(yariv, YARIV_CAST(const uint32_t *, spirv) + i + k++,
sizeof(uint32_t));
yariv += sizeof(uint32_t);
break;
case YarivOpDecorateLocation:
// skip the decoration for location that we are not going to encode
k++;
// encode the location as a varint
yariv += yariv_encode_unsigned_varint(
YARIV_CAST(const uint32_t *, spirv)[i + k++], yariv);
break;
}
// and move i along to the next opcode
i += word_count;
// and (maybe) update last_id too!
last_id = maybe_update_id;
}
return 0;
}
size_t yariv_decode_size(const void *yariv, size_t yariv_size) {
// the SPIR-V header is 5 words
size_t spirv_size = 5 * sizeof(uint32_t);
size_t i = 2;
// we need to decode the varints in the header
// * the first varint is for our generators magic number
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
// * the second varint is for our bound
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
// iterate through all the opcodes
while (i < yariv_size) {
uint32_t opcode, word_count, k;
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&opcode);
// shuffle the opcode back to its actual opcode
opcode = yariv_shuffle_opcode(opcode);
// our opcode/word-count pair takes up at least one word
spirv_size += sizeof(uint32_t);
if (!yariv_opcode_has_word_count(opcode, &word_count)) {
// if the word count wasn't constant for the opcode, we encoded it as a
// varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&word_count);
// when we encoded the word count, we removed the known constant part of
// the word count (derived from the opcode) we need to re-add this as we
// re-encode word count
word_count += yariv_word_count_constant_part(opcode);
}
// by default, we use unsigned varint encoding from the word immediately
// following the opcode/word-count word
k = 1;
if (yariv_opcode_has_id(opcode)) {
// if our opcode has an id, we used a signed varint encoding relative to
// the last id
i +=
yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
spirv_size += sizeof(uint32_t);
// and since we have already decoded the first word, k should skip
// another word for the remaining unsigned varint decoding
k += 1;
} else if (yariv_opcode_has_type_and_id(opcode)) {
// if our opcode has a type and id, we used a signed varint encoding
// for the id relative to the last id
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
0);
spirv_size += sizeof(uint32_t);
i +=
yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
spirv_size += sizeof(uint32_t);
// and since we have already decoded the first two words, k should skip
// two words for the remaining unsigned varint decoding
k += 2;
}
switch (opcode) {
default:
// then we decode some words as signed varints
for (; k < yariv_word_count_to_id_delta(opcode, word_count); k++) {
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
0);
spirv_size += sizeof(uint32_t);
}
// then we decode the remaining words as unsigned varints
for (; k < word_count; k++) {
i += yariv_decode_unsigned_varint(
YARIV_CAST(const uint8_t *, yariv) + i, 0);
spirv_size += sizeof(uint32_t);
}
break;
case YarivOpExtInstImport:
// our literal string was just be memcpy'ed over
spirv_size += sizeof(uint32_t) * (word_count - k);
i += sizeof(uint32_t) * (word_count - k);
break;
case YarivOpVectorShuffleTwoLiterals:
case YarivOpVectorShuffleThreeLiterals:
case YarivOpVectorShuffleFourLiterals:
// we use the signed varint encoding relative to last id for the two
// vectors we are shuffling (but we don't update last id crucially)
i +=
yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
spirv_size += sizeof(uint32_t);
i +=
yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
spirv_size += sizeof(uint32_t);
// our literals are at most 3 bits each, and we have n of them
if (YarivOpVectorShuffleTwoLiterals == opcode) {
spirv_size += 2 * sizeof(uint32_t);
i += sizeof(uint8_t);
} else if (YarivOpVectorShuffleThreeLiterals == opcode) {
spirv_size += 3 * sizeof(uint32_t);
i += sizeof(uint8_t) * 2;
} else if (YarivOpVectorShuffleFourLiterals == opcode) {
spirv_size += 4 * sizeof(uint32_t);
i += sizeof(uint8_t) * 2;
}
break;
case YarivOpVectorSwizzleTwoLiterals:
case YarivOpVectorSwizzleThreeLiterals:
case YarivOpVectorSwizzleFourLiterals:
// we use the signed varint encoding relative to last id for the one
// vector we are shuffling (but we don't update last id crucially)
i +=
yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
spirv_size += sizeof(uint32_t);
spirv_size += sizeof(uint32_t);
// our literals are at most 2 bits each, and we have n of them
i += sizeof(uint8_t);
if (YarivOpVectorSwizzleTwoLiterals == opcode) {
spirv_size += 2 * sizeof(uint32_t);
} else if (YarivOpVectorSwizzleThreeLiterals == opcode) {
spirv_size += 3 * sizeof(uint32_t);
} else if (YarivOpVectorSwizzleFourLiterals == opcode) {
spirv_size += 4 * sizeof(uint32_t);
}
break;
case YarivOpCompositeExtractWithLiteralZero:
case YarivOpCompositeExtractWithLiteralOne:
case YarivOpCompositeExtractWithLiteralTwo:
case YarivOpCompositeExtractWithLiteralThree:
// we use the signed varint encoding relative to last id for the one
// vector we are shuffling (but we don't update last id crucially)
i +=
yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i, 0);
spirv_size += sizeof(uint32_t);
// we skipped a literal that we need to re-encode
spirv_size += sizeof(uint32_t);
break;
case YarivOpDecorateRelaxedPrecision:
// we skipped a decoration that we need to re-encode
spirv_size += sizeof(uint32_t);
break;
case YarivOpMemberDecorateOffset:
// we encoded the member literal as a varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
0);
spirv_size += sizeof(uint32_t);
// we skipped a decoration that we need to re-encode
spirv_size += sizeof(uint32_t);
// we encoded the offset as a varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
0);
spirv_size += sizeof(uint32_t);
break;
case YarivOpConstantWithOneFloatLiteral:
// we encoded our literal as a 4 byte value
spirv_size += sizeof(uint32_t);
i += sizeof(uint32_t);
break;
case YarivOpDecorateLocation:
// we skipped a decoration that we need to re-encode
spirv_size += sizeof(uint32_t);
// we encoded the offset as a varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
0);
spirv_size += sizeof(uint32_t);
break;
}
}
return spirv_size;
}
int yariv_decode(void *out_spirv, size_t out_spirv_size, const void *yariv,
size_t yariv_size) {
size_t i;
int32_t last_id = 1, temp_id, maybe_update_id;
const uint32_t type_offset = 1;
uint32_t *spirv = YARIV_CAST(uint32_t *, out_spirv);
// FIXME: I should really check we don't try and write beyond out_spirv_size
// in out_spirv!
(void)out_spirv_size;
// for the SPIR-V header
// * we re-encode SPIR-V's magic number
*spirv++ = 0x07230203u;
// * we re-encode the version number
*spirv++ =
(YARIV_CAST(uint32_t, YARIV_CAST(const uint8_t *, yariv)[0]) << 16) |
(YARIV_CAST(uint32_t, YARIV_CAST(const uint8_t *, yariv)[1]) << 8);
i = 2;
// * we used varint encoding for the generators magic number
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
spirv++);
// * we used varint encoding for the bound
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
spirv++);
// * we re-encode the instruction schema (which is zero)
*spirv++ = 0;
while (i < yariv_size) {
uint32_t opcode, word_count, word, k;
maybe_update_id = last_id;
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&opcode);
// shuffle the opcode back to its actual opcode
opcode = yariv_shuffle_opcode(opcode);
if (!yariv_opcode_has_word_count(opcode, &word_count)) {
// if the word count wasn't constant for the opcode, we encoded it as a
// varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&word_count);
// when we encoded the word count, we removed the known constant part of
// the word count (derived from the opcode) we need to re-add this as we
// re-encode word count
word_count += yariv_word_count_constant_part(opcode);
}
switch (opcode) {
default:
*spirv++ = (word_count << 16) | opcode;
break;
case YarivOpStoreWithMemoryAccess:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpStore;
break;
case YarivOpLoadWithMemoryAccess:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpLoad;
break;
case YarivOpDecorateRelaxedPrecision:
case YarivOpDecorateWithNoLiterals:
case YarivOpDecorateWithOneLiteral:
case YarivOpDecorateLocation:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpDecorate;
break;
case YarivOpMemberDecorateWithNoLiterals:
case YarivOpMemberDecorateWithOneLiteral:
case YarivOpMemberDecorateOffset:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpMemberDecorate;
break;
case YarivOpVariableWithInitializer:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpVariable;
break;
case YarivOpConstantWithManyLiterals:
case YarivOpConstantWithOneFloatLiteral:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpConstant;
break;
case YarivOpAccessChainWithOneIndex:
case YarivOpAccessChainWithTwoIndices:
case YarivOpAccessChainWithThreeIndices:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpAccessChain;
break;
case YarivOpVectorShuffleTwoLiterals:
case YarivOpVectorShuffleThreeLiterals:
case YarivOpVectorShuffleFourLiterals:
case YarivOpVectorSwizzleTwoLiterals:
case YarivOpVectorSwizzleThreeLiterals:
case YarivOpVectorSwizzleFourLiterals:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpVectorShuffle;
break;
case YarivOpCompositeExtractWithLiteralZero:
case YarivOpCompositeExtractWithLiteralOne:
case YarivOpCompositeExtractWithLiteralTwo:
case YarivOpCompositeExtractWithLiteralThree:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpCompositeExtract;
break;
case YarivOpCompositeConstructOneConstituent:
case YarivOpCompositeConstructTwoConstituents:
case YarivOpCompositeConstructThreeConstituents:
// we added this fake opcode during encoding to allow us to compress
// some more, so now we have to undo this
*spirv++ = (word_count << 16) | YarivOpCompositeConstruct;
break;
}
// by default, we use unsigned varint encoding from the word immediately
// following the opcode/word-count word
k = 1;
if (yariv_opcode_has_id(opcode)) {
// if our opcode has an id, we used a signed varint encoding relative to
// the last id
int32_t id;
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&id);
maybe_update_id += id;
*spirv++ = YARIV_CAST(uint32_t, maybe_update_id);
// and since we have already decoded the first word, k should skip
// another word for the remaining unsigned varint decoding
k += 1;
} else if (yariv_opcode_has_type_and_id(opcode)) {
// if our opcode has a type and id, we used a signed varint encoding
// relative for the id to the last id
uint32_t type;
int32_t id;
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&type);
*spirv++ = YARIV_CAST(uint32_t, type + type_offset);
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&id);
maybe_update_id += id;
*spirv++ = YARIV_CAST(uint32_t, maybe_update_id);
// and since we have already decoded the first two words, k should skip
// two words for the remaining unsigned varint decoding
k += 2;
}
switch (opcode) {
default:
// then we decode some words as signed varints
for (; k < yariv_word_count_to_id_delta(opcode, word_count); k++) {
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&temp_id);
*spirv++ = YARIV_CAST(uint32_t, temp_id + last_id);
}
// followed by all remaining words as varints
for (; k < word_count; k++) {
i += yariv_decode_unsigned_varint(
YARIV_CAST(const uint8_t *, yariv) + i, &word);
*spirv++ = word;
}
break;
case YarivOpExtInstImport:
// our literal string was just be memcpy'ed over
memcpy(spirv, YARIV_CAST(const uint8_t *, yariv) + i,
sizeof(uint32_t) * (word_count - k));
spirv += word_count - k;
i += sizeof(uint32_t) * (word_count - k);
break;
case YarivOpVectorShuffleTwoLiterals:
case YarivOpVectorShuffleThreeLiterals:
case YarivOpVectorShuffleFourLiterals:
// we use the signed varint encoding relative to last id for the two
// vectors we are shuffling (but we don't update last id crucially)
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&temp_id);
*spirv++ = YARIV_CAST(uint32_t, last_id + temp_id);
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&temp_id);
*spirv++ = YARIV_CAST(uint32_t, last_id + temp_id);
// our literals were at most 3 bits each, and we have n of them
if (YarivOpVectorShuffleTwoLiterals == opcode) {
const uint32_t component0 = YARIV_CAST(const uint8_t *, yariv)[i++];
*spirv++ = component0 >> 3;
*spirv++ = component0 & 0x7u;
} else if (YarivOpVectorShuffleThreeLiterals == opcode) {
const uint32_t component0 = YARIV_CAST(const uint8_t *, yariv)[i++];
const uint32_t component1 = YARIV_CAST(const uint8_t *, yariv)[i++];
*spirv++ = component0 >> 3;
*spirv++ = component0 & 0x7u;
*spirv++ = component1;
} else if (YarivOpVectorShuffleFourLiterals == opcode) {
const uint32_t component0 = YARIV_CAST(const uint8_t *, yariv)[i++];
const uint32_t component1 = YARIV_CAST(const uint8_t *, yariv)[i++];
*spirv++ = component0 >> 3;
*spirv++ = component0 & 0x7u;
*spirv++ = component1 >> 3;
*spirv++ = component1 & 0x7u;
}
break;
case YarivOpVectorSwizzleTwoLiterals:
case YarivOpVectorSwizzleThreeLiterals:
case YarivOpVectorSwizzleFourLiterals:
// we use the signed varint encoding relative to last id for the one
// vector we are shuffling (but we don't update last id crucially)
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&temp_id);
*spirv++ = YARIV_CAST(uint32_t, last_id + temp_id);
*spirv++ = YARIV_CAST(uint32_t, last_id + temp_id);
// our literals were at most 2 bits each, and we have n of them
if (YarivOpVectorSwizzleTwoLiterals == opcode) {
const uint32_t component = YARIV_CAST(const uint8_t *, yariv)[i++];
*spirv++ = component >> 2;
*spirv++ = component & 0x3u;
} else if (YarivOpVectorSwizzleThreeLiterals == opcode) {
const uint32_t component = YARIV_CAST(const uint8_t *, yariv)[i++];
*spirv++ = component >> 4;
*spirv++ = (component >> 2) & 0x3u;
*spirv++ = component & 0x3u;
} else if (YarivOpVectorSwizzleFourLiterals == opcode) {
const uint32_t component = YARIV_CAST(const uint8_t *, yariv)[i++];
*spirv++ = component >> 6;
*spirv++ = (component >> 4) & 0x3u;
*spirv++ = (component >> 2) & 0x3u;
*spirv++ = component & 0x3u;
}
break;
case YarivOpCompositeExtractWithLiteralZero:
case YarivOpCompositeExtractWithLiteralOne:
case YarivOpCompositeExtractWithLiteralTwo:
case YarivOpCompositeExtractWithLiteralThree:
// we use the signed varint encoding relative to last id for the one
// vector we are shuffling (but we don't update last id crucially)
i += yariv_decode_signed_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&temp_id);
*spirv++ = YARIV_CAST(uint32_t, last_id + temp_id);
// we skipped a literal that we need to re-encode
if (YarivOpCompositeExtractWithLiteralZero == opcode) {
*spirv++ = 0;
} else if (YarivOpCompositeExtractWithLiteralOne == opcode) {
*spirv++ = 1;
} else if (YarivOpCompositeExtractWithLiteralTwo == opcode) {
*spirv++ = 2;
} else if (YarivOpCompositeExtractWithLiteralThree == opcode) {
*spirv++ = 3;
}
break;
case YarivOpDecorateRelaxedPrecision:
// we skipped a decoration that we need to re-encode
*spirv++ = 0; // output the RelaxedPrecision decoration
break;
case YarivOpMemberDecorateOffset:
// we encoded the member literal as a varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&k);
*spirv++ = k;
// we skipped a decoration that we need to re-encode
*spirv++ = 35; // output the Offset decoration
// we encoded the offset as a varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&k);
*spirv++ = k;
break;
case YarivOpConstantWithOneFloatLiteral:
memcpy(spirv++, YARIV_CAST(const uint8_t *, yariv) + i, sizeof(uint32_t));
i += sizeof(uint32_t);
break;
case YarivOpDecorateLocation:
// we skipped a decoration that we need to re-encode
*spirv++ = 30; // output the Location decoration
// we encoded the location as a varint
i += yariv_decode_unsigned_varint(YARIV_CAST(const uint8_t *, yariv) + i,
&k);
*spirv++ = k;
break;
}
// and maybe move the id along
last_id = maybe_update_id;
}
return 0;
}
uint32_t yariv_word_count_to_id_delta(uint32_t opcode, uint32_t word_count) {
(void)word_count;
switch (opcode) {
default:
// by default we want no IDs to be delta encoded
return 0;
case YarivOpAccessChain:
case YarivOpStore:
case YarivOpLoad:
case YarivOpFMul:
case YarivOpFAdd:
case YarivOpFSub:
case YarivOpConstantComposite:
case YarivOpCompositeConstruct:
case YarivOpCompositeConstructOneConstituent:
case YarivOpCompositeConstructTwoConstituents:
case YarivOpCompositeConstructThreeConstituents:
case YarivOpDot:
case YarivOpVectorTimesScalar:
case YarivOpFNegate:
case YarivOpFDiv:
case YarivOpFOrdEqual:
case YarivOpFOrdLessThan:
case YarivOpFOrdLessThanEqual:
case YarivOpFOrdGreaterThan:
case YarivOpFOrdGreaterThanEqual:
case YarivOpFOrdNotEqual:
case YarivOpIEqual:
case YarivOpIAdd:
case YarivOpFunctionCall:
case YarivOpSDiv:
case YarivOpUDiv:
case YarivOpSLessThan:
case YarivOpSLessThanEqual:
case YarivOpPhi:
case YarivOpLogicalAnd:
case YarivOpVectorTimesMatrix:
case YarivOpMatrixTimesVector:
case YarivOpLogicalNot:
case YarivOpIMul:
case YarivOpISub:
case YarivOpConvertSToF:
case YarivOpConvertFToS:
case YarivOpConvertUToF:
case YarivOpConvertFToU:
case YarivOpFMod:
case YarivOpLogicalOr:
case YarivOpBitcast:
case YarivOpShiftLeftLogical:
case YarivOpShiftRightArithmetic:
case YarivOpShiftRightLogical:
case YarivOpMatrixTimesScalar:
case YarivOpMatrixTimesMatrix:
case YarivOpSelect:
case YarivOpTranspose:
return word_count;
case YarivOpBranchConditional:
return 4;
case YarivOpVectorShuffle:
return 5;
case YarivOpImageSampleImplicitLod:
case YarivOpImageSampleExplicitLod:
return 5;
case YarivOpImageSampleDrefImplicitLod:
case YarivOpImageSampleDrefExplicitLod:
return 6;
}
}
uint32_t yariv_word_count_constant_part(uint32_t opcode) {
switch (opcode) {
default:
// by default we can assume we have a word count of at least one, because
// the opcode itself must reside in a word count
return 1;
case YarivOpSourceContinued:
case YarivOpSourceExtension:
case YarivOpGroupDecorate:
case YarivOpGroupMemberDecorate:
case YarivOpExtension:
case YarivOpTypeStruct:
return 2;
case YarivOpSource:
case YarivOpName:
case YarivOpString:
case YarivOpDecorate:
case YarivOpExtInstImport:
case YarivOpExecutionMode:
case YarivOpTypeOpaque:
case YarivOpTypeFunction:
case YarivOpConstant:
case YarivOpConstantComposite:
case YarivOpSpecConstant:
case YarivOpSpecConstantComposite:
case YarivOpStore:
case YarivOpCopyMemory:
case YarivOpCompositeConstruct:
case YarivOpPhi:
case YarivOpSwitch:
return 3;
case YarivOpMemberName:
case YarivOpMemberDecorate:
case YarivOpEntryPoint:
case YarivOpSpecConstantOp:
case YarivOpVariable:
case YarivOpLoad:
case YarivOpCopyMemorySized:
case YarivOpAccessChain:
case YarivOpInBoundsAccessChain:
case YarivOpFunctionCall:
case YarivOpImageWrite:
case YarivOpCompositeExtract:
case YarivOpBranchConditional:
return 4;
case YarivOpExtInst:
case YarivOpPtrAccessChain:
case YarivOpInBoundsPtrAccessChain:
case YarivOpImageSampleImplicitLod:
case YarivOpImageSampleProjImplicitLod:
case YarivOpImageFetch:
case YarivOpImageRead:
case YarivOpImageSparseSampleImplicitLod:
case YarivOpImageSparseSampleProjImplicitLod:
case YarivOpImageSparseFetch:
case YarivOpImageSparseRead:
case YarivOpVectorShuffle:
case YarivOpCompositeInsert:
return 5;
case YarivOpImageSparseSampleProjDrefImplicitLod:
return 6;
case YarivOpImageSparseSampleProjExplicitLod:
return 7;
}
}
uint32_t yariv_opcode_maybe_split(uint32_t opcode, const uint32_t *spirv,
uint32_t word_count) {
uint32_t k;
switch (opcode) {
default:
break;
case YarivOpStore:
// if the store has a memory access, we will encode it as a different
// opcode instead to allow us to compress load some more
if (4 == word_count) {
opcode = YarivOpStoreWithMemoryAccess;
}
break;
case YarivOpLoad:
// if the load have a memory access, we will encode it as a different
// opcode instead to allow us to compress load some more
if (5 == word_count) {
opcode = YarivOpLoadWithMemoryAccess;
}
break;
case YarivOpDecorate:
// if the decoration has 0 or 1 literals, we will encode it as a different
// opcode instead to allow us to compress decorate some more
if (3 == word_count) {
if (0 == spirv[2]) {
opcode = YarivOpDecorateRelaxedPrecision;
} else {
opcode = YarivOpDecorateWithNoLiterals;
}
} else if (4 == word_count) {
if (30 == spirv[2]) {
opcode = YarivOpDecorateLocation;
} else {
opcode = YarivOpDecorateWithOneLiteral;
}
}
break;
case YarivOpMemberDecorate:
// if the decoration has 0 or 1 literals, we will encode it as a different
// opcode instead to allow us to compress decorate some more
if (4 == word_count) {
opcode = YarivOpMemberDecorateWithNoLiterals;
} else if (5 == word_count) {
if (35 == spirv[3]) {
opcode = YarivOpMemberDecorateOffset;
} else {
opcode = YarivOpMemberDecorateWithOneLiteral;
}
}
break;
case YarivOpVariable:
if (5 == word_count) {
opcode = YarivOpVariableWithInitializer;
}
break;
case YarivOpConstant:
if (4 < word_count) {
opcode = YarivOpConstantWithManyLiterals;
} else if (0xFF800000u & spirv[3]) {
opcode = YarivOpConstantWithOneFloatLiteral;
}
break;
case YarivOpAccessChain:
// If the access chain had one, two or three indices, we will encode it as a
// different opcode instead to allow us to compress it some more
if (5 == word_count) {
opcode = YarivOpAccessChainWithOneIndex;
} else if (6 == word_count) {
opcode = YarivOpAccessChainWithTwoIndices;
} else if (7 == word_count) {
opcode = YarivOpAccessChainWithThreeIndices;
}
break;
case YarivOpVectorShuffle: {
const int haveBothIdsTheSame = spirv[3] == spirv[4];
int hasUndef = 0;
int hasLiteralsLessThan4 = 1;
int hasLiteralsLessThan8 = 1;
// If the vector shuffle has no undef literals (0xFFFFFFFu), and it is
// requesting a result vector of two, three or four width, we will encode it
// as a different opcode instead to allow us to compress it some more
for (k = 5; k < word_count; k++) {
if (0xFFFFFFFFu == spirv[k]) {
// we are using the undef literal so we can't encode the shuffle more
// efficiently!
hasUndef = 1;
break;
} else {
if (3 < spirv[k]) {
// we are using vector types greater than vec4's so we can't encode
// the
// shuffle more efficiently!
hasLiteralsLessThan4 = 0;
}
if (7 < spirv[k]) {
// we are using vector types greater than vec4's so we can't encode
// the
// shuffle more efficiently!
hasLiteralsLessThan8 = 0;
}
}
}
// we found an undef, so we can't encode the opcode differently
if (hasUndef) {
break;
}
if (hasLiteralsLessThan4) {
if (haveBothIdsTheSame) {
if (7 == word_count) {
opcode = YarivOpVectorSwizzleTwoLiterals;
} else if (8 == word_count) {
opcode = YarivOpVectorSwizzleThreeLiterals;
} else if (9 == word_count) {
opcode = YarivOpVectorSwizzleFourLiterals;
}
}
} else if (hasLiteralsLessThan8) {
if (7 == word_count) {
opcode = YarivOpVectorShuffleTwoLiterals;
} else if (8 == word_count) {
opcode = YarivOpVectorShuffleThreeLiterals;
} else if (9 == word_count) {
opcode = YarivOpVectorShuffleFourLiterals;
}
}
} break;
case YarivOpCompositeExtract:
if (5 == word_count) {
switch (spirv[4]) {
default:
break;
case 0:
opcode = YarivOpCompositeExtractWithLiteralZero;
break;
case 1:
opcode = YarivOpCompositeExtractWithLiteralOne;
break;
case 2:
opcode = YarivOpCompositeExtractWithLiteralTwo;
break;
case 3:
opcode = YarivOpCompositeExtractWithLiteralThree;
break;
}
}
break;
case YarivOpCompositeConstruct:
if (4 == word_count) {
opcode = YarivOpCompositeConstructOneConstituent;
} else if (5 == word_count) {
opcode = YarivOpCompositeConstructTwoConstituents;
} else if (6 == word_count) {
opcode = YarivOpCompositeConstructThreeConstituents;
}
break;
}
return opcode;
}
int yariv_opcode_has_id(uint32_t opcode) {
switch (opcode) {
default:
// by default we assume the opcode does not have an id
return 0;
case YarivOpName:
case YarivOpMemberName:
// technically member name has a type and no id, but it behaves like
// an ID for the context we require
case YarivOpString:
case YarivOpLine:
case YarivOpDecorate:
case YarivOpMemberDecorate:
// technically member decorate has a type and no id, but it behaves like
// an ID for the context we require
case YarivOpDecorationGroup:
case YarivOpGroupDecorate:
case YarivOpGroupMemberDecorate:
case YarivOpExtInstImport:
case YarivOpExtInst:
case YarivOpExecutionMode:
case YarivOpStore:
case YarivOpCopyMemory:
case YarivOpCopyMemorySized:
case YarivOpLoopMerge:
case YarivOpSelectionMerge:
case YarivOpLabel:
case YarivOpBranch:
case YarivOpBranchConditional:
case YarivOpSwitch:
case YarivOpReturnValue:
case YarivOpLifetimeStart:
case YarivOpLifetimeStop:
case YarivOpAtomicFlagClear:
case YarivOpEmitStreamVertex:
case YarivOpEndStreamPrimitive:
case YarivOpControlBarrier:
case YarivOpMemoryBarrier:
case YarivOpRetainEvent:
case YarivOpReleaseEvent:
case YarivOpSetUserEventStatus:
case YarivOpCaptureEventProfilingInfo:
case YarivOpDecorateWithNoLiterals:
case YarivOpDecorateWithOneLiteral:
case YarivOpMemberDecorateWithNoLiterals:
case YarivOpMemberDecorateWithOneLiteral:
case YarivOpDecorateRelaxedPrecision:
case YarivOpMemberDecorateOffset:
case YarivOpDecorateLocation:
return 1;
}
}
int yariv_opcode_has_type_and_id(uint32_t opcode) {
switch (opcode) {
default:
// by default we assume the opcode does not have a type and id
return 0;
case YarivOpUndef:
case YarivOpExtInst:
case YarivOpConstantTrue:
case YarivOpConstantFalse:
case YarivOpConstant:
case YarivOpConstantComposite:
case YarivOpConstantSampler:
case YarivOpConstantNull:
case YarivOpSpecConstantTrue:
case YarivOpSpecConstantFalse:
case YarivOpSpecConstant:
case YarivOpSpecConstantComposite:
case YarivOpSpecConstantOp:
case YarivOpVariable:
case YarivOpImageTexelPointer:
case YarivOpLoad:
case YarivOpAccessChain:
case YarivOpInBoundsAccessChain:
case YarivOpPtrAccessChain:
case YarivOpArrayLength:
case YarivOpGenericPtrMemSemantics:
case YarivOpInBoundsPtrAccessChain:
case YarivOpFunction:
case YarivOpFunctionParameter:
case YarivOpFunctionCall:
case YarivOpSampledImage:
case YarivOpImageSampleImplicitLod:
case YarivOpImageSampleExplicitLod:
case YarivOpImageSampleDrefImplicitLod:
case YarivOpImageSampleDrefExplicitLod:
case YarivOpImageSampleProjImplicitLod:
case YarivOpImageSampleProjExplicitLod:
case YarivOpImageSampleProjDrefImplicitLod:
case YarivOpImageSampleProjDrefExplicitLod:
case YarivOpImageFetch:
case YarivOpImageGather:
case YarivOpImageDrefGather:
case YarivOpImageRead:
case YarivOpImageWrite:
case YarivOpImage:
case YarivOpImageQueryFormat:
case YarivOpImageQueryOrder:
case YarivOpImageQuerySizeLod:
case YarivOpImageQuerySize:
case YarivOpImageQueryLod:
case YarivOpImageQueryLevels:
case YarivOpImageQuerySamples:
case YarivOpImageSparseSampleImplicitLod:
case YarivOpImageSparseSampleExplicitLod:
case YarivOpImageSparseSampleDrefImplicitLod:
case YarivOpImageSparseSampleDrefExplicitLod:
case YarivOpImageSparseSampleProjImplicitLod:
case YarivOpImageSparseSampleProjExplicitLod:
case YarivOpImageSparseSampleProjDrefImplicitLod:
case YarivOpImageSparseSampleProjDrefExplicitLod:
case YarivOpImageSparseFetch:
case YarivOpImageSparseGather:
case YarivOpImageSparseDrefGather:
case YarivOpImageSparseTexelsResident:
case YarivOpImageSparseRead:
case YarivOpConvertFToU:
case YarivOpConvertFToS:
case YarivOpConvertSToF:
case YarivOpConvertUToF:
case YarivOpUConvert:
case YarivOpSConvert:
case YarivOpFConvert:
case YarivOpQuantizeToF16:
case YarivOpConvertPtrToU:
case YarivOpSatConvertSToU:
case YarivOpSatConvertUToS:
case YarivOpConvertUToPtr:
case YarivOpPtrCastToGeneric:
case YarivOpGenericCastToPtr:
case YarivOpGenericCastToPtrExplicit:
case YarivOpBitcast:
case YarivOpVectorExtractDynamic:
case YarivOpVectorInsertDynamic:
case YarivOpVectorShuffle:
case YarivOpCompositeConstruct:
case YarivOpCompositeExtract:
case YarivOpCompositeInsert:
case YarivOpCopyObject:
case YarivOpTranspose:
case YarivOpSNegate:
case YarivOpFNegate:
case YarivOpIAdd:
case YarivOpFAdd:
case YarivOpISub:
case YarivOpFSub:
case YarivOpIMul:
case YarivOpFMul:
case YarivOpUDiv:
case YarivOpSDiv:
case YarivOpFDiv:
case YarivOpUMod:
case YarivOpSRem:
case YarivOpSMod:
case YarivOpFRem:
case YarivOpFMod:
case YarivOpVectorTimesScalar:
case YarivOpMatrixTimesScalar:
case YarivOpVectorTimesMatrix:
case YarivOpMatrixTimesVector:
case YarivOpMatrixTimesMatrix:
case YarivOpOuterProduct:
case YarivOpDot:
case YarivOpIAddCarry:
case YarivOpISubBorrow:
case YarivOpUMulExtended:
case YarivOpSMulExtended:
case YarivOpShiftRightLogical:
case YarivOpShiftRightArithmetic:
case YarivOpShiftLeftLogical:
case YarivOpBitwiseOr:
case YarivOpBitwiseXor:
case YarivOpBitwiseAnd:
case YarivOpNot:
case YarivOpBitFieldInsert:
case YarivOpBitFieldSExtract:
case YarivOpBitFieldUExtract:
case YarivOpBitReverse:
case YarivOpBitCount:
case YarivOpAny:
case YarivOpAll:
case YarivOpIsNan:
case YarivOpIsInf:
case YarivOpIsFinite:
case YarivOpIsNormal:
case YarivOpSignBitSet:
case YarivOpLessOrGreater:
case YarivOpOrdered:
case YarivOpUnordered:
case YarivOpLogicalEqual:
case YarivOpLogicalNotEqual:
case YarivOpLogicalOr:
case YarivOpLogicalAnd:
case YarivOpLogicalNot:
case YarivOpSelect:
case YarivOpIEqual:
case YarivOpINotEqual:
case YarivOpUGreaterThan:
case YarivOpSGreaterThan:
case YarivOpUGreaterThanEqual:
case YarivOpSGreaterThanEqual:
case YarivOpULessThan:
case YarivOpSLessThan:
case YarivOpULessThanEqual:
case YarivOpSLessThanEqual:
case YarivOpFOrdEqual:
case YarivOpFUnordEqual:
case YarivOpFOrdNotEqual:
case YarivOpFUnordNotEqual:
case YarivOpFOrdLessThan:
case YarivOpFUnordLessThan:
case YarivOpFOrdGreaterThan:
case YarivOpFUnordGreaterThan:
case YarivOpFOrdLessThanEqual:
case YarivOpFUnordLessThanEqual:
case YarivOpFOrdGreaterThanEqual:
case YarivOpFUnordGreaterThanEqual:
case YarivOpDPdx:
case YarivOpDPdy:
case YarivOpFwidth:
case YarivOpDPdxFine:
case YarivOpDPdyFine:
case YarivOpFwidthFine:
case YarivOpDPdxCoarse:
case YarivOpDPdyCoarse:
case YarivOpFwidthCoarse:
case YarivOpPhi:
case YarivOpAtomicLoad:
case YarivOpAtomicStore:
case YarivOpAtomicExchange:
case YarivOpAtomicCompareExchange:
case YarivOpAtomicCompareExchangeWeak:
case YarivOpAtomicIIncrement:
case YarivOpAtomicIDecrement:
case YarivOpAtomicIAdd:
case YarivOpAtomicISub:
case YarivOpAtomicSMin:
case YarivOpAtomicUMin:
case YarivOpAtomicSMax:
case YarivOpAtomicUMax:
case YarivOpAtomicAnd:
case YarivOpAtomicOr:
case YarivOpAtomicXor:
case YarivOpAtomicFlagTestAndSet:
case YarivOpLoadWithMemoryAccess:
case YarivOpStoreWithMemoryAccess:
case YarivOpVariableWithInitializer:
case YarivOpConstantWithManyLiterals:
case YarivOpAccessChainWithOneIndex:
case YarivOpAccessChainWithTwoIndices:
case YarivOpAccessChainWithThreeIndices:
case YarivOpVectorShuffleTwoLiterals:
case YarivOpVectorShuffleThreeLiterals:
case YarivOpVectorShuffleFourLiterals:
case YarivOpVectorSwizzleTwoLiterals:
case YarivOpVectorSwizzleThreeLiterals:
case YarivOpVectorSwizzleFourLiterals:
case YarivOpCompositeExtractWithLiteralZero:
case YarivOpCompositeExtractWithLiteralOne:
case YarivOpCompositeExtractWithLiteralTwo:
case YarivOpCompositeExtractWithLiteralThree:
case YarivOpCompositeConstructOneConstituent:
case YarivOpCompositeConstructTwoConstituents:
case YarivOpCompositeConstructThreeConstituents:
case YarivOpConstantWithOneFloatLiteral:
return 1;
}
}
int yariv_opcode_has_word_count(uint32_t opcode, uint32_t *word_count) {
uint32_t count;
switch (opcode) {
default:
// word count was not static for this opcode, so we can't infer it!
return 0;
case YarivOpNop:
case YarivOpNoLine:
case YarivOpFunctionEnd:
case YarivOpKill:
case YarivOpReturn:
case YarivOpEmitVertex:
case YarivOpEndPrimitive:
count = 1;
break;
case YarivOpDecorationGroup:
case YarivOpCapability:
case YarivOpTypeVoid:
case YarivOpTypeBool:
case YarivOpTypeSampler:
case YarivOpTypeEvent:
case YarivOpTypeDeviceEvent:
case YarivOpTypeReserveId:
case YarivOpTypeQueue:
case YarivOpLabel:
case YarivOpBranch:
case YarivOpReturnValue:
case YarivOpEmitStreamVertex:
case YarivOpEndStreamPrimitive:
case YarivOpRetainEvent:
case YarivOpReleaseEvent:
count = 2;
break;
case YarivOpUndef:
case YarivOpMemoryModel:
case YarivOpTypeFloat:
case YarivOpTypeSampledImage:
case YarivOpTypeRuntimeArray:
case YarivOpTypePipe:
case YarivOpTypeForwardPointer:
case YarivOpConstantTrue:
case YarivOpConstantFalse:
case YarivOpConstantNull:
case YarivOpSpecConstantTrue:
case YarivOpSpecConstantFalse:
case YarivOpFunctionParameter:
case YarivOpSelectionMerge:
case YarivOpLifetimeStart:
case YarivOpLifetimeStop:
case YarivOpMemoryBarrier:
case YarivOpCreateUserEvent:
case YarivOpSetUserEventStatus:
case YarivOpGetDefaultQueue:
count = 3;
break;
case YarivOpLine:
case YarivOpTypeInt:
case YarivOpTypeVector:
case YarivOpTypeMatrix:
case YarivOpTypeArray:
case YarivOpTypePointer:
case YarivOpGenericPtrMemSemantics:
case YarivOpImage:
case YarivOpImageQueryFormat:
case YarivOpImageQueryOrder:
case YarivOpImageQuerySize:
case YarivOpImageQueryLevels:
case YarivOpImageQuerySamples:
case YarivOpImageSparseTexelsResident:
case YarivOpConvertFToU:
case YarivOpConvertFToS:
case YarivOpConvertSToF:
case YarivOpConvertUToF:
case YarivOpUConvert:
case YarivOpSConvert:
case YarivOpFConvert:
case YarivOpQuantizeToF16:
case YarivOpConvertPtrToU:
case YarivOpSatConvertSToU:
case YarivOpSatConvertUToS:
case YarivOpConvertUToPtr:
case YarivOpPtrCastToGeneric:
case YarivOpGenericCastToPtr:
case YarivOpBitcast:
case YarivOpCopyObject:
case YarivOpTranspose:
case YarivOpSNegate:
case YarivOpFNegate:
case YarivOpNot:
case YarivOpBitReverse:
case YarivOpBitCount:
case YarivOpAny:
case YarivOpAll:
case YarivOpIsNan:
case YarivOpIsInf:
case YarivOpIsFinite:
case YarivOpIsNormal:
case YarivOpSignBitSet:
case YarivOpLogicalNot:
case YarivOpDPdx:
case YarivOpDPdy:
case YarivOpFwidth:
case YarivOpDPdxFine:
case YarivOpDPdyFine:
case YarivOpFwidthFine:
case YarivOpDPdxCoarse:
case YarivOpDPdyCoarse:
case YarivOpFwidthCoarse:
case YarivOpLoopMerge:
case YarivOpAtomicFlagClear:
case YarivOpControlBarrier:
case YarivOpGroupWaitEvents:
case YarivOpIsValidEvent:
case YarivOpCaptureEventProfilingInfo:
case YarivOpIsValidReserveId:
count = 4;
break;
case YarivOpArrayLength:
case YarivOpFunction:
case YarivOpSampledImage:
case YarivOpImageQuerySizeLod:
case YarivOpImageQueryLod:
case YarivOpGenericCastToPtrExplicit:
case YarivOpVectorExtractDynamic:
case YarivOpIAdd:
case YarivOpFAdd:
case YarivOpISub:
case YarivOpFSub:
case YarivOpIMul:
case YarivOpFMul:
case YarivOpUDiv:
case YarivOpSDiv:
case YarivOpFDiv:
case YarivOpUMod:
case YarivOpSRem:
case YarivOpSMod:
case YarivOpFRem:
case YarivOpFMod:
case YarivOpVectorTimesScalar:
case YarivOpMatrixTimesScalar:
case YarivOpVectorTimesMatrix:
case YarivOpMatrixTimesVector:
case YarivOpMatrixTimesMatrix:
case YarivOpOuterProduct:
case YarivOpDot:
case YarivOpIAddCarry:
case YarivOpISubBorrow:
case YarivOpUMulExtended:
case YarivOpSMulExtended:
case YarivOpShiftRightLogical:
case YarivOpShiftRightArithmetic:
case YarivOpShiftLeftLogical:
case YarivOpBitwiseOr:
case YarivOpBitwiseXor:
case YarivOpBitwiseAnd:
case YarivOpLessOrGreater:
case YarivOpOrdered:
case YarivOpUnordered:
case YarivOpLogicalEqual:
case YarivOpLogicalNotEqual:
case YarivOpLogicalOr:
case YarivOpLogicalAnd:
case YarivOpIEqual:
case YarivOpINotEqual:
case YarivOpUGreaterThan:
case YarivOpSGreaterThan:
case YarivOpUGreaterThanEqual:
case YarivOpSGreaterThanEqual:
case YarivOpULessThan:
case YarivOpSLessThan:
case YarivOpULessThanEqual:
case YarivOpSLessThanEqual:
case YarivOpFOrdEqual:
case YarivOpFUnordEqual:
case YarivOpFOrdNotEqual:
case YarivOpFUnordNotEqual:
case YarivOpFOrdLessThan:
case YarivOpFUnordLessThan:
case YarivOpFOrdGreaterThan:
case YarivOpFUnordGreaterThan:
case YarivOpFOrdLessThanEqual:
case YarivOpFUnordLessThanEqual:
case YarivOpFOrdGreaterThanEqual:
case YarivOpFUnordGreaterThanEqual:
case YarivOpAtomicStore:
case YarivOpGroupAll:
case YarivOpGroupAny:
case YarivOpCommitReadPipe:
case YarivOpCommitWritePipe:
count = 5;
break;
case YarivOpConstantSampler:
case YarivOpImageTexelPointer:
case YarivOpVectorInsertDynamic:
case YarivOpBitFieldSExtract:
case YarivOpBitFieldUExtract:
case YarivOpSelect:
case YarivOpAtomicLoad:
case YarivOpAtomicIIncrement:
case YarivOpAtomicIDecrement:
case YarivOpAtomicFlagTestAndSet:
case YarivOpGroupBroadcast:
case YarivOpGroupIAdd:
case YarivOpGroupFAdd:
case YarivOpGroupFMin:
case YarivOpGroupUMin:
case YarivOpGroupSMin:
case YarivOpGroupFMax:
case YarivOpGroupUMax:
case YarivOpGroupSMax:
case YarivOpBuildNDRange:
case YarivOpGetNumPipePackets:
case YarivOpGetMaxPipePackets:
case YarivOpGroupCommitReadPipe:
case YarivOpGroupCommitWritePipe:
count = 6;
break;
case YarivOpBitFieldInsert:
case YarivOpAtomicExchange:
case YarivOpAtomicIAdd:
case YarivOpAtomicISub:
case YarivOpAtomicSMin:
case YarivOpAtomicUMin:
case YarivOpAtomicSMax:
case YarivOpAtomicUMax:
case YarivOpAtomicAnd:
case YarivOpAtomicOr:
case YarivOpAtomicXor:
case YarivOpEnqueueMarker:
case YarivOpGetKernelWorkGroupSize:
case YarivOpGetKernelPreferredWorkGroupSizeMultiple:
case YarivOpReadPipe:
case YarivOpWritePipe:
case YarivOpReserveReadPipePackets:
case YarivOpReserveWritePipePackets:
count = 7;
break;
case YarivOpGetKernelNDrangeSubGroupCount:
case YarivOpGetKernelNDrangeMaxSubGroupSize:
case YarivOpGroupReserveReadPipePackets:
case YarivOpGroupReserveWritePipePackets:
count = 8;
break;
case YarivOpAtomicCompareExchange:
case YarivOpAtomicCompareExchangeWeak:
case YarivOpGroupAsyncCopy:
case YarivOpReservedReadPipe:
case YarivOpReservedWritePipe:
count = 9;
break;
case YarivOpStore: // beware: in SPIR-V this has a non constant encoding!
case YarivOpDecorateWithNoLiterals: // this fake opcode has a static size
case YarivOpDecorateRelaxedPrecision: // this fake opcode has a static size
count = 3;
break;
case YarivOpConstant: // beware: in SPIR-V this has a non constant encoding!
case YarivOpLoad: // beware: in SPIR-V this has a non constant encoding!
case YarivOpVariable: // beware: in SPIR-V this has a non constant encoding!
case YarivOpStoreWithMemoryAccess: // this fake opcode has a static size
case YarivOpDecorateWithOneLiteral: // this fake opcode has a static size
case YarivOpMemberDecorateWithNoLiterals: // this fake opcode has a static
// size
case YarivOpCompositeConstructOneConstituent: // this fake opcode has a static
// size
case YarivOpConstantWithOneFloatLiteral: // this fake opcode has a static size
case YarivOpDecorateLocation: // this fake opcode has a static size
count = 4;
break;
case YarivOpLoadWithMemoryAccess: // this fake opcode has a static size
case YarivOpMemberDecorateWithOneLiteral: // this fake opcode has a static
// size
case YarivOpVariableWithInitializer: // this fake opcode has a static size
case YarivOpConstantWithManyLiterals: // this fake opcode has a static size
case YarivOpAccessChainWithOneIndex: // this fake opcode has a static size
case YarivOpCompositeExtractWithLiteralZero: // this fake opcode has a static
// size
case YarivOpCompositeExtractWithLiteralOne: // this fake opcode has a static
// size
case YarivOpCompositeExtractWithLiteralTwo: // this fake opcode has a static
// size
case YarivOpCompositeExtractWithLiteralThree: // this fake opcode has a static
// size
case YarivOpCompositeConstructTwoConstituents: // this fake opcode has a
// static size
case YarivOpMemberDecorateOffset: // this fake opcode has a static size
count = 5;
break;
case YarivOpAccessChainWithTwoIndices: // this fake opcode has a static size
case YarivOpCompositeConstructThreeConstituents: // this fake opcode has a
// static size
count = 6;
break;
case YarivOpAccessChainWithThreeIndices: // this fake opcode has a static size
case YarivOpVectorShuffleTwoLiterals: // this fake opcode has a static size
case YarivOpVectorSwizzleTwoLiterals: // this fake opcode has a static size
count = 7;
break;
case YarivOpVectorShuffleThreeLiterals: // this fake opcode has a static size
case YarivOpVectorSwizzleThreeLiterals: // this fake opcode has a static size
count = 8;
break;
case YarivOpVectorShuffleFourLiterals: // this fake opcode has a static size
case YarivOpVectorSwizzleFourLiterals: // this fake opcode has a static size
count = 9;
break;
}
if (word_count) {
*word_count = count;
}
return 1;
}
uint32_t yariv_shuffle_opcode(uint32_t opcode) {
switch (opcode) {
default:
return opcode;
#define YARIV_SWAP(x, y) \
case (x): \
return (y); \
case (y): \
return (x)
YARIV_SWAP(YarivOpLabel, YarivOpNop);
YARIV_SWAP(YarivOpFSub, YarivOpUndef);
YARIV_SWAP(YarivOpFMul, YarivOpSourceContinued);
YARIV_SWAP(YarivOpFAdd, YarivOpSource);
YARIV_SWAP(YarivOpBranch, YarivOpSourceExtension);
YARIV_SWAP(YarivOpDecorateWithNoLiterals, YarivOpLine);
YARIV_SWAP(YarivOpDecorateWithOneLiteral, YarivOpExtension);
YARIV_SWAP(YarivOpMemberDecorateWithNoLiterals, YarivOpExtInstImport);
YARIV_SWAP(YarivOpMemberDecorateWithOneLiteral, YarivOpMemoryModel);
YARIV_SWAP(YarivOpAccessChainWithOneIndex, YarivOpExecutionMode);
YARIV_SWAP(YarivOpAccessChainWithTwoIndices, YarivOpCapability);
YARIV_SWAP(YarivOpAccessChainWithThreeIndices, YarivOpTypeVoid);
YARIV_SWAP(YarivOpVectorShuffleTwoLiterals, YarivOp9);
YARIV_SWAP(YarivOpVectorShuffleThreeLiterals, YarivOp13);
YARIV_SWAP(YarivOpVectorShuffleFourLiterals, YarivOp18);
YARIV_SWAP(YarivOpDot, YarivOp40);
YARIV_SWAP(YarivOpVectorTimesScalar, YarivOp47);
YARIV_SWAP(YarivOpFDiv, YarivOp53);
YARIV_SWAP(YarivOpVectorSwizzleTwoLiterals, YarivOp58);
YARIV_SWAP(YarivOpVectorSwizzleThreeLiterals, YarivOp76);
YARIV_SWAP(YarivOpVectorSwizzleFourLiterals, YarivOp85);
YARIV_SWAP(YarivOpBranchConditional, YarivOpTypeEvent);
YARIV_SWAP(YarivOpSelectionMerge, YarivOpTypeDeviceEvent);
YARIV_SWAP(YarivOpCompositeExtractWithLiteralZero,
YarivOpGenericPtrMemSemantics);
YARIV_SWAP(YarivOpCompositeExtractWithLiteralOne, YarivOpPtrCastToGeneric);
YARIV_SWAP(YarivOpCompositeExtractWithLiteralTwo, YarivOpGenericCastToPtr);
YARIV_SWAP(YarivOpCompositeExtractWithLiteralThree,
YarivOpGenericCastToPtrExplicit);
YARIV_SWAP(YarivOpCompositeConstructOneConstituent, YarivOpTypeReserveId);
YARIV_SWAP(YarivOpCompositeConstructTwoConstituents, YarivOpTypeQueue);
YARIV_SWAP(YarivOpCompositeConstructThreeConstituents, YarivOpTypePipe);
YARIV_SWAP(YarivOpDecorateRelaxedPrecision, YarivOpImageTexelPointer);
YARIV_SWAP(YarivOpMemberDecorateOffset, YarivOp108);
YARIV_SWAP(YarivOpConstantWithOneFloatLiteral, YarivOpTypeForwardPointer);
YARIV_SWAP(YarivOpDecorateLocation, YarivOp125);
YARIV_SWAP(YarivOpReturnValue, YarivOpTypeRuntimeArray);
YARIV_SWAP(YarivOpFOrdEqual, YarivOpCompositeInsert);
YARIV_SWAP(YarivOpFOrdLessThanEqual, YarivOpVectorExtractDynamic);
YARIV_SWAP(YarivOpFOrdLessThan, YarivOpConstantFalse);
YARIV_SWAP(YarivOpIEqual, YarivOpTranspose);
YARIV_SWAP(YarivOpReturn, YarivOpSNegate);
YARIV_SWAP(YarivOpIAdd, YarivOpCopyObject);
#undef YARIV_SWAP
}
}
size_t yariv_encode_signed_varint(int32_t i, uint8_t *out) {
// we use zig-zag encoding of the original integer
return yariv_encode_unsigned_varint(
YARIV_CAST(uint32_t, (i << 1) ^ (i >> 31)), out);
}
size_t yariv_decode_signed_varint(const uint8_t *in, int32_t *out) {
uint32_t u;
const size_t r = yariv_decode_unsigned_varint(in, &u);
if (out) {
// we use zig-zag decoding of the unsigned integer
*out = YARIV_CAST(int32_t, u >> 1) ^ -(YARIV_CAST(int32_t, u) & 1);
}
return r;
}
size_t yariv_encode_unsigned_varint(uint32_t i, uint8_t *out) {
size_t r = 0;
while (i > 127) {
if (out) {
out[r] = (YARIV_CAST(uint8_t, i) & 0x7Fu) | 0x80u;
}
i >>= 7;
r++;
}
if (out) {
out[r] = YARIV_CAST(uint8_t, i);
}
return r + 1;
}
size_t yariv_decode_unsigned_varint(const uint8_t *in, uint32_t *out) {
uint32_t r = 0;
size_t i;
// the maximum length of a uint32_t varint is 5 bytes
for (i = 0; i < 5; i++) {
// bring in the 7 significant bits of this part of the varint
r |= (0x7Fu & in[i]) << 7 * i;
// if we don't have the 'there is another byte in our varint' bit set
if (0u == (0x80u & in[i])) {
if (out) {
*out = r;
}
return i + 1;
}
}
return 0;
}
#undef YARIV_CAST
#ifdef __cplusplus
}
#endif
#endif // SHEREDOM_YARIV_H_INCLUDED
|
danilw/vulkan-shadertoy-launcher
|
vk_utils/vk_render_helper.c
|
// Danil, 2021+ Vulkan shader launcher, self https://github.com/danilw/vulkan-shadertoy-launcher
// The MIT License
#include "vk_render_helper.h"
int vk_render_get_essentials(struct vk_render_essentials *essentials, struct vk_physical_device *phy_dev,
struct vk_device *dev, struct vk_swapchain *swapchain)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
essentials->images = vk_get_swapchain_images(dev, swapchain, &essentials->image_count);
if (essentials->images == NULL)
return -1;
uint32_t *presentable_queues = NULL;
uint32_t presentable_queue_count = 0;
retval = vk_get_presentable_queues(phy_dev, dev, swapchain->surface, &presentable_queues, &presentable_queue_count);
if (!vk_error_is_success(&retval) || presentable_queue_count == 0)
{
printf("No presentable queue families! What kind of graphics card is this!\n");
return -1;
}
essentials->present_queue = dev->command_pools[presentable_queues[0]].queues[0];
essentials->cmd_buffer = dev->command_pools[presentable_queues[0]].buffers[0];
free(presentable_queues);
VkSemaphoreCreateInfo sem_info = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
};
res = vkCreateSemaphore(dev->device, &sem_info, NULL, &essentials->sem_post_acquire);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to create post-acquire semaphore\n");
return -1;
}
res = vkCreateSemaphore(dev->device, &sem_info, NULL, &essentials->sem_pre_submit);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to create pre-submit semaphore\n");
return -1;
}
VkFenceCreateInfo fence_info = {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
};
res = vkCreateFence(dev->device, &fence_info, NULL, &essentials->exec_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to create fence\n");
return -1;
}
essentials->first_render = true;
return 0;
}
void vk_render_cleanup_essentials(struct vk_render_essentials *essentials, struct vk_device *dev)
{
vkDeviceWaitIdle(dev->device);
vkDestroySemaphore(dev->device, essentials->sem_post_acquire, NULL);
vkDestroySemaphore(dev->device, essentials->sem_pre_submit, NULL);
vkDestroyFence(dev->device, essentials->exec_fence, NULL);
free(essentials->images);
}
VkResult vk_render_start(struct vk_render_essentials *essentials, struct vk_device *dev,
struct vk_swapchain *swapchain, VkImageLayout to_layout, uint32_t *image_index)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
res = vkAcquireNextImageKHR(dev->device, swapchain->swapchain, 1000000000, essentials->sem_post_acquire, NULL, image_index);
vk_error_set_vkresult(&retval, res);
if (res == VK_TIMEOUT)
{
printf("A whole second and no image. I give up.\n");
return res;
}
else if (res == VK_SUBOPTIMAL_KHR)
printf("presentation is suboptimal.\n");
else if (res == VK_ERROR_OUT_OF_DATE_KHR) {
// this is not error, this is resize event for AMD hardware
return res;
}
else if (res < 0)
{
vk_error_printf(&retval, "Couldn't acquire image\n");
return res;
}
if (!essentials->first_render)
{
res = vkWaitForFences(dev->device, 1, &essentials->exec_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Wait for fence failed\n");
return res;
}
}
essentials->first_render = false;
vkResetCommandBuffer(essentials->cmd_buffer, 0);
VkCommandBufferBeginInfo begin_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
};
res = vkBeginCommandBuffer(essentials->cmd_buffer, &begin_info);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Couldn't even begin recording a command buffer\n");
return res;
}
VkImageMemoryBarrier image_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
.dstAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = to_layout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = essentials->images[*image_index],
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
vkCmdPipelineBarrier(essentials->cmd_buffer,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
0,
0, NULL,
0, NULL,
1, &image_barrier);
return 0;
}
static vk_error fill_object(struct vk_device *dev, VkDeviceMemory to, void *from, size_t size, const char *object, const char *name)
{
void *mem = NULL;
vk_error retval = VK_ERROR_NONE;
VkResult res;
res = vkMapMemory(dev->device, to, 0, size, 0, &mem);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to map memory of the %s %s\n", name, object);
return retval;
}
memcpy(mem, from, size);
vkUnmapMemory(dev->device, to);
return retval;
}
vk_error vk_render_fill_buffer(struct vk_device *dev, struct vk_buffer *to, void *from, size_t size, const char *name)
{
return fill_object(dev, to->buffer_mem, from, size, "buffer", name);
}
vk_error vk_render_fill_image(struct vk_device *dev, struct vk_image *to, void *from, size_t size, const char *name)
{
return fill_object(dev, to->image_mem, from, size, "image", name);
}
static vk_error copy_object_start(struct vk_device *dev, struct vk_render_essentials *essentials, const char *object, const char *name)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
vkResetCommandBuffer(essentials->cmd_buffer, 0);
VkCommandBufferBeginInfo begin_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
};
res = vkBeginCommandBuffer(essentials->cmd_buffer, &begin_info);
vk_error_set_vkresult(&retval, res);
if (res)
vk_error_printf(&retval, "Couldn't begin recording a command buffer to copy the %s %s\n", name, object);
return retval;
}
static vk_error copy_object_end(struct vk_device *dev, struct vk_render_essentials *essentials)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
vkEndCommandBuffer(essentials->cmd_buffer);
res = vkResetFences(dev->device, 1, &essentials->exec_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to reset fence\n");
return retval;
}
VkSubmitInfo submit_info = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.commandBufferCount = 1,
.pCommandBuffers = &essentials->cmd_buffer,
};
vkQueueSubmit(essentials->present_queue, 1, &submit_info, essentials->exec_fence);
res = vkWaitForFences(dev->device, 1, &essentials->exec_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
return retval;
}
vk_error vk_render_copy_buffer(struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_buffer *to, struct vk_buffer *from, size_t size, const char *name)
{
vk_error retval = VK_ERROR_NONE;
retval = copy_object_start(dev, essentials, "buffer", name);
if (!vk_error_is_success(&retval))
return retval;
VkBufferCopy copy_region = {
.srcOffset = 0,
.dstOffset = 0,
.size = size,
};
vkCmdCopyBuffer(essentials->cmd_buffer, from->buffer, to->buffer, 1, ©_region);
return copy_object_end(dev, essentials);
}
vk_error vk_render_copy_image(struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *to, VkImageLayout to_layout, struct vk_image *from, VkImageLayout from_layout,
VkImageCopy *region, const char *name)
{
vk_error retval = VK_ERROR_NONE;
retval = copy_object_start(dev, essentials, "image", name);
if (!vk_error_is_success(&retval))
return retval;
vkCmdCopyImage(essentials->cmd_buffer, from->image, from_layout, to->image, to_layout, 1, region);
return copy_object_end(dev, essentials);
}
vk_error vk_render_copy_buffer_to_image(struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *to, VkImageLayout to_layout, struct vk_buffer *from,
VkBufferImageCopy *region, const char *name)
{
vk_error retval = VK_ERROR_NONE;
retval = copy_object_start(dev, essentials, "image", name);
if (!vk_error_is_success(&retval))
return retval;
vkCmdCopyBufferToImage(essentials->cmd_buffer, from->buffer, to->image, to_layout, 1, region);
return copy_object_end(dev, essentials);
}
vk_error vk_render_copy_image_to_buffer(struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_buffer *to, struct vk_image *from, VkImageLayout from_layout,
VkBufferImageCopy *region, const char *name)
{
vk_error retval = VK_ERROR_NONE;
retval = copy_object_start(dev, essentials, "buffer", name);
if (!vk_error_is_success(&retval))
return retval;
vkCmdCopyImageToBuffer(essentials->cmd_buffer, from->image, from_layout, to->buffer, 1, region);
return copy_object_end(dev, essentials);
}
vk_error vk_render_transition_images(struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *images, uint32_t image_count,
VkImageLayout from, VkImageLayout to, VkImageAspectFlags aspect, const char *name)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
vkResetCommandBuffer(essentials->cmd_buffer, 0);
VkCommandBufferBeginInfo begin_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
};
res = vkBeginCommandBuffer(essentials->cmd_buffer, &begin_info);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Couldn't begin recording a command buffer to transition the %s image\n", name);
return retval;
}
VkImageMemoryBarrier image_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = 0,
.dstAccessMask = 0,
.oldLayout = from,
.newLayout = to,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.subresourceRange = {
.aspectMask = aspect,
.baseMipLevel = 0,
.levelCount = VK_REMAINING_MIP_LEVELS,
.baseArrayLayer = 0,
.layerCount = VK_REMAINING_ARRAY_LAYERS,
},
};
for (uint32_t i = 0; i < image_count; ++i)
{
image_barrier.image = images[i].image;
vkCmdPipelineBarrier(essentials->cmd_buffer,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
0,
0, NULL,
0, NULL,
1, &image_barrier);
}
vkEndCommandBuffer(essentials->cmd_buffer);
res = vkResetFences(dev->device, 1, &essentials->exec_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to reset fence\n");
return retval;
}
VkSubmitInfo submit_info = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.commandBufferCount = 1,
.pCommandBuffers = &essentials->cmd_buffer,
};
vkQueueSubmit(essentials->present_queue, 1, &submit_info, essentials->exec_fence);
res = vkWaitForFences(dev->device, 1, &essentials->exec_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
return retval;
}
vk_error create_staging_buffer(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_buffer *staging, uint8_t *contents, size_t size, const char *name)
{
vk_error retval = VK_ERROR_NONE;
*staging = (struct vk_buffer){
.size = size,
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.host_visible = true,
};
retval = vk_create_buffers(phy_dev, dev, staging, 1);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Failed to create staging %s buffer\n", name);
return retval;
}
char staging_name[50];
snprintf(staging_name, 50, "staging %s", name);
retval = vk_render_fill_buffer(dev, staging, contents, size, staging_name);
return retval;
}
vk_error vk_render_transition_images_mipmaps(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *image, VkImageAspectFlags aspect, const char *name)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(phy_dev->physical_device, image->format, &formatProperties);
if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) {
printf("texture image format does not support linear blitting! %s image\n", name);
retval.error.type=VK_ERROR_ERRNO;
return retval;
}
vkResetCommandBuffer(essentials->cmd_buffer, 0);
VkCommandBufferBeginInfo begin_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
};
res = vkBeginCommandBuffer(essentials->cmd_buffer, &begin_info);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Couldn't begin recording a command buffer to transition the %s image\n", name);
return retval;
}
int32_t mipWidth = image->extent.width;
int32_t mipHeight = image->extent.height;
uint32_t mipLevels = (int)(log(MAX(image->extent.width, image->extent.height))/log(2)) + 1;
VkImageMemoryBarrier image_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = image->image,
.subresourceRange = {
.aspectMask = aspect,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
for (uint32_t i = 1; i < mipLevels; i++) {
image_barrier.subresourceRange.baseMipLevel = i - 1;
image_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
image_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
image_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
image_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
vkCmdPipelineBarrier(essentials->cmd_buffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, NULL,
0, NULL,
1, &image_barrier);
VkImageBlit blit = {0};
blit.srcOffsets[0] = (struct VkOffset3D){.x=0, .y=0, .z=0};
blit.srcOffsets[1] = (struct VkOffset3D){.x=mipWidth, .y=mipHeight, .z=1};
blit.srcSubresource.aspectMask = aspect;
blit.srcSubresource.mipLevel = i - 1;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.dstOffsets[0] = (struct VkOffset3D){.x=0, .y=0, .z=0};
blit.dstOffsets[1] = (struct VkOffset3D){.x=(mipWidth > 1 ? mipWidth / 2 : 1), .y=(mipHeight > 1 ? mipHeight / 2 : 1), .z=1 };
blit.dstSubresource.aspectMask = aspect;
blit.dstSubresource.mipLevel = i;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = 1;
vkCmdBlitImage(essentials->cmd_buffer,
image->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
image->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, &blit,
VK_FILTER_LINEAR);
image_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
image_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
image_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(essentials->cmd_buffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
0, NULL,
0, NULL,
1, &image_barrier);
if (mipWidth > 1) mipWidth /= 2;
if (mipHeight > 1) mipHeight /= 2;
}
image_barrier.subresourceRange.baseMipLevel = mipLevels - 1;
image_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
image_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
image_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(essentials->cmd_buffer,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0, NULL,
0, NULL,
1, &image_barrier);
vkEndCommandBuffer(essentials->cmd_buffer);
res = vkResetFences(dev->device, 1, &essentials->exec_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to reset fence\n");
return retval;
}
VkSubmitInfo submit_info = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.commandBufferCount = 1,
.pCommandBuffers = &essentials->cmd_buffer,
};
vkQueueSubmit(essentials->present_queue, 1, &submit_info, essentials->exec_fence);
res = vkWaitForFences(dev->device, 1, &essentials->exec_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
return retval;
}
vk_error vk_render_update_texture(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *image, VkImageLayout base_layout, uint8_t *contents, const char *name)
{
vk_error retval = VK_ERROR_NONE;
struct vk_buffer staging;
retval = create_staging_buffer(phy_dev, dev, essentials, &staging, contents, image->extent.width * image->extent.height * 4, name);
if (!vk_error_is_success(&retval))
return retval;
retval = vk_render_transition_images(dev, essentials, image, 1, base_layout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, name);
if (!vk_error_is_success(&retval))
return retval;
VkBufferImageCopy image_copy = {
.imageSubresource = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.layerCount = 1,
},
.imageExtent = {
.width = image->extent.width,
.height = image->extent.height,
.depth = 1,
},
};
retval = vk_render_copy_buffer_to_image(dev, essentials, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &staging, &image_copy, name);
if (!vk_error_is_success(&retval))
return retval;
retval = vk_render_transition_images(dev, essentials, image, 1, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, base_layout, VK_IMAGE_ASPECT_COLOR_BIT, name);
if (!vk_error_is_success(&retval))
return retval;
vk_free_buffers(dev, &staging, 1);
return retval;
}
vk_error vk_render_init_texture(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *image, VkImageLayout layout, uint8_t *contents, const char *name)
{
vk_error retval = VK_ERROR_NONE;
struct vk_buffer staging;
retval = create_staging_buffer(phy_dev, dev, essentials, &staging, contents, image->extent.width * image->extent.height * 4, name);
if (!vk_error_is_success(&retval))
return retval;
retval = vk_render_transition_images(dev, essentials, image, 1, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, name);
if (!vk_error_is_success(&retval))
return retval;
VkBufferImageCopy image_copy = {
.imageSubresource = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.layerCount = 1,
},
.imageExtent = {
.width = image->extent.width,
.height = image->extent.height,
.depth = 1,
},
};
retval = vk_render_copy_buffer_to_image(dev, essentials, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &staging, &image_copy, name);
if (!vk_error_is_success(&retval))
return retval;
if(image->mipmaps)
retval = vk_render_transition_images_mipmaps(phy_dev, dev, essentials, image, VK_IMAGE_ASPECT_COLOR_BIT, name);
else
retval = vk_render_transition_images(dev, essentials, image, 1, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, layout, VK_IMAGE_ASPECT_COLOR_BIT, name);
vk_free_buffers(dev, &staging, 1);
return retval;
}
vk_error vk_render_init_buffer(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_buffer *buffer, void *contents, const char *name)
{
vk_error retval = VK_ERROR_NONE;
struct vk_buffer staging;
retval = create_staging_buffer(phy_dev, dev, essentials, &staging, contents, buffer->size, name);
if (!vk_error_is_success(&retval))
return retval;
retval = vk_render_copy_buffer(dev, essentials, buffer, &staging, buffer->size, name);
vk_free_buffers(dev, &staging, 1);
return retval;
}
int vk_render_finish(struct vk_render_essentials *essentials, struct vk_device *dev,
struct vk_swapchain *swapchain, VkImageLayout from_layout, uint32_t image_index,
VkSemaphore wait_sem, VkSemaphore signal_sem)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
VkImageMemoryBarrier image_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT,
.oldLayout = from_layout,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = essentials->images[image_index],
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
vkCmdPipelineBarrier(essentials->cmd_buffer,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0,
0, NULL,
0, NULL,
1, &image_barrier);
vkEndCommandBuffer(essentials->cmd_buffer);
res = vkResetFences(dev->device, 1, &essentials->exec_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to reset fence\n");
return res;
}
VkSemaphore wait_sems[2] = {essentials->sem_post_acquire, wait_sem};
VkSemaphore signal_sems[2] = {essentials->sem_pre_submit, signal_sem};
VkPipelineStageFlags wait_sem_stages[2] = {VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT};
VkSubmitInfo submit_info = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.waitSemaphoreCount = wait_sem?2:1,
.pWaitSemaphores = wait_sems,
.pWaitDstStageMask = wait_sem_stages,
.commandBufferCount = 1,
.pCommandBuffers = &essentials->cmd_buffer,
.signalSemaphoreCount = signal_sem?2:1,
.pSignalSemaphores = signal_sems,
};
vkQueueSubmit(essentials->present_queue, 1, &submit_info, essentials->exec_fence);
VkPresentInfoKHR present_info = {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.waitSemaphoreCount = 1,
.pWaitSemaphores = &essentials->sem_pre_submit,
.swapchainCount = 1,
.pSwapchains = &swapchain->swapchain,
.pImageIndices = &image_index,
};
res = vkQueuePresentKHR(essentials->present_queue, &present_info);
if (res == VK_ERROR_OUT_OF_DATE_KHR) {
return VK_ERROR_OUT_OF_DATE_KHR;
} else if (res == VK_SUBOPTIMAL_KHR) {
return 0;
} else if (res == VK_ERROR_SURFACE_LOST_KHR) {
return VK_ERROR_SURFACE_LOST_KHR;
} else {
vk_error_set_vkresult(&retval, res);
if (res < 0)
{
vk_error_printf(&retval, "Failed to queue image for presentation\n");
return -1;
}
}
return 0;
}
|
danilw/vulkan-shadertoy-launcher
|
launcher/textures.h
|
static vk_error init_texture_mem(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *image, uint8_t *texture, int width, int height, const char *name, bool mipmaps, bool linear)
{
vk_error retval = VK_ERROR_NONE;
VkFormat img_format=VK_FORMAT_R8G8B8A8_UNORM; //VK_FORMAT_R8G8B8A8_SRGB
*image = (struct vk_image) {
.format = img_format,
.extent = { .width = width, .height = height },
.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
.make_view = true,
.host_visible = false,
.anisotropyEnable = true,
.repeat_mode = VK_SAMPLER_ADDRESS_MODE_REPEAT, //VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER //VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE
.mipmaps = mipmaps,
.linear = linear||mipmaps,
};
retval = vk_create_images(phy_dev, dev, image, 1);
if (!vk_error_is_success(&retval))
{
retval.error.type=VK_ERROR_ERRNO;
vk_error_printf(&retval, "Failed to create texture images\n");
return retval;
}
retval = vk_render_init_texture(phy_dev, dev, essentials, image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, texture, name);
return retval;
}
#ifdef USE_stb_image
static vk_error init_texture_file(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials,
struct vk_image *image, const char *name, bool mipmaps)
{
vk_error retval = VK_ERROR_NONE;
int width, height, channels;
stbi_set_flip_vertically_on_load(true); //flip image Y
uint8_t *generated_texture = stbi_load(name, &width, &height, &channels, STBI_rgb_alpha);
if(generated_texture == NULL) {
retval.error.type=VK_ERROR_ERRNO;
printf("Error in loading image %s\n", name);
return retval;
}
retval = init_texture_mem(phy_dev, dev, essentials, image, generated_texture, width, height, name, mipmaps, true);
stbi_image_free(generated_texture);
return retval;
}
#endif
static vk_error texture_empty(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_render_essentials *essentials, struct vk_image *image, int width, int height)
{
vk_error retval = VK_ERROR_NONE;
size_t texture_size = width * height * 4 * sizeof(uint8_t);
uint8_t *generated_texture = malloc(texture_size);
if(generated_texture == NULL) {
retval.error.type=VK_ERROR_ERRNO;
printf("Error in allocating memory\n");
return retval;
}
for (unsigned int i = 0; i < height; ++i){
for (unsigned int j = 0; j < width; ++j){
size_t pixel = (i * width + j) * 4 * sizeof(uint8_t);
generated_texture[pixel + 0] = 0x00;
generated_texture[pixel + 1] = 0x00;
generated_texture[pixel + 2] = 0x00;
generated_texture[pixel + 3] = 0x00;
}
}
retval = init_texture_mem(phy_dev, dev, essentials, image, generated_texture, width, height, "empty", false, false);
free(generated_texture);
return retval;
}
|
danilw/vulkan-shadertoy-launcher
|
os_utils/xcb_x11_utils.h
|
#include <xcb/xcb_keysyms.h>
static uint8_t local_k_map[0xff+1]={0}; //+1 to have 0xff index
static uint8_t get_ASCII_key(uint8_t key){return local_k_map[key];}
static void get_modifiers(uint32_t mask, bool *c_lock, bool *n_lock, bool *s_lock);
static uint8_t check_num(bool nmod,uint8_t key);
static void app_handle_xcb_event(struct app_os_window *os_window, const xcb_generic_event_t *event, bool (*save_map)[3], bool (*state_map)[2]) {
uint8_t event_code = event->response_type & 0x7f;
switch (event_code) {
case XCB_EXPOSE:
break;
case XCB_CLIENT_MESSAGE:
if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*os_window->atom_wm_delete_window).atom) {
os_window->app_data.quit = true;
}
break;
case XCB_KEY_RELEASE: {
const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
uint8_t keyA=get_ASCII_key((uint8_t)key->detail);
if(keyA>0){
keyboard_need_update=true;
keyboard_draw=true;
bool a,b,c;
get_modifiers(key->state,&a,&b,&c);
keyA=check_num(b,keyA);
if((!state_map[keyA][0])&&(!state_map[keyA][1])){
save_map[keyA][0]=keyboard_map[keyA][0];
save_map[keyA][1]=keyboard_map[keyA][1];
save_map[keyA][2]=keyboard_map[keyA][2];
}
state_map[keyA][0]=true;
update_key_map(keyA,0,false);
}
} break;
case XCB_KEY_PRESS: {
const xcb_key_press_event_t *key = (const xcb_key_press_event_t *)event;
uint8_t keyA=get_ASCII_key((uint8_t)key->detail);
if(keyA>0){
bool a,b,c;
get_modifiers(key->state,&a,&b,&c);
keyA=check_num(b,keyA);
if((!state_map[keyA][0])&&(!state_map[keyA][1])){
save_map[keyA][0]=keyboard_map[keyA][0];
save_map[keyA][1]=keyboard_map[keyA][1];
save_map[keyA][2]=keyboard_map[keyA][2];
}
state_map[keyA][1]=true;
if(!keyboard_map[keyA][0]){
keyboard_need_update=true;
keyboard_draw=true;
update_key_map(keyA,2,!keyboard_map[keyA][2]);
update_key_map(keyA,1,true);
update_key_map(keyA,0,true);
}
}
} break;
case XCB_MOTION_NOTIFY: {
const xcb_motion_notify_event_t *ev = (const xcb_motion_notify_event_t *)event;
os_window->app_data.iMouse[0] = ev->event_x;
os_window->app_data.iMouse[1] = os_window->app_data.iResolution[1] - ev->event_y;
} break;
case XCB_BUTTON_PRESS: {
const xcb_button_press_event_t *ev = (const xcb_button_press_event_t *)event;
switch (ev->detail) {
case 1:
os_window->app_data.iMouse_click[0] = true;
os_window->app_data.iMouse_lclick[0] = ev->event_x;
os_window->app_data.iMouse_lclick[1] = os_window->app_data.iResolution[1] - ev->event_y;
break;
case 3:
os_window->app_data.iMouse_click[1] = true;
os_window->app_data.iMouse_rclick[0] = ev->event_x;
os_window->app_data.iMouse_rclick[1] = os_window->app_data.iResolution[1] - ev->event_y;
break;
case 4:
/*printf ("Wheel Button up in window %ld, at coordinates (%d,%d)\n",
ev->event, ev->event_x, ev->event_y);*/
break;
case 5:
/*printf ("Wheel Button down in window %ld, at coordinates (%d,%d)\n",
ev->event, ev->event_x, ev->event_y);*/
break;
//default:
/*printf ("Button %d pressed in window %ld, at coordinates (%d,%d)\n",
ev->detail, ev->event, ev->event_x, ev->event_y);*/
}
} break;
case XCB_BUTTON_RELEASE: {
const xcb_button_release_event_t *ev = (const xcb_button_release_event_t *)event;
switch (ev->detail) {
case 1:
os_window->app_data.iMouse_click[0] = false;
os_window->app_data.iMouse_lclick[0] = -os_window->app_data.iMouse_lclick[0];
os_window->app_data.iMouse_lclick[1] = -os_window->app_data.iMouse_lclick[1];
break;
case 3:
os_window->app_data.iMouse_click[1] = false;
os_window->app_data.iMouse_rclick[0] = -os_window->app_data.iMouse_rclick[0];
os_window->app_data.iMouse_rclick[1] = -os_window->app_data.iMouse_rclick[1];
break;
}
/*print_modifiers(ev->state);
printf ("Button %d released in window %ld, at coordinates (%d,%d)\n",
ev->detail, ev->event, ev->event_x, ev->event_y);*/
} break;
case XCB_CONFIGURE_NOTIFY: {
const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
if ((os_window->app_data.iResolution[0] != cfg->width) || (os_window->app_data.iResolution[1] != cfg->height)) {
os_window->is_minimized = false;
os_window->app_data.iResolution[0] = cfg->width;
os_window->app_data.iResolution[1] = cfg->height;
if((os_window->app_data.iResolution[0]<=1)||(os_window->app_data.iResolution[1]<=1)){
os_window->is_minimized = true;
}else{
os_window->resize_event=true;
}
}
} break;
default:
break;
}
}
static void app_init_connection(struct app_os_window *os_window) {
const xcb_setup_t *setup;
xcb_screen_iterator_t iter;
int scr;
const char *display_envar = getenv("DISPLAY");
if (display_envar == NULL || display_envar[0] == '\0') {
printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
fflush(stdout);
exit(1);
}
os_window->connection = xcb_connect(NULL, &scr);
if (xcb_connection_has_error(os_window->connection) > 0) {
printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
fflush(stdout);
exit(1);
}
setup = xcb_get_setup(os_window->connection);
iter = xcb_setup_roots_iterator(setup);
while (scr-- > 0) xcb_screen_next(&iter);
os_window->screen = iter.data;
}
static void gen_key_map(xcb_connection_t* connection);
static void app_create_xcb_window(struct app_os_window *os_window) {
uint32_t value_mask, value_list[32];
os_window->xcb_window = xcb_generate_id(os_window->connection);
value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
value_list[0] = os_window->screen->black_pixel;
value_list[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION |
XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
xcb_create_window(os_window->connection, XCB_COPY_FROM_PARENT, os_window->xcb_window, os_window->screen->root, 0, 0, os_window->app_data.iResolution[0], os_window->app_data.iResolution[1],
0, XCB_WINDOW_CLASS_INPUT_OUTPUT, os_window->screen->root_visual, value_mask, value_list);
xcb_intern_atom_cookie_t cookie = xcb_intern_atom(os_window->connection, 1, 12, "WM_PROTOCOLS");
xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(os_window->connection, cookie, 0);
xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(os_window->connection, 0, 16, "WM_DELETE_WINDOW");
os_window->atom_wm_delete_window = xcb_intern_atom_reply(os_window->connection, cookie2, 0);
xcb_change_property (os_window->connection, XCB_PROP_MODE_REPLACE, os_window->xcb_window,
XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8,
strlen (os_window->name), os_window->name);
xcb_change_property (os_window->connection, XCB_PROP_MODE_REPLACE, os_window->xcb_window,
XCB_ATOM_WM_ICON_NAME, XCB_ATOM_STRING, 8,
strlen(os_window->name), os_window->name);
xcb_change_property(os_window->connection, XCB_PROP_MODE_REPLACE, os_window->xcb_window, (*reply).atom, 4, 32, 1,
&(*os_window->atom_wm_delete_window).atom);
free(reply);
xcb_map_window(os_window->connection, os_window->xcb_window);
const uint32_t coords[] = { 100, 100 };
xcb_configure_window(os_window->connection, os_window->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
xcb_flush(os_window->connection);
gen_key_map(os_window->connection);
}
static void get_modifiers(uint32_t mask, bool *c_lock, bool *n_lock, bool *s_lock)
{
const char **mod, *mods[] = {
"Shift", "Lock", "Ctrl", "Alt",
"Mod2", "Mod3", "Mod4", "Mod5",
"Button1", "Button2", "Button3", "Button4", "Button5"
};
//printf("Modifier mask: ");
int cntr=0;
*c_lock=false;*n_lock=false;*s_lock=false;
for (mod = mods; mask; mask >>= 1, mod++){
//if (mask & 1)printf("%s ",*mod);
if ((mask & 1)&&(cntr==1))*c_lock=true;
if ((mask & 1)&&(cntr==4))*n_lock=true;
cntr++;
}
//putchar('\n');
}
//shadertoy keys
static const uint8_t Key_Backspace = 8, Key_Tab = 9, Key_Enter = 13, Key_Shift = 16, Key_Space = 32,
Key_Ctrl = 17, Key_Alt = 18, Key_Pause = 19, Key_Caps = 20, Key_Escape = 27, Key_PageUp = 33, Key_PageDown = 34, Key_End = 35,
Key_Home = 36, Key_LeftArrow = 37, Key_UpArrow = 38, Key_RightArrow = 39, Key_DownArrow = 40, Key_Insert = 45,
Key_Delete = 46, Key_0 = 48, Key_1 = 49, Key_2 = 50, Key_3 = 51, Key_4 = 52,
Key_5 = 53, Key_6 = 54, Key_7 = 55, Key_8 = 56, Key_9 = 57, Key_A = 65, Key_B = 66,
Key_C = 67, Key_D = 68, Key_E = 69, Key_F = 70, Key_G = 71, Key_H = 72,
Key_I = 73, Key_J = 74, Key_K = 75, Key_L = 76, Key_M = 77, Key_N = 78, Key_O = 79, Key_P = 80, Key_Q = 81,
Key_R = 82, Key_S = 83, Key_T = 84, Key_U = 85,
Key_V = 86, Key_W = 87, Key_X = 88, Key_Y = 89, Key_Z = 90, Key_LeftWindow = 91, Key_RightWindows = 92,
Key_Select = 93, Key_Numpad0 = 96, Key_Numpad1 = 97, Key_Numpad2 = 98, Key_Numpad3 = 99,
Key_Numpad4 = 100, Key_Numpad5 = 101, Key_Numpad6 = 102, Key_Numpad7 = 103, Key_Numpad8 = 104, Key_Numpad9 = 105,
Key_NumpadMultiply = 106, Key_NumpadAdd = 107, Key_NumpadSubtract = 109, Key_NumpadPeriod = 110, Key_NumpadDivide = 111,
Key_F1 = 112, Key_F2 = 113, Key_F3 = 114, Key_F4 = 115, Key_F5 = 116, Key_F6 = 117, Key_F7 = 118, Key_F8 = 119, Key_F9 = 120,
Key_F10 = 121, Key_F11 = 122, Key_F12 = 123, Key_NumLock = 144, Key_ScrollLock = 145,
Key_SemiColon = 186, Key_Equal = 187, Key_Comma = 188, Key_Dash = 189, Key_Period = 190,
Key_ForwardSlash = 191, Key_GraveAccent = 192, Key_OpenBracket = 219, Key_BackSlash = 220, Key_CloseBraket = 221, Key_SingleQuote = 222;
// this is not ASCII keys, this used to detect keys when NumLock pressed/not
#define Key_npx0 239
#define Key_npx1 240
#define Key_npx2 241
#define Key_npx3 242
#define Key_npx4 243
#define Key_npx5 244
#define Key_npx6 245
#define Key_npx7 246
#define Key_npx8 247
#define Key_npx9 248
#define Key_npx10 249
static uint8_t check_num(bool nmod,uint8_t key){
if(nmod){
switch(key){
case Key_npx0:return Key_Numpad0;
case Key_npx1:return Key_Numpad1;
case Key_npx2:return Key_Numpad2;
case Key_npx3:return Key_Numpad3;
case Key_npx4:return Key_Numpad4;
case Key_npx5:return Key_Numpad5;
case Key_npx6:return Key_Numpad6;
case Key_npx7:return Key_Numpad7;
case Key_npx8:return Key_Numpad8;
case Key_npx9:return Key_Numpad9;
case Key_npx10:return Key_NumpadPeriod;
}
}else{
switch(key){
case Key_npx0:return Key_Insert;
case Key_npx1:return Key_End;
case Key_npx2:return Key_DownArrow;
case Key_npx3:return Key_PageDown;
case Key_npx4:return Key_LeftArrow;
case Key_npx5:return 0;
case Key_npx6:return Key_RightArrow;
case Key_npx7:return Key_Home;
case Key_npx8:return Key_UpArrow;
case Key_npx9:return Key_PageUp;
case Key_npx10:return Key_Delete;
}
}
return key;
}
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
// keyboard mapping can be wrong on some keys(not tested) when used some unique keyboards with swapped keys order
// example where first(main) key is <@> and only second is <2>, I expect that keyboard has first(main) key is <2>
static void gen_key_map(xcb_connection_t* connection){
xcb_key_symbols_t* keySymbols = xcb_key_symbols_alloc(connection);
xcb_keycode_t* keycode=NULL;
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_A);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_A;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_B);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_B;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_C);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_C;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_D);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_D;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_E);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_E;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_G);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_G;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_H);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_H;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_I);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_I;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_J);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_J;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_K);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_K;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_L);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_L;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_M);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_M;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_N);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_N;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_O);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_O;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_P);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_P;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Q);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Q;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_R);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_R;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_S);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_S;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_T);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_T;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_U);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_U;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_V);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_V;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_W);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_W;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_X);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_X;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Y);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Y;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Z);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Z;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_space);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Space;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_0);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_0;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_1);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_1;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_2);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_2;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_3);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_3;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_4);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_4;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_5);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_5;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_6);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_6;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_7);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_7;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_8);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_8;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_9);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_9;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Escape);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Escape;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Control_L);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Ctrl;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Shift_L);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Shift;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Alt_L);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Alt;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Super_L);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_LeftWindow;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Control_R);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Ctrl;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Shift_R);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Shift;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Alt_R);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Alt;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Super_R);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_RightWindows;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_BackSpace);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Backspace;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Tab);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Tab;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Return);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Enter;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Pause);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Pause;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Caps_Lock);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Caps;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Page_Up);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_PageUp;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Page_Down);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_PageDown;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_End);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_End;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Home);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Home;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Left);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_LeftArrow;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Up);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_UpArrow;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Right);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_RightArrow;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Down);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_DownArrow;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Insert);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Insert;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Delete);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Delete;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Select);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Select;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_0);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad0;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_1);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad1;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_2);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad2;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_3);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad3;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_4);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad4;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_5);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad5;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_6);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad6;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_7);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad7;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_8);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad8;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_9);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Numpad9;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Space);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Space;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Tab);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Tab;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Home);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx7;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Left);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx4;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Up);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx8;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Right);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx6;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Down);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx2;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Page_Up);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx9;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Page_Down);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx3;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_End);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx1;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Insert);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx0;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Delete);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_npx10;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Enter);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Enter;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Multiply);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_NumpadMultiply;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Add);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_NumpadAdd;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Subtract);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_NumpadSubtract;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Separator);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_NumpadPeriod;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_KP_Divide);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_NumpadDivide;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F1);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F1;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F2);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F2;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F3);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F3;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F4);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F4;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F5);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F5;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F6);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F6;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F7);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F7;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F8);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F8;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F9);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F9;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F10);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F10;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F11);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F11;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_F12);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_F12;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Num_Lock);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_NumLock;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_Scroll_Lock);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_ScrollLock;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_semicolon);
if(keycode)if(keycode[1]>0)local_k_map[(uint8_t)max(min(keycode[1],0xff),0)]=Key_SemiColon;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_equal);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Equal;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_comma);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Comma;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_minus);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Dash;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_period);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_Period;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_slash);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_ForwardSlash;
if(keycode)if(keycode[1]>0)local_k_map[(uint8_t)max(min(keycode[1],0xff),0)]=Key_ForwardSlash;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_grave);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_GraveAccent;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_bracketleft);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_OpenBracket;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_backslash);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_BackSlash;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_bracketright);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_CloseBraket;free(keycode);
keycode=xcb_key_symbols_get_keycode(keySymbols, XK_apostrophe);
if(keycode)local_k_map[(uint8_t)max(min(keycode[0],0xff),0)]=Key_SingleQuote;free(keycode);
xcb_key_symbols_free( keySymbols );
}
|
danilw/vulkan-shadertoy-launcher
|
build_scripts/yariv/main.c
|
<reponame>danilw/vulkan-shadertoy-launcher
#include <stdio.h>
#include <string.h>
#include "yariv.h"
void *spirv;
size_t spirv_size;
static void replacestr(char *line, const char *search, const char *replace)
{
char *sp;
if ((sp = strstr(line, search)) == NULL) {
return;
}
int search_len = strlen(search);
int replace_len = strlen(replace);
int tail_len = strlen(sp+search_len);
memmove(sp+replace_len,sp+search_len,tail_len+1);
memcpy(sp, replace, replace_len);
}
int main(int argc,char* argv[]) {
if(argc > 2) {
printf("Too many arguments supplied. One argument expected.\n");
return 0;
}
if(argc == 1) {
printf("One argument expected.\n");
return 0;
}
if(strstr(argv[1], ".spv") == NULL){
printf("error in file name, need file.spv \n");
return 0;
}
FILE *f = fopen(argv[1], "rb");
if (f==NULL){
printf("File not found.\n");
return 0;
}
fseek(f, 0, SEEK_END);
spirv_size = ftell(f);
fseek(f, 0, SEEK_SET);
spirv = malloc(spirv_size);
fread(spirv, 1, spirv_size, f);
fclose(f);
void *out_yariv;
size_t out_yariv_size;
out_yariv_size = yariv_encode_size(yariv_encode_flags_strip, spirv, spirv_size);
out_yariv = malloc(out_yariv_size);
yariv_encode(yariv_encode_flags_strip, out_yariv, out_yariv_size, spirv, spirv_size);
char str[200];
strcpy(str,argv[1]);
replacestr(str,".spv",".yariv");
FILE *fp;
fp = fopen(str, "w");
fwrite(out_yariv,out_yariv_size,1,fp);
fclose(fp);
free(out_yariv);
printf("converted %s to %s yariv_size %ld \n",argv[1],str,out_yariv_size);
}
|
danilw/vulkan-shadertoy-launcher
|
launcher/main.c
|
// Danil, 2021+ Vulkan shadertoy launcher, self https://github.com/danilw/vulkan-shadertoy-launcher
#include <stdio.h>
#include <stdlib.h>
// USEFUL defines (list, use search to see what they do)
// NO_RESIZE_BUF
// CUSTOM_BUF_SIZE
// USE_stb_image
// OFFSCREEN_BUFFERS
// IMAGE_TEXTURES
// USE_MIPMAPS
// YARIV_SHADER
// buffers is VK_FORMAT_R32G32B32A32_SFLOAT
// FPS_LOCK(30) hotkey function 30 FPS lock (no Vsync)
// check_hotkeys function where hotkeys defined
// Discard disabled, to make it work if needed change VK_C_CLEAR to VK_KEEP in this file (works in buffers)
// define to not resize offscreen-buf on window resize (buffer size will be same as window on startup)
// #define NO_RESIZE_BUF
// if you need custom static buffer size (iResolution unique to each buffer and will be equal to this value in buffers)
// #define CUSTOM_BUF_SIZE {.width = 256, .height = 256,}
#if defined(VK_USE_PLATFORM_XCB_KHR)||defined(VK_USE_PLATFORM_WAYLAND_KHR)
#include <unistd.h>
#endif
#ifdef _WIN32
#pragma comment(linker, "/subsystem:windows")
#endif
#include <time.h>
#include "../vk_utils/vk_utils.h"
#include "../vk_utils/vk_render_helper.h"
#include "../os_utils/utils.h"
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
static int resize_size[2] = {1280, 720}; // in Wayland surface should set own size
#endif
static bool main_image_srgb = false; // srgb surface fix
// USE_stb_image this define to NOT use stb_image.h (compiled size will be 15Kb smaller)
// when stb_image.h not used - every image is empty(vec4(0.0)) 1x1 pixel look textures.h texture_empty
//#define USE_stb_image
#ifdef USE_stb_image
// using stb_image
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_THREAD_LOCALS
#define STBI_ONLY_PNG
#include "stb_image.h"
#endif
// numbers buffers <*.frag> files
// number of buffers to create, any number(>0), if you need 0 use https://github.com/danilw/vulkan-shader-launcher
// names shaders/spv/<file>.spv look files names in that folder
#define OFFSCREEN_BUFFERS 4
// number of images(>0)
// names textures/<X>.png X start from 1
#define IMAGE_TEXTURES 4
// linear or mipmap for textures
#define USE_MIPMAPS true
// keyboard is texture that send from this data
static bool keyboard_map[0xff][3] = {0}; //[ASCII code][0: current state of key, 1: Keypress, 2: toggle for key]
static uint8_t keyboard_texture[256 * 3 * 4] = {0}; // texture
static bool keyboard_need_update = false;
static bool keyboard_draw = false;
// update to 2021 Shadertoy iMouse.w change https://www.shadertoy.com/view/llySRh (comments)
static bool last_iMousel_clicked[2] = {false, false};
// do not edit, it just to see where keyboard texture used
#define iKeyboard 1
// to build-in compressed shaders into bin(exe) file
// used OFFSCREEN_BUFFERS size, names of .hex files should be set manually(and edit yariv_shaders[]), this example using 4 buffers same as on shadertoy
//#define YARIV_SHADER
#ifdef YARIV_SHADER
const unsigned char buf_fs_code[] = {
#include "../yariv_shaders/bin/buf.frag.hex"
};
const unsigned char buf1_fs_code[] = {
#include "../yariv_shaders/bin/buf1.frag.hex"
};
const unsigned char buf2_fs_code[] = {
#include "../yariv_shaders/bin/buf2.frag.hex"
};
const unsigned char buf3_fs_code[] = {
#include "../yariv_shaders/bin/buf3.frag.hex"
};
const unsigned char buf_vs_code[] = {
#include "../yariv_shaders/bin/buf.vert.hex"
};
const unsigned char fs_code[] = {
#include "../yariv_shaders/bin/main.frag.hex"
};
const unsigned char vs_code[] = {
#include "../yariv_shaders/bin/main.vert.hex"
};
const unsigned char *yariv_shaders[] = {
buf_fs_code, buf1_fs_code, buf2_fs_code, buf3_fs_code
};
const int yariv_shaders_size[] = {
sizeof(buf_fs_code), sizeof(buf1_fs_code), sizeof(buf2_fs_code), sizeof(buf3_fs_code)
};
#endif
struct shaders_push_constants
{
float iMouse[4];
float iDate[4];
int iMouse_lr[2];
float iResolution[2];
int debugdraw; // look function check_hotkeys
int pCustom; //custom data
float iTime;
float iTimeDelta;
int iFrame;
};
enum
{
BUFFER_VERTICES = 0,
BUFFER_INDICES = 1,
};
enum
{
SHADER_MAIN_VERTEX = 0,
SHADER_MAIN_FRAGMENT = 1,
};
struct render_data
{
struct objects
{
struct vertex
{
float pos[3];
} vertices[4];
uint16_t indices[4];
} objects;
struct shaders_push_constants push_constants;
struct vk_image images[IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard];
struct vk_buffer buffers[2];
struct vk_shader shaders[2 + OFFSCREEN_BUFFERS * 2];
struct vk_graphics_buffers *main_gbuffers;
struct vk_offscreen_buffers *buf_obuffers;
VkRenderPass buf_render_pass[OFFSCREEN_BUFFERS];
struct vk_layout buf_layout[OFFSCREEN_BUFFERS];
struct vk_pipeline buf_pipeline[OFFSCREEN_BUFFERS];
VkDescriptorSet buf_desc_set[OFFSCREEN_BUFFERS];
VkRenderPass main_render_pass;
struct vk_layout main_layout;
struct vk_pipeline main_pipeline;
VkDescriptorSet main_desc_set;
};
struct render_data render_data = {
.main_gbuffers = NULL,
.buf_obuffers = NULL,
};
VkInstance vk;
struct vk_physical_device phy_dev;
struct vk_device dev;
struct vk_swapchain swapchain = {0};
struct app_os_window os_window;
struct vk_render_essentials essentials;
VkFence offscreen_fence = VK_NULL_HANDLE;
VkQueue offscreen_queue[OFFSCREEN_BUFFERS] = {VK_NULL_HANDLE};
VkCommandBuffer offscreen_cmd_buffer[OFFSCREEN_BUFFERS] = {VK_NULL_HANDLE};
VkSemaphore wait_buf_sem = VK_NULL_HANDLE, wait_main_sem = VK_NULL_HANDLE;
bool first_submission = true;
bool enterFullscreen();
#if defined(VK_USE_PLATFORM_WIN32_KHR)
#include <shellapi.h>
static HWND chWnd;
static void check_hotkeys(struct app_os_window *os_window);
static void update_key_map(int w, int h, bool val);
static void update_keypress();
static bool render_loop_draw(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_swapchain *swapchain,
struct app_os_window *os_window);
static bool on_window_resize(struct vk_physical_device *phy_dev, struct vk_device *dev,
struct vk_render_essentials *essentials, struct vk_swapchain *swapchain,
struct render_data *render_data, struct app_os_window *os_window);
#include "../os_utils/os_win_utils.h"
#elif defined(VK_USE_PLATFORM_XCB_KHR)
static void update_key_map(int w, int h, bool val);
#include "../os_utils/xcb_x11_utils.h"
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
static void update_key_map(int w, int h, bool val);
#include "../os_utils/wayland_utils.h"
#endif
#include "textures.h"
static void update_key_map(int w, int h, bool val)
{
keyboard_map[w][h] = val;
keyboard_texture[(h * 256 + w) * 4] = val ? 0xff : 0x00;
}
static void update_keypress()
{
if (keyboard_need_update)
keyboard_draw = true;
else
keyboard_draw = false;
if (keyboard_need_update)
{
for (uint8_t i = 0; i < 0xff; i++)
{
update_key_map(i, 1, false);
}
}
keyboard_need_update = false;
}
static bool update_iKeyboard_texture(struct vk_physical_device *phy_dev, struct vk_device *dev,
struct vk_render_essentials *essentials, struct render_data *render_data)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
if (!keyboard_draw)
return true;
if (!essentials->first_render)
{
res = vkWaitForFences(dev->device, 1, &essentials->exec_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Wait for fence failed\n");
return false;
}
}
retval =
vk_render_update_texture(phy_dev, dev, essentials, &render_data->images[IMAGE_TEXTURES + OFFSCREEN_BUFFERS],
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, keyboard_texture, "iKeyboard");
if (!vk_error_is_success(&retval))
return false;
return true;
}
static bool fullscreen = false;
static bool fs_once = true;
static void check_hotkeys(struct app_os_window *os_window)
{
const int Key_Escape = 27, Key_Space = 32, Key_0 = 48, Key_1 = 49, Key_f = 70, Key_f11 = 122;
if (keyboard_map[Key_Escape][1])
os_window->app_data.quit = true;
if (keyboard_map[Key_Space][1])
os_window->app_data.pause = !os_window->app_data.pause;
if (keyboard_map[Key_0][1])
os_window->app_data.drawdebug = !os_window->app_data.drawdebug;
if (keyboard_map[Key_1][1])
os_window->fps_lock = !os_window->fps_lock;
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
//example resize event for Wayland
if (keyboard_map[Key_f][1]){
os_window->resize_event = true;
static bool switch_res=true;
if(switch_res){
switch_res=false;
os_window->app_data.iResolution[0]=1920;
os_window->app_data.iResolution[1]=1080;
}else{
switch_res=true;
os_window->app_data.iResolution[0]=1280;
os_window->app_data.iResolution[1]=720;
}
}
#else
if (keyboard_map[Key_f][1]||keyboard_map[Key_f11][1]) {
if (fs_once) { enterFullscreen(); fs_once = false; }
}
else fs_once = true;
#endif
}
static vk_error allocate_render_data(struct vk_physical_device *phy_dev, struct vk_device *dev,
struct vk_swapchain *swapchain, struct vk_render_essentials *essentials,
struct render_data *render_data, bool reload_shaders)
{
static bool load_once = false;
vk_error retval = VK_ERROR_NONE;
VkResult res;
if (!load_once)
{
render_data->buffers[BUFFER_VERTICES] = (struct vk_buffer){
.size = sizeof render_data->objects.vertices,
.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
.host_visible = false,
};
render_data->buffers[BUFFER_INDICES] = (struct vk_buffer){
.size = sizeof render_data->objects.indices,
.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
.host_visible = false,
};
retval = vk_create_buffers(phy_dev, dev, render_data->buffers, 2);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Failed to create vertex, index and transformation buffers\n");
return retval;
}
}
if (!load_once)
{
render_data->objects = (struct objects){
.vertices =
{
[0] =
(struct vertex){
.pos = {3.001, 1.001, 0.0},
},
[1] =
(struct vertex){
.pos = {-1.001, -3.001, 0.0},
},
[2] =
(struct vertex){
.pos = {-1.001, 1.001, 0.0},
},
},
.indices =
{
0,
1,
2,
},
};
retval = vk_render_init_buffer(phy_dev, dev, essentials, &render_data->buffers[BUFFER_VERTICES],
render_data->objects.vertices, "vertex");
if (!vk_error_is_success(&retval))
return retval;
retval = vk_render_init_buffer(phy_dev, dev, essentials, &render_data->buffers[BUFFER_INDICES],
render_data->objects.indices, "index");
if (!vk_error_is_success(&retval))
return retval;
for (uint32_t i = 0; i < IMAGE_TEXTURES; i++)
{
char txt[255] = {0};
sprintf(txt, "textures/%d.png", i + 1);
#ifdef USE_stb_image
retval = init_texture_file(phy_dev, dev, essentials, &render_data->images[i], txt, USE_MIPMAPS);
if (!vk_error_is_success(&retval))retval = texture_empty(phy_dev, dev, essentials, &render_data->images[i], 1, 1);
#else
retval = texture_empty(phy_dev, dev, essentials, &render_data->images[i], 1, 1);
if (!vk_error_is_success(&retval))
return retval;
#endif
}
for (uint32_t i = IMAGE_TEXTURES; i < IMAGE_TEXTURES + OFFSCREEN_BUFFERS; i++)
{
retval = texture_empty(phy_dev, dev, essentials, &render_data->images[i], 1, 1);
if (!vk_error_is_success(&retval))
return retval;
}
retval = texture_empty(phy_dev, dev, essentials, &render_data->images[IMAGE_TEXTURES + OFFSCREEN_BUFFERS], 256,
3); // iKeyboard
if (!vk_error_is_success(&retval))
return retval;
}
if ((!load_once) || (reload_shaders))
{
render_data->shaders[SHADER_MAIN_VERTEX] = (struct vk_shader){
.spirv_file = "shaders/spv/main.vert.spv",
.stage = VK_SHADER_STAGE_VERTEX_BIT,
};
render_data->shaders[SHADER_MAIN_FRAGMENT] = (struct vk_shader){
.spirv_file = "shaders/spv/main.frag.spv",
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
};
char txt[OFFSCREEN_BUFFERS][255] = {0};
for (uint32_t i = 0; i < OFFSCREEN_BUFFERS * 2; i += 2)
{
render_data->shaders[i + 2] = (struct vk_shader){
.spirv_file = "shaders/spv/buf.vert.spv",
.stage = VK_SHADER_STAGE_VERTEX_BIT,
};
if (i > 0)
{
sprintf(txt[i / 2], "shaders/spv/buf%d.frag.spv", i / 2);
}
else
{
sprintf(txt[i / 2], "shaders/spv/buf.frag.spv");
}
render_data->shaders[i + 2 + 1] = (struct vk_shader){
.spirv_file = txt[i / 2],
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
};
}
#ifdef YARIV_SHADER
retval = vk_load_shader_yariv(dev, (const uint32_t *)vs_code, &render_data->shaders[SHADER_MAIN_VERTEX].shader,
sizeof(vs_code));
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not load the shaders\n");
return retval;
}
retval = vk_load_shader_yariv(dev, (const uint32_t *)fs_code,
&render_data->shaders[SHADER_MAIN_FRAGMENT].shader, sizeof(fs_code));
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not load the shaders\n");
return retval;
}
for (uint32_t i = 0; i < OFFSCREEN_BUFFERS * 2; i += 2)
{
retval = vk_load_shader_yariv(dev, (const uint32_t *)buf_vs_code,
&render_data->shaders[i + 2].shader, sizeof(buf_vs_code));
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not load the shaders\n");
return retval;
}
retval = vk_load_shader_yariv(dev, (const uint32_t *)(yariv_shaders[i/2]),
&render_data->shaders[i + 2 + 1].shader, yariv_shaders_size[i/2]);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not load the shaders\n");
return retval;
}
}
#else
retval = vk_load_shaders(dev, render_data->shaders, 2 + OFFSCREEN_BUFFERS * 2);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not load the shaders\n");
return retval;
}
#endif
}
struct VkExtent2D init_size;
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
init_size.width = resize_size[0];
init_size.height = resize_size[1];
#else
init_size.width = swapchain->surface_caps.currentExtent.width;
init_size.height = swapchain->surface_caps.currentExtent.height;
#endif
render_data->main_gbuffers = malloc(essentials->image_count * sizeof *render_data->main_gbuffers);
for (uint32_t i = 0; i < essentials->image_count; ++i)
render_data->main_gbuffers[i] = (struct vk_graphics_buffers){
.surface_size = init_size,
.swapchain_image = essentials->images[i],
};
#ifdef NO_RESIZE_BUF
if (!load_once)
{
#endif
render_data->buf_obuffers = malloc(2 * (sizeof(*render_data->buf_obuffers)) * OFFSCREEN_BUFFERS);
for (uint32_t i = 0; i < 2 * OFFSCREEN_BUFFERS; i++)
render_data->buf_obuffers[i] = (struct vk_offscreen_buffers)
{
#if defined(CUSTOM_BUF_SIZE) && defined(NO_RESIZE_BUF)
.surface_size = (struct VkExtent2D)CUSTOM_BUF_SIZE,
#else
.surface_size = init_size,
#endif
};
#ifdef NO_RESIZE_BUF
}
#endif
// 8bit BGRA for main_image VK_FORMAT_B8G8R8A8_UNORM
if(swapchain->surface_format.format!=VK_FORMAT_B8G8R8A8_UNORM)main_image_srgb=true;
retval = vk_create_graphics_buffers(phy_dev, dev, swapchain->surface_format.format, render_data->main_gbuffers,
essentials->image_count, &render_data->main_render_pass, VK_C_CLEAR,
VK_WITHOUT_DEPTH);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not create graphics buffers\n");
return retval;
}
#ifdef NO_RESIZE_BUF
if (!load_once)
{
#endif
for (uint32_t i = 0; i < OFFSCREEN_BUFFERS; i++)
{
// 32 bit format RGBA for buffers VK_FORMAT_R32G32B32A32_SFLOAT
retval = vk_create_offscreen_buffers(phy_dev, dev, VK_FORMAT_R32G32B32A32_SFLOAT,
&render_data->buf_obuffers[i * 2], 2, &render_data->buf_render_pass[i],
VK_C_CLEAR, VK_WITHOUT_DEPTH, true);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not create off-screen buffers\n");
return retval;
}
}
#ifdef NO_RESIZE_BUF
}
#endif
struct vk_image **image_pointer; //&render_data->buf_obuffers[2].color
image_pointer = malloc(1 * sizeof(struct vk_image *) * (IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard));
for (uint32_t i = 0; i < IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard; i++)
{
image_pointer[i] = &render_data->images[i];
}
VkPushConstantRange push_constant_range = {
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.offset = 0,
.size = sizeof render_data->push_constants,
};
/*******************
* BUF PART *
*******************/
#ifdef NO_RESIZE_BUF
if (!load_once)
{
#endif
for (int i = 0; i < OFFSCREEN_BUFFERS; i++)
{
/* Layouts */
struct vk_resources resources = {
.images = *image_pointer,
.image_count = IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard,
.buffers = render_data->buffers,
.buffer_count = 2,
.shaders = &render_data->shaders[SHADER_MAIN_FRAGMENT + 1 + i * 2],
.shader_count = 2,
.push_constants = &push_constant_range,
.push_constant_count = 1,
.render_pass = render_data->buf_render_pass[i],
};
render_data->buf_layout[i] = (struct vk_layout){
.resources = &resources,
};
uint32_t img_patern[3] = {IMAGE_TEXTURES, OFFSCREEN_BUFFERS, iKeyboard};
retval = vk_make_graphics_layouts(dev, &render_data->buf_layout[i], 1, true, img_patern, 3);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "BUF: Could not create descriptor set or pipeline layouts\n");
return retval;
}
/* Pipeline */
VkVertexInputBindingDescription vertex_binding = {
.binding = 0,
.stride = sizeof *render_data->objects.vertices,
.inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
};
VkVertexInputAttributeDescription vertex_attributes[1] = {
[0] =
{
.location = 0,
.binding = 0,
.format = VK_FORMAT_R32G32B32_SFLOAT,
.offset = 0,
},
};
render_data->buf_pipeline[i] = (struct vk_pipeline){
.layout = &render_data->buf_layout[i],
.vertex_input_state =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &vertex_binding,
.vertexAttributeDescriptionCount = 1,
.pVertexAttributeDescriptions = vertex_attributes,
},
.input_assembly_state =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
},
.tessellation_state =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO,
},
.thread_count = 1,
};
retval = vk_make_graphics_pipelines(dev, &render_data->buf_pipeline[i], 1, false);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "BUF: Could not create graphics pipeline\n");
return retval;
}
/* Descriptor Set */
VkDescriptorSetAllocateInfo set_info = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.descriptorPool = render_data->buf_pipeline[i].set_pool,
.descriptorSetCount = 1,
.pSetLayouts = &render_data->buf_layout[i].set_layout,
};
res = vkAllocateDescriptorSets(dev->device, &set_info, &render_data->buf_desc_set[i]);
retval = VK_ERROR_NONE;
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "BUF: Could not allocate descriptor set from pool\n");
return retval;
}
}
#ifdef NO_RESIZE_BUF
}
#endif
/*******************
* MAIN_IMAGE PART *
*******************/
{
/* Layouts */
struct vk_resources resources = {
.images = *image_pointer,
.image_count = IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard,
.buffers = render_data->buffers,
.buffer_count = 2,
.shaders = &render_data->shaders[SHADER_MAIN_VERTEX],
.shader_count = 2,
.push_constants = &push_constant_range,
.push_constant_count = 1,
.render_pass = render_data->main_render_pass,
};
render_data->main_layout = (struct vk_layout){
.resources = &resources,
};
uint32_t img_patern[3] = {IMAGE_TEXTURES, OFFSCREEN_BUFFERS, iKeyboard};
retval = vk_make_graphics_layouts(dev, &render_data->main_layout, 1, true, img_patern, 3);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not create descriptor set or pipeline layouts\n");
return retval;
}
/* Pipeline */
VkVertexInputBindingDescription vertex_binding = {
.binding = 0,
.stride = sizeof *render_data->objects.vertices,
.inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
};
VkVertexInputAttributeDescription vertex_attributes[1] = {
[0] =
{
.location = 0,
.binding = 0,
.format = VK_FORMAT_R32G32B32_SFLOAT,
.offset = 0,
},
};
render_data->main_pipeline = (struct vk_pipeline){
.layout = &render_data->main_layout,
.vertex_input_state =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &vertex_binding,
.vertexAttributeDescriptionCount = 1,
.pVertexAttributeDescriptions = vertex_attributes,
},
.input_assembly_state =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
},
.tessellation_state =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO,
},
.thread_count = 1,
};
retval = vk_make_graphics_pipelines(dev, &render_data->main_pipeline, 1, false);
if (!vk_error_is_success(&retval))
{
vk_error_printf(&retval, "Could not create graphics pipeline\n");
return retval;
}
/* Descriptor Set */
VkDescriptorSetAllocateInfo set_info = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.descriptorPool = render_data->main_pipeline.set_pool,
.descriptorSetCount = 1,
.pSetLayouts = &render_data->main_layout.set_layout,
};
res = vkAllocateDescriptorSets(dev->device, &set_info, &render_data->main_desc_set);
retval = VK_ERROR_NONE;
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Could not allocate descriptor set from pool\n");
return retval;
}
}
load_once = true;
free(image_pointer);
return retval;
}
static void free_render_data(struct vk_device *dev, struct vk_render_essentials *essentials,
struct render_data *render_data)
{
vkDeviceWaitIdle(dev->device);
vk_free_pipelines(dev, &render_data->main_pipeline, 1);
vk_free_layouts(dev, &render_data->main_layout, 1);
vk_free_pipelines(dev, render_data->buf_pipeline, OFFSCREEN_BUFFERS);
vk_free_layouts(dev, render_data->buf_layout, OFFSCREEN_BUFFERS);
vk_free_images(dev, render_data->images, IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard);
vk_free_buffers(dev, render_data->buffers, 2);
vk_free_shaders(dev, render_data->shaders, 2 + OFFSCREEN_BUFFERS * 2);
for (int i = 0; i < OFFSCREEN_BUFFERS; i++)
{
vk_free_offscreen_buffers(dev, &render_data->buf_obuffers[i * 2], 2, render_data->buf_render_pass[i]);
}
vk_free_graphics_buffers(dev, render_data->main_gbuffers, essentials->image_count, render_data->main_render_pass);
free(render_data->main_gbuffers);
free(render_data->buf_obuffers);
}
// TO DO FREE BZUF FENCE LOOP
static void exit_cleanup_render_loop(struct vk_device *dev, struct vk_render_essentials *essentials,
struct render_data *render_data, VkSemaphore wait_buf_sem,
VkSemaphore wait_main_sem, VkFence offscreen_fence)
{
vkDeviceWaitIdle(dev->device);
if (offscreen_fence != VK_NULL_HANDLE)
vkDestroyFence(dev->device, offscreen_fence, NULL);
if (wait_main_sem != VK_NULL_HANDLE)
vkDestroySemaphore(dev->device, wait_main_sem, NULL);
if (wait_buf_sem != VK_NULL_HANDLE)
vkDestroySemaphore(dev->device, wait_buf_sem, NULL);
free_render_data(dev, essentials, render_data);
vk_render_cleanup_essentials(essentials, dev);
}
static void render_loop_init(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_swapchain *swapchain,
struct app_os_window *os_window)
{
int res;
vk_error retval = VK_ERROR_NONE;
static bool once = false;
res = vk_render_get_essentials(&essentials, phy_dev, dev, swapchain);
if (res)
{
vk_render_cleanup_essentials(&essentials, dev);
return;
}
if (!once)
{
uint32_t *presentable_queues = NULL;
uint32_t presentable_queue_count = 0;
retval =
vk_get_presentable_queues(phy_dev, dev, swapchain->surface, &presentable_queues, &presentable_queue_count);
if (!vk_error_is_success(&retval) || presentable_queue_count == 0)
{
printf(
"No presentable queue families. You should have got this error in vk_render_get_essentials before.\n");
free(presentable_queues);
vk_render_cleanup_essentials(&essentials, dev);
return;
}
for (uint32_t i = 0; i < OFFSCREEN_BUFFERS; i++)
{
offscreen_queue[i] =
dev->command_pools[presentable_queues[0]].queues[0]; // used only one presentable queue always
offscreen_cmd_buffer[i] = dev->command_pools[presentable_queues[0]].buffers[1 + i];
}
free(presentable_queues);
}
retval =
allocate_render_data(phy_dev, dev, swapchain, &essentials, &render_data, os_window->reload_shaders_on_resize);
if (!vk_error_is_success(&retval))
{
free_render_data(dev, &essentials, &render_data);
vk_render_cleanup_essentials(&essentials, dev);
return;
}
#ifdef NO_RESIZE_BUF
if (!once)
{
#endif
for (int i = 0; i < OFFSCREEN_BUFFERS * 2; i++)
{
retval = vk_render_transition_images(dev, &essentials, &render_data.buf_obuffers[i].color, 1,
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_ASPECT_COLOR_BIT, "off-screen color");
if (!vk_error_is_success(&retval))
{
free_render_data(dev, &essentials, &render_data);
vk_render_cleanup_essentials(&essentials, dev);
return;
}
}
#ifdef NO_RESIZE_BUF
}
#endif
if (!once)
{
VkSemaphoreCreateInfo sem_info = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
};
res = vkCreateSemaphore(dev->device, &sem_info, NULL, &wait_buf_sem);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to create wait-render semaphore\n");
exit_cleanup_render_loop(dev, &essentials, &render_data, wait_buf_sem, wait_main_sem, offscreen_fence);
return;
}
res = vkCreateSemaphore(dev->device, &sem_info, NULL, &wait_main_sem);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to create wait-post-process semaphore\n");
exit_cleanup_render_loop(dev, &essentials, &render_data, wait_buf_sem, wait_main_sem, offscreen_fence);
return;
}
VkFenceCreateInfo fence_info = {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
};
res = vkCreateFence(dev->device, &fence_info, NULL, &offscreen_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to create fence\n");
exit_cleanup_render_loop(dev, &essentials, &render_data, wait_buf_sem, wait_main_sem, offscreen_fence);
return;
}
}
once = true;
os_window->prepared = true;
os_window->resize_event = false;
return;
}
static void exit_cleanup(VkInstance vk, struct vk_device *dev, struct vk_swapchain *swapchain,
struct app_os_window *os_window)
{
if(swapchain)vk_free_swapchain(vk, dev, swapchain);
if(dev)vk_cleanup(dev);
#if defined(VK_USE_PLATFORM_XCB_KHR)
xcb_destroy_window(os_window->connection, os_window->xcb_window);
xcb_disconnect(os_window->connection);
free(os_window->atom_wm_delete_window);
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
xdg_toplevel_destroy(os_window->xdg_toplevel);
xdg_surface_destroy(os_window->xdg_surface);
wl_keyboard_destroy(os_window->keyboard);
wl_pointer_destroy(os_window->pointer);
wl_seat_destroy(os_window->seat);
wl_surface_destroy(os_window->surface);
xdg_wm_base_destroy(os_window->shell);
wl_compositor_destroy(os_window->compositor);
wl_registry_destroy(os_window->registry);
wl_display_disconnect(os_window->display);
#endif
vk_exit(vk);
}
static bool on_window_resize(struct vk_physical_device *phy_dev, struct vk_device *dev,
struct vk_render_essentials *essentials, struct vk_swapchain *swapchain,
struct render_data *render_data, struct app_os_window *os_window)
{
vk_error res = VK_ERROR_NONE;
if (!os_window->prepared)
return true;
vkDeviceWaitIdle(dev->device);
os_window->prepared = false;
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
resize_size[0] = os_window->app_data.iResolution[0];
resize_size[1] = os_window->app_data.iResolution[1];
#endif
vk_free_pipelines(dev, &render_data->main_pipeline, 1);
vk_free_graphics_buffers(dev, render_data->main_gbuffers, essentials->image_count, render_data->main_render_pass);
vk_free_layouts(dev, &render_data->main_layout, 1);
#ifndef NO_RESIZE_BUF
vk_free_pipelines(dev, render_data->buf_pipeline, OFFSCREEN_BUFFERS);
for (int i = 0; i < OFFSCREEN_BUFFERS; i++)
{
vk_free_offscreen_buffers(dev, &render_data->buf_obuffers[i * 2], 2, render_data->buf_render_pass[i]);
}
vk_free_layouts(dev, render_data->buf_layout, OFFSCREEN_BUFFERS);
#endif
if (os_window->reload_shaders_on_resize)
vk_free_shaders(dev, render_data->shaders, 2 + OFFSCREEN_BUFFERS * 2);
vk_render_cleanup_essentials(essentials, dev);
free(render_data->main_gbuffers);
#ifndef NO_RESIZE_BUF
free(render_data->buf_obuffers);
#endif
res = vk_get_swapchain(vk, phy_dev, dev, swapchain, os_window, 1, &os_window->present_mode);
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not create surface and swapchain\n");
exit_cleanup(vk, dev, swapchain, os_window);
return false;
}
render_loop_init(phy_dev, dev, swapchain, os_window);
return true;
}
void update_params(struct app_data_struct *app_data, bool fps_lock)
{
float rdelta = 0;
if (fps_lock)
FPS_LOCK(30);
float delta = update_fps_delta();
if (!app_data->pause)
{
app_data->iTime += delta;
}
app_data->iFrame++;
app_data->iTimeDelta = delta;
float pause_time = pres_pause(app_data->pause);
}
void set_push_constants(struct app_os_window *os_window)
{
struct my_time_struct my_time;
get_local_time(&my_time);
float day_sec = ((float)my_time.msec) / 1000.0 + my_time.sec + my_time.min * 60 + my_time.hour * 3600;
last_iMousel_clicked[0] = last_iMousel_clicked[1];
last_iMousel_clicked[1] = os_window->app_data.iMouse_click[0];
render_data.push_constants = (struct shaders_push_constants){
.iResolution[0] = os_window->app_data.iResolution[0],
.iResolution[1] = os_window->app_data.iResolution[1],
.iTime = os_window->app_data.iTime,
.iTimeDelta = os_window->app_data.iTimeDelta,
.iFrame = os_window->app_data.iFrame,
.iMouse[0] = os_window->app_data.iMouse[0],
.iMouse[1] = os_window->app_data.iMouse[1],
.iMouse[2] = os_window->app_data.iMouse_lclick[0],
.iMouse[3] = (last_iMousel_clicked[0]) ? -abs(os_window->app_data.iMouse_lclick[1])
: os_window->app_data.iMouse_lclick[1],
.iMouse_lr[0] = (int)os_window->app_data.iMouse_click[0],
.iMouse_lr[1] = (int)os_window->app_data.iMouse_click[1],
.iDate[0] = my_time.year,
.iDate[1] = my_time.month,
.iDate[2] = my_time.day,
.iDate[3] = day_sec,
.debugdraw = (int)os_window->app_data.drawdebug,
.pCustom=(os_window->app_data.pause?1:0)+(main_image_srgb?10:0),
};
}
void update_push_constants_window_size(struct app_os_window *os_window)
{
render_data.push_constants.iMouse[0] = os_window->app_data.iMouse[0];
render_data.push_constants.iMouse[1] = os_window->app_data.iMouse[1];
render_data.push_constants.iMouse[2] = os_window->app_data.iMouse_lclick[0];
render_data.push_constants.iMouse[3] =
(last_iMousel_clicked[0]) ? -abs(os_window->app_data.iMouse_lclick[1]) : os_window->app_data.iMouse_lclick[1],
render_data.push_constants.iResolution[0] = os_window->app_data.iResolution[0];
render_data.push_constants.iResolution[1] = os_window->app_data.iResolution[1];
}
#define sign(x) ((x > 0) ? 1 : ((x < 0) ? -1 : 0))
void update_push_constants_local_size(float width, float height)
{
render_data.push_constants.iMouse[0] =
((render_data.push_constants.iMouse[0] / render_data.push_constants.iResolution[1]) -
0.5 * (render_data.push_constants.iResolution[0] / render_data.push_constants.iResolution[1])) *
height +
0.5 * width;
render_data.push_constants.iMouse[1] =
((render_data.push_constants.iMouse[1] / render_data.push_constants.iResolution[1]) - 0.5) * height +
0.5 * height;
render_data.push_constants.iMouse[2] =
sign(render_data.push_constants.iMouse[2]) *
(((fabs(render_data.push_constants.iMouse[2]) / render_data.push_constants.iResolution[1]) -
0.5 * (render_data.push_constants.iResolution[0] / render_data.push_constants.iResolution[1])) *
height +
0.5 * width);
render_data.push_constants.iMouse[3] =
sign(render_data.push_constants.iMouse[3]) *
(((fabs(render_data.push_constants.iMouse[3]) / render_data.push_constants.iResolution[1]) - 0.5) * height +
0.5 * height);
render_data.push_constants.iResolution[0] = width;
render_data.push_constants.iResolution[1] = height;
}
static bool render_loop_buf(struct vk_physical_device *phy_dev, struct vk_device *dev,
struct vk_render_essentials *essentials, struct render_data *render_data,
VkCommandBuffer cmd_buffer, int render_index, int buffer_index,
struct app_data_struct *app_data)
{
vk_error retval = VK_ERROR_NONE;
VkResult res;
if ((!essentials->first_render) && (buffer_index == 0))
{
res = vkWaitForFences(dev->device, 1, &essentials->exec_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Wait for fence failed\n");
return false;
}
}
#ifdef NO_RESIZE_BUF
update_push_constants_local_size(render_data->buf_obuffers[render_index + buffer_index * 2].surface_size.width,
render_data->buf_obuffers[render_index + buffer_index * 2].surface_size.height);
#endif
vkResetCommandBuffer(cmd_buffer, 0);
VkCommandBufferBeginInfo begin_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
};
res = vkBeginCommandBuffer(cmd_buffer, &begin_info);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "BUF: Couldn't even begin recording a command buffer\n");
return false;
};
VkImageMemoryBarrier image_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
.dstAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = render_data->buf_obuffers[render_index + buffer_index * 2].color.image,
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
vkCmdPipelineBarrier(cmd_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, 0, NULL,
0, NULL, 1, &image_barrier);
VkClearValue clear_values = {
.color =
{
.float32 = {0.0, 0.0, 0.0, 0.0},
},
};
VkRenderPassBeginInfo pass_info = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
.renderPass = render_data->buf_render_pass[buffer_index],
.framebuffer = render_data->buf_obuffers[render_index + buffer_index * 2].framebuffer,
.renderArea =
{
.offset =
{
.x = 0,
.y = 0,
},
.extent = render_data->buf_obuffers[render_index + buffer_index * 2].surface_size,
},
.clearValueCount = 1,
.pClearValues = &clear_values,
};
vkCmdBeginRenderPass(cmd_buffer, &pass_info, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, render_data->buf_pipeline[buffer_index].pipeline);
int render_index_t[OFFSCREEN_BUFFERS];
for (int i = 0; i < OFFSCREEN_BUFFERS; i++)
{
if (i < buffer_index)
{
render_index_t[i] = render_index + i * 2;
}
else
{
render_index_t[i] = render_index - 1 + i * 2;
if (render_index_t[i] < i * 2)
render_index_t[i] = 1 + i * 2;
}
}
VkDescriptorImageInfo set_write_image_info[IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard] = {0};
for (uint32_t i = 0; i < IMAGE_TEXTURES; i++)
{
set_write_image_info[i] = (VkDescriptorImageInfo){
.sampler = render_data->images[i].sampler,
.imageView = render_data->images[i].view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
}
for (uint32_t i = 0; i < OFFSCREEN_BUFFERS; i++)
{
set_write_image_info[IMAGE_TEXTURES + i] = (VkDescriptorImageInfo){
.sampler = render_data->buf_obuffers[render_index_t[i]].color.sampler,
.imageView = render_data->buf_obuffers[render_index_t[i]].color.view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
}
set_write_image_info[IMAGE_TEXTURES + OFFSCREEN_BUFFERS] = (VkDescriptorImageInfo){
.sampler = render_data->images[IMAGE_TEXTURES + OFFSCREEN_BUFFERS].sampler,
.imageView = render_data->images[IMAGE_TEXTURES + OFFSCREEN_BUFFERS].view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
VkWriteDescriptorSet set_write[3] = {
[0] =
{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = render_data->buf_desc_set[buffer_index],
.dstBinding = 0,
.descriptorCount = IMAGE_TEXTURES,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &set_write_image_info[0],
},
[1] =
{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = render_data->buf_desc_set[buffer_index],
.dstBinding = IMAGE_TEXTURES,
.descriptorCount = OFFSCREEN_BUFFERS,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &set_write_image_info[IMAGE_TEXTURES],
},
[2] =
{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = render_data->buf_desc_set[buffer_index],
.dstBinding = IMAGE_TEXTURES + OFFSCREEN_BUFFERS,
.descriptorCount = iKeyboard,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &set_write_image_info[IMAGE_TEXTURES + OFFSCREEN_BUFFERS],
},
};
vkUpdateDescriptorSets(dev->device, 3, set_write, 0, NULL);
vkCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
render_data->buf_layout[buffer_index].pipeline_layout, 0, 1,
&render_data->buf_desc_set[buffer_index], 0, NULL);
VkDeviceSize vertices_offset = 0;
vkCmdBindVertexBuffers(cmd_buffer, 0, 1, &render_data->buffers[BUFFER_VERTICES].buffer, &vertices_offset);
vkCmdBindIndexBuffer(cmd_buffer, render_data->buffers[BUFFER_INDICES].buffer, 0, VK_INDEX_TYPE_UINT16);
VkViewport viewport = {
.x = 0,
.y = 0,
.width = render_data->buf_obuffers[render_index + buffer_index * 2].surface_size.width,
.height = render_data->buf_obuffers[render_index + buffer_index * 2].surface_size.height,
.minDepth = 0,
.maxDepth = 1,
};
vkCmdSetViewport(cmd_buffer, 0, 1, &viewport);
VkRect2D scissor = {
.offset =
{
.x = 0,
.y = 0,
},
.extent = render_data->buf_obuffers[render_index + buffer_index * 2].surface_size,
};
vkCmdSetScissor(cmd_buffer, 0, 1, &scissor);
vkCmdPushConstants(cmd_buffer, render_data->buf_layout[buffer_index].pipeline_layout, VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof render_data->push_constants, &render_data->push_constants);
vkCmdDrawIndexed(cmd_buffer, 4, 1, 0, 0, 0);
vkCmdEndRenderPass(cmd_buffer);
image_barrier = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = render_data->buf_obuffers[render_index + buffer_index * 2].color.image,
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
vkCmdPipelineBarrier(cmd_buffer, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0,
NULL, 0, NULL, 1, &image_barrier);
vkEndCommandBuffer(cmd_buffer);
return true;
}
static bool render_loop_draw(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_swapchain *swapchain,
struct app_os_window *os_window)
{
static int render_index = 0;
int res;
vk_error retval = VK_ERROR_NONE;
set_push_constants(os_window);
if (!update_iKeyboard_texture(phy_dev, dev, &essentials, &render_data))
return false;
for (int i = 0; i < OFFSCREEN_BUFFERS; i++)
{
if (!render_loop_buf(phy_dev, dev, &essentials, &render_data, offscreen_cmd_buffer[i], render_index, i,
&os_window->app_data))
{
printf("Error on rendering buffers \n");
return false;
}
update_push_constants_window_size(os_window);
if (i == 0)
{ // wait main screen
if (!first_submission)
{
res = vkWaitForFences(dev->device, 1, &offscreen_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Wait for main fence failed\n");
return false;
}
}
VkPipelineStageFlags wait_sem_stages[1] = {VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT};
VkSubmitInfo submit_info = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.waitSemaphoreCount = first_submission ? 0 : 1,
.pWaitSemaphores = &wait_main_sem,
.pWaitDstStageMask = wait_sem_stages,
.commandBufferCount = 1,
.pCommandBuffers = &offscreen_cmd_buffer[i],
.signalSemaphoreCount = 1,
.pSignalSemaphores = &wait_buf_sem,
};
res = vkResetFences(dev->device, 1, &offscreen_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to reset fence\n");
return false;
}
vkQueueSubmit(offscreen_queue[i], 1, &submit_info, offscreen_fence);
first_submission = false;
}
else
{ // wait last buf/shader in loop, if multi VkQueue supported
res = vkWaitForFences(dev->device, 1, &offscreen_fence, true, 1000000000);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Wait for buf fence failed\n");
return false;
}
VkPipelineStageFlags wait_sem_stages[1] = {VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT};
VkSubmitInfo submit_info = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.waitSemaphoreCount = 1,
.pWaitSemaphores = &wait_buf_sem,
.pWaitDstStageMask = wait_sem_stages,
.commandBufferCount = 1,
.pCommandBuffers = &offscreen_cmd_buffer[i],
.signalSemaphoreCount = 1,
.pSignalSemaphores = &wait_main_sem, // used main sem
};
res = vkResetFences(dev->device, 1, &offscreen_fence);
vk_error_set_vkresult(&retval, res);
if (res)
{
vk_error_printf(&retval, "Failed to reset fence\n");
return false;
}
vkQueueSubmit(offscreen_queue[i], 1, &submit_info, offscreen_fence);
VkSemaphore tmp_sem = wait_buf_sem;
wait_buf_sem = wait_main_sem;
wait_main_sem = tmp_sem;
}
}
uint32_t image_index;
res = vk_render_start(&essentials, dev, swapchain, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, &image_index);
if (res == VK_ERROR_OUT_OF_DATE_KHR)
{
os_window->resize_event = true;
res = 0;
first_submission = true;
return true;
}
else if (res == VK_ERROR_SURFACE_LOST_KHR)
{
vkDestroySurfaceKHR(vk, swapchain->surface, NULL);
retval = vk_create_surface(vk, &swapchain->surface, os_window);
if (!vk_error_is_success(&retval))
return false;
os_window->resize_event = true;
res = 0;
first_submission = true;
return true;
}
if (res)
return false;
VkClearValue clear_values = {
.color =
{
.float32 = {0.0, 0.0, 0.0, 0.0},
},
};
VkRenderPassBeginInfo pass_info = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
.renderPass = render_data.main_render_pass,
.framebuffer = render_data.main_gbuffers[image_index].framebuffer,
.renderArea =
{
.offset =
{
.x = 0,
.y = 0,
},
.extent = render_data.main_gbuffers[image_index].surface_size,
},
.clearValueCount = 1,
.pClearValues = &clear_values,
};
vkCmdBeginRenderPass(essentials.cmd_buffer, &pass_info, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(essentials.cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, render_data.main_pipeline.pipeline);
VkDescriptorImageInfo set_write_image_info[IMAGE_TEXTURES + OFFSCREEN_BUFFERS + iKeyboard] = {0};
for (uint32_t i = 0; i < IMAGE_TEXTURES; i++)
{
set_write_image_info[i] = (VkDescriptorImageInfo){
.sampler = render_data.images[i].sampler,
.imageView = render_data.images[i].view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
}
for (uint32_t i = 0; i < OFFSCREEN_BUFFERS; i++)
{
set_write_image_info[IMAGE_TEXTURES + i] = (VkDescriptorImageInfo){
.sampler = render_data.buf_obuffers[i * 2 + render_index].color.sampler,
.imageView = render_data.buf_obuffers[i * 2 + render_index].color.view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
}
set_write_image_info[IMAGE_TEXTURES + OFFSCREEN_BUFFERS] = (VkDescriptorImageInfo){
.sampler = render_data.images[IMAGE_TEXTURES + OFFSCREEN_BUFFERS].sampler,
.imageView = render_data.images[IMAGE_TEXTURES + OFFSCREEN_BUFFERS].view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
VkWriteDescriptorSet set_write[3] = {
[0] =
{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = render_data.main_desc_set,
.dstBinding = 0,
.descriptorCount = IMAGE_TEXTURES,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &set_write_image_info[0],
},
[1] =
{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = render_data.main_desc_set,
.dstBinding = IMAGE_TEXTURES,
.descriptorCount = OFFSCREEN_BUFFERS,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &set_write_image_info[IMAGE_TEXTURES],
},
[2] =
{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = render_data.main_desc_set,
.dstBinding = IMAGE_TEXTURES + OFFSCREEN_BUFFERS,
.descriptorCount = iKeyboard,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &set_write_image_info[IMAGE_TEXTURES + OFFSCREEN_BUFFERS],
},
};
vkUpdateDescriptorSets(dev->device, 3, set_write, 0, NULL);
vkCmdBindDescriptorSets(essentials.cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
render_data.main_layout.pipeline_layout, 0, 1, &render_data.main_desc_set, 0, NULL);
VkDeviceSize vertices_offset = 0;
vkCmdBindVertexBuffers(essentials.cmd_buffer, 0, 1, &render_data.buffers[BUFFER_VERTICES].buffer, &vertices_offset);
vkCmdBindIndexBuffer(essentials.cmd_buffer, render_data.buffers[BUFFER_INDICES].buffer, 0, VK_INDEX_TYPE_UINT16);
VkViewport viewport = {
.x = 0,
.y = 0,
.width = render_data.main_gbuffers[image_index].surface_size.width,
.height = render_data.main_gbuffers[image_index].surface_size.height,
.minDepth = 0,
.maxDepth = 1,
};
vkCmdSetViewport(essentials.cmd_buffer, 0, 1, &viewport);
VkRect2D scissor = {
.offset =
{
.x = 0,
.y = 0,
},
.extent = render_data.main_gbuffers[image_index].surface_size,
};
vkCmdSetScissor(essentials.cmd_buffer, 0, 1, &scissor);
vkCmdPushConstants(essentials.cmd_buffer, render_data.main_layout.pipeline_layout, VK_SHADER_STAGE_FRAGMENT_BIT, 0,
sizeof render_data.push_constants, &render_data.push_constants);
// vkCmdDraw(essentials.cmd_buffer, 4, 1, 0, 0);
vkCmdDrawIndexed(essentials.cmd_buffer, 4, 1, 0, 0, 0);
vkCmdEndRenderPass(essentials.cmd_buffer);
res = vk_render_finish(&essentials, dev, swapchain, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, image_index,
wait_buf_sem, wait_main_sem);
if (res == VK_ERROR_OUT_OF_DATE_KHR)
{
os_window->resize_event = true;
res = 0;
}
else if (res == VK_ERROR_SURFACE_LOST_KHR)
{
vkDestroySurfaceKHR(vk, swapchain->surface, NULL);
retval = vk_create_surface(vk, &swapchain->surface, os_window);
if (!vk_error_is_success(&retval))
return false;
os_window->resize_event = true;
res = 0;
}
if (res)
return false;
update_params(&os_window->app_data, os_window->fps_lock);
render_index = (render_index + 1) % 2;
os_window->pause_refresh = false;
return true;
}
void init_win_params(struct app_os_window *os_window)
{
os_window->app_data.iResolution[0] = 1280;
os_window->app_data.iResolution[1] = 720;
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
resize_size[0] = os_window->app_data.iResolution[0];
resize_size[1] = os_window->app_data.iResolution[1];
#endif
os_window->app_data.iFrame = 0;
os_window->app_data.iMouse[0] = 0;
os_window->app_data.iMouse[1] = 0;
os_window->app_data.iMouse_click[0] = false;
os_window->app_data.iMouse_click[1] = false;
os_window->app_data.iMouse_lclick[0] = 0;
os_window->app_data.iMouse_lclick[1] = 0;
os_window->app_data.iTime = 0;
os_window->app_data.pause = false;
os_window->app_data.quit = false;
os_window->app_data.drawdebug = false;
os_window->fps_lock = false;
os_window->is_minimized = false;
os_window->prepared = false;
os_window->resize_event = false;
os_window->reload_shaders_on_resize = false;
os_window->print_debug = false;
os_window->pause_refresh = false;
strncpy(os_window->name, "Vulkan Shadertoy launcher", APP_NAME_STR_LEN);
#if defined(VK_USE_PLATFORM_WIN32_KHR)
os_window->connection = NULL;
os_window->window = NULL;
os_window->minsize.x = 1;
os_window->minsize.y = 1;
#elif defined(VK_USE_PLATFORM_XCB_KHR)
os_window->atom_wm_delete_window = NULL;
os_window->xcb_window = 0;
os_window->screen = NULL;
os_window->connection = NULL;
os_window->display = NULL;
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
os_window->display = NULL;
os_window->registry = NULL;
os_window->compositor = NULL;
os_window->surface = NULL;
os_window->shell = NULL;
os_window->seat = NULL;
os_window->pointer = NULL;
os_window->keyboard = NULL;
os_window->xdg_surface = NULL;
os_window->xdg_toplevel = NULL;
os_window->configured = false;
#endif
}
#if defined(VK_USE_PLATFORM_XCB_KHR)
bool enterFullscreen() {
// idk how to make borderless fullscren on xcb
return true;
}
static void render_loop_xcb(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_swapchain *swapchain,
struct app_os_window *os_window)
{
while (!os_window->app_data.quit)
{
update_keypress();
xcb_generic_event_t *event;
if (os_window->app_data.pause)
{
event = xcb_wait_for_event(os_window->connection);
}
else
{
event = xcb_poll_for_event(os_window->connection);
}
// a workaround for repeated key events
// save original state of each modifyed button and check if it was modifyed twice
bool save_map[0xff + 1][3] = {0};
bool state_map[0xff + 1][2] = {0};
while (event)
{
app_handle_xcb_event(os_window, event, save_map, state_map);
free(event);
event = xcb_poll_for_event(os_window->connection);
}
if (keyboard_need_update)
{
for (int i = 0; i < 0xff; i++)
{
if ((state_map[i][0]) && (state_map[i][1]))
{
update_key_map(i, 0, save_map[i][0]);
update_key_map(i, 1, save_map[i][1]);
update_key_map(i, 2, save_map[i][2]);
}
}
}
check_hotkeys(os_window);
if ((!os_window->is_minimized) && (!os_window->resize_event))
{
if (!os_window->app_data.quit)
{
os_window->app_data.quit = !render_loop_draw(phy_dev, dev, swapchain, os_window);
}
else
break;
}
else
{
if ((!os_window->is_minimized) && os_window->resize_event)
{
on_window_resize(phy_dev, dev, &essentials, swapchain, &render_data,
os_window); // execute draw or resize per frame, not together
os_window->resize_event=false;
}
}
if (os_window->is_minimized)
{ // I do not delete everything on minimize, only stop rendering
sleep_ms(16);
}
}
exit_cleanup_render_loop(dev, &essentials, &render_data, wait_buf_sem, wait_main_sem, offscreen_fence);
}
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
static void render_loop_wayland(struct vk_physical_device *phy_dev, struct vk_device *dev, struct vk_swapchain *swapchain,
struct app_os_window *os_window)
{
static bool init_surface_size_once=true; // in Wayland surface should set window size, I do it on start, on start window size 0,0
while (!os_window->app_data.quit)
{
update_keypress();
while (!os_window->configured)
wl_display_dispatch(os_window->display);
while (wl_display_prepare_read(os_window->display) != 0)
wl_display_dispatch_pending(os_window->display);
wl_display_flush(os_window->display);
wl_display_read_events(os_window->display);
wl_display_dispatch_pending(os_window->display);
check_hotkeys(os_window);
if (((!os_window->is_minimized) && (!os_window->resize_event)&&((!os_window->app_data.pause)||((os_window->app_data.pause)&&(os_window->pause_refresh))))
|| init_surface_size_once)
{
if (!os_window->app_data.quit)
{
os_window->app_data.quit = !render_loop_draw(phy_dev, dev, swapchain, os_window);
}
else
break;
init_surface_size_once = false;
}
else
{
if ((!os_window->is_minimized) && os_window->resize_event)
{
on_window_resize(phy_dev, dev, &essentials, swapchain, &render_data,
os_window);
}
}
if(os_window->is_minimized||(((os_window->app_data.pause)&&(!os_window->pause_refresh)))){ //I do not delete everything on minimize, only stop rendering
sleep_ms(16);
}
}
exit_cleanup_render_loop(dev, &essentials, &render_data, wait_buf_sem, wait_main_sem, offscreen_fence);
}
#endif
void print_usage(char *name)
{
printf("Usage: %s \n"
"\t[--present_mode <present mode enum>]\n"
"\t <present_mode_enum>\tVK_PRESENT_MODE_IMMEDIATE_KHR = %d\n"
"\t\t\t\tVK_PRESENT_MODE_MAILBOX_KHR = %d\n"
"\t\t\t\tVK_PRESENT_MODE_FIFO_KHR = %d\n"
"\t\t\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = %d\n"
"\t[--debug]\n"
"\t[--reload_shaders] will reload shaders form file on resize\n"
"\t[--gpu <index(0/1/2/etc)>] use selected GPU to render\n"
"Control: Keyboard 1-debug, 2-vsynk 60fps, Space-pause\n",
name, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
VK_PRESENT_MODE_FIFO_RELAXED_KHR);
}
#if defined(VK_USE_PLATFORM_WIN32_KHR)
static int old_w, old_h;
static RECT rcClient, rcWind;
bool exitFullscreen();
bool enterFullscreen() {
return true;
// for some reason this code works only on Nvidia, on AMD it does not work(crash)
/*
if (!chWnd)return false;
if (fullscreen){return exitFullscreen();}
HWND hwnd = chWnd;
POINT ptDiff;
GetClientRect(hwnd, &rcClient);
GetWindowRect(hwnd, &rcWind);
ptDiff.x = (rcWind.right - rcWind.left) - rcClient.right;
ptDiff.y = (rcWind.bottom - rcWind.top) - rcClient.bottom;
old_w = os_window.app_data.iResolution[0]+ptDiff.x;
old_h = os_window.app_data.iResolution[1]+ptDiff.y;
int fullscreenWidth = GetSystemMetrics(SM_CXSCREEN);
int fullscreenHeight = GetSystemMetrics(SM_CYSCREEN);
LONG lStyle = GetWindowLong(hwnd, GWL_STYLE);
lStyle &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU);
SetWindowLong(hwnd, GWL_STYLE, lStyle);
LONG lExStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
lExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
SetWindowLong(hwnd, GWL_EXSTYLE, lExStyle);
SetWindowPos(hwnd, HWND_TOP, 0, 0, fullscreenWidth, fullscreenHeight, SWP_SHOWWINDOW); //HWND_TOPMOST
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
fullscreen = true;
return true;
*/
}
bool exitFullscreen() {
if (!chWnd)return false;
HWND hwnd = chWnd;
SetWindowLongPtr(hwnd, GWL_EXSTYLE, WS_EX_LEFT);
SetWindowLongPtr(hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
SetWindowPos(hwnd, HWND_NOTOPMOST, rcWind.left, rcWind.top, old_w, old_h, SWP_SHOWWINDOW);
fullscreen = false;
return true;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow)
{
MSG msg;
bool done;
int argc;
char **argv;
msg.wParam = 0;
LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
if (NULL == commandLineArgs)
{
argc = 0;
}
if (argc > 0)
{
argv = (char **)malloc(sizeof(char *) * argc);
if (argv == NULL)
{
argc = 0;
}
else
{
for (int iii = 0; iii < argc; iii++)
{
size_t wideCharLen = wcslen(commandLineArgs[iii]);
size_t numConverted = 0;
argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
if (argv[iii] != NULL)
{
wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
}
}
}
}
else
{
argv = NULL;
}
vk_error res = VK_ERROR_NONE;
int retval = EXIT_FAILURE;
init_win_params(&os_window);
uint32_t dev_index = 0;
bool use_gpu_idx = false;
os_window.present_mode = VK_PRESENT_MODE_FIFO_KHR;
if (argc > 1)
{
if (strcmp(argv[1], "--help") == 0)
{
SetStdOutToNewConsole();
print_usage(argv[0]);
Sleep(44000);
return 0;
}
}
for (int i = 1; i < argc; i++)
{
if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1))
{
os_window.present_mode = atoi(argv[i + 1]);
i++;
continue;
}
if ((strcmp(argv[i], "--gpu") == 0) && (i < argc - 1))
{
dev_index = atoi(argv[i + 1]);
use_gpu_idx = true;
i++;
continue;
}
if (strcmp(argv[i], "--debug") == 0)
{
os_window.print_debug = true;
continue;
}
if (strcmp(argv[i], "--reload_shaders") == 0)
{
os_window.reload_shaders_on_resize = true;
continue;
}
}
if (argc > 0 && argv != NULL)
{
for (int iii = 0; iii < argc; iii++)
{
if (argv[iii] != NULL)
{
free(argv[iii]);
}
}
free(argv);
}
if (os_window.print_debug)
{
SetStdOutToNewConsole();
}
os_window.connection = hInstance;
res = vk_init(&vk);
if (!vk_error_is_success(&res))
{
vk_error_printf(&res, "Could not initialize Vulkan\n");
return retval;
}
app_create_window(&os_window);
res = vk_create_surface(vk, &swapchain.surface, &os_window);
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not create surface.\n");
exit_cleanup(vk, NULL, NULL, &os_window);
return retval;
}
res = vk_enumerate_devices(vk, &swapchain.surface, &phy_dev, &dev_index, use_gpu_idx);
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not enumerate devices\n");
vkDestroySurfaceKHR(vk, swapchain.surface, NULL);
exit_cleanup(vk, NULL, NULL, &os_window);
return retval;
}
res = vk_setup(&phy_dev, &dev, VK_QUEUE_GRAPHICS_BIT,
1 + OFFSCREEN_BUFFERS); // using number of command buffers equal to offscreen buffers
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not setup logical device, command pools and queues\n");
exit_cleanup(vk, &dev, &swapchain, &os_window);
return retval;
}
swapchain.swapchain = VK_NULL_HANDLE;
res = vk_get_swapchain(vk, &phy_dev, &dev, &swapchain, &os_window, 1, &os_window.present_mode);
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not create surface and swapchain\n");
exit_cleanup(vk, &dev, &swapchain, &os_window);
return retval;
}
render_loop_init(&phy_dev, &dev, &swapchain, &os_window);
done = false;
while (!done)
{
PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
process_msg(&msg, &done);
RedrawWindow(os_window.window, NULL, NULL, RDW_INTERNALPAINT);
}
exit_cleanup_render_loop(&dev, &essentials, &render_data, wait_buf_sem, wait_main_sem, offscreen_fence);
exit_cleanup(vk, &dev, &swapchain, &os_window);
return (int)msg.wParam;
}
#elif defined(VK_USE_PLATFORM_XCB_KHR) || defined(VK_USE_PLATFORM_WAYLAND_KHR)
int main(int argc, char **argv)
{
vk_error res;
int retval = EXIT_FAILURE;
VkInstance vk;
struct vk_physical_device phy_dev = {0};
struct vk_device dev = {0};
struct vk_swapchain swapchain = {0};
struct app_os_window os_window;
init_win_params(&os_window);
uint32_t dev_index = 0;
bool use_gpu_idx = false;
os_window.present_mode = VK_PRESENT_MODE_FIFO_KHR;
if (argc > 1)
{
if (strcmp(argv[1], "--help") == 0)
{
print_usage(argv[0]);
return 0;
}
}
for (int i = 1; i < argc; i++)
{
if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1))
{
os_window.present_mode = atoi(argv[i + 1]);
i++;
continue;
}
if ((strcmp(argv[i], "--gpu") == 0) && (i < argc - 1))
{
dev_index = atoi(argv[i + 1]);
use_gpu_idx = true;
i++;
continue;
}
if (strcmp(argv[i], "--debug") == 0)
{
os_window.print_debug = true;
continue;
}
if (strcmp(argv[i], "--reload_shaders") == 0)
{
os_window.reload_shaders_on_resize = true;
continue;
}
}
srand(time(NULL));
res = vk_init(&vk);
if (!vk_error_is_success(&res))
{
vk_error_printf(&res, "Could not initialize Vulkan\n");
return retval;
}
#if defined(VK_USE_PLATFORM_XCB_KHR)
printf("Init XCB\n");
app_init_connection(&os_window);
app_create_xcb_window(&os_window);
#else
printf("Init Wayland\n");
initWaylandConnection(&os_window);
setupWindow(&os_window);
#endif
res = vk_create_surface(vk, &swapchain.surface, &os_window);
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not create surface.\n");
exit_cleanup(vk, NULL, NULL, &os_window);
return retval;
}
res = vk_enumerate_devices(vk, &swapchain.surface, &phy_dev, &dev_index, use_gpu_idx);
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not enumerate devices\n");
vkDestroySurfaceKHR(vk, swapchain.surface, NULL);
exit_cleanup(vk, NULL, NULL, &os_window);
return retval;
}
res = vk_setup(&phy_dev, &dev, VK_QUEUE_GRAPHICS_BIT, 1 + OFFSCREEN_BUFFERS); // cmd buffers alloc
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not setup logical device, command pools and queues\n");
exit_cleanup(vk, &dev, &swapchain, &os_window);
return retval;
}
swapchain.swapchain = VK_NULL_HANDLE;
res = vk_get_swapchain(vk, &phy_dev, &dev, &swapchain, &os_window, 1, &os_window.present_mode);
if (vk_error_is_error(&res))
{
vk_error_printf(&res, "Could not create surface and swapchain\n");
exit_cleanup(vk, &dev, &swapchain, &os_window);
return retval;
}
render_loop_init(&phy_dev, &dev, &swapchain, &os_window);
#if defined(VK_USE_PLATFORM_XCB_KHR)
render_loop_xcb(&phy_dev, &dev, &swapchain, &os_window);
#else
render_loop_wayland(&phy_dev, &dev, &swapchain, &os_window);
#endif
retval = 0;
exit_cleanup(vk, &dev, &swapchain, &os_window);
return retval;
}
#endif
|
AbigailBuccaneer/alive2
|
llvm_util/llvm2alive.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "ir/function.h"
#include <optional>
#include <ostream>
namespace llvm {
class DataLayout;
class Function;
class TargetLibraryInfo;
}
namespace llvm_util {
struct initializer {
initializer(std::ostream &os, const llvm::DataLayout &DL);
};
std::optional<IR::Function> llvm2alive(llvm::Function &F,
const llvm::TargetLibraryInfo &TLI);
}
|
AbigailBuccaneer/alive2
|
llvm_util/known_fns.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "ir/function.h"
#include <functional>
#include <memory>
#include <utility>
namespace llvm {
class CallInst;
class ConstantExpr;
class TargetLibraryInfo;
}
namespace IR {
class BasicBlock;
class Instr;
}
namespace llvm_util {
// returned bool indicates whether it's a known function call
std::pair<std::unique_ptr<IR::Instr>, bool>
known_call(llvm::CallInst &i, const llvm::TargetLibraryInfo &TLI,
IR::BasicBlock &BB,
std::function<IR::Value*(llvm::ConstantExpr *)> constexpr_conv);
}
|
AbigailBuccaneer/alive2
|
ir/value.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "ir/state.h"
#include "ir/type.h"
#include "smt/expr.h"
#include <ostream>
#include <string>
#include <variant>
namespace smt { class Model; }
namespace IR {
class VoidValue;
class Value {
Type &type;
std::string name;
protected:
Value(Type &type, std::string &&name)
: type(type), name(std::move(name)) {}
void setName(std::string &&str) { name = std::move(str); }
public:
auto bits() const { return type.bits(); }
auto& getName() const { return name; }
auto& getType() const { return type; }
bool isVoid() const;
virtual void print(std::ostream &os) const = 0;
virtual StateValue toSMT(State &s) const = 0;
virtual smt::expr getTypeConstraints() const;
void fixupTypes(const smt::Model &m);
static VoidValue voidVal;
friend std::ostream& operator<<(std::ostream &os, const Value &val);
virtual ~Value() {}
};
class UndefValue final : public Value {
public:
UndefValue(Type &type) : Value(type, "undef") {}
void print(std::ostream &os) const override;
StateValue toSMT(State &s) const override;
};
class PoisonValue final : public Value {
public:
PoisonValue(Type &type) : Value(type, "poison") {}
void print(std::ostream &os) const override;
StateValue toSMT(State &s) const override;
};
class VoidValue final : public Value {
public:
VoidValue() : Value(Type::voidTy, "void") {}
void print(std::ostream &os) const override;
StateValue toSMT(State &s) const override;
};
class NullPointerValue final : public Value {
public:
NullPointerValue(Type &type) : Value(type, "null") {}
void print(std::ostream &os) const override;
StateValue toSMT(State &s) const override;
};
class GlobalVariable final : public Value {
// The size of this global variable (in bytes)
uint64_t allocsize;
unsigned align;
// Initial value stored at this global variable.
// This is initialized only if the global is constant.
// If it has no initial value, this is nullptr.
Value *initval;
// initval can be null even if isconst is true if this is an external const.
bool isconst;
public:
GlobalVariable(Type &type, std::string &&name, uint64_t allocsize,
unsigned align, Value *initval, bool isconst) :
Value(type, std::move(name)), allocsize(allocsize), align(align),
initval(initval), isconst(isconst) {}
uint64_t size() const { return allocsize; }
bool isConst() const { return isconst; }
const Value* initVal() const { return initval; }
void print(std::ostream &os) const override;
StateValue toSMT(State &s) const override;
};
class Input final : public Value {
std::string smt_name;
public:
Input(Type &type, std::string &&name);
void copySMTName(const Input &other);
void print(std::ostream &os) const override;
StateValue toSMT(State &s) const override;
smt::expr getTyVar() const;
};
}
|
AbigailBuccaneer/alive2
|
smt/smt.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include <string>
namespace smt {
struct smt_initializer {
smt_initializer();
~smt_initializer();
void reset();
private:
void init();
void destroy();
};
void set_query_timeout(std::string ms);
const char* get_query_timeout();
void set_memory_limit(uint64_t limit);
bool hit_memory_limit();
bool hit_half_memory_limit();
}
|
AbigailBuccaneer/alive2
|
smt/exprs.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "smt/expr.h"
#include <map>
#include <set>
#include <utility>
namespace smt {
template <typename T>
class DisjointExpr {
std::map<T, expr> vals; // val -> domain
std::optional<T> default_val;
public:
DisjointExpr() {}
DisjointExpr(const T &default_val) : default_val(default_val) {}
DisjointExpr(T &&default_val) : default_val(std::move(default_val)) {}
template <typename V, typename D>
void add(V &&val, D &&domain) {
if (domain.isFalse())
return;
if (domain.isTrue())
vals.clear();
auto [I, inserted] = vals.try_emplace(std::forward<V>(val),
std::forward<D>(domain));
if (!inserted)
I->second |= std::forward<D>(domain);
}
T operator()() const {
std::optional<T> ret;
for (auto &[val, domain] : vals) {
if (domain.isTrue())
return val;
ret = ret ? T::mkIf(domain, val, *ret) : val;
}
return ret ? *ret : *default_val;
}
};
class FunctionExpr {
std::map<expr, expr> fn; // key -> val
expr default_val;
public:
FunctionExpr() {}
FunctionExpr(expr &&default_val) : default_val(std::move(default_val)) {}
void add(expr &&key, expr &&val);
void add(const FunctionExpr &other);
void del(const expr &key);
expr operator()(expr &key) const;
auto begin() const { return fn.begin(); }
auto end() const { return fn.end(); }
// for container use only
bool operator<(const FunctionExpr &rhs) const;
};
}
|
AbigailBuccaneer/alive2
|
tools/alive_parser.h
|
<reponame>AbigailBuccaneer/alive2
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "tools/transform.h"
#include <string>
#include <string_view>
#include <vector>
namespace IR { class Type; }
namespace tools {
std::vector<Transform> parse(std::string_view buf);
struct parser_initializer {
parser_initializer();
~parser_initializer();
};
struct ParseException {
std::string str;
unsigned lineno;
ParseException(std::string &&str, unsigned lineno)
: str(std::move(str)), lineno(lineno) {}
};
constexpr unsigned PARSER_READ_AHEAD = 16;
}
|
AbigailBuccaneer/alive2
|
tools/alive_lexer.h
|
<reponame>AbigailBuccaneer/alive2
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include <string>
#include <string_view>
namespace tools {
enum token {
#define TOKEN(x) x,
#include "tools/tokens.h"
#undef TOKEN
};
struct yylval_t {
union {
uint64_t num;
double fp_num;
std::string_view str;
};
yylval_t() {}
};
void yylex_init(std::string_view str);
token yylex();
extern yylval_t yylval;
extern unsigned yylineno;
extern const char *const token_name[];
struct LexException {
std::string str;
unsigned lineno;
LexException(std::string &&str, unsigned lineno)
: str(std::move(str)), lineno(lineno) {}
};
constexpr unsigned LEXER_READ_AHEAD = 16;
}
|
AbigailBuccaneer/alive2
|
ir/state.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "ir/memory.h"
#include "ir/state_value.h"
#include "smt/expr.h"
#include "smt/exprs.h"
#include <array>
#include <ostream>
#include <set>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace IR {
class Value;
class BasicBlock;
class Function;
class State {
public:
using ValTy = std::pair<StateValue, std::set<smt::expr>>;
// DomainTy: (reachability from entry to this basic block, undef vars)
using DomainTy = std::pair<smt::expr, std::set<smt::expr>>;
private:
const Function &f;
bool source;
bool disable_undef_rewrite = false;
smt::expr precondition = true;
smt::expr axioms = true;
const BasicBlock *current_bb;
std::set<smt::expr> quantified_vars;
// var -> ((value, not_poison), undef_vars, already_used?)
std::unordered_map<const Value*, unsigned> values_map;
std::vector<std::tuple<const Value*, ValTy, bool>> values;
// dst BB -> src BB -> (domain data, memory)
std::unordered_map<const BasicBlock*,
std::unordered_map<const BasicBlock*,
std::pair<DomainTy, Memory>>>
predecessor_data;
std::unordered_set<const BasicBlock*> seen_bbs;
// Global variables' memory block ids
std::unordered_map<std::string, unsigned> glbvar_bids;
// temp state
DomainTy domain;
Memory memory;
std::set<smt::expr> undef_vars;
std::array<StateValue, 32> tmp_values;
unsigned i_tmp_values = 0; // next available position in tmp_values
// return_domain: a boolean expression describing return condition
smt::expr return_domain;
smt::DisjointExpr<StateValue> return_val;
smt::DisjointExpr<Memory> return_memory;
std::set<smt::expr> return_undef_vars;
public:
State(const Function &f, bool source);
static void resetGlobals();
const StateValue& exec(const Value &v);
const StateValue& operator[](const Value &val);
const ValTy& at(const Value &val) const;
const smt::expr* jumpCondFrom(const BasicBlock &bb) const;
bool startBB(const BasicBlock &bb);
void addJump(const BasicBlock &dst);
// boolean cond
void addJump(StateValue &&cond, const BasicBlock &dst);
// i1 cond
void addCondJump(const StateValue &cond, const BasicBlock &dst_true,
const BasicBlock &dst_false);
void addReturn(const StateValue &val);
void addAxiom(smt::expr &&axiom) { axioms &= std::move(axiom); }
void addPre(smt::expr &&cond) { precondition &= std::move(cond); }
void addUB(smt::expr &&ub);
void addUB(const smt::expr &ub);
void addQuantVar(const smt::expr &var);
void addUndefVar(smt::expr &&var);
void resetUndefVars();
auto& getFn() const { return f; }
auto& getMemory() { return memory; }
auto& getAxioms() const { return axioms; }
auto& getPre() const { return precondition; }
const auto& getValues() const { return values; }
const auto& getQuantVars() const { return quantified_vars; }
auto& returnDomain() const { return return_domain; }
Memory returnMemory() const { return return_memory(); }
std::pair<StateValue, const std::set<smt::expr>&> returnVal() const {
return { return_val(), return_undef_vars };
}
void startParsingPre() { disable_undef_rewrite = true; }
// whether this is source or target program
bool isSource() const { return source; }
void addGlobalVarBid(const std::string &glbvar, unsigned bid);
// Checks whether glbvar has block id assigned.
// If it has, bid is updated with the block id.
bool hasGlobalVarBid(const std::string &glbvar, unsigned &bid) const;
void copyGlobalVarBidsFromSrc(const State &src);
private:
void addJump(const BasicBlock &dst, smt::expr &&domain);
};
}
|
AbigailBuccaneer/alive2
|
tools/transform.h
|
<filename>tools/transform.h
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "ir/function.h"
#include "smt/solver.h"
#include "util/errors.h"
#include <string>
#include <ostream>
#include <unordered_map>
namespace tools {
struct TransformPrintOpts {
bool print_fn_header = true;
};
struct Transform {
std::string name;
IR::Function src, tgt;
IR::Predicate *precondition = nullptr;
void print(std::ostream &os, const TransformPrintOpts &opt) const;
friend std::ostream& operator<<(std::ostream &os, const Transform &t);
};
class TypingAssignments {
smt::Solver s, sneg;
smt::Result r;
bool has_only_one_solution = false;
bool is_unsat = false;
TypingAssignments(const smt::expr &e);
public:
bool operator!() const { return !(bool)*this; }
operator bool() const;
void operator++(void);
bool hasSingleTyping() const { return has_only_one_solution; }
friend class TransformVerify;
};
class TransformVerify {
Transform &t;
std::unordered_map<std::string, const IR::Instr*> tgt_instrs;
bool check_each_var;
public:
TransformVerify(Transform &t, bool check_each_var);
util::Errors verify() const;
TypingAssignments getTypings() const;
void fixupTypes(const TypingAssignments &ty);
};
}
|
AbigailBuccaneer/alive2
|
ir/globals.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
namespace IR {
/// Upperbound of the number of non-local pointers returned by instructions
extern unsigned num_max_nonlocals_inst;
/// Upperbound of the number of local blocks (max(src, tgt))
extern unsigned num_locals;
// Upperbound of the number of nonlocal blocks
extern unsigned num_nonlocals;
/// Number of bits needed for encoding a memory block id
extern unsigned bits_for_bid;
// Number of bits needed for encoding a pointer's offset
extern unsigned bits_for_offset;
/// sizeof(size_t). This is assume to be equal to pointer size
extern unsigned bits_size_t;
extern bool little_endian;
/// Wether the null pointer is used in either function
extern bool nullptr_is_used;
/// Wether int2ptr or ptr2int are used in either function
extern bool has_int2ptr;
extern bool has_ptr2int;
}
|
AbigailBuccaneer/alive2
|
ir/memory.h
|
<filename>ir/memory.h
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "ir/state_value.h"
#include "ir/type.h"
#include "smt/expr.h"
#include "smt/exprs.h"
#include <optional>
#include <ostream>
#include <string>
#include <utility>
namespace smt { class FunctionExpr; }
namespace IR {
class Memory;
class State;
class Pointer {
const Memory &m;
// [bid, offset]
// The top bit of bid is 1 if the block is local, 0 otherwise.
// A local memory block is a memory block that is
// allocated by an instruction during the current function call. This does
// not include allocated blocks from a nested function call. A heap-allocated
// block can also be a local memory block.
// Otherwise, a pointer is pointing to a non-local block, which can be either
// of global variable, heap, or a stackframe that is not this function call.
// TODO: missing support for address space
smt::expr p;
unsigned total_bits() const;
smt::expr get_value(const char *name, const smt::FunctionExpr &fn,
const smt::expr &ret_type) const;
public:
Pointer(const Memory &m, const char *var_name,
const smt::expr &local = false);
Pointer(const Memory &m, smt::expr p) : m(m), p(std::move(p)) {}
Pointer(const Memory &m, unsigned bid, bool local);
Pointer(const Memory &m, const smt::expr &bid, const smt::expr &offset);
smt::expr is_local() const;
smt::expr get_bid() const;
smt::expr get_short_bid() const; // same as get_bid but ignoring is_local bit
smt::expr get_offset() const;
smt::expr get_address(bool simplify = true) const;
smt::expr block_size(bool simplify = true) const;
const smt::expr& operator()() const { return p; }
smt::expr short_ptr() const;
smt::expr release() { return std::move(p); }
unsigned bits() const { return p.bits(); }
Pointer operator+(unsigned) const;
Pointer operator+(const smt::expr &bytes) const;
void operator+=(const smt::expr &bytes);
smt::expr add_no_overflow(const smt::expr &offset) const;
smt::expr operator==(const Pointer &rhs) const;
smt::expr operator!=(const Pointer &rhs) const;
StateValue sle(const Pointer &rhs) const;
StateValue slt(const Pointer &rhs) const;
StateValue sge(const Pointer &rhs) const;
StateValue sgt(const Pointer &rhs) const;
StateValue ule(const Pointer &rhs) const;
StateValue ult(const Pointer &rhs) const;
StateValue uge(const Pointer &rhs) const;
StateValue ugt(const Pointer &rhs) const;
smt::expr inbounds() const;
smt::expr is_aligned(unsigned align) const;
void is_dereferenceable(unsigned bytes, unsigned align, bool iswrite);
void is_dereferenceable(const smt::expr &bytes, unsigned align, bool iswrite);
void is_disjoint(const smt::expr &len1, const Pointer &ptr2,
const smt::expr &len2) const;
smt::expr is_block_alive() const;
smt::expr is_readonly() const;
enum AllocType {
NON_HEAP,
MALLOC,
CXX_NEW,
};
smt::expr get_alloc_type() const;
smt::expr is_heap_allocated() const;
smt::expr refined(const Pointer &other) const;
smt::expr block_refined(const Pointer &other) const;
const Memory& getMemory() const { return m; }
static Pointer mkNullPointer(const Memory &m);
smt::expr isNull() const;
friend std::ostream& operator<<(std::ostream &os, const Pointer &p);
};
class Memory {
State *state;
bool did_pointer_store = false;
smt::expr non_local_block_val; // array: (bid, offset) -> Byte
smt::expr local_block_val;
smt::expr non_local_block_liveness; // array: bid -> bool
smt::expr local_block_liveness;
smt::expr local_avail_space; // available space in local block area.
smt::FunctionExpr local_blk_addr; // bid -> (bits_size_t - 1)
smt::FunctionExpr local_blk_size;
smt::FunctionExpr local_blk_kind;
smt::expr mk_val_array() const;
smt::expr mk_liveness_array() const;
void store(const Pointer &p, const smt::expr &val, smt::expr &local,
smt::expr &non_local, bool index_bid = false);
public:
enum BlockKind {
HEAP, STACK, GLOBAL, CONSTGLOBAL
};
Memory(State &state);
static void resetGlobalData();
static void resetLocalBids();
smt::expr mkInput(const char *name) const;
std::pair<smt::expr, smt::expr> mkUndefInput() const;
// Allocates a new memory block.
// If bid is not specified, it creates a fresh block id by increasing
// last_bid.
// If bid is specified, the bid is used, and last_bid is not increased.
// In this case, it is caller's responsibility to give a unique bid, and
// bumpLastBid() should be called in advance to correctly do this.
// The newly assigned bid is stored to bid_out if bid_out != nullptr.
smt::expr alloc(const smt::expr &size, unsigned align, BlockKind blockKind,
std::optional<unsigned> bid = std::nullopt,
unsigned *bid_out = nullptr,
const smt::expr &precond = true);
void free(const smt::expr &ptr);
void store(const smt::expr &ptr, const StateValue &val, const Type &type,
unsigned align);
StateValue load(const smt::expr &ptr, const Type &type, unsigned align);
void memset(const smt::expr &ptr, const StateValue &val,
const smt::expr &bytesize, unsigned align);
void memcpy(const smt::expr &dst, const smt::expr &src,
const smt::expr &bytesize, unsigned align_dst, unsigned align_src,
bool move);
smt::expr ptr2int(const smt::expr &ptr);
smt::expr int2ptr(const smt::expr &val);
smt::expr refined(const Memory &other) const;
static Memory mkIf(const smt::expr &cond, const Memory &then,
const Memory &els);
unsigned bitsByte() const;
// for container use only
bool operator<(const Memory &rhs) const;
friend class Pointer;
};
}
|
AbigailBuccaneer/alive2
|
util/config.h
|
#pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
namespace util::config {
extern bool symexec_print_each_value;
extern bool skip_smt;
extern bool disable_poison_input;
extern bool disable_undef_input;
}
|
ethers/elements
|
src/pow.h
|
<filename>src/pow.h<gh_stars>10-100
// Copyright (c) 2009-2010 <NAME>
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_POW_H
#define BITCOIN_POW_H
#include <stdint.h>
#include <string>
class CBlockHeader;
class CBlockIndex;
class CProof;
class CScript;
class CWallet;
class uint256;
/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckBitcoinProof(const CBlockHeader& block);
/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckProof(const CBlockHeader& block);
/** Scans nonces looking for a hash with at least some zero bits */
bool GenerateProof(CBlockHeader* pblock, CWallet* pwallet);
void ResetProof(CBlockHeader& block);
bool CheckChallenge(const CBlockHeader& block, const CBlockIndex& indexLast);
void ResetChallenge(CBlockHeader& block, const CBlockIndex& indexLast);
uint256 GetBlockProof(const CBlockIndex& block);
CScript CombineBlockSignatures(const CBlockHeader& header, const CScript& scriptSig1, const CScript& scriptSig2);
/** Avoid using these functions when possible */
double GetChallengeDifficulty(const CBlockIndex* blockindex);
std::string GetChallengeStr(const CBlockIndex& block);
std::string GetChallengeStrHex(const CBlockIndex& block);
uint32_t GetNonce(const CBlockHeader& block);
void SetNonce(CBlockHeader& block, uint32_t nNonce);
#endif // BITCOIN_POW_H
|
ethers/elements
|
src/callrpc.h
|
<filename>src/callrpc.h<gh_stars>10-100
// Copyright (c) 2009-2010 <NAME>
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CALLRPC_H
#define BITCOIN_CALLRPC_H
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "uint256.h"
#include <string>
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
json_spirit::Object CallRPC(const std::string& strMethod, const json_spirit::Array& params, std::string port="");
bool IsConfirmedBitcoinBlock(const uint256& hash, int nMinConfirmationDepth);
#endif // BITCOIN_CALLRPC_H
|
ethers/elements
|
src/secp256k1/src/schnorr_impl.h
|
/***********************************************************************
* Copyright (c) 2015 <NAME> *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php. *
***********************************************************************/
#ifndef _SECP256K1_SCHNORR_IMPL_H_
#define _SECP256K1_SCHNORR_IMPL_H_
#include <string.h>
#include "schnorr.h"
#include "num.h"
#include "field.h"
#include "group.h"
#include "ecmult.h"
#include "ecmult_gen.h"
/**
* Custom Schnorr-based signature scheme:
*
* Signing:
* Inputs: 32-byte message m, 32-byte scalar key x (!=0), 32-byte scalar nonce k (!=0)
*
* Compute point R = k * G. Reject nonce if R's y coordinate is odd.
* Compute 32-byte r, the serialization of R's x coordinate.
* Compute scalar h = Hash(r || m). Reject nonce if h == 0 or h >= order.
* Compute scalar s = k - h * x.
* The signature is (r, s).
*
*
* Verification:
* Inputs: 32-byte message m, public key point Q, signature: (32-byte r, scalar s)
*
* Signature is invalid if s >= order.
* Signature is invalid if r >= p.
* Compute scalar h = Hash(r || m). Signature is invalid if h == 0 or h >= order.
* Option 1 (faster for single verification):
* Compute point R = h * Q + s * G. Signature is invalid if R is infinity or R's y coordinate is odd.
* Signature is valid if the serialization of R's x coordinate equals r.
* Option 2 (allows batch validation and pubkey recovery):
* Decompress x coordinate r into point R, with odd y coordinate.
* Signature is valid if R + h * Q + s * G == 0.
*/
static int secp256k1_schnorr_sig_sign(const secp256k1_ecmult_gen_context_t* ctx, unsigned char *sig64, const secp256k1_scalar_t *key, const secp256k1_scalar_t *nonce, secp256k1_schnorr_msghash_t hash, const unsigned char *msg32) {
secp256k1_gej_t Rj;
secp256k1_ge_t Ra;
unsigned char h32[32];
secp256k1_scalar_t h, s;
int overflow;
if (secp256k1_scalar_is_zero(key) || secp256k1_scalar_is_zero(nonce)) {
return 0;
}
secp256k1_ecmult_gen(ctx, &Rj, nonce);
secp256k1_ge_set_gej(&Ra, &Rj);
secp256k1_fe_normalize(&Ra.y);
secp256k1_fe_normalize(&Ra.x);
if (secp256k1_fe_is_odd(&Ra.y)) {
return 0;
}
secp256k1_fe_get_b32(sig64, &Ra.x);
hash(h32, sig64, msg32);
overflow = 0;
secp256k1_scalar_set_b32(&h, h32, &overflow);
if (overflow || secp256k1_scalar_is_zero(&h)) {
return 0;
}
secp256k1_scalar_mul(&s, &h, key);
secp256k1_scalar_negate(&s, &s);
secp256k1_scalar_add(&s, &s, nonce);
secp256k1_scalar_get_b32(sig64 + 32, &s);
return 1;
}
static int secp256k1_schnorr_sig_verify(const secp256k1_ecmult_context_t* ctx, const unsigned char *sig64, const secp256k1_ge_t *pubkey, secp256k1_schnorr_msghash_t hash, const unsigned char *msg32) {
secp256k1_gej_t Qj, Rj;
secp256k1_ge_t Ra;
secp256k1_fe_t Rx;
secp256k1_scalar_t h, s;
unsigned char hh[32];
int overflow;
if (secp256k1_ge_is_infinity(pubkey)) {
return 0;
}
hash(hh, sig64, msg32);
overflow = 0;
secp256k1_scalar_set_b32(&h, hh, &overflow);
if (overflow || secp256k1_scalar_is_zero(&h)) {
return 0;
}
overflow = 0;
secp256k1_scalar_set_b32(&s, sig64 + 32, &overflow);
if (overflow) {
return 0;
}
if (!secp256k1_fe_set_b32(&Rx, sig64)) {
return 0;
}
secp256k1_gej_set_ge(&Qj, pubkey);
secp256k1_ecmult(ctx, &Rj, &Qj, &h, &s);
if (secp256k1_gej_is_infinity(&Rj)) {
return 0;
}
secp256k1_ge_set_gej_var(&Ra, &Rj);
secp256k1_fe_normalize_var(&Ra.y);
if (secp256k1_fe_is_odd(&Ra.y)) {
return 0;
}
return secp256k1_fe_equal_var(&Rx, &Ra.x);
}
static const secp256k1_scalar_t secp256k1_schnorr_batch_coefs[] = {
SECP256K1_SCALAR_CONST(1,1,2,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,3,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,5,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,7,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,9,1,1),
SECP256K1_SCALAR_CONST(1,3,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,5,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,7,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,9,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,8,1),
SECP256K1_SCALAR_CONST(1,1,3,1,2,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,2,1,4,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1),
SECP256K1_SCALAR_CONST(1,1,1,1,1,1,1,1)
};
static int secp256k1_schnorr_sig_verify_batch(const secp256k1_ecmult_context_t* ctx, int n, unsigned char (* const sig64)[64], const secp256k1_ge_t *pubkey, secp256k1_schnorr_msghash_t hash, const unsigned char *msg32) {
secp256k1_gej_t S;
secp256k1_gej_t P[SECP256K1_SCHNORR_MAX_BATCH * 2 - 1];
secp256k1_ge_t R0;
secp256k1_scalar_t f[SECP256K1_SCHNORR_MAX_BATCH * 2 - 1];
secp256k1_scalar_t ss;
secp256k1_fe_t Rx;
unsigned char hh[32];
int overflow;
int k;
VERIFY_CHECK(n <= SECP256K1_SCHNORR_MAX_BATCH);
VERIFY_CHECK(n >= 1);
secp256k1_scalar_set_int(&f[0], 1);
for (k = 0; k < n; k++) {
secp256k1_scalar_t s;
secp256k1_ge_t Ra;
if (k) {
f[k - 1] = secp256k1_schnorr_batch_coefs[k - 1];
}
/* Find Rs (into the first half of P). */
if (!secp256k1_fe_set_b32(&Rx, sig64[k])) {
return 0;
}
secp256k1_ge_set_xo_var(&Ra, &Rx, 1);
if (k) {
secp256k1_gej_set_ge(&P[k - 1], &Ra);
} else {
R0 = Ra;
}
/* Find s (multiplied by corresponding f, added together in ss). */
overflow = 0;
secp256k1_scalar_set_b32(&s, sig64[k] + 32, &overflow);
if (overflow) {
return 0;
}
if (k) {
secp256k1_scalar_mul(&s, &s, &f[k - 1]);
secp256k1_scalar_add(&ss, &ss, &s);
} else {
ss = s;
}
/* Find Qs (into the second half of P). */
if (secp256k1_ge_is_infinity(&pubkey[k])) {
return 0;
}
secp256k1_gej_set_ge(&P[k + n - 1], &pubkey[k]);
/* Find h (multiplied by corresponding f, into the second half of f). */
hash(hh, sig64[k], msg32);
overflow = 0;
secp256k1_scalar_set_b32(&f[k + n - 1], hh, &overflow);
if (overflow || secp256k1_scalar_is_zero(&f[k + n - 1])) {
return 0;
}
if (k) {
secp256k1_scalar_mul(&f[k + n - 1], &f[k + n - 1], &f[k - 1]);
}
}
secp256k1_ecmult_points(ctx, 2 * n - 1, &S, P, f, &ss);
secp256k1_gej_add_ge_var(&S, &S, &R0, NULL);
return (secp256k1_gej_is_infinity(&S));
}
#endif
|
ethers/elements
|
src/blind.h
|
<reponame>ethers/elements
#ifndef BITCOIN_BLIND_H_
#define BITCOIN_BLIND_H_ 1
#include "key.h"
#include "pubkey.h"
#include "primitives/transaction.h"
void ECC_Blinding_Start();
void ECC_Blinding_Stop();
int UnblindOutput(const CKey& blinding_key, const CTxOut& txout, CAmount& amount_out, std::vector<unsigned char>& blinding_factor_out);
void BlindOutputs(const std::vector<std::vector<unsigned char> >& input_blinding_factors, const std::vector<std::vector<unsigned char> >& output_blinding_factors, const std::vector<CPubKey>& output_pubkeys, CMutableTransaction& tx);
#endif
|
ethers/elements
|
src/primitives/transaction.h
|
<gh_stars>10-100
// Copyright (c) 2009-2010 <NAME>
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_PRIMITIVES_TRANSACTION_H
#define BITCOIN_PRIMITIVES_TRANSACTION_H
#include "amount.h"
#include "hash.h"
#include "script/script.h"
#include "serialize.h"
#include "uint256.h"
#define SERIALIZE_VERSION_MASK_NO_WITNESS 0x40000000
#define SERIALIZE_VERSION_MASK_ONLY_WITNESS 0x80000000
#define SERIALIZE_VERSION_MASK_BITCOIN_TX 0x20000000
#define SERIALIZE_VERSION_MASK_PREHASH 0x10000000
class CTxOutValue
{
public:
static const size_t nCommitmentSize = 33;
std::vector<unsigned char> vchCommitment;
std::vector<unsigned char> vchRangeproof;
std::vector<unsigned char> vchNonceCommitment;
CTxOutValue();
CTxOutValue(CAmount);
CTxOutValue(const std::vector<unsigned char>& vchValueCommitment, const std::vector<unsigned char>& vchRangeproofIn);
ADD_SERIALIZE_METHODS;
template<typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
bool fBitcoinTx = nVersion & SERIALIZE_VERSION_MASK_BITCOIN_TX;
bool fWitness = (nVersion & SERIALIZE_VERSION_MASK_NO_WITNESS) == 0;
bool fOnlyWitness = nVersion & SERIALIZE_VERSION_MASK_ONLY_WITNESS;
assert(!fBitcoinTx || IsAmount() || (IsNull() && ser_action.ForRead()));
if (fBitcoinTx) {
CAmount amount = 0;
if (!ser_action.ForRead())
amount = GetAmount();
READWRITE(amount);
if (ser_action.ForRead())
SetToAmount(amount);
} else {
if (!fOnlyWitness) READWRITE(REF(CFlatData(&vchCommitment[0], &vchCommitment[nCommitmentSize])));
if (fWitness) {
if (nVersion & SERIALIZE_VERSION_MASK_PREHASH) {
uint256 prehash = (CHashWriter(nType, nVersion) << vchRangeproof << vchNonceCommitment).GetHash();
READWRITE(prehash);
} else {
READWRITE(vchRangeproof);
READWRITE(vchNonceCommitment);
}
}
}
}
bool IsValid() const;
bool IsNull() const;
bool IsAmount() const;
CAmount GetAmount() const;
void SetToAmount(CAmount nAmount);
friend bool operator==(const CTxOutValue& a, const CTxOutValue& b);
friend bool operator!=(const CTxOutValue& a, const CTxOutValue& b);
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
uint32_t n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(FLATDATA(*this));
}
void SetNull() { hash = 0; n = (uint32_t) -1; }
bool IsNull() const { return (hash == 0 && n == (uint32_t) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const;
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
uint32_t nSequence;
CTxIn()
{
nSequence = ~(uint32_t)0;
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=~(uint32_t)0);
CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=~(uint32_t)0);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
bool fWitness = (nVersion & SERIALIZE_VERSION_MASK_NO_WITNESS) == 0;
bool fOnlyWitness = nVersion & SERIALIZE_VERSION_MASK_ONLY_WITNESS;
assert((nType != SER_GETHASH && !fOnlyWitness && fWitness) || nType == SER_GETHASH);
if (!fOnlyWitness) READWRITE(prevout);
if (fWitness) READWRITE(scriptSig);
if (!fOnlyWitness) READWRITE(nSequence);
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const;
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
CTxOutValue nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(const CTxOutValue& valueIn, CScript scriptPubKeyIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(nValue);
READWRITE(scriptPubKey);
}
void SetNull()
{
nValue = CTxOutValue();
scriptPubKey.clear();
}
bool IsNull() const
{
return nValue.IsNull() && scriptPubKey.empty();
}
bool IsDust(CFeeRate minRelayTxFee) const
{
if (!nValue.IsAmount())
return false; // FIXME
// "Dust" is defined in terms of CTransaction::minRelayTxFee,
// which has units satoshis-per-kilobyte.
// If you'd pay more than 1/3 in fees
// to spend something, then we consider it dust.
// A typical txout is 34 bytes big, and will
// need a CTxIn of at least 148 bytes to spend:
// so dust is a txout less than 546 satoshis
// with default minRelayTxFee.
size_t nSize = GetSerializeSize(SER_DISK,0)+148u;
return (nValue.GetAmount() < 3*minRelayTxFee.GetFee(nSize));
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToString() const;
};
struct CMutableTransaction;
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
private:
/** Memory only. */
const uint256 hash;
const uint256 hashWitness; // Just witness
const uint256 hashFull; // Including witness
const uint256 hashBitcoin; // For Bitcoin Transactions
void UpdateHash() const;
public:
static const int32_t CURRENT_VERSION=1;
// The local variables are made const to prevent unintended modification
// without updating the cached hash value. However, CTransaction is not
// actually immutable; deserialization and assignment are implemented,
// and bypass the constness. This is safe, as they update the entire
// structure, including the hash.
const int32_t nVersion;
const std::vector<CTxIn> vin;
const CAmount nTxFee;
const std::vector<CTxOut> vout;
const uint32_t nLockTime;
/** Construct a CTransaction that qualifies as IsNull() */
CTransaction();
/** Convert a CMutableTransaction into a CTransaction. */
CTransaction(const CMutableTransaction &tx);
CTransaction& operator=(const CTransaction& tx);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
bool fWitness = (nVersion & SERIALIZE_VERSION_MASK_NO_WITNESS) == 0;
bool fOnlyWitness = nVersion & SERIALIZE_VERSION_MASK_ONLY_WITNESS;
bool fBitcoinTx = nVersion & SERIALIZE_VERSION_MASK_BITCOIN_TX;
assert(!fBitcoinTx || (fBitcoinTx && fWitness && !fOnlyWitness));
assert((nType != SER_GETHASH && !fOnlyWitness && fWitness) || nType == SER_GETHASH);
if (!fOnlyWitness) READWRITE(*const_cast<int32_t*>(&this->nVersion));
READWRITE(*const_cast<std::vector<CTxIn>*>(&vin));
if (!fBitcoinTx && !fOnlyWitness) READWRITE(*const_cast<CAmount*>(&nTxFee));
if (!fOnlyWitness) READWRITE(*const_cast<std::vector<CTxOut>*>(&vout));
if (!fOnlyWitness) READWRITE(*const_cast<uint32_t*>(&nLockTime));
if (ser_action.ForRead())
UpdateHash();
}
bool IsNull() const {
return vin.empty() && vout.empty();
}
/* Transaction hash without witness information */
const uint256& GetHash() const {
return hash;
}
/* Transaction hash including witness information */
const uint256& GetFullHash() const {
return hashFull;
}
/* Hash of just witness information */
const uint256& GetWitnessHash() const {
return hashWitness;
}
/* Transaction hash including witness information */
const uint256& GetBitcoinHash() const {
assert(hashBitcoin != 0);
return hashBitcoin;
}
// Compute priority, given priority of inputs and (optionally) tx size
double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const;
// Compute modified tx size for priority calculation (optionally given tx size)
unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const;
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return a.hash == b.hash;
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return a.hash != b.hash;
}
std::string ToString() const;
};
/** A mutable version of CTransaction. */
struct CMutableTransaction
{
int32_t nVersion;
std::vector<CTxIn> vin;
CAmount nTxFee;
std::vector<CTxOut> vout;
uint32_t nLockTime;
CMutableTransaction();
CMutableTransaction(const CTransaction& tx);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
bool fWitness = (nVersion & SERIALIZE_VERSION_MASK_NO_WITNESS) == 0;
bool fOnlyWitness = nVersion & SERIALIZE_VERSION_MASK_ONLY_WITNESS;
bool fBitcoinTx = nVersion & SERIALIZE_VERSION_MASK_BITCOIN_TX;
assert(!fBitcoinTx);
assert((nType != SER_GETHASH && !fOnlyWitness && fWitness) || nType == SER_GETHASH);
if (!fOnlyWitness) READWRITE(this->nVersion);
READWRITE(vin);
if (!fOnlyWitness) READWRITE(nTxFee);
if (!fOnlyWitness) READWRITE(vout);
if (!fOnlyWitness) READWRITE(nLockTime);
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
/** Compute the hash of this CMutableTransaction. This is computed on the
* fly, as opposed to GetHash() in CTransaction, which uses a cached result.
*/
uint256 GetHash() const;
};
#endif // BITCOIN_PRIMITIVES_TRANSACTION_H
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Animation/FTUtils/FTUtils+UIGestureRecognizer.h
|
<gh_stars>1-10
/*
The MIT License
Copyright (c) 2011 Free Time Studios and <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#if kSupportFTAnimation
#if NS_BLOCKS_AVAILABLE
typedef void (^FTGestureActionBlock)(id recognizer);
/**
This category defines methods and properties which allow the use of blocks
for working with `UIGestureRecognizer` and its subclasses.
For more information on working with gestures in iOS, see Apple's
[Event Handling Guide for iOS][1].
[1]:http://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/Introduction/Introduction.html
*/
@interface UIGestureRecognizer(FTBlockAdditions)
#pragma mark - Creating a block based Gesture Recognizer
///---------------------------------------------------------------------------
/// @name Creating a block based Gesture Recognizer
///---------------------------------------------------------------------------
/**
Creates an autoreleased instance of a `UIGestureRecognizer` subclass with
its actionBlock set to `nil`.
@warning *Important:* Until the actionBlock is set, the returned object will do nothing.
@return An instance of a `UIGestureRecognizer` subclass.
@see actionBlock
*/
+ (id)recognizer;
/**
Creates an autoreleased instance of a `UIGestureRecognizer` subclass which
uses _action_ to handle gesture actions.
@return An instance of a `UIGestureRecognizer` subclass.
@param action A block which will handle the gesture actions.
@see actionBlock
*/
+ (id)recognizerWithActionBlock:(FTGestureActionBlock)action;
#pragma mark - Setting and getting the action handler blocks
///---------------------------------------------------------------------------
/// @name Setting and getting the action handler blocks
///---------------------------------------------------------------------------
/**
A block to be executed when a `UIGestureRecognizer` action is fired.
The block is passed a single parameter which is the `UIGestureRecognizer`
instance for this property.
*/
@property (copy) FTGestureActionBlock actionBlock;
/**
A property indicating that the block should *not* be called when
the recognizer fires.
Useful if you need to temporarily disable an action but you still
want the block to be around later on.
*/
@property (nonatomic, assign) BOOL disabled;
@end
#endif
#endif
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/CommonLibraryMacroConfig.h
|
<gh_stars>1-10
//
// CommonLibraryMacroConfig.h
// TCShow
//
// Created by AlexiChen on 16/6/2.
// Copyright © 2016年 AlexiChen. All rights reserved.
//
#ifndef CommonLibraryMacroConfig_h
#define CommonLibraryMacroConfig_h
// 是否支持ADAnimation
#ifndef kSupportADTransition
#define kSupportADTransition 0
#endif
// 是否支持FTAnimation
#ifndef kSupportFTAnimation
#define kSupportFTAnimation 1
#endif
#ifndef kSupportGTM64
#define kSupportGTM64 0
#endif
#ifndef kSupportKeyChainHelper
#define kSupportKeyChainHelper 0
#endif
#ifndef kSupportMKMapViewZoomLevel
#define kSupportMKMapViewZoomLevel 0
#endif
#ifndef kSupportNSDataCommon
#define kSupportNSDataCommon 0
#endif
#ifndef kSupportUIImageImageEffect
#define kSupportUIImageImageEffect 0
#endif
#ifndef kSupportNSObjectKVOCategory
#define kSupportNSObjectKVOCategory 0
#endif
#ifndef kSupportModifyFrame
#define kSupportModifyFrame 0
#endif
#ifndef kSupportUIImageNonCommon
#define kSupportUIImageNonCommon 0
#endif
#ifndef kSupportModifyFrame
#define kSupportModifyFrame 0
#endif
#ifndef kSupportUIViewEffect
#define kSupportUIViewEffect 0
#endif
#ifndef kSupportUnusedCommonView
#define kSupportUnusedCommonView 0
#endif
#ifndef kSupportMKNetworkKit
#define kSupportMKNetworkKit 0
#endif
#ifndef kSupportLibraryPage
#define kSupportLibraryPage 1
#endif
#ifndef kSupportPopupView
#define kSupportPopupView 0
#endif
#ifndef kSupportScrollController
#define kSupportScrollController 0
#endif
#ifndef kSupportUIViewInitMethod
#define kSupportUIViewInitMethod 1
#endif
#ifndef kSupportNetReachablity
#define kSupportNetReachablity 0
#endif
#endif /* CommonLibraryMacroConfig_h */
|
754340156/NQ_quanfu
|
allrichstore/AppDelegate/BaseAppDelegate.h
|
<reponame>754340156/NQ_quanfu
//
// BaseAppDelegate.h
// CommonLibrary
//
// Created by Alexi on 3/6/14.
// Copyright (c) 2014 CommonLibrary. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BaseAppDelegate : UIResponder<UIApplicationDelegate>
{
@protected
UIBackgroundTaskIdentifier _backgroundTaskIdentifier;
}
@property (strong, nonatomic) UIWindow *window;
+ (instancetype)sharedAppDelegate;
- (void)configAppLaunch;
//配置单例
- (void)configureSingle;
//配置极光推送
- (void)configJpushWithLaunchOptions:(NSDictionary *)launchOptions;
//进入登录界面
- (void)enterLoginUI;
// 进入主界面逻辑
- (void)enterMainUI;
// 代码中尽量改用以下方式去push/pop/present界面
- (UINavigationController *)navigationViewController;
- (UIViewController *)topViewController;
- (void)pushViewController:(UIViewController *)viewController;
- (NSArray *)popToViewController:(UIViewController *)viewController;
- (void)pushViewController:(UIViewController *)viewController withBackTitle:(NSString *)title;
- (UIViewController *)popViewController;
- (NSArray *)popToRootViewController;
- (void)presentViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)())completion;
- (void)dismissViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)())completion;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBViewClass/CustomCell/Image_Text_Ver_Cell.h
|
//
// Image_Text_Ver_Cell.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/11.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface Image_Text_Ver_Cell : UICollectionViewCell
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *label;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/Common/Search/C/SearchResultVC.h
|
<reponame>754340156/NQ_quanfu
//
// SearchResultVC.h
// allrichstore
//
// Created by 任强宾 on 16/11/8.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "GoodsListSecondStyleVC.h"
@interface SearchResultVC : GoodsListSecondStyleVC
@property (nonatomic, strong) UITextField *searchTF;
@property (nonatomic, copy) NSString *searchText;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/Home/Message/C/MessageVC.h
|
<filename>allrichstore/UI/Home/Message/C/MessageVC.h
//
// MessageVC.h
// allrichstore
//
// Created by 任强宾 on 16/11/15.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
@interface MessageVC : BaseVC
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Animation/ADTransition/ADTransition.h
|
<reponame>754340156/NQ_quanfu<gh_stars>1-10
//
// ADTransition.h
// CommonLibrary
//
// Created by James on 3/7/14.
// Copyright (c) 2014 CommonLibrary. All rights reserved.
//
#if kSupportADTransition
#import <Foundation/Foundation.h>
@interface ADTransition : NSObject
// modify by James to Add Scale Transition
@property (nonatomic, assign) UIViewController *sourceViewController;
@property (nonatomic, assign) UIView *sourceView;
@property (nonatomic, assign) UIImage *sourceImage;
@property (nonatomic, assign) UIViewController *destinationViewController;
@property (nonatomic, assign) CGSize destinationSize;
@property (nonatomic, assign) UIImage *destinationImage;
@property (nonatomic, strong) UIView *shadowView;
@property (nonatomic, strong) UITapGestureRecognizer *shadowTapGesture;
@property (nonatomic, assign) BOOL presented;
/**
* The length of time to perform the animation.
*/
@property (nonatomic) NSTimeInterval animationDuration;
/**
* Setup the sources for the transition. The snapshot image will be
* taken just before the animation.
* @param sourceView The view to transition from.
* @param sourceViewController The view controller to present from.
*/
- (void)setSourceView:(UIView *)sourceView inViewController:(UIViewController *)sourceViewController;
/**
* Setup the sources for the transition.
* @param sourceView The view to transition from.
* @param sourceViewController The view controller to present from.
* @param sourceImage The placeholder image for the source view. Specifying nil
* will take a snapshot just before the animation.
*/
- (void)setSourceView:(UIView *)sourceView inViewController:(UIViewController *)sourceViewController withSnapshotImage:(UIImage *)sourceImage;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
/**
* Setup the sources for the transition from a
* UICollectionViewController. The source view will be automatically taken from
* the indexPath, and if necessary scrolled into view. The snapshot image will
* be taken just before the animation.
* @param indexPath The index path indicating the cell to animate from
* @param sourceViewController The view controller to present from.
*/
- (void)setSourceIndexPath:(NSIndexPath *)indexPath inCollectionViewController:(UICollectionViewController *)sourceViewController;
/**
* Setup the sources for the transition from a
* UICollectionViewController. The source view will be automatically taken from
* the indexPath, and if necessary scrolled into view.
* @param indexPath The index path indicating the cell to animate from
* @param sourceViewController The view controller to present from.
* @param sourceImage The placeholder image for the source view. Specifying nil
* will take a snapshot just before the animation.
*/
- (void)setSourceIndexPath:(NSIndexPath *)indexPath inCollectionViewController:(UICollectionViewController *)sourceViewController withSnapshotImage:(UIImage *)sourceImage;
#endif
/**
* Setup the sources for the transition from a UITableViewController.
* The source view will be automatically taken from the indexPath, and if
* necessary, scrolled into view. The snapshot image will be taken just before
* the animation.
* @param indexPath The index path indicating the cell to animate from
* @param sourceViewController The view controller to present from.
*/
- (void)setSourceIndexPath:(NSIndexPath *)indexPath inTableViewController:(UITableViewController *)sourceViewController;
/**
* Setup the sources for the transition from a UITableViewController.
* The source view will be automatically taken from the indexPath, and if
* necessary.
* @param indexPath The index path indicating the cell to animate from
* @param sourceViewController The view controller to present from.
* @param sourceImage The placeholder image for the source view. Specifying nil
* will take a snapshot just before the animation.
*/
- (void)setSourceIndexPath:(NSIndexPath *)indexPath inTableViewController:(UITableViewController *)sourceViewController withSnapshotImage:(UIImage *)sourceImage;
/**
* Update the index path when using a UICollectionViewController or
* UITableViewController.
*/
- (void)updateIndexPath:(NSIndexPath *)indexPath;
/**
* Set the view controller to be presented. The snapshot image will be
* taken just before the animation.
* @param destinationViewController The view controller to present.
*/
- (void)setDestinationViewController:(UIViewController *)destinationViewController;
/**
* Set the view controller to be presented.
* @param destinationViewController The view controller to present.
* @param destinationImage The placeholder image for the destination view.
* Specifying nil will take a snapshot just before the animation.
*/
- (void)setDestinationViewController:(UIViewController *)destinationViewController withSnapshotImage:(UIImage *)destinationImage;
/**
* Set the view controller to be presented. The view controller will
* be shown as a child view controller in the given frame. The snapshot image
* will be taken just before the animation.
* @param destinationViewController The view controller to present.
* @param destinationSize The size for the destination view controller to take
* up on the screen.
*/
- (void)setDestinationViewController:(UIViewController *)destinationViewController asChildWithSize:(CGSize)destinationSize;
/**
* Set the view controller to be presented. The view controller will
* be shown as a child view controller in the given frame.
* @param destinationViewController The view controller to present.
* @param destinationSize The size for the destination view controller to take
* up on the screen.
* @param sourceImage The placeholder image for the source view. Specifying nil
* will take a snapshot just before the animation.
*/
- (void)setDestinationViewController:(UIViewController *)destinationViewController asChildWithSize:(CGSize)destinationSize withSnapshotImage:(UIImage *)destinationImage;
/**
* Perform the animation.
*/
- (void)perform;
/**
* Perform the animation.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)performWithCompletion:(void (^)(void))completion;
/**
* Reverse the animation.
*/
- (void)reverse;
/**
* Reverse the animation.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)reverseWithCompletion:(void (^)(void))completion;
// by james modify
- (CGRect)actualRectInView:(UIView *)view;
- (CGRect)fullScreenRect;
- (CGRect)rectAtCenterOfRect:(CGRect)rect withSize:(CGSize)size;
- (CGRect)rectBetween:(CGRect)firstRect andRect:(CGRect)secondRect;
@end
#endif
|
754340156/NQ_quanfu
|
allrichstore/UI/Common/Main/M/BannerModel.h
|
<filename>allrichstore/UI/Common/Main/M/BannerModel.h
//
// BannerModel.h
// LiveTest
//
// Created by 任强宾 on 16/8/29.
// Copyright © 2016年 NeiQuan. All rights reserved.
//
#import "BaseModel.h"
#import "SDCycleScrollView+Extend.h" //轮播图扩展
@interface BannerModel : BaseModel<SDCycleModelAble, NSCopying>
//图片的地址
@property (nonatomic, copy) NSString *bImgurl;
//标题
@property (nonatomic, copy) NSString *bName;
//点击banner之后的跳转的链接地址
@property (nonatomic, copy) NSString *bUrl;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBViewClass/GuidePagesView.h
|
<reponame>754340156/NQ_quanfu<gh_stars>1-10
//
// GuidePagesView.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/4.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
#define MainScreen_width [UIScreen mainScreen].bounds.size.width//宽
#define MainScreen_height [UIScreen mainScreen].bounds.size.height//高
@interface GuidePagesView : UIView
//自定义初始化方法
- (instancetype)initPagesViewWithFrame:(CGRect)frame Images:(NSArray *)images;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Global.h
|
//
// NSObject_Global.h
// CommonLibrary
//
// Created by AlexiChen on 14-1-16.
// Copyright (c) 2014年 CommonLibrary. All rights reserved.
//
//主窗口的宽、高
#define kMainScreenWidth MainScreenWidth()
#define kMainScreenHeight MainScreenHeight()
#define Localized(Str) NSLocalizedString(Str, Str)
static __inline__ CGFloat MainScreenWidth()
{
return UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [UIScreen mainScreen].bounds.size.width : [UIScreen mainScreen].bounds.size.height;
}
static __inline__ CGFloat MainScreenHeight()
{
return UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [UIScreen mainScreen].bounds.size.height : [UIScreen mainScreen].bounds.size.width;
}
//#ifndef DebugLog
//
//#define DebugLog(fmt, ...) {\
// NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];\
// [dateFormatter setDateStyle:NSDateFormatterMediumStyle];\
// [dateFormatter setTimeStyle:NSDateFormatterShortStyle];\
// [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];\
// [[TIMManager sharedInstance] log:TIM_LOG_INFO tag:@"时间统计" msg:[NSString stringWithFormat:(@"[%s Line %d] 时间点:%@ \n" fmt), __PRETTY_FUNCTION__, __LINE__, [dateFormatter stringFromDate:[NSDate date]], ##__VA_ARGS__]];\
// }
//#endif
//角度与弧度转换
#define degreesToRadian(x) (M_PI * (x) / 180.0)
#define radianToDegrees(x) (180.0 * (x) / M_PI)
//判断设备是否是ipad
#define isiPad ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
//判断设备是否IPHONE5
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBCategory/UIScrollView++/UIScrollView+qbExtension.h
|
<filename>allrichstore/Tools/QBClass/QBCategory/UIScrollView++/UIScrollView+qbExtension.h
//
// UIScrollView+qbExtension.h
// allrichstore
//
// Created by 任强宾 on 16/11/27.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIScrollView (qbExtension)
@property (nonatomic, assign) UIEdgeInsets insets;
//设置刷新头
- (void)setRefreshHeader:(id)header;
//设置刷新尾
- (void)setRefreshFooter:(id)footer;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBViewClass/QBNaviBarView.h
|
//
// QBNaviBarView.h
// PRJ_CreditRecruit
//
// Created by 任强宾 on 16/5/17.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface QBNaviBarView : UIView
@property (nonatomic, strong) UIView *statusBar;
@property (nonatomic, strong) UIView *naviBar;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UIView *leftView;
@property (nonatomic, strong) UIView *rightView;
//初始化方法
- (instancetype)initWithStatusBarColor:(UIColor *)statusBarColor
naviBarColor:(UIColor *)naviBarColor;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBCategory/NSString++/NSString+Base64.h
|
//
// NSString+Base64.h
// LiveTest
//
// Created by 任强宾 on 16/8/1.
// Copyright © 2016年 NeiQuan. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (Base64)
/**
* 转换为Base64编码
*/
- (NSString *)base64EncodedString;
/**
* 将Base64编码还原
*/
- (NSString *)base64DecodedString;
@end
|
754340156/NQ_quanfu
|
allrichstore/Other/Rule.h
|
<filename>allrichstore/Other/Rule.h<gh_stars>1-10
//
// Rule.h
// FullRich
//
// Created by 任强宾 on 16/10/26.
// Copyright © 2016年 任强宾. All rights reserved.
//
#ifndef Rule_h
#define Rule_h
/*********************字符长度********************/
#define MaxLength_Title 16 //标题的最大长度
#define Length_verifiCode 6 //短信验证码的长度
#define Length_password_min 6 //密码的最短位数
#define Length_password_max 18 //密码的最长位数
/*********************数字大小********************/
//请求列表每页的大小
#define PageSize_list 10
/*********************时间长度********************/
#define TimeDuration_SendPraise 0.3
#define TimeDuration_RefreshPraise 0.2
//提示语显示后跳转的时间
#define TimeDuration_ToastMsg 1.6
#endif /* Rule_h */
|
754340156/NQ_quanfu
|
allrichstore/UI/Home/SelfBusiness/C/SelfBusinessVC.h
|
//
// SelfBusinessVC.h
// allrichstore
//
// Created by 任强宾 on 16/11/4.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
#import "PulldownMoreView.h" //下拉展示更多菜单
@interface SelfBusinessVC : BaseVC
@end
@interface SelfBusinessModel : NSObject<PulldownMoreModelAble, NSCoding>
@property (nonatomic, assign) long id; //id
@property (nonatomic, copy) NSString *teName; //名称
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Animation/ADTransition/ADHeaders.h
|
<reponame>754340156/NQ_quanfu
//
// ADHeaders.h
// CommonLibrary
//
// Created by James on 3/7/14.
// Copyright (c) 2014 CommonLibrary. All rights reserved.
//
#if kSupportADTransition
#ifndef CommonLibrary_ADHeaders_h
#define CommonLibrary_ADHeaders_h
#import "UIView+CaptureImage.h"
#import "ADTransition.h"
#import "UIViewController+ADTransition.h"
#import "ADFlipTransition.h"
#import "UIViewController+ADFlipTransition.h"
#import "UITableViewController+ADFlipTransition.h"
#import "UICollectionViewController+ADFlipTransition.h"
#import "ADScaleTransition.h"
#import "UIViewController+ADScaleTransition.h"
#import "UITableViewController+ADScaleTransition.h"
#import "UICollectionViewController+ADScaleTransition.h"
#endif
#endif
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Category/UIView+CaptureImage.h
|
<reponame>754340156/NQ_quanfu<gh_stars>1-10
//
// UIView+CaptureImage.h
// CommonLibrary
//
// Created by AlexiChen on 15/12/5.
// Copyright © 2015年 AlexiChen. All rights reserved.
//
#if kSupportADTransition
#import <UIKit/UIKit.h>
@interface UIView (CaptureImage)
- (UIImage *)captureImage;
- (UIImage *)captureImageAtRect:(CGRect)rect;
@end
#endif
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBViewClass/CustomCell/CustomCellHeader.h
|
<gh_stars>1-10
//
// CustomCellHeader.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/11.
// Copyright © 2016年 任强宾. All rights reserved.
//
#ifndef CustomCellHeader_h
#define CustomCellHeader_h
#import "TitleAndPromptCell.h"
#import "IconAndTitleCell.h"
#import "Image_Text_Ver_Cell.h"
#endif /* CustomCellHeader_h */
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Category/NSObject+KVOCategory.h
|
//
// NSObject+KVOCategory.h
// CommonLibrary
//
// Created by Alexi on 5/16/14.
// Copyright (c) 2014 Alexi. All rights reserved.
//
#if kSupportNSObjectKVOCategory
#import <Foundation/Foundation.h>
@interface NSObject (KVOCategory)
- (void)observedBy:(NSObject *)observer forKeyPaths:(NSArray *)keyPaths;
- (void)observedBy:(NSObject *)observer forKeyPaths:(NSArray *)keyPaths options:(NSKeyValueObservingOptions)options;
- (void)cancelObservedBy:(NSObject *)observer forKeyPaths:(NSArray *)keyPaths;
@end
#endif
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBCategory/UITextField++/UITextFieldCategoryHeader.h
|
<filename>allrichstore/Tools/QBClass/QBCategory/UITextField++/UITextFieldCategoryHeader.h<gh_stars>1-10
//
// UITextFieldCategoryHeader.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/4.
// Copyright © 2016年 任强宾. All rights reserved.
//
#ifndef UITextFieldCategoryHeader_h
#define UITextFieldCategoryHeader_h
#import "UITextField+Extension.h"
#endif /* UITextFieldCategoryHeader_h */
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/UIFramework/NSObject+loadPadClass.h
|
//
// NSObject+loadClass.h
// CommonLibrary
//
// Created by <NAME> on 2/28/13.
// Copyright (c) 2013 AlexiChen. All rights reserved.
//
#import <Foundation/Foundation.h>
// 声明:
// 为了区分设备:(iphone ipad)上同一逻辑界面,不同的展现,以及不同的业务处理所封装
// 因为优先完成iphone相关逻辑,对于ipad上不同的处理,作选择性继承
// 命名规则:
// AClassName: iphone处理下相关的类名
// 如果判断当前是ipad时,那么使用以下方法时,发果发现本地有AClassName_Pad这个类,则创建AClassName_Pad相应的实例
// 否则则走iphone相关的逻辑
// 注意以下代码最好只在区分(iphone 与 ipad)上使用
@interface NSObject (loadClass)
- (void)configParams:(id)params;
+ (Class)getPadClass:(Class)phone;
// 等效于使用 [[newClass alloc] init]
+ (id)loadClass:(Class)newClass;
// 等效于使用 [[newClass alloc] initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil]
+ (id)loadClassFromNib:(Class)newClass;
// 等效于使用
// newClassInstance = [[newClass alloc] init]
// [newClassInstance configParams:params]
+ (id)loadClass:(Class)newClass withParams:(id)params;
// 等效于使用
// newClassInstance = [[newClass alloc] init]
// [newClassInstance configParams:params]
+ (id)loadClass:(Class)newClass withParams:(id)params withConfigSelector:(SEL)selector;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBViewClass/BlankPageView.h
|
//
// BlankPageView.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/4.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, BlankPageType)
{
BlankPageTypeView = 0,
BlankPageTypeProject,
BlankPageTypeNoButton,
BlankPageTypeMaterialScheduling
};
@interface BlankPageView : UIView
@property (nonatomic, strong) UIImageView *monkeyView;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UIButton *reloadButton;
@property (nonatomic, copy) void(^reloadButtonBlock)(id sender);
- (void)configWithType:(BlankPageType)blankPageType hasData:(BOOL)hasData noDataStr:(NSString *)noDataStr hasError:(BOOL)hasError errorStr:(NSString *)errorStr reloadButtonBlock:(void(^)(id sender))block;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBCategory/UINavigationController++/UINavigationControllCategoryHeader.h
|
<gh_stars>1-10
//
// UINavigationControllCategoryHeader.h
// allrichstore
//
// Created by 任强宾 on 16/11/2.
// Copyright © 2016年 allrich88. All rights reserved.
//
#ifndef UINavigationControllCategoryHeader_h
#define UINavigationControllCategoryHeader_h
#import "UINavigationController+QBTransition.h"
#endif /* UINavigationControllCategoryHeader_h */
|
754340156/NQ_quanfu
|
allrichstore/UI/Home/Main/V/GoodsListLayoutCell.h
|
//
// GoodsListLayoutCell.h
// allrichstore
//
// Created by zhaozhe on 16/10/31.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseCollectionViewCell.h"
@class GoodsModel;
@interface GoodsListLayoutCell : BaseCollectionViewCell
/** model */
@property(nonatomic,strong) GoodsModel * model;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/Home/SelfBusiness/V/PulldownMenuView/PulldownView.h
|
<gh_stars>1-10
//
// PulldownView.h
// allrichstore
//
// Created by 任强宾 on 16/11/4.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol PulldownViewDelegate <NSObject>
@end
@class PulldownModel;
@interface PulldownView : UIView
{
UIColor *_oneMenuCell_NormalColor; //一级菜单正常色
UIColor *_oneMenuCell_SelectedColor;//一级菜单选中色
UIColor *_twoMenuCell_NormalColor; //二级菜单正常色
UIColor *_twoMenuCell_SelectedColor;//二级菜单选中色
UIImageView *_bottomLineView; //一级菜单底部的滑条
BOOL _isMultiselect; //是否是多选
}
/**
二级下拉菜单
@param frame 初始frame
@param menuModel 菜单数据源model
*/
- (instancetype)initWithFrame:(CGRect)frame
menuModel:(PulldownModel *)menuModel;
@property (nonatomic, strong) PulldownModel *menuModel;
@property (nonatomic, assign) id<PulldownViewDelegate> delegate;
@property (nonatomic, strong) UIColor *oneMenuCell_NormalColor;
@property (nonatomic, strong) UIColor *oneMenuCell_SelectedColor;
@property (nonatomic, strong) UIColor *twoMenuCell_NormalColor;
@property (nonatomic, strong) UIColor *twoMenuCell_SelectedColor;
@property (nonatomic, strong) UIImageView *bottomLineView; //一级菜单底部的滑条
//滑动条的高度
@property (nonatomic, assign) CGFloat slideBarHeight;
//滑动条的宽度
@property (nonatomic, assign) CGFloat slideBarWidth;
//滑动条的颜色
@property (nonatomic, strong) UIColor *slideBarColor;
//滑动条的上偏移
@property (nonatomic, assign) CGFloat slideBarOffSetH;
//滑条的图片
@property (nonatomic, strong) UIImage *sliderImage;
@property (nonatomic, assign) BOOL isMultiselect;
//配置参数
- (void)configParams;
//一级菜单的collectionView
@property (nonatomic, strong) UICollectionView *oneLevelCollectView;
//二级菜单的collectionView
@property (nonatomic, strong) UICollectionView *twoLevelCollectView;
@end
@interface CellButton : UIButton
@end
#pragma mark - 一级菜单的cell
//一级菜单的cell
@interface PulldownOneMenuCell : UICollectionViewCell
@property (nonatomic, strong) UIButton *btn;
@end
#pragma mark - 二级菜单的cell
//二级菜单的cell
@interface PulldownTwoMenuCell : UICollectionViewCell
@property (nonatomic, strong) CellButton *btn;
@end
#pragma mark - 菜单的model
//二级筛选
@class OneMenuModel, TwoMenuModel;
@interface PulldownModel : NSObject
@property (nonatomic, strong) NSArray<OneMenuModel *> *oneMenuArray;
@property (nonatomic, copy) NSString *menuTitle;
@end
@interface OneMenuModel : NSObject
@property (nonatomic, strong) NSArray<TwoMenuModel *> *twoMenuArray;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) BOOL isSelected;
@end
@interface TwoMenuModel : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) BOOL isSelected;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Category/UIView+ModifyFrame.h
|
<reponame>754340156/NQ_quanfu<gh_stars>1-10
//
// UIView+ModifyFrame.h
// CommonLibrary
//
// Created by Alexi on 14-2-21.
// Copyright (c) 2014年 CommonLibrary. All rights reserved.
//
#if kUnSupportModifyFrame
#import <UIKit/UIKit.h>
@interface UIView (ModifyFrame)
@property float x;
@property float y;
@property CGPoint origin;
@property float width;
@property float height;
@property CGSize boundsSize;
- (CGPoint)originRelativeToWindow;
- (CGPoint)centerRelativeToWindow;
- (CGRect)relativeToWindow;
@end
@interface UIViewController (ModifyFrame)
@property float x;
@property float y;
@property float width;
@property float height;
@property CGSize boundsSize;
@end
#endif
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/TipUtility/HUDHelper.h
|
<reponame>754340156/NQ_quanfu<filename>allrichstore/Tools/CommonLibrary/TipUtility/HUDHelper.h
//
// HUDHelper.h
//
//
// Created by Alexi on 12-11-28.
// Copyright (c) 2012年 . All rights reserved.
//
#import "MBProgressHUD.h"
@interface HUDHelper : NSObject
{
@private
MBProgressHUD *_syncHUD;
}
+ (HUDHelper *)sharedInstance;
+ (void)alert:(NSString *)msg;
+ (void)alert:(NSString *)msg action:(CommonVoidBlock)action;
+ (void)alert:(NSString *)msg cancel:(NSString *)cancel;
+ (void)alert:(NSString *)msg cancel:(NSString *)cancel action:(CommonVoidBlock)action;
+ (void)alertTitle:(NSString *)title message:(NSString *)msg cancel:(NSString *)cancel;
+ (void)alertTitle:(NSString *)title message:(NSString *)msg cancel:(NSString *)cancel action:(CommonVoidBlock)action;
// 网络请求
- (MBProgressHUD *)loading;
- (MBProgressHUD *)loading:(NSString *)msg;
- (MBProgressHUD *)loading:(NSString *)msg inView:(UIView *)view;
- (void)loading:(NSString *)msg delay:(CGFloat)seconds execute:(void (^)())exec completion:(void (^)())completion;
- (void)stopLoading:(MBProgressHUD *)hud;
- (void)stopLoading:(MBProgressHUD *)hud message:(NSString *)msg;
- (void)stopLoading:(MBProgressHUD *)hud message:(NSString *)msg delay:(CGFloat)seconds completion:(void (^)())completion;
- (void)tipMessage:(NSString *)msg;
- (void)tipMessage:(NSString *)msg delay:(CGFloat)seconds;
- (void)tipMessage:(NSString *)msg delay:(CGFloat)seconds completion:(void (^)())completion;
// 网络请求
- (void)syncLoading;
- (void)syncLoading:(NSString *)msg;
- (void)syncLoading:(NSString *)msg inView:(UIView *)view;
- (void)syncStopLoading;
- (void)syncStopLoadingMessage:(NSString *)msg;
- (void)syncStopLoadingMessage:(NSString *)msg delay:(CGFloat)seconds completion:(void (^)())completion;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/Common/Invoice/V/InvoiceInfoCell.h
|
//
// InvoiceInfoCell.h
// allrichstore
//
// Created by 任强宾 on 16/11/21.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseTableViewCell.h"
@interface InvoiceInfoCell : BaseTableViewCell
@property (nonatomic, strong) UITextField *rightTF;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/GoodsClass/Main/V/GoodsClassCell.h
|
<reponame>754340156/NQ_quanfu
//
// GoodsClassCell.h
// allrichstore
//
// Created by 任强宾 on 16/11/24.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseCollectionViewCell.h"
#import "GoodsClassModel.h"
//分类菜单的cell
@interface GoodsClassCell : BaseCollectionViewCell
@property (nonatomic, strong) GoodsClassModel *model;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Animation/FTUtils/FTAnimation+UIView.h
|
/*
The MIT License
Copyright (c) 2009 Free Time Studios and <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#if kSupportFTAnimation
#import "FTAnimationManager.h"
#import "NSObject+CommonBlock.h"
/**
This category provides extra methods on `UIView` which make it very easy to use
the FTAnimationManager pre-built animations.
*/
@interface UIView (FTAnimationAdditions)
- (void)animation:(CommonBlock)animationBlock duration:(NSTimeInterval)duration completion:(CommonBlock)block;
///---------------------------------------------------------------------------
/// @name Sliding the view on and off the screen
///---------------------------------------------------------------------------
/**
Slides the view in from the *direction* edge or corner of the screen.
@param direction The edge or corner of the screen where animation will originate.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)slideInFrom:(FTAnimationDirection)direction duration:(NSTimeInterval)duration delegate:(id)delegate;
/**
Slides the view in from a specified edge or corner of the screen.
@param direction The edge or corner of the screen where animation will originate.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@paramstartSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)slideInFrom:(FTAnimationDirection)direction duration:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Slides the view out to the *direction* edge or corner of the screen.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)slideOutTo:(FTAnimationDirection)direction duration:(NSTimeInterval)duration delegate:(id)delegate;
/**
Slides the view out to a specified edge or corner of the screen.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@param startSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)slideOutTo:(FTAnimationDirection)direction duration:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/** Slides the view in from the *direction* edge or corner of the *enclosingView*. */
- (void)slideInFrom:(FTAnimationDirection)direction inView:(UIView*)enclosingView duration:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/** Slides the view out of the *enclosingView* to the *direction* edge or corner. */
- (void)slideOutTo:(FTAnimationDirection)direction inView:(UIView*)enclosingView duration:(NSTimeInterval)duration
delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Backs the view out to a specified edge or corner of the screen. The view will make a
slight movement in the opposite *direction* before sliding offscreen.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)backOutTo:(FTAnimationDirection)direction withFade:(BOOL)fade duration:(NSTimeInterval)duration delegate:(id)delegate;
/**
Backs the view out to a specified edge or corner of the screen. The view will make a
slight movement in the opposite *direction* before sliding offscreen.
@param direction The edge or corner of the screen where animation will originate.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@param startSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)backOutTo:(FTAnimationDirection)direction withFade:(BOOL)fade duration:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Backs the view in from a specified edge or corner of the screen. The view will make a
slight movement in the opposite *direction* before sliding onscreen.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)backInFrom:(FTAnimationDirection)direction withFade:(BOOL)fade duration:(NSTimeInterval)duration delegate:(id)delegate;
/**
Backs the view in from a specified edge or corner of the screen. The view will make a
slight movement in the opposite *direction* before sliding onscreen.
@param direction The edge or corner of the screen where animation will originate.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@param startSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)backInFrom:(FTAnimationDirection)direction withFade:(BOOL)fade duration:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Backs the view off of a specified edge or corner of the *enclosingView*. The view will
make a slight movement in the opposite *direction* before sliding off of the *enclosingView*.
*/
- (void)backOutTo:(FTAnimationDirection)direction inView:(UIView*)enclosingView withFade:(BOOL)fade duration:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Backs the view in from a specified edge or corner of the *enclosingView*. The view will
make a slight movement in the opposite *direction* before sliding over the *enclosingView*.
*/
- (void)backInFrom:(FTAnimationDirection)direction inView:(UIView*)enclosingView withFade:(BOOL)fade duration:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
///---------------------------------------------------------------------------
/// @name Fading the view in and out
///---------------------------------------------------------------------------
/**
Causes the view to fade in from invisible to fully opaque.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)fadeIn:(NSTimeInterval)duration delegate:(id)delegate;
/**
Causes the view to fade in from invisible to fully opaque.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@param startSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)fadeIn:(NSTimeInterval)duration delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Causes the view to fade out until it is invisible.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)fadeOut:(NSTimeInterval)duration delegate:(id)delegate;
/**
Causes the view to fade out until it is invisible.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@param startSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)fadeOut:(NSTimeInterval)duration delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Causes the background color of the view to fade in from invisible to completely
opaque.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)fadeBackgroundColorIn:(NSTimeInterval)duration delegate:(id)delegate;
/**
Causes the background color of the view to fade in from invisible to completely
opaque.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@param startSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)fadeBackgroundColorIn:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
Causes the background color of the view to fade out until it is invisible.
@param direction The edge or corner of the screen where animation will end.
@param duration The duration (in seconds) of the animation.
@param delegate The *delegate* will be forwarded the standard `CAAnimationDelegate`
methods.
*/
- (void)fadeBackgroundColorOut:(NSTimeInterval)duration delegate:(id)delegate;
/**
Causes the background color of the view to fade out until it is invisible.
@param duration The duration (in seconds) of the animation.
@param delegate An object on which to send the *startSelector* and *stopSelector*
messages. The animation framework _does not_ retain *delegate*. If it is `nil`,
neither message will be sent.
@param startSelector A selector to be messaged on *delegate* right before the start
of the animation. This parameter can be `nil`.
@param startSelector A selector to be messaged on *delegate* after the animation has
finished normally or been cancelled. This parameter can be `nil`.
*/
- (void)fadeBackgroundColorOut:(NSTimeInterval)duration delegate:(id)delegate
startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
///---------------------------------------------------------------------------
/// @name Scaling the view up and down
///---------------------------------------------------------------------------
/**
Pops the view in from the center of the screen similar to the animation of a `UIAlertView`.
The view will start invisible and small in the center of the screen, and it will be animated
to its final size with a rubber band bounce at the end.
*/
- (void)popIn:(NSTimeInterval)duration delegate:(id)delegate;
/**
Pops the view in from the center of the screen similar to the animation of a `UIAlertView`.
The view will start invisible and small in the center of the screen, and it will be animated
to its final size with a rubber band bounce at the end.
*/
- (void)popIn:(NSTimeInterval)duration delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
This is the reverse of the *popIn* animation. The view will scale to a slightly larger size
before shrinking to nothing in the middle of the screen.
*/
- (void)popOut:(NSTimeInterval)duration delegate:(id)delegate;
/**
This is the reverse of the *popIn* animation. The view will scale to a slightly larger size
before shrinking to nothing in the middle of the screen.
*/
- (void)popOut:(NSTimeInterval)duration delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
The view will fade in and shrink from double its size down to its regular size. This makes
it appear as though the view is falling onto the screen from the user's vantage point.
*/
- (void)fallIn:(NSTimeInterval)duration delegate:(id)delegate;
/**
The view will fade in and shrink from double its size down to its regular size. This makes
it appear as though the view is falling onto the screen from the user's vantage point.
*/
- (void)fallIn:(NSTimeInterval)duration delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
The view will shrink to nothing in the middle of the screen and disappear.
*/
- (void)fallOut:(NSTimeInterval)duration delegate:(id)delegate;
/**
The view will shrink to nothing in the middle of the screen and disappear.
*/
- (void)fallOut:(NSTimeInterval)duration delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
/**
The view will scale up to twice its size while fading to invisible.
*/
- (void)flyOut:(NSTimeInterval)duration delegate:(id)delegate;
/**
The view will scale up to twice its size while fading to invisible.
*/
- (void)flyOut:(NSTimeInterval)duration delegate:(id)delegate startSelector:(SEL)startSelector stopSelector:(SEL)stopSelector;
@end
#endif
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBCategory/UILabel++/UILabelCategoryHeader.h
|
<gh_stars>1-10
//
// UILabelCategoryHeader.h
// MeiYiQuan
//
// Created by 任强宾 on 16/9/29.
// Copyright © 2016年 任强宾. All rights reserved.
//
#ifndef UILabelCategoryHeader_h
#define UILabelCategoryHeader_h
#import "UILabel+Compute.h" //计算
#endif /* UILabelCategoryHeader_h */
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Animation/ADTransition/Flip/UIViewController+ADFlipTransition.h
|
<reponame>754340156/NQ_quanfu
/*
* The MIT License (MIT)
*
* Copyright (c) 2012-2013 <NAME>. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#if kSupportADTransition
#import <UIKit/UIKit.h>
#import "ADFlipTransition.h"
/**
* A convenience category on UIViewController to easily present and dismiss
* using ADFlipTransition.
*/
@interface UIViewController (ADFlipTransition)
/**
* Present a view controller modally from the current view controller using a
* flip animation.
* @param destinationViewController The view controller to present
* @param sourceView A subview of the current view controller to flip from
* @param completion A block to run on completion. Can be NULL.
*/
- (void)flipToViewController:(UIViewController *)destinationViewController fromView:(UIView *)sourceView withCompletion:(void (^)(void))completion;
/**
* Present a view controller modally from the current view controller using a
* flip animation.
* @param destinationViewController The view controller to present
* @param sourceView A subview of the current view controller to flip 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)flipToViewController:(UIViewController *)destinationViewController fromView:(UIView *)sourceView withSourceSnapshotImage:(UIImage *)sourceSnapshot andDestinationSnapshot:(UIImage *)destinationSnapshot withCompletion:(void (^)(void))completion;
/**
* Present a view controller as a child view controller from the current view
* controller using a flip animation.
* @param destinationViewController The view controller to present
* @param sourceView A subview of the current view controller to flip 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)flipToViewController:(UIViewController *)destinationViewController fromView:(UIView *)sourceView asChildWithSize:(CGSize)destinationSize withCompletion:(void (^)(void))completion;
/**
* Present a view controller as a child view controller from the current view
* controller using a flip animation.
* @param destinationViewController The view controller to present
* @param sourceView A subview of the current view controller to flip 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)flipToViewController:(UIViewController *)destinationViewController fromView:(UIView *)sourceView asChildWithSize:(CGSize)destinationSize withSourceSnapshotImage:(UIImage *)sourceSnapshot andDestinationSnapshot:(UIImage *)destinationSnapshot withCompletion:(void (^)(void))completion;
/**
* Dismiss the current modal view controller with a flip animation.
* @discussion Only works when the current view controller has been presented
* using one of the category convenience methods to present the view controller.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)dismissFlipWithCompletion:(void (^)(void))completion;
/**
* Dismiss the current modal view controller with a flip animation to a cell in
* a UICollectionViewController or UITableViewController.
* @discussion Only works when the current view controller has been presented
* using one of the category convenience methods to present the view controller.
* @param indexPath The location of the cell to flip back to.
* @param completion A block to run on completion. Can be NULL.
*/
- (void)dismissFlipToIndexPath:(NSIndexPath *)indexPath withCompletion:(void (^)(void))completion;
@end
#endif
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBViewClass/FoldMenuView/FoldMenu_HeaderView.h
|
<gh_stars>1-10
//
// FoldMenu_HeaderView.h
// allrichstore
//
// Created by 任强宾 on 16/11/3.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FoldMenu_HeaderView : UITableViewHeaderFooterView
@property (nonatomic, strong) QButton *menuBtn;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/Common/GoodDetail/Comment/M/SecondCommentModel.h
|
//
// SecondCommentModel.h
// allrichstore
//
// Created by zhaozhe on 16/11/23.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseModel.h"
@interface SecondCommentModel : BaseModel
/** icon */
@property(nonatomic,copy) NSString * icon;
/** title */
@property(nonatomic,copy) NSString * title;
/** content */
@property(nonatomic,copy) NSString * content;
/** time */
@property(nonatomic,copy) NSString * time;
/** 评论id */
@property(nonatomic,copy) NSString * cmid;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBUIClass/LabelCell.h
|
//
// LabelCell.h
// allrichstore
//
// Created by 任强宾 on 16/11/17.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface LabelCell : UITableViewCell
@property (nonatomic, strong) UILabel *label;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/CommonView/ImageTitleButton.h
|
//
// ImageTitleButton.h
// CommonLibrary
//
// Created by Alexi on 3/21/14.
// Copyright (c) 2014 Alexi. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MenuButton.h"
typedef enum
{
EImageTopTitleBottom,
ETitleTopImageBottom,
EImageLeftTitleRight,
ETitleLeftImageRight,
EImageLeftTitleRightLeft,
EImageLeftTitleRightCenter,
ETitleLeftImageRightCenter,
ETitleLeftImageRightLeft,
EFitTitleLeftImageRight, // 根据内容调整
}ImageTitleButtonStyle;
@interface ImageTitleButton : MenuButton
{
@protected
UIEdgeInsets _margin;
CGSize _padding;
CGSize _imageSize;
ImageTitleButtonStyle _style;
}
@property (nonatomic, assign) UIEdgeInsets margin;
@property (nonatomic, assign) CGSize padding;
@property (nonatomic, assign) CGSize imageSize;
@property (nonatomic, assign) ImageTitleButtonStyle style;
- (instancetype)initWithStyle:(ImageTitleButtonStyle)style;
- (instancetype)initWithStyle:(ImageTitleButtonStyle)style maggin:(UIEdgeInsets)margin;
- (instancetype)initWithStyle:(ImageTitleButtonStyle)style maggin:(UIEdgeInsets)margin padding:(CGSize)padding;
- (void)setTintColor:(UIColor *)color;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/Login/C/LoginVC.h
|
<filename>allrichstore/UI/Login/C/LoginVC.h<gh_stars>1-10
//
// LoginVC.h
// allrichstore
//
// Created by 任强宾 on 16/10/31.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
@interface LoginVC : BaseVC
/** 登录成功回调 */
@property(nonatomic,copy) void (^loginSuccessBlock)();
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/CommonView/CommonViewHeaders.h
|
<reponame>754340156/NQ_quanfu
//
// CommonViewHeaders.h
// CommonLibrary
//
// Created by AlexiChen on 14-1-17.
// Copyright (c) 2014年 CommonLibrary. All rights reserved.
//
#ifndef CommonLibrary_CommonViewHeaders_h
#define CommonLibrary_CommonViewHeaders_h
#import "MenuButton.h"
#if kSupportUnusedCommonView
#import "CheckButton.h"
#import "MoreTableView.h"
#endif
#import "ImageTitleButton.h"
#import "KeyValueTableViewController.h"
#endif
|
754340156/NQ_quanfu
|
allrichstore/UI/Common/GoodDetail/Comment/C/CommentVC.h
|
<reponame>754340156/NQ_quanfu<filename>allrichstore/UI/Common/GoodDetail/Comment/C/CommentVC.h<gh_stars>1-10
//
// CommentVC.h
// allrichstore
//
// Created by zhaozhe on 16/11/3.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
@interface CommentVC : BaseVC
/** 商品id */
@property(nonatomic,copy) NSString * goodId;
@end
|
754340156/NQ_quanfu
|
allrichstore/Library/SGPickerView_DatePicker/SGLocationPickerSheetView.h
|
//
// SGLocationPickerSheetView.h
// SGPickerView_DatePickerExample
//
// Created by Sorgle on 16/9/23.
// Copyright © 2016年 Sorgle. All rights reserved.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
//
// - - 如在使用中, 遇到什么问题或者有更好建议者, 请于<EMAIL>邮箱联系 - - - - - //
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - GitHub下载地址 https://github.com/kingsic/SGPickerView_DatePicker.git - - //
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
#import <UIKit/UIKit.h>
@interface SGLocationPickerSheetView : UIView
/** pickerView */
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
/** 取消按钮的点击事件 */
- (void)addTargetCancelBtn:(id)target action:(SEL)action;
/** 确定按钮的点击事件 */
- (void)addTargetSureBtn:(id)target action:(SEL)action;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBViewClass/PickerView.h
|
//
// PickerView.h
// MeiYiQuan
//
// Created by 任强宾 on 16/9/28.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, PickerViewType)
{
PickerViewTypeNormal = 0,
PickerViewTypeHaveBtn
};
typedef void(^PickerViewBlock)(NSArray *selectedArray);
@interface PickerView : UIView <UIPickerViewDelegate, UIPickerViewDataSource>
/**
* 自定义初始化方法
*
* @param style 类型
* @param dataArray 数组嵌套数组的形式传进来
* @param block 内部事件通过block传递出来
*/
- (instancetype)initWithStyle:(PickerViewType)style dataArray:(NSArray *)dataArray pickerViewHeight:(CGFloat)pickerViewHeight inView:(UIView *)view block:(PickerViewBlock)block;
//显示
- (void)show;
//隐藏
- (void)dismiss;
//绑定默认值
- (void)configDataFromArray:(NSArray *)array;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/QBClass/QBUIClass/TextField.h
|
//
// TextField.h
// PRJ_CreditRecruit
//
// Created by apple on 16/2/29.
// Copyright © 2016年 河南维创盈通科技有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TextField : UITextField
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Animation/ADTransition/Flip/ADFlipTransition.h
|
#if kSupportADTransition
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
// Flip Transition
@interface ADFlipTransition : ADTransition
@end
#endif
|
754340156/NQ_quanfu
|
allrichstore/UI/Login/C/ThirdLoginVC.h
|
<gh_stars>1-10
//
// ThirdLoginVC.h
// allrichstore
//
// Created by 任强宾 on 16/11/15.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
@interface ThirdLoginVC : BaseVC
//第三方登录的类型
@property (nonatomic, assign) ThirdLoginType thirdLoginType;
//第三方登录的昵称
@property (nonatomic, copy) NSString *thirdNickName;
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/ShoppingCart/CreateOrder/V/CreateOrderMessageCell.h
|
//
// CreateOrderMessageCell.h
// allrichstore
//
// Created by zhaozhe on 16/11/21.
// Copyright © 2016年 allrich88. All rights reserved.
//买家留言
#import "BaseTableViewCell.h"
@interface CreateOrderMessageCell : BaseTableViewCell
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/ShoppingCart/CreateOrder/C/CreateOrderVC.h
|
//
// CreateOrderVC.h
// allrichstore
//
// Created by zhaozhe on 16/11/16.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseVC.h"
@interface CreateOrderVC : BaseVC
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/ShoppingCart/Main/M/ShoppingCartModel.h
|
//
// ShoppingCartModel.h
// allrichstore
//
// Created by zhaozhe on 16/11/15.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import "BaseModel.h"
#define kCellHeight 120.0f
#define kHeaderH 45.0f
typedef NS_ENUM(NSInteger, HeadClickState) {
HeadClickStateNormal,
HeadClickStateSelected
};
typedef NS_ENUM(NSInteger, CellClickState) {
CellClickStateNormal,
CellClickStateSelected
};
@class ShoppingCartListModel;
@interface ShoppingCartModel : BaseModel
/** 店铺名 */
@property(nonatomic,copy) NSString * shopName;
/** 头部选中状态 */
@property (nonatomic,assign) BOOL isHeadSelected;
/** 商品数组 */
@property(nonatomic,strong) NSArray <ShoppingCartListModel*>* goods;
- (void)resetHeadClickState;
- (void)resetCellClickState;
- (void)resetAllState:(BOOL)state;
@end
@interface ShoppingCartListModel : BaseModel
/** 商品头像 */
@property(nonatomic,copy) NSString * icon;
/** 商品名 */
@property(nonatomic,copy) NSString * title;
/** 副标题1 */
@property(nonatomic,copy) NSString * subTitle1;
/** 副标题2 */
@property(nonatomic,copy) NSString * subTitle2;
/** 价格 */
@property(nonatomic,copy) NSString * price;
/** 当前数量 */
@property(nonatomic,copy) NSString * count;
/** 库存 */
@property(nonatomic,copy) NSString * inventory;
/** cell 选中状态 */
@property (nonatomic, assign) BOOL isCellSelected;
@end
|
754340156/NQ_quanfu
|
allrichstore/Base/V/NetErrorItem.h
|
//
// NetErrorItem.h
// LiveTest
//
// Created by 任强宾 on 16/9/13.
// Copyright © 2016年 NeiQuan. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface NetErrorItem : UICollectionViewCell
@end
|
754340156/NQ_quanfu
|
allrichstore/UI/ShoppingCart/CreateOrder/V/CreateOrderHeaderView.h
|
<gh_stars>1-10
//
// CreateOrderHeaderView.h
// allrichstore
//
// Created by zhaozhe on 16/11/16.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
@class CreateOrderModel;
@protocol CreateOrderHeaderViewDelegate <NSObject>
- (void)CreateOrderHeaderViewDelegate_clickSelf;
@end
@interface CreateOrderHeaderView : UIView
/** model */
@property(nonatomic,strong) CreateOrderModel * model;
/** 代理*/
@property (nonatomic,weak) id <CreateOrderHeaderViewDelegate> delegate;
@end
|
754340156/NQ_quanfu
|
allrichstore/Tools/CommonLibrary/Font/FontHelper.h
|
<gh_stars>1-10
//
// FontHelper.h
// CommonLibrary
//
// Created by Alexi on 13-10-22.
// Copyright (c) 2013年 ywchen. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FontHelper : NSObject
// 标题字体
@property (nonatomic, readonly) UIFont *titleFont;
// 子标题字体
@property (nonatomic, readonly) UIFont *subTitleFont;
// 文本字体
@property (nonatomic, readonly) UIFont *textFont;
// 子文本字体
@property (nonatomic, readonly) UIFont *subTextFont;
// 提示语字体
@property (nonatomic, readonly) UIFont *tipFont;
// 超大号字体
@property (nonatomic, readonly) UIFont *superLargeFont;
// 大号字体
@property (nonatomic, readonly) UIFont *largeFont;
// 中号字体
@property (nonatomic, readonly) UIFont *mediumFont;
// 小号字体
@property (nonatomic, readonly) UIFont *smallFont;
+ (instancetype)shareHelper;
+ (UIFont *)fontWithName:(NSString *)name size:(CGFloat)size;
+ (UIFont *)fontWithSize:(CGFloat)size;
+ (UIFont *)boldFontWithSize:(CGFloat)size;
@end
|
754340156/NQ_quanfu
|
allrichstore/Base/V/BaseTableViewCell.h
|
//
// BaseTableViewCell.h
// MeiYiQuan
//
// Created by 任强宾 on 16/10/21.
// Copyright © 2016年 任强宾. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, CellBtnStyle)
{
CellBtnStyle_Play = 1,
CellBtnStyle_Share,
CellBtnStyle_Comment,
CellBtnStyle_Like,
CellBtnStyle_DisLike,
};
@interface BaseTableViewCell : UITableViewCell
{
UIButton *_imgBtn; //展示图标的btn
UIImageView *_imgView; //展示图片的imageView
UILabel *_titleLabel; //展示标题的label
UILabel *_contentLabel; //展示内容的label
UILabel *_timeLabel; //展示时间的label
UILabel *_stateLabel; //展示当前状态的
BOOL _isHaveSeleBgView; //是否有选中背景色
UIColor *_seleBgColor; //选中背景色的颜色
BOOL _isHaveHighlightColor; //是否有高亮背景色
UIColor *_highlightBgColor; //高亮时的背景颜色
BOOL _isEditState; //是否是编辑状态
}
@property (nonatomic, strong) UIButton *imgBtn;
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UILabel *stateLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIView *bottomLineView;
@property (nonatomic, assign) CGFloat bottomMargin;
@property (nonatomic, assign) CGFloat bottomLeftMargin;
@property (nonatomic, assign) CGFloat bottomRightMargin;
@property (nonatomic, assign) CGFloat bottomHeight;
@property (nonatomic, strong) UIColor *boottomLineColor;
@property (nonatomic, assign) BOOL isHaveSeleBgView;
@property (nonatomic, strong) UIColor *seleBgColor;
@property (nonatomic, assign) BOOL isHaveHighlightColor;
@property (nonatomic, strong) UIColor *highlightBgColor;
@property (nonatomic, assign) BOOL isEditState;
- (void)createViews;
- (void)layoutViews;
+ (CGFloat)cellHeight;
@end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.