repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
cran/edesign
src/edesign.h
#ifndef EDESIGN_H #define EDESIGN_H #include "entrp.h" /* C and Fortran interface */ #endif
cran/edesign
src/entrp.h
<reponame>cran/edesign<filename>src/entrp.h<gh_stars>1-10 #ifndef ENTRP_H #define ENTRP_H #include "R.h" /* for F77_NAME */ /* exported functions, called from R code */ extern void F77_NAME(grd) (double *a,int *lda,int *na,int *nf,int *ne, int *ns,int *s,double *opt,int *ind,double *as, int *ldas,double *bs,int *ldbs,double *inv, int *ldinv,double *v,double *w,int *ierr); extern void F77_NAME(grddl) (double *a,int *lda,int *na,int *nf,int *ne, int *ns,int *s,double *opt,int *ind,double *as, int *ldas,double *bs,int *ldbs,int *ierr); extern void F77_NAME(change) (double *a,int *lda,int *na,int *nf,int *ne, int *ns,int *s,double *opt,int *ind,double *as, int *ldas,double *bs,int *ldbs,double *inv, int *ldinv,double *v,double *w,int *ierr); extern void F77_NAME(subde1) (double *det,double *a,int *lda,int *na, double *as,int *ldas,int *ind,int *ni, double *bs,int *ldbs,int *ierr); /* internal functions, called from C code */ extern double F77_NAME(upbnd)(double*,int*,int*,int*,int*,int*,int*,double*, int*,double*,int*,double*,int*,double*,int*, int*,int*,double*,double*,int*,int*); extern double F77_NAME(subdet)(double*,int*,int*,double*,int*,int*, double*, int*,int*,double*); extern double F77_NAME(chdet)(double*,int*,int*); extern void F77_NAME(chol1)(double*,int*,int*,double*,int*,int*); extern void F77_NAME(ivecpr)(int*,int*); extern void F77_NAME(psubm)(double*,int*,int*,double*,int*,int*,int*); /* main C function */ void entrp(double *A,int *lda,int *na,int *nf,int *ne,int *ns,int *S, double *opt,int *S_Work,int *F,int *E,int *ind,int *ind1, double *As,int *ldas,double *Bs,int *ldbs,double *Cs,int *ldcs, double *Inv,int *ldinv,double *W,double* WORK,int *LWORK, int *IWORK,double *tol,int *maxcount,int *iter,int *verbose); #endif
matthew-macgregor/cpp-dotnet-core-dllimport
src/cpp-lib/so-demo.h
#ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 # ifdef MODULE_API_EXPORTS # define MODULE_API __declspec(dllexport) # else # define MODULE_API __declspec(dllimport) # endif #else #define MODULE_API #endif MODULE_API void RunningInNativeCPP(); #ifdef __cplusplus } #endif
Rubetoman/Zork
Zork/Zork/Entity.h
<reponame>Rubetoman/Zork<filename>Zork/Zork/Entity.h #include <string> #pragma once using namespace std; /* Base class for classes that have a name as a variable.*/ class Entity { protected: string name; // Name of the Entity. public: void setName(string name); // Sets the name variable of the Entity. string getName(); // Get the name variable of Entity. };
Rubetoman/Zork
Zork/Zork/RoomFunctions.h
<filename>Zork/Zork/RoomFunctions.h #ifndef ROOMFUNCTIONS_H // To make sure you don't declare the function more than once by including the header multiple times. #define ROOMFUNCTIONS_H #include <string> #include <vector> #include "main.h" #pragma once /* Show names of the Rooms stored on rooms vector. They are shown followed by a number so the player inserts the number of the room desired. */ void showRooms(); /* Prints out the name of the Items stored on the Room the player currently is. It is used to number and show the Items so the player can choose one of them. */ void showRoomItems(); /* Looks for pickupable Items on the Room where the player is located. Lets the player to pick up one of the Items showed. */ void lookForItems(); /* Change player position to another Room.*/ Room move(); #endif
Rubetoman/Zork
Zork/Zork/main.h
#ifndef MAIN_H // To make sure you don't declare the function more than once by including the header multiple times. #define MAIN_H #include <string> #include <vector> #include "Item.h" #include "Inventory.h" #include "InventoryFunctions.h" #include "Room.h" #pragma once using namespace std; // Global variables extern Inventory inventory; // Inventory of the player: contains all picked up objects. extern Room bedroom; /* Rooms declarations*/ extern Room livingRoom; extern Room kitchen; extern Room toilet; extern Room entrance; extern Room currentRoom; // Room where the player currently is. extern vector<Room> rooms; // Vector with all the rooms on the current map. /* Gets player Input introduced on the console in form of integer. The range for the integer must be declared by passing minimum and maximum values. The options provided to player are always numbered and the player will Input the number of the option choosen. */ int getInput(int min, int max); /* Waits for the player to press any key on the keyboard. Shows a message that depends on the boolean: true-> back, false-> continue. This gives time for the player to read what is printed by the application. */ void waitForInput(bool back); /* Animation for the text displayed. Prints the string passed as an agument followed by three dots with some time between. Gives the player the impression that something is being computed and gives time between actions. */ void showLoadingText(string text); /* Controlls the main structure of the game. Shows options of each room and class other functions to manage the gameplay. */ void game(); /* Initializes all the variables and objects for the game. */ void initialization(); /* Shows text of the file whose name is passed as an argument. If the .txt file it's on a different folder give the path also. Used to show title and README. */ void openFile(string fileName); /* Main menu to choose between play the game, open README or exit. */ void mainMenu(); #endif
Rubetoman/Zork
Zork/Zork/Item.h
<reponame>Rubetoman/Zork #include "Entity.h" #include <string> #include <vector> #pragma once class Item : public Entity { protected: string description; // Description of the Item. Will be shown when examining the Item. vector<Item> compatibleItems; // Items that can be combined with it. public: void setDescription(string description); // Set a description for the Item. string getDescription(); // Get the description of the Item. void setCompatibleItem(Item i); // Set an Item compatible to combine it. void setCompatibleItems(vector<Item> v); // Set some Items compatible to combine them with it. vector<Item> getCompatibleItems(); // Get a vector with all the compatible Items. bool isCompatible(Item i); // Check if an Item is compatible to combine them. };
Rubetoman/Zork
Zork/Zork/Inventory.h
#ifndef INVENTORY_H // To make sure you don't declare the function more than once by including the header multiple times. #define INVENTORY_H #include "Entity.h" #include "Item.h" #include <string> #include <vector> #pragma once /* Inventory object that inherits from Entity. Is used to store Items inside, mainly for the player inventory. */ class Inventory : public Entity { protected: vector<Item> items; // Items stored on the Inventory. public: int getItemNumber(Item i); // Get the number on the inventory of an Item. int getItemNumber(string name); // Get the number on the inventory of an Item by its name. void addItem(Item i); // Add an item to the Inventory. void addItems(vector<Item> v); // Add some Items to the Inventory. void deleteItem(Item i); // Deletes an Item from Inventory. void deleteItem(size_t number); // Deletes an Item from the Inventory by passsing the number of the Item inside the Inventory. bool hasItem(Item i); // Check whether an Item is located on the Inventory. bool hasItem(string i); // Check whether an Item with the name given is located on the Inventory. vector<Item> getItems(); // Returns a vector with the Items located on the Inventory. }; #endif
Rubetoman/Zork
Zork/Zork/InventoryFunctions.h
#ifndef INVENTORYFUNCTIONS_H // To make sure you don't declare the function more than once by including the header multiple times. #define INVENTORYFUNCTIONS_H #include "Item.h" #pragma once using namespace std; /* Drop an Item of the player's Inventory on the room the player currently is located. The Item is deleted from player's Inventory and stored at the end of the Room Items vector. */ void dropItem(int number); /* Pick up an Item from the Room the player is located and add it to the player's Inventory. The Item is removed from the Items vector of the Room and added at the end of the player Inventory. */ void pickUpItem(int number); /* Shows the description variable of an Item. It's called when the player chooses to examine the Item. It calls to WaitForInput to give time to the player to read the description. */ void showItemDescription(int number); /* Prints the names of the Items that can be combined with the Item given and are stored on the player's Inventory. It's needed so the player can choose the Item to combine with the one selected before. */ int showCombinableItems(Item i); /* Get the name of a combinable Item with the one given. The combinable Item will be the one on the position given as an Integer. It's used because the player chooses the Item by position and not by name. */ string getCombinableItemName(Item i, int number); /* Combine two Items chosen by the position inside the Inventory into a new Item alone. */ void combineItems(int itemA, int itemB); /* Manages the selection of the Item to combine with the one already provided. */ void chooseToCombine(int number); /* Manages the Item selected by the player. Lets the player examine, drop and combine the Item selected from the Inventory. */ void manageItem(int itemNumber); /* Prints out the name of the Items stored on player's Inventory. It is used to number and show the Items so the player can choose one of them. */ void showPlayerItems(); /* Function used to manage the Items inside player's Inventory. Lets the player choose between all the Items inside the Inventory. */ void manageInventory(); #endif
Rubetoman/Zork
Zork/Zork/Game.h
<reponame>Rubetoman/Zork #pragma once #include "stdafx.h" #include "Functions.h" #include <iostream> #include <string> #include <conio.h> #include <iomanip> #include <stdlib.h> using namespace std; class Game { public: Game(); virtual ~Game(); //Operators //Functions void mainMenu(); //Accessors inline bool getPlaying() const { return this->playing; } //Modifiers private: int choice; bool playing; };
Rubetoman/Zork
Zork/Zork/Room.h
<reponame>Rubetoman/Zork<filename>Zork/Zork/Room.h #ifndef ROOM_H // To make sure you don't declare the function more than once by including the header multiple times. #define ROOM_H #include "Entity.h" #include "Item.h" #include <string> #include <vector> #pragma once /* Room object that inherits from Entity. Is used for each location of the map and store on them useful variables. */ class Room : public Entity { protected: string description; // Description of the room. vector<Item> items; // Items stored on the room. vector<Room> connectedRooms;// Rooms that can be accessed from the room. public: void setDescription(string description); // Set a description for the Room. string getDescription(); // Get description of the Room. void setConnectedRoom(Room r); // Set a Room connected. void setConnectedRooms(vector<Room> v); // Set some Rooms connected. vector<Room> getConnectedRooms(); // Get a vector with Rooms connected. bool isRoomConnected(Room r); // See if a room is connected. void addItem(Item i); // Add an Item to the Room storage. void addItems(vector<Item> v); // Add some Items to the Room storage. void deleteItem(Item i); // Remove an Item from Room storage. vector<Item> getItems(); // Get a vector with all the Items stored on the Room. int getItemNumber(string name); // Get an integer with a position of the Item passed by name. }; #endif
darkomen/TFG
programacion/PLC/fuzzy_v1.c
<gh_stars>1-10 (*Vamos almacenando el diámetro medido e incrementamos el numero de muestras tomadas.*) dim_acumulado:=dim_acumulado+dim; n_actual:=n_actual+1; (*Si hemos tomado el numero deseado de muetras empiezamos el control*) IF n_actual >= n THEN (*Calculamos la media*) dim_media:=(dim_acumulado/n); (*Ajustamos la velocidad*) (*Si estamos por debajo del rango, disminuimos la velocidad*) IF (dim_media <= (1.60) ) THEN caso:=0; v:=v-d_v*5; ELSIF (dim_media > (1.60) AND dim_media < (1.70) ) AND (dim_media_ant<dim_media)THEN caso:=1; v:=v+d_v*2.5; ELSIF (dim_media > (1.60) AND dim_media < (1.70) ) AND (dim_media_ant>dim_media)THEN caso:=2; v:=v-d_v*2.5; ELSIF (dim_media >= (1.70)) AND (dim_media <= (1.75) ) AND (dim_media_ant<dim_media)THEN caso:=3; (*12/08/2015 con esta velocidad es una buena aproximació v:=v+d_v*1;*) v:=v+d_v*2; ELSIF (dim_media >= (1.70)) AND (dim_media <= (1.75) ) AND (dim_media_ant>dim_media)THEN caso:=4; (*12/08/2015 con esta velocidad es una buena aproximació*) v:=v-d_v*1; (*v:=v-d_v*2;*) ELSIF (dim_media > (1.75)) AND (dim_media <= (1.80) ) AND (dim_media_ant<dim_media)THEN caso:=5; (* 11/8/2015 con esta velocidad es una buena aproximación v:=v+d_v*1;*) v:=v+d_v*2; ELSIF (dim_media > (1.75)) AND (dim_media <= (1.80) ) AND (dim_media_ant>dim_media)THEN caso:=6; (*12/08/2015 con esta velocidad es una buena aproximació*) v:=v-d_v*1; (*v:=v-d_v*2;*) ELSIF (dim_media > (1.80) AND dim_media < (1.90)) AND (dim_media_ant<dim_media)THEN caso:=7; v:=v+d_v*2.5; ELSIF (dim_media > (1.80) AND dim_media < (1.90)) AND (dim_media_ant>dim_media)THEN caso:=8; v:=v-d_v*2.5; ELSIF (dim_media >= (1.90)) THEN caso:=9; v:=v+d_v*5; END_IF; ~~ (* CASE caso OF 0: v:=v-d_v*5; 1,7: v:=v-+d_v*2; 2,8: v:=v-d_v*2; 3,5: v:=v-+d_v*1; 4,6: v:=v-d_v*1; 9: v:=v-+d_v*5; END_CASE *) (*Hacemos que lavariable de salida no pase los límites marcados.*) IF (v <= v_min )THEN v:=v_min; END_IF; IF (v >= v_max) THEN v:=v_max; END_IF; (*Reseteamos contadores para la siguiente iteracción*) n_actual:=0; dim_acumulado:=0; dim_media_ant:=dim_media; END_IF; v_:=v; (*Volcamos la V calculada a la salida*)
pscott/app-symbol
src/apdu/messages/sign_transaction.c
/******************************************************************************* * XYM Wallet * (c) 2020 Ledger * (c) 2020 FDS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include "sign_transaction.h" #include <os.h> #include "global.h" #include "xym/xym_helpers.h" #include "ui/main/idle_menu.h" #include "transaction/transaction.h" #include "printers.h" #define PREFIX_LENGTH 4 parse_context_t parseContext; void sign_transaction() { uint8_t privateKeyData[64]; cx_ecfp_private_key_t privateKey; uint32_t tx = 0; if (signState != PENDING_REVIEW) { reset_transaction_context(); display_idle_menu(); return; } // Abort if we accidentally end up here again after the transaction has already been signed if (parseContext.data == NULL) { display_idle_menu(); return; } BEGIN_TRY { TRY { io_seproxyhal_io_heartbeat(); os_perso_derive_node_bip32( CX_CURVE_256K1, transactionContext.bip32Path, transactionContext.pathLength, privateKeyData, NULL); cx_ecfp_init_private_key(transactionContext.curve, privateKeyData, XYM_PRIVATE_KEY_LENGTH, &privateKey); explicit_bzero(privateKeyData, sizeof(privateKeyData)); io_seproxyhal_io_heartbeat(); tx = (uint32_t) cx_eddsa_sign(&privateKey, CX_LAST, CX_SHA512, transactionContext.rawTx, transactionContext.rawTxLength, NULL, 0, G_io_apdu_buffer, IO_APDU_BUFFER_SIZE, NULL); } CATCH_OTHER(e) { THROW(e); } FINALLY { explicit_bzero(privateKeyData, sizeof(privateKeyData)); explicit_bzero(&privateKey, sizeof(privateKey)); // Always reset transaction context after a transaction has been signed reset_transaction_context(); } } END_TRY G_io_apdu_buffer[tx++] = 0x90; G_io_apdu_buffer[tx++] = 0x00; // Send back the response, do not restart the event loop io_exchange(CHANNEL_APDU | IO_RETURN_AFTER_TX, tx); // Display back the original UX display_idle_menu(); } void reject_transaction() { if (signState != PENDING_REVIEW) { reset_transaction_context(); display_idle_menu(); return; } G_io_apdu_buffer[0] = 0x69; G_io_apdu_buffer[1] = 0x85; // Send back the response, do not restart the event loop io_exchange(CHANNEL_APDU | IO_RETURN_AFTER_TX, 2); // Reset transaction context and display back the original UX reset_transaction_context(); display_idle_menu(); } bool isFirst(uint8_t p1) { //return (p1 & P1_CONFIRM) == 0; return (p1 & P1_MASK_ORDER) == 0; } bool hasMore(uint8_t p1) { // return (p1 & P1_MORE) != 0; return (p1 & P1_MASK_MORE) != 0; } void handle_first_packet(uint8_t p1, uint8_t p2, uint8_t *workBuffer, uint8_t dataLength, volatile unsigned int *flags) { uint32_t i; if (!isFirst(p1)) { THROW(0x6A80); } // Reset old transaction data that might still remain reset_transaction_context(); parseContext.data = transactionContext.rawTx; transactionContext.pathLength = workBuffer[0]; if ((transactionContext.pathLength < 0x01) || (transactionContext.pathLength > MAX_BIP32_PATH)) { THROW(0x6a81); } workBuffer++; dataLength--; for (i = 0; i < transactionContext.pathLength; i++) { transactionContext.bip32Path[i] = (workBuffer[0] << 24u) | (workBuffer[1] << 16u) | (workBuffer[2] << 8u) | (workBuffer[3]); workBuffer += 4; dataLength -= 4; } if (((p2 & P2_SECP256K1) == 0) && ((p2 & P2_ED25519) == 0)) { THROW(0x6B00); } if (((p2 & P2_SECP256K1) != 0) && ((p2 & P2_ED25519) != 0)) { THROW(0x6B00); } transactionContext.curve = (((p2 & P2_ED25519) != 0) ? CX_CURVE_Ed25519 : CX_CURVE_256K1); handle_packet_content(p1, p2, workBuffer, dataLength, flags); } void handle_subsequent_packet(uint8_t p1, uint8_t p2, uint8_t *workBuffer, uint8_t dataLength, volatile unsigned int *flags) { if (isFirst(p1)) { THROW(0x6A80); } handle_packet_content(p1, p2, workBuffer, dataLength, flags); } void handle_packet_content(uint8_t p1, uint8_t p2, uint8_t *workBuffer, uint8_t dataLength, volatile unsigned int *flags) { uint16_t totalLength = PREFIX_LENGTH + parseContext.length + dataLength; if (totalLength > MAX_RAW_TX) { // Abort if the user is trying to sign a too large transaction THROW(0x6700); } // Append received data to stored transaction data memcpy(parseContext.data + parseContext.length, workBuffer, dataLength); parseContext.length += dataLength; if (hasMore(p1)) { // Reply to sender with status OK signState = WAITING_FOR_MORE; THROW(0x9000); } else { // No more data to receive, finish up and present transaction to user signState = PENDING_REVIEW; transactionContext.rawTxLength = parseContext.length; // Try to parse the transaction. If the parsing fails, throw an exception // to cause the processing to abort and the transaction context to be reset. switch (parse_txn_context(&parseContext)) { case E_TOO_MANY_FIELDS: // Abort if there are too many fields to show on Ledger device THROW(0x6700); break; case E_NOT_ENOUGH_DATA: case E_INVALID_DATA: // Mask real cause behind generic error (INCORRECT_DATA) THROW(0x6a80); break; default: break; } review_transaction(&parseContext.result, sign_transaction, reject_transaction); *flags |= IO_ASYNCH_REPLY; } } void handle_sign(uint8_t p1, uint8_t p2, uint8_t *workBuffer, uint8_t dataLength, volatile unsigned int *flags) { switch (signState) { case IDLE: handle_first_packet(p1, p2, workBuffer, dataLength, flags); break; case WAITING_FOR_MORE: handle_subsequent_packet(p1, p2, workBuffer, dataLength, flags); break; default: THROW(0x6A80); } }
pscott/app-symbol
src/xym/format/printers.h
<gh_stars>0 /******************************************************************************* * XYM Wallet * (c) 2017 Ledger * (c) 2020 FDS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef LEDGER_APP_XYM_PRINTERS_H #define LEDGER_APP_XYM_PRINTERS_H #include <stdint.h> #include "parse/xym_parse.h" enum _parser_error { E_SUCCESS = 0, E_NOT_ENOUGH_DATA = -1, E_INVALID_DATA = -2, E_TOO_MANY_FIELDS = -3, }; int snprintf_hex(char *dst, uint16_t maxLen, const uint8_t *src, uint16_t dataLength, uint8_t reverse); int snprintf_hex2ascii(char *dst, uint16_t maxLen, const uint8_t *src, uint16_t dataLength); int snprintf_ascii(char *dst, uint16_t maxLen, const uint8_t *src, uint16_t dataLength); int snprintf_number(char *dst, uint16_t maxLen, uint64_t value); int snprintf_mosaic(char *dst, uint16_t maxLen, mosaic_t *mosaic, char *asset); #endif //LEDGER_APP_XYM_PRINTERS_H
pscott/app-symbol
src/apdu/messages/sign_transaction.h
/******************************************************************************* * XYM Wallet * (c) 2020 Ledger * (c) 2020 FDS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef LEDGER_APP_XYM_SIGNTRANSACTION_H #define LEDGER_APP_XYM_SIGNTRANSACTION_H #include <stdint.h> #include "xym/parse/xym_parse.h" extern parse_context_t parseContext; void handle_sign(uint8_t p1, uint8_t p2, uint8_t *workBuffer, uint8_t dataLength, volatile unsigned int *flags); void handle_packet_content(uint8_t p1, uint8_t p2, uint8_t *workBuffer, uint8_t dataLength, volatile unsigned int *flags); #endif //LEDGER_APP_XYM_SIGNTRANSACTION_H
pscott/app-symbol
tests/test_transaction_parser.c
<reponame>pscott/app-symbol<filename>tests/test_transaction_parser.c #include <malloc.h> #include <stddef.h> #include <setjmp.h> #include <stdarg.h> #include <stdint.h> #include "cmocka.h" #include "parse/xym_parse.h" #include "format/format.h" #include "apdu/global.h" // FIXME: transaction_context_t should be defined elsewhere transaction_context_t transactionContext; typedef struct { const char *field_name; const char *field_value; } result_entry_t; static uint8_t *load_transaction_data(const char *filename, size_t *size) { uint8_t *data; FILE *f = fopen(filename, "rb"); assert_non_null(f); fseek(f, 0, SEEK_END); long filesize = ftell(f); fseek(f, 0, SEEK_SET); data = malloc(filesize); assert_non_null(data); assert_int_equal(fread(data, 1, filesize, f), filesize); *size = filesize; fclose(f); return data; } static void check_transaction_results(const char *filename, int num_fields, const result_entry_t *expected) { parse_context_t context = {0}; char field_name[MAX_FIELDNAME_LEN]; char field_value[MAX_FIELD_LEN]; size_t tx_length; uint8_t * const tx_data = load_transaction_data(filename, &tx_length); assert_non_null(tx_data); context.data = tx_data; context.length = tx_length; assert_int_equal(parse_txn_context(&context), 0); assert_int_equal(context.result.numFields, num_fields); for (int i = 0; i < context.result.numFields; i++) { const field_t *field = &context.result.fields[i]; resolve_fieldname(field, field_name); format_field(field, field_value); assert_string_equal(expected[i].field_name, field_name); assert_string_equal(expected[i].field_value, field_value); } free(tx_data); return; } static void test_parse_transfer_transaction(void **state) { (void) state; const result_entry_t expected[6] = { {"Transaction Type", "Transfer"}, {"Recipient", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Amount", "45 XYM"}, {"Message Type", "Plain text"}, {"Message", "This is a test message"}, {"Fee", "2 XYM"} }; check_transaction_results("../testcases/transfer_transaction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_transfer_transaction_not_xym(void **state) { (void) state; const result_entry_t expected[8] = { {"Transaction Type", "Transfer"}, {"Recipient", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Mosaics", "Found 1"}, {"Unknown Mosaic", "Divisibility and levy cannot be shown"}, {"Amount", "45000000 micro 0x5E62990DCAC5B21A"}, {"Message Type", "Plain text"}, {"Message", "This is a test message"}, {"Fee", "2 XYM"} }; check_transaction_results("../testcases/transfer_transaction_not_xym.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_create_mosaic(void **state) { (void) state; const result_entry_t expected[14] = { {"Transaction Type", "Aggregate Complete"}, {"Agg. Tx Hash", "E5F37FE3F83F4F0A2F21E7CF25F75CF29A20D7929CBEB7EB552EDA846969281F"}, {"Inner TX Type", "Mosaic definition"}, {"Mosaic ID", "532CB823113F2471"}, {"Divisibility", "0"}, {"Duration", "0d 0h 5m"}, {"Transferable", "Yes"}, {"Supply Mutable", "Yes"}, {"Restrictable", "Yes"}, {"Inner TX Type", "Mosaic Supply Change"}, {"Mosaic ID", "532CB823113F2471"}, {"Change Direction", "Increase"}, {"Change Amount", "1000000"}, {"Fee", "2 XYM"}, }; check_transaction_results("../testcases/create_mosaic.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_create_namespace(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Namespace Registration"}, {"Namespace Type", "Root namespace"}, {"Name", "foo576sgnlxdnfbdx"}, {"Duration", "60d 0h 0m"}, {"Fee", "2 XYM"}, }; check_transaction_results("../testcases/create_namespace.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_create_sub_namespace(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Namespace Registration"}, {"Namespace Type", "Sub namespace"}, {"Name", "foo576sgnlxdnfbdx"}, {"Parent ID", "000000000002A300"}, {"Fee", "2 XYM"}, }; check_transaction_results("../testcases/create_sub_namespace.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_supply_change_mosaic(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Mosaic Supply Change"}, {"Mosaic ID", "7CDF3B117A3C40CC"}, {"Change Direction", "Increase"}, {"Change Amount", "1000000"}, {"Fee", "2 XYM"} }; check_transaction_results("../testcases/supply_change_mosaic.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_link_namespace_to_mosaic(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Mosaic Alias"}, {"Alias Type", "Unlink address"}, {"Namespace ID", "82A9D1AC587EC054"}, {"Mosaic ID", "7CDF3B117A3C40CC"}, {"Fee", "2 XYM"} }; check_transaction_results("../testcases/link_namespace_to_mosaic.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_link_namespace_to_address(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Address Alias"}, {"Alias Type", "Link address"}, {"Namespace ID", "82A9D1AC587EC054"}, {"Address", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Fee", "2 XYM"} }; check_transaction_results("../testcases/link_namespace_to_address.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_account_address_restriction(void **state) { (void) state; const result_entry_t expected[8] = { {"Transaction Type", "Account Address Restriction"}, {"Addition Count", "1 address(es)"}, {"Address", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Deletion Count", "Not change"}, {"Restriction Flag", "Block"}, {"Restriction Flag", "Imcoming"}, {"Restriction Flag", "Address"}, {"Fee", "0.16 XYM"} }; check_transaction_results("../testcases/account_address_restriction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_account_mosaic_restriction(void **state) { (void) state; const result_entry_t expected[7] = { {"Transaction Type", "Account Mosaic Restriction"}, {"Addition Count", "1 mosaic(s)"}, {"Mosaic ID", "5BA212858B2B48BC"}, {"Deletion Count", "Not change"}, {"Restriction Flag", "Block"}, {"Restriction Flag", "Mosaic"}, {"Fee", "0.144 XYM"} }; check_transaction_results("../testcases/account_mosaic_restriction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_account_operation_restriction(void **state) { (void) state; const result_entry_t expected[8] = { {"Transaction Type", "Account Operation Restriction"}, {"Addition Count", "1 operation(s)"}, {"Operation Type", "Account Key Link"}, {"Deletion Count", "Not change"}, {"Restriction Flag", "Block"}, {"Restriction Flag", "Outgoing"}, {"Restriction Flag", "Transaction Type"}, {"Fee", "0.138 XYM"} }; check_transaction_results("../testcases/account_operation_restriction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_account_multisig(void **state) { (void) state; const result_entry_t expected[10] = { {"Transaction Type", "Aggregate Bonded"}, {"Agg. Tx Hash", "043D6F6E851CAE4ED2B975AEEF61DFDF00B85BBB2503AC23DD7586E3C0B07956"}, {"Inner TX Type", "Multisig Account Modification"}, {"Address Add Num", "2"}, {"Address", "TALSLGUUF5VOB2RSWAPDNBUHIBKTNZQREXWPOAI"}, {"Address", "TBFXGDVDW4TMYEVJ7L3YWTJXGVH7Q4RNXOKQCNY"}, {"Address Del Num", "0"}, {"Min Approval", "Add 1 address(es)"}, {"Min Removal", "Add 1 address(es)"}, {"Fee", "2 XYM"} }; check_transaction_results("../testcases/account_multisig.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_hash_lock_account_multisig(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Funds Lock"}, {"Lock Quantity", "10 XYM"}, {"Duration", "0d 4h 0m"}, {"Tx Hash", "2B51EBCBC3E40EFE8AF68A0408F5A72474B1327A64E3E3B47D9B139230C7833B"}, {"Fee", "2 XYM"} }; check_transaction_results("../testcases/hash_lock_account_multisig.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_multisig_transfer_transaction(void **state) { (void) state; const result_entry_t expected[8] = { {"Transaction Type", "Aggregate Bonded"}, {"Agg. Tx Hash", "4941C270B56778E01629FC82EDDC622668F076CE1583AFCCA3F6DE7FE03615BB"}, {"Inner TX Type", "Transfer"}, {"Recipient", "TBKQPST7HUOJA2PBNYNA7TT4LLKGA5BB5UY6M4Y"}, {"Amount", "10 XYM"}, {"Message Type", "Plain text"}, {"Message", "Test message"}, {"Fee", "0.03024 XYM"}, }; check_transaction_results("../testcases/multisig_transfer_transaction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_multisig_create_mosaic(void **state) { (void) state; const result_entry_t expected[14] = { {"Transaction Type", "Aggregate Bonded"}, {"Agg. Tx Hash", "705B456E99A2FA7DA3D4F02ABB1993774426B8095705C2116E6FB59E95A2587D"}, {"Inner TX Type", "Mosaic definition"}, {"Mosaic ID", "78CA2F4797C65A64"}, {"Divisibility", "0"}, {"Duration", "Unlimited"}, {"Transferable", "Yes"}, {"Supply Mutable", "Yes"}, {"Restrictable", "No"}, {"Inner TX Type", "Mosaic Supply Change"}, {"Mosaic ID", "78CA2F4797C65A64"}, {"Change Direction", "Increase"}, {"Change Amount", "500000000"}, {"Fee", "0.033696 XYM"}, }; check_transaction_results("../testcases/multisig_create_mosaic.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_multisig_create_namespace(void **state) { (void) state; const result_entry_t expected[7] = { {"Transaction Type", "Aggregate Bonded"}, {"Agg. Tx Hash", "B96E1C08F8434BFDC4D1F292EB3F911B1A3C5B3EE102887A8ACDD75A79A4BB62"}, {"Inner TX Type", "Namespace Registration"}, {"Namespace Type", "Root namespace"}, {"Name", "multisig"}, {"Duration", "60d 0h 0m"}, {"Fee", "0.026784 XYM"} }; check_transaction_results("../testcases/multisig_create_namespace.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_hash_lock_multisig_create_namespace(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Funds Lock"}, {"Lock Quantity", "10 XYM"}, {"Duration", "0d 8h 20m"}, {"Tx Hash", "E019A4A92002505B8B5029AE556958ADCDFBEDAC26C2F79DE1668C5BC588EDF7"}, {"Fee", "0.019872 XYM"}, }; check_transaction_results("../testcases/hash_lock_multisig_create_namespace.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_multisig_create_sub_namespace(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Namespace Registration"}, {"Namespace Type", "Sub namespace"}, {"Name", "sub_namespace_multisig"}, {"Parent ID", "D64FAC0976CC0914"}, {"Fee", "0.018144 XYM"} }; check_transaction_results("../testcases/multisig_create_sub_namespace.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_cosignature_transaction(void **state) { (void) state; const result_entry_t expected[8] = { {"Transaction Type", "Aggregate Bonded"}, {"Agg. Tx Hash", "0EFE6E4A881D312984767CABBE53DAC00419E179932A5C784B51132FBE5F7C88"}, {"Detail TX Type", "Transfer"}, {"Recipient", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Amount", "10 XYM"}, {"Message Type", "Plain text"}, {"Message", "SDV"}, {"Fee", "0.48 XYM"} }; check_transaction_results("../testcases/cosignature_transaction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_account_metadata_transaction(void **state) { (void) state; const result_entry_t expected[8] = { {"Transaction Type", "Aggregate Complete"}, {"Agg. Tx Hash", "5F221AD2C6D297E683692CE332B24157057E6FB43A832F18C13495EC49544E08"}, {"Inner TX Type", "Account Metadata"}, {"Target Address", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Metadata Key", "AB8385A30DFCEA7A"}, {"Value", "this is the value field of account metadata"}, {"Value Size Delta", "Increase 43 byte(s)"}, {"Fee", "0.296 XYM"} }; check_transaction_results("../testcases/account_metadata_transaction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_mosaic_metadata_transaction(void **state) { (void) state; const result_entry_t expected[9] = { {"Transaction Type", "Aggregate Complete"}, {"Agg. Tx Hash", "FD62E4D107693B6B0A7D862F2BBE49695565764AE41AE0D0344C47AE82DCB00C"}, {"Inner TX Type", "Mosaic Metadata"}, {"Target Address", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Mosaic ID", "6E32F5200421C596"}, {"Metadata Key", "<KEY>"}, {"Value", "This is the mosaic metadata value field"}, {"Value Size Delta", "Increase 39 byte(s)"}, {"Fee", "0.304 XYM"} }; check_transaction_results("../testcases/mosaic_metadata_transaction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_namespace_metadata_transaction(void **state) { (void) state; const result_entry_t expected[9] = { {"Transaction Type", "Aggregate Complete"}, {"Agg. Tx Hash", "668FE1351AC31C35536EE3A368F2C2310DD3D7E67A8345050548AE8B6596015D"}, {"Inner TX Type", "Namespace Metadata"}, {"Target Address", "TDZKL2HAMOWRVEEF55NVCZ7C6GSWIXCI7IWAESI"}, {"Namespace ID", "8547528FC63C2AD6"}, {"Metadata Key", "<KEY>"}, {"Value", "Namespace metadata value field"}, {"Value Size Delta", "Increase 30 byte(s)"}, {"Fee", "0.296 XYM"} }; check_transaction_results("../testcases/namespace_metadata_transaction.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_delegated_harvesting(void **state) { (void) state; const result_entry_t expected[12] = { {"Transaction Type", "Aggregate Complete"}, {"Agg. Tx Hash", "0C8666CEF61F61B78515149A1414455C77A0CCD7C9AD5F39DFE46761AB6556DF"}, {"Inner TX Type", "Account Key Link"}, {"Action", "Link"}, {"Linked Acct. PbK", "00278C080D6B149902E1576723DA6362065D3A134BEE6383827353540492B911"}, {"Inner TX Type", "Vrf Key Link"}, {"Action", "Link"}, {"Linked Vrf PbK", "C1A71431325873D83894977C68C783A4EED7A3391EAFD704BF8500361EC321DB"}, {"Inner TX Type", "Node Key Link"}, {"Action", "Link"}, {"Linked Node PbK", "81890592F960AAEBDA7612C8917FA9C267A845D78D74D4B3651AF093E6775001"}, {"Fee", "0.0432 XYM"} }; check_transaction_results("../testcases/delegated_harvesting.raw", sizeof(expected) / sizeof(expected[0]), expected); } static void test_parse_persistent_harvesting_delegation_transfer(void **state) { (void) state; const result_entry_t expected[5] = { {"Transaction Type", "Transfer"}, {"Recipient", "TBR6AUIUNBRSXJ34RSCZOJTK4GQNVDEUEDCPMIY"}, {"Message Type", "Persistent harvesting delegation"}, {"Harvesting Message", "FE2A8061577301E28AEC26D42EFCE832BE498BB8CFCC7687BC5BC6B22A82F4BA415A7DF13E1DEA994EAD70125CA250DD6CD8AEA8BAE26AD9A8FC9CB45A996E59BD8894E3D618043887E2383A6BB161A18AB58F406D7DFF384CBD6A669FD152E5AD84B372425212CAAECCB712674AA6C737894BB14FADFE93A3E3AF73A34187D49740891C"}, {"Fee", "0.292 XYM"} }; check_transaction_results("../testcases/persistent_harvesting_delegation_transfer.raw", sizeof(expected) / sizeof(expected[0]), expected); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_parse_transfer_transaction), cmocka_unit_test(test_parse_transfer_transaction_not_xym), cmocka_unit_test(test_parse_create_mosaic), cmocka_unit_test(test_parse_create_namespace), cmocka_unit_test(test_parse_create_sub_namespace), cmocka_unit_test(test_parse_supply_change_mosaic), cmocka_unit_test(test_parse_link_namespace_to_mosaic), cmocka_unit_test(test_parse_link_namespace_to_address), cmocka_unit_test(test_parse_account_address_restriction), cmocka_unit_test(test_parse_account_mosaic_restriction), cmocka_unit_test(test_parse_account_operation_restriction), cmocka_unit_test(test_parse_account_multisig), cmocka_unit_test(test_parse_hash_lock_account_multisig), cmocka_unit_test(test_parse_multisig_transfer_transaction), cmocka_unit_test(test_parse_multisig_create_mosaic), cmocka_unit_test(test_parse_multisig_create_namespace), cmocka_unit_test(test_parse_hash_lock_multisig_create_namespace), cmocka_unit_test(test_parse_multisig_create_sub_namespace), cmocka_unit_test(test_parse_cosignature_transaction), cmocka_unit_test(test_parse_account_metadata_transaction), cmocka_unit_test(test_parse_mosaic_metadata_transaction), cmocka_unit_test(test_parse_namespace_metadata_transaction), cmocka_unit_test(test_parse_delegated_harvesting), cmocka_unit_test(test_parse_persistent_harvesting_delegation_transfer) }; return cmocka_run_group_tests(tests, NULL, NULL); }
pscott/app-symbol
tests/bolos_target.h
<reponame>pscott/app-symbol<filename>tests/bolos_target.h #pragma once #define TARGET_NANOX
pscott/app-symbol
src/xym/parse/xym_parse.h
/******************************************************************************* * XYM Wallet * (c) 2020 FDS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef LEDGER_APP_XYM_XYMPARSE_H #define LEDGER_APP_XYM_XYMPARSE_H #include "limitations.h" #include "xym/format/fields.h" #include "xym/xym_helpers.h" #define XYM_PERSISTENT_DELEGATED_HARVESTING 0xFE #define ALIGNMENT_BYTES 8 #pragma pack(push, 1) typedef struct { uint64_t mosaicId; uint64_t amount; } mosaic_t; typedef struct { uint64_t maxFee; uint64_t deadline; } txn_fee_t; #pragma pack(pop) typedef struct { uint8_t numFields; field_t fields[MAX_FIELD_COUNT]; } result_t; typedef struct { uint16_t transactionType; const uint8_t *data; result_t result; uint32_t length; uint32_t offset; } parse_context_t; int parse_txn_context(parse_context_t *parseContext); #endif //LEDGER_APP_XYM_XYMPARSE_H
pscott/app-symbol
src/apdu/messages/get_public_key.c
<reponame>pscott/app-symbol /******************************************************************************* * XYM Wallet * (c) 2020 Ledger * (c) 2020 FDS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include "get_public_key.h" #include "apdu/global.h" #include "xym/xym_helpers.h" #include "ui/main/idle_menu.h" #include "ui/address/address_ui.h" uint8_t xymPublicKey[XYM_PUBLIC_KEY_LENGTH]; uint32_t set_result_get_publicKey() { uint32_t tx = 0; //publicKey G_io_apdu_buffer[tx++] = XYM_PUBLIC_KEY_LENGTH; memcpy(G_io_apdu_buffer + tx, xymPublicKey, XYM_PUBLIC_KEY_LENGTH); tx += 32; return tx; } void on_address_confirmed() { uint32_t tx = set_result_get_publicKey(); G_io_apdu_buffer[tx++] = 0x90; G_io_apdu_buffer[tx++] = 0x00; // Send back the response, do not restart the event loop io_exchange(CHANNEL_APDU | IO_RETURN_AFTER_TX, tx); // Display back the original UX display_idle_menu(); } void on_address_rejected() { G_io_apdu_buffer[0] = 0x69; G_io_apdu_buffer[1] = 0x85; // Send back the response, do not restart the event loop io_exchange(CHANNEL_APDU | IO_RETURN_AFTER_TX, 2); // Display back the original UX display_idle_menu(); } void handle_public_key(uint8_t p1, uint8_t p2, uint8_t *dataBuffer, uint16_t dataLength, volatile unsigned int *flags, volatile unsigned int *tx) { uint8_t privateKeyData[XYM_PRIVATE_KEY_LENGTH]; uint32_t bip32Path[MAX_BIP32_PATH]; uint32_t i; uint8_t bip32PathLength = *(dataBuffer++); cx_ecfp_private_key_t privateKey; cx_ecfp_public_key_t publicKey; uint8_t algo; cx_curve_t curve; char address[XYM_PRETTY_ADDRESS_LENGTH+1]; uint8_t p2Chain = p2 & 0x3F; UNUSED(p2Chain); if (dataLength != XYM_PKG_GETPUBLICKEY_LENGTH) { THROW(0x6a80); } if ((bip32PathLength < 0x01) || (bip32PathLength > MAX_BIP32_PATH)) { THROW(0x6a80); } if ((p1 != P1_CONFIRM) && (p1 != P1_NON_CONFIRM)) { THROW(0x6B00); } if (((p2 & P2_SECP256K1) == 0) && ((p2 & P2_ED25519) == 0)) { THROW(0x6B00); } if (((p2 & P2_SECP256K1) != 0) && ((p2 & P2_ED25519) != 0)) { THROW(0x6B00); } curve = (((p2 & P2_ED25519) != 0) ? CX_CURVE_Ed25519 : CX_CURVE_256K1); //Read and convert path's data for (i = 0; i < bip32PathLength; i++) { bip32Path[i] = (dataBuffer[0] << 24) | (dataBuffer[1] << 16) | (dataBuffer[2] << 8) | (dataBuffer[3]); dataBuffer += 4; } uint8_t network_type = *dataBuffer; io_seproxyhal_io_heartbeat(); BEGIN_TRY { TRY { // Changed hashing algorithm to cope with catapult-server changes. All Key derivation and signing are now using SHA512. // Removed SignSchema so NetworkType is no longer bonded to the schema anymore (sha3 / keccak). // This change will affect all existing keypairs / address (derived from public key) and transaction signatures. algo = CX_SHA512; os_perso_derive_node_bip32(CX_CURVE_256K1, bip32Path, bip32PathLength, privateKeyData, NULL); cx_ecfp_init_private_key(curve, privateKeyData, XYM_PRIVATE_KEY_LENGTH, &privateKey); io_seproxyhal_io_heartbeat(); cx_ecfp_generate_pair2(curve, &publicKey, &privateKey, 1, algo); explicit_bzero(&privateKey, sizeof(privateKey)); explicit_bzero(privateKeyData, sizeof(privateKeyData)); io_seproxyhal_io_heartbeat(); xym_public_key_and_address(&publicKey, network_type, (uint8_t*) &xymPublicKey, (char*) &address, XYM_PRETTY_ADDRESS_LENGTH + 1 ); io_seproxyhal_io_heartbeat(); address[XYM_PRETTY_ADDRESS_LENGTH] = '\0'; } CATCH_OTHER(e) { THROW(e); } FINALLY { explicit_bzero(privateKeyData, sizeof(privateKeyData)); explicit_bzero(&privateKey, sizeof(privateKey)); } } END_TRY if (p1 == P1_NON_CONFIRM) { *tx = set_result_get_publicKey(); THROW(0x9000); } else { display_address_confirmation_ui( address, on_address_confirmed, on_address_rejected ); *flags |= IO_ASYNCH_REPLY; } }
pscott/app-symbol
src/xym/parse/xym_parse.c
<gh_stars>0 /******************************************************************************* * XYM Wallet * (c) 2020 FDS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include "xym_parse.h" #include "apdu/global.h" #include "xym/format/printers.h" #pragma pack(push, 1) typedef struct { uint8_t recipientAddress[XYM_ADDRESS_LENGTH]; uint16_t messageSize; uint8_t mosaicsCount; uint32_t reserved1; uint8_t reserved2; } txn_header_t; typedef struct { uint64_t mosaicId; uint64_t duration; uint32_t nonce; uint8_t flags; uint8_t divisibility; } mosaic_definition_data_t; typedef struct { mosaic_t mosaic; uint8_t action; } mosaic_supply_change_data_t; typedef struct { uint32_t size; uint32_t reserve1; uint8_t signerPublicKey[XYM_PUBLIC_KEY_LENGTH]; uint32_t reserve2; uint8_t version; uint8_t network; uint16_t innerTxType; } inner_tx_header_t; typedef struct { uint8_t transactionHash[XYM_TRANSACTION_HASH_LENGTH]; uint32_t payloadSize; uint32_t reserse; } aggregate_txn_t; typedef struct { uint64_t duration; uint64_t namespaceId; uint8_t registrationType; uint8_t nameSize; } ns_header_t; typedef struct { uint8_t address[XYM_ADDRESS_LENGTH]; uint64_t metadataKey; } metadata_header_1_t; typedef struct { int16_t valueSizeDelta; uint16_t valueSize; } metadata_header_2_t; typedef struct { metadata_header_1_t address_data; metadata_header_2_t value_data; } am_header_t; typedef struct { metadata_header_1_t address_data; uint64_t mosaicNamespaceId; metadata_header_2_t value_data; } mnm_header_t; typedef struct { uint64_t namespaceId; uint8_t address[XYM_ADDRESS_LENGTH]; uint8_t aliasAction; } aa_header_t; typedef struct { uint64_t namespaceId; uint64_t mosaicId; uint8_t aliasAction; } ma_header_t; typedef struct { uint16_t restrictionFlags; uint8_t restrictionAdditionsCount; uint8_t restrictionDeletionsCount; uint32_t reserve; } ar_header_t; typedef struct { uint8_t linkedPublicKey[XYM_PUBLIC_KEY_LENGTH]; uint8_t linkAction; } key_link_header_t; typedef struct { int8_t minRemovalDelta; int8_t minApprovalDelta; uint8_t addressAdditionsCount; uint8_t addressDeletionsCount; uint32_t reserve; } multisig_account_t; typedef struct { mosaic_t mosaic; uint64_t blockDuration; uint8_t aggregateBondedHash[XYM_TRANSACTION_HASH_LENGTH]; } fl_header_t; typedef struct { uint8_t transactionHash[XYM_TRANSACTION_HASH_LENGTH]; uint8_t version; uint8_t networkType; uint16_t transactionType; } common_header_t; #pragma pack(pop) #define BAIL_IF(x) {int err = x; if (err) return err;} #define BAIL_IF_ERR(x, err) {if (x) return err;} // Security check static bool has_data(parse_context_t *context, uint32_t numBytes) { if (context->offset + numBytes < context->offset) { return false; } return context->offset + numBytes - 1 < context->length; } static field_t *get_field(parse_context_t *context, int idx) { return &context->result.fields[idx]; } static int _set_field_data(field_t* field, uint8_t id, uint8_t data_type, uint32_t length, const uint8_t* data) { field->id = id; field->dataType = data_type; field->length = length; field->data = data; return E_SUCCESS; } static int set_field_data(parse_context_t *context, int idx, uint8_t id, uint8_t data_type, uint32_t length, const uint8_t* data) { BAIL_IF_ERR(idx >= MAX_FIELD_COUNT, E_TOO_MANY_FIELDS); BAIL_IF_ERR(data == NULL, E_NOT_ENOUGH_DATA); return _set_field_data(get_field(context, idx), id, data_type, length, data); } static int add_new_field(parse_context_t *context, uint8_t id, uint8_t data_type, uint32_t length, const uint8_t* data) { return set_field_data(context, context->result.numFields++, id, data_type, length, data); } // Read data and security check static const uint8_t* read_data(parse_context_t *context, uint32_t numBytes) { BAIL_IF_ERR(!has_data(context, numBytes), NULL); uint32_t offset = context->offset; context->offset += numBytes; #ifdef HAVE_PRINTF PRINTF("******* Read: %d bytes - Move offset: %d->%d/%d\n", numBytes, offset, context->offset, context->length); #endif return context->data + offset; } // Move position and security check static const uint8_t* move_pos(parse_context_t *context, uint32_t numBytes) { return read_data(context, numBytes); // Read data and security check } static int parse_transfer_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } txn_header_t *txn = (txn_header_t*) read_data(context, sizeof(txn_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); uint32_t length = txn->mosaicsCount * sizeof(mosaic_t) + txn->messageSize; BAIL_IF_ERR(!has_data(context, length), E_INVALID_DATA); // Show Recipient address BAIL_IF(add_new_field(context, XYM_STR_RECIPIENT_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, (const uint8_t*) txn->recipientAddress)); // Show sent mosaic count field if (txn->mosaicsCount > 1) { BAIL_IF(add_new_field(context, XYM_UINT8_MOSAIC_COUNT, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->mosaicsCount)); } // Show mosaics amount for (uint8_t i = 0; i < txn->mosaicsCount; i++) { mosaic_t *mosaic = (mosaic_t*) read_data(context, sizeof(mosaic_t)); BAIL_IF_ERR(mosaic == NULL, E_NOT_ENOUGH_DATA); if (txn->mosaicsCount == 1 && mosaic->mosaicId != XYM_TESTNET_MOSAIC_ID) { // Show sent mosaic count field (only 1 unknown mosaic) BAIL_IF(add_new_field(context, XYM_UINT8_MOSAIC_COUNT, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->mosaicsCount)); } if (mosaic->mosaicId != XYM_TESTNET_MOSAIC_ID) { // Unknow mosaic notification BAIL_IF(add_new_field(context, XYM_UNKNOWN_MOSAIC, STI_STR, 0, (const uint8_t*) mosaic)); } BAIL_IF(add_new_field(context, XYM_MOSAIC_AMOUNT, STI_MOSAIC_CURRENCY, sizeof(mosaic_t), (const uint8_t*) mosaic)); // Read data and security check } if (txn->messageSize == 0) { // Show Empty Message BAIL_IF(add_new_field(context, XYM_STR_TXN_MESSAGE, STI_MESSAGE, txn->messageSize, (const uint8_t*) &txn->messageSize)); } else { BAIL_IF_ERR(!has_data(context, sizeof(uint8_t)), E_INVALID_DATA); const uint8_t *msgType = context->data + context->offset; // Show Message Type BAIL_IF(add_new_field(context, XYM_UINT8_TXN_MESSAGE_TYPE, STI_UINT8, sizeof(uint8_t), msgType)); // Read data and security check if (*msgType == XYM_PERSISTENT_DELEGATED_HARVESTING) { // Show persistent harvesting delegation message #if defined(TARGET_NANOX) BAIL_IF(add_new_field(context, XYM_STR_TXN_HARVESTING, STI_HEX_MESSAGE, txn->messageSize, read_data(context, txn->messageSize))); // Read data and security check #elif defined(TARGET_NANOS) BAIL_IF(add_new_field(context, XYM_STR_TXN_HARVESTING_1, STI_HEX_MESSAGE, MAX_FIELD_LEN/2 - 1, read_data(context, MAX_FIELD_LEN/2 - 1))); // Read data and security check BAIL_IF(add_new_field(context, XYM_STR_TXN_HARVESTING_2, STI_HEX_MESSAGE, MAX_FIELD_LEN/2 - 1, read_data(context, MAX_FIELD_LEN/2 - 1))); // Read data and security check BAIL_IF(add_new_field(context, XYM_STR_TXN_HARVESTING_3, STI_HEX_MESSAGE, txn->messageSize - MAX_FIELD_LEN + 2, read_data(context, txn->messageSize - MAX_FIELD_LEN + 2))); // Read data and security check #endif } else { BAIL_IF_ERR(move_pos(context, 1) == NULL, E_NOT_ENOUGH_DATA); // Message type // Show Message in plain text BAIL_IF(add_new_field(context, XYM_STR_TXN_MESSAGE, STI_MESSAGE, txn->messageSize - 1, read_data(context, txn->messageSize - 1))); // Read data and security check } } if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_mosaic_definition_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } mosaic_definition_data_t *txn = (mosaic_definition_data_t*) read_data(context, sizeof(mosaic_definition_data_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show mosaic id BAIL_IF(add_new_field(context, XYM_UINT64_MOSAIC_ID, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->mosaicId)); // Show mosaic divisibility BAIL_IF(add_new_field(context, XYM_UINT8_MD_DIV, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->divisibility)); // Show duration BAIL_IF(add_new_field(context, XYM_UINT64_DURATION, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->duration)); // Show mosaic flag (Transferable) BAIL_IF(add_new_field(context, XYM_UINT8_MD_TRANS_FLAG, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->flags)); // Show mosaic flag (Supply mutable) BAIL_IF(add_new_field(context, XYM_UINT8_MD_SUPPLY_FLAG, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->flags)); // Show mosaic flag (Restrictable) BAIL_IF(add_new_field(context, XYM_UINT8_MD_RESTRICT_FLAG, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->flags)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_mosaic_supply_change_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } mosaic_supply_change_data_t *txn = (mosaic_supply_change_data_t*) read_data(context, sizeof(mosaic_supply_change_data_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show mosaic id BAIL_IF(add_new_field(context, XYM_UINT64_MOSAIC_ID, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->mosaic.mosaicId)); // Show supply change action BAIL_IF(add_new_field(context, XYM_UINT8_MSC_ACTION, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->action)); // Show amount BAIL_IF(add_new_field(context, XYM_UINT64_MSC_AMOUNT, STI_UINT64, sizeof(mosaic_t), (const uint8_t*) &txn->mosaic.amount)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_multisig_account_modification_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } multisig_account_t *txn = (multisig_account_t*) read_data(context, sizeof(multisig_account_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show address additions count BAIL_IF(add_new_field(context, XYM_UINT8_MAM_ADD_COUNT, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->addressAdditionsCount)); // Show list of addition address for (uint8_t i = 0; i < txn->addressAdditionsCount; i++) { BAIL_IF(add_new_field(context, XYM_STR_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, read_data(context, XYM_ADDRESS_LENGTH))); // Read data and security check } // Show address deletions count BAIL_IF(add_new_field(context, XYM_UINT8_MAM_DEL_COUNT, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->addressDeletionsCount)); // Show list of addition address for (uint8_t i = 0; i < txn->addressDeletionsCount; i++) { BAIL_IF(add_new_field(context, XYM_STR_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, read_data(context, XYM_ADDRESS_LENGTH))); // Read data and security check } // Show min approval delta BAIL_IF(add_new_field(context, XYM_INT8_MAM_APPROVAL_DELTA, STI_INT8, sizeof(int8_t), (const uint8_t*) &txn->minApprovalDelta)); // Show min removal delta BAIL_IF(add_new_field(context, XYM_INT8_MAM_REMOVAL_DELTA, STI_INT8, sizeof(int8_t), (const uint8_t*) &txn->minRemovalDelta)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_namespace_registration_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } ns_header_t *txn = (ns_header_t*) read_data(context, sizeof(ns_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show namespace reg type BAIL_IF(add_new_field(context, XYM_UINT8_NS_REG_TYPE, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->registrationType)); // Show namespace/sub-namespace name BAIL_IF(add_new_field(context, XYM_STR_NAMESPACE, STI_STR, txn->nameSize, read_data(context, txn->nameSize))); // Read data and security check // Show Duration/ParentID BAIL_IF(add_new_field(context, txn->registrationType==0?XYM_UINT64_DURATION:XYM_UINT64_PARENTID, STI_UINT64, sizeof(uint64_t), (uint8_t*) &txn->duration)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_account_metadata_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } am_header_t *txn = (am_header_t*) read_data(context, sizeof(am_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show metadata target address BAIL_IF(add_new_field(context, XYM_STR_METADATA_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, (const uint8_t*) &txn->address_data.address)); // Show scope metadata key BAIL_IF(add_new_field(context, XYM_UINT64_METADATA_KEY, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->address_data.metadataKey)); // Show different value BAIL_IF(add_new_field(context, XYM_STR_METADATA_VALUE, STI_MESSAGE, txn->value_data.valueSize, read_data(context, txn->value_data.valueSize))); // Read data and security check // Show value size delta BAIL_IF(add_new_field(context, XYM_INT16_VALUE_DELTA, STI_INT16, sizeof(uint16_t), (const uint8_t*) &txn->value_data.valueSizeDelta)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_mosaic_namespace_metadata_txn_content(parse_context_t *context, bool isMultisig, bool isMosaicMetadata) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } mnm_header_t *txn = (mnm_header_t*) read_data(context, sizeof(mnm_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show metadata target address BAIL_IF(add_new_field(context, XYM_STR_METADATA_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, (const uint8_t*) &txn->address_data.address)); // Show target mosaic/namespace id BAIL_IF(add_new_field(context, isMosaicMetadata ? XYM_UINT64_MOSAIC_ID : XYM_UINT64_NS_ID, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->mosaicNamespaceId)); // Show scope metadata key BAIL_IF(add_new_field(context, XYM_UINT64_METADATA_KEY, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->address_data.metadataKey)); // Show different value BAIL_IF(add_new_field(context, XYM_STR_METADATA_VALUE, STI_MESSAGE, txn->value_data.valueSize, read_data(context, txn->value_data.valueSize))); // Read data and security check // Show value size delta BAIL_IF(add_new_field(context, XYM_INT16_VALUE_DELTA, STI_INT16, sizeof(uint16_t), (const uint8_t*) &txn->value_data.valueSizeDelta)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_address_alias_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } aa_header_t *txn = (aa_header_t*) read_data(context, sizeof(aa_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show alias type BAIL_IF(add_new_field(context, XYM_UINT8_AA_TYPE, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->aliasAction)); // Show namespace id BAIL_IF(add_new_field(context, XYM_UINT64_NS_ID, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->namespaceId)); // Show Recipient address BAIL_IF(add_new_field(context, XYM_STR_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, (const uint8_t*) txn->address)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_mosaic_alias_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } ma_header_t *txn = (ma_header_t*) read_data(context, sizeof(ma_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show alisa type BAIL_IF(add_new_field(context, XYM_UINT8_AA_TYPE, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->aliasAction)); // Show namespace id BAIL_IF(add_new_field(context, XYM_UINT64_NS_ID, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->namespaceId)); // Show mosaic BAIL_IF(add_new_field(context, XYM_UINT64_MOSAIC_ID, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->mosaicId)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_account_restriction_txn_content(parse_context_t *context, bool isMultisig, uint8_t restrictionType) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } ar_header_t *txn = (ar_header_t*) read_data(context, sizeof(ar_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show address/mosaicId additions count BAIL_IF(add_new_field(context, restrictionType, STI_UINT8_ADDITION, sizeof(uint8_t), (const uint8_t*) &txn->restrictionAdditionsCount)); // Show list of addition address/mosaicId for (uint8_t i = 0; i < txn->restrictionAdditionsCount; i++) { switch (restrictionType) { case XYM_UINT8_AA_RESTRICTION: BAIL_IF(add_new_field(context, XYM_STR_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, read_data(context, XYM_ADDRESS_LENGTH))); // Read data and security check break; case XYM_UINT8_AM_RESTRICTION: BAIL_IF(add_new_field(context, XYM_UINT64_MOSAIC_ID, STI_UINT64, sizeof(uint64_t), read_data(context, sizeof(uint64_t)))); // Read data and security check break; case XYM_UINT8_AO_RESTRICTION: BAIL_IF(add_new_field(context, XYM_UINT16_ENTITY_RESTRICT_OPERATION, STI_UINT16, sizeof(uint16_t), read_data(context, sizeof(uint16_t)))); // Read data and security check break; default: return E_INVALID_DATA; } } // Show address/mosaicId deletions count BAIL_IF(add_new_field(context, restrictionType, STI_UINT8_DELETION, sizeof(uint8_t), (const uint8_t*) &txn->restrictionDeletionsCount)); // Show list of addition address for (uint8_t i = 0; i < txn->restrictionDeletionsCount; i++) { switch (restrictionType) { case XYM_UINT8_AA_RESTRICTION: BAIL_IF(add_new_field(context, XYM_STR_ADDRESS, STI_ADDRESS, XYM_ADDRESS_LENGTH, read_data(context, XYM_ADDRESS_LENGTH))); // Read data and security check break; case XYM_UINT8_AM_RESTRICTION: BAIL_IF(add_new_field(context, XYM_UINT64_MOSAIC_ID, STI_UINT64, sizeof(uint64_t), read_data(context, sizeof(uint64_t)))); // Read data and security check break; case XYM_UINT8_AO_RESTRICTION: BAIL_IF(add_new_field(context, XYM_UINT16_ENTITY_RESTRICT_OPERATION, STI_UINT16, sizeof(uint16_t), read_data(context, sizeof(uint16_t)))); // Read data and security check break; default: return E_INVALID_DATA; } } // Show restriction operation BAIL_IF(add_new_field(context, XYM_UINT16_AR_RESTRICT_OPERATION, STI_UINT16, sizeof(int16_t), (const uint8_t*) &txn->restrictionFlags)); if(restrictionType != XYM_UINT8_AM_RESTRICTION) { // Show restriction direction BAIL_IF(add_new_field(context, XYM_UINT16_AR_RESTRICT_DIRECTION, STI_UINT16, sizeof(int16_t), (const uint8_t*) &txn->restrictionFlags)); } // Show restriction type BAIL_IF(add_new_field(context, XYM_UINT16_AR_RESTRICT_TYPE, STI_UINT16, sizeof(int16_t), (const uint8_t*) &txn->restrictionFlags)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_key_link_txn_content(parse_context_t *context, bool isMultisig, uint8_t txType) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } key_link_header_t *txn = (key_link_header_t*) read_data(context, sizeof(key_link_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show link action type BAIL_IF(add_new_field(context, XYM_UINT8_KL_TYPE, STI_UINT8, sizeof(uint8_t), (const uint8_t*) &txn->linkAction)); // Show linked public key BAIL_IF(add_new_field(context, txType, STI_PUBLIC_KEY, XYM_PUBLIC_KEY_LENGTH, (const uint8_t *) &txn->linkedPublicKey)); if (!isMultisig) { // Show fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_fund_lock_txn_content(parse_context_t *context, bool isMultisig) { // get header first txn_fee_t *fee = NULL; if (!isMultisig) { fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); } fl_header_t *txn = (fl_header_t*) read_data(context, sizeof(fl_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); // Show lock quantity BAIL_IF(add_new_field(context, XYM_MOSAIC_HL_QUANTITY, STI_MOSAIC_CURRENCY, sizeof(mosaic_t), (const uint8_t*) &txn->mosaic)); // Show duration BAIL_IF(add_new_field(context, XYM_UINT64_DURATION, STI_UINT64, sizeof(uint64_t), (const uint8_t*) &txn->blockDuration)); // Show transaction hash BAIL_IF(add_new_field(context, XYM_HASH256_HL_HASH, STI_HASH256, XYM_TRANSACTION_HASH_LENGTH, (const uint8_t*) &txn->aggregateBondedHash)); if (!isMultisig) { // Show tx fee BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); } return E_SUCCESS; } static int parse_inner_txn_content(parse_context_t *context, uint32_t len, bool isCosigning) { uint32_t totalSize = 0; do { // get header first inner_tx_header_t *txn = (inner_tx_header_t*) read_data(context, sizeof(inner_tx_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); totalSize += txn->size; // Show Transaction type BAIL_IF(add_new_field(context, isCosigning ? XYM_UINT16_TRANSACTION_DETAIL_TYPE : XYM_UINT16_INNER_TRANSACTION_TYPE, STI_UINT16, sizeof(uint16_t), (const uint8_t*) &txn->innerTxType)); switch (txn->innerTxType) { case XYM_TXN_TRANSFER: BAIL_IF(parse_transfer_txn_content(context, true)); break; case XYM_TXN_MOSAIC_DEFINITION: BAIL_IF(parse_mosaic_definition_txn_content(context, true)); break; case XYM_TXN_MOSAIC_SUPPLY_CHANGE: BAIL_IF(parse_mosaic_supply_change_txn_content(context, true)); break; case XYM_TXN_MODIFY_MULTISIG_ACCOUNT: BAIL_IF(parse_multisig_account_modification_txn_content(context, true)); break; case XYM_TXN_REGISTER_NAMESPACE: BAIL_IF(parse_namespace_registration_txn_content(context, true)); break; case XYM_TXN_ACCOUNT_METADATA: BAIL_IF(parse_account_metadata_txn_content(context, true)); break; case XYM_TXN_MOSAIC_METADATA: BAIL_IF(parse_mosaic_namespace_metadata_txn_content(context, true, true)); break; case XYM_TXN_NAMESPACE_METADATA: BAIL_IF(parse_mosaic_namespace_metadata_txn_content(context, true, false)); break; case XYM_TXN_ADDRESS_ALIAS: BAIL_IF(parse_address_alias_txn_content(context, true)); break; case XYM_TXN_MOSAIC_ALIAS: BAIL_IF(parse_mosaic_alias_txn_content(context, true)); break; case XYM_TXN_ACCOUNT_ADDRESS_RESTRICTION: BAIL_IF(parse_account_restriction_txn_content(context, true, XYM_UINT8_AA_RESTRICTION)); break; case XYM_TXN_ACCOUNT_MOSAIC_RESTRICTION: BAIL_IF(parse_account_restriction_txn_content(context, true, XYM_UINT8_AM_RESTRICTION)); break; case XYM_TXN_ACCOUNT_OPERATION_RESTRICTION: BAIL_IF(parse_account_restriction_txn_content(context, true, XYM_UINT8_AO_RESTRICTION)); break; case XYM_TXN_ACCOUNT_KEY_LINK: BAIL_IF(parse_key_link_txn_content(context, true, XYM_PUBLICKEY_ACCOUNT_KEY_LINK)); break; case XYM_TXN_NODE_KEY_LINK: BAIL_IF(parse_key_link_txn_content(context, true, XYM_PUBLICKEY_NODE_KEY_LINK)); break; case XYM_TXN_VRF_KEY_LINK: BAIL_IF(parse_key_link_txn_content(context, true, XYM_PUBLICKEY_VRF_KEY_LINK)); break; case XYM_TXN_FUND_LOCK: BAIL_IF(parse_fund_lock_txn_content(context, true)); break; default: return E_INVALID_DATA; } // Filling zeros BAIL_IF_ERR(move_pos(context, txn->size % ALIGNMENT_BYTES == 0 ? 0 : ALIGNMENT_BYTES - (txn->size % ALIGNMENT_BYTES)) == NULL, E_INVALID_DATA); // Move position and security check } while (totalSize < len - sizeof(inner_tx_header_t)); return E_SUCCESS; } static int parse_aggregate_txn_content(parse_context_t *context) { // get header first txn_fee_t *fee = (txn_fee_t*) read_data(context, sizeof(txn_fee_t)); // Read data and security check BAIL_IF_ERR(fee == NULL, E_NOT_ENOUGH_DATA); aggregate_txn_t *txn = (aggregate_txn_t*) read_data(context, sizeof(aggregate_txn_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); bool isCosigning = transactionContext.rawTxLength == XYM_TRANSACTION_HASH_LENGTH; const uint8_t* p_tx_hash = isCosigning ? context-> data : txn->transactionHash; // Show transaction hash BAIL_IF(add_new_field(context, XYM_HASH256_AGG_HASH, STI_HASH256, XYM_TRANSACTION_HASH_LENGTH, p_tx_hash)); BAIL_IF_ERR(!has_data(context, txn->payloadSize), E_INVALID_DATA); BAIL_IF(parse_inner_txn_content(context, txn->payloadSize, isCosigning)); // Show max fee of aggregate tx BAIL_IF(add_new_field(context, XYM_UINT64_TXN_FEE, STI_XYM, sizeof(uint64_t), (const uint8_t*) &fee->maxFee)); return E_SUCCESS; } static int parse_txn_detail(parse_context_t *context, common_header_t *txn) { int result; context->result.numFields = 0; // Show Transaction type BAIL_IF(add_new_field(context, XYM_UINT16_TRANSACTION_TYPE, STI_UINT16, sizeof(uint16_t), (const uint8_t*) &context->transactionType)); switch (txn->transactionType) { case XYM_TXN_TRANSFER: result = parse_transfer_txn_content(context, false); break; case XYM_TXN_AGGREGATE_COMPLETE: result = parse_aggregate_txn_content(context); break; case XYM_TXN_AGGREGATE_BONDED: result = parse_aggregate_txn_content(context); break; case XYM_TXN_MODIFY_MULTISIG_ACCOUNT: result = parse_multisig_account_modification_txn_content(context, false); break; case XYM_TXN_REGISTER_NAMESPACE: result = parse_namespace_registration_txn_content(context, false); break; case XYM_TXN_ADDRESS_ALIAS: result = parse_address_alias_txn_content(context, false); break; case XYM_TXN_MOSAIC_ALIAS: result = parse_mosaic_alias_txn_content(context, false); break; case XYM_TXN_ACCOUNT_ADDRESS_RESTRICTION: result = parse_account_restriction_txn_content(context, false, XYM_UINT8_AA_RESTRICTION); break; case XYM_TXN_ACCOUNT_MOSAIC_RESTRICTION: result = parse_account_restriction_txn_content(context, false, XYM_UINT8_AM_RESTRICTION); break; case XYM_TXN_ACCOUNT_OPERATION_RESTRICTION: result = parse_account_restriction_txn_content(context, false, XYM_UINT8_AO_RESTRICTION); break; case XYM_TXN_MOSAIC_DEFINITION: result = parse_mosaic_definition_txn_content(context, false); break; case XYM_TXN_MOSAIC_SUPPLY_CHANGE: result = parse_mosaic_supply_change_txn_content(context, false); break; case XYM_TXN_FUND_LOCK: result = parse_fund_lock_txn_content(context, false); break; default: result = E_INVALID_DATA; break; } return result; } static void set_sign_data_length(parse_context_t *context) { if ((context->transactionType == XYM_TXN_AGGREGATE_COMPLETE) || (context->transactionType == XYM_TXN_AGGREGATE_BONDED)) { const unsigned char TESTNET_GENERATION_HASH[] = {0x6C, 0x1B, 0x92, 0x39, 0x1C, 0xCB, 0x41, 0xC9, 0x64, 0x78, 0x47, 0x1C, 0x26, 0x34, 0xC1, 0x11, 0xD9, 0xE9, 0x89, 0xDE, 0xCD, 0x66, 0x13, 0x0C, 0x04, 0x30, 0xB5, 0xB8, 0xD2, 0x01, 0x17, 0xCD}; if (memcmp(TESTNET_GENERATION_HASH, context->data, XYM_TRANSACTION_HASH_LENGTH) == 0) { // Sign data from generation hash to transaction hash // XYM_AGGREGATE_SIGNING_LENGTH = XYM_TRANSACTION_HASH_LENGTH // + sizeof(common_header_t) + sizeof(txn_fee_t) = 84 transactionContext.rawTxLength = XYM_AGGREGATE_SIGNING_LENGTH; } else { // Sign transaction hash only (multisig cosigning transaction) transactionContext.rawTxLength = XYM_TRANSACTION_HASH_LENGTH; } } else { // Sign all data in the transaction transactionContext.rawTxLength = context->length; } } static common_header_t *parse_txn_header(parse_context_t *context) { // get gen_hash and transaction_type common_header_t *txn = (common_header_t *) read_data(context, sizeof(common_header_t)); // Read data and security check BAIL_IF_ERR(txn == NULL, NULL); context->transactionType = txn->transactionType; return txn; } int parse_txn_context(parse_context_t *context) { common_header_t* txn = parse_txn_header(context); BAIL_IF_ERR(txn == NULL, E_NOT_ENOUGH_DATA); set_sign_data_length(context); return parse_txn_detail(context, txn); }
pscott/app-symbol
src/apdu/entry.c
/******************************************************************************* * XYM Wallet * (c) 2017 Ledger * (c) 2020 FDS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include "entry.h" #include <os.h> #include "constants.h" #include "global.h" #include "messages/get_public_key.h" #include "messages/sign_transaction.h" #include "messages/get_app_configuration.h" unsigned char lastINS = 0; void handle_apdu(volatile unsigned int *flags, volatile unsigned int *tx) { unsigned short sw = 0; BEGIN_TRY { TRY { if (G_io_apdu_buffer[OFFSET_CLA] != CLA) { THROW(0x6E00); } // Reset transaction context before starting to parse a new APDU message type. // This helps protect against "Instruction Change" attacks if (G_io_apdu_buffer[OFFSET_INS] != lastINS) { reset_transaction_context(); } lastINS = G_io_apdu_buffer[OFFSET_INS]; switch (G_io_apdu_buffer[OFFSET_INS]) { case INS_GET_PUBLIC_KEY: handle_public_key(G_io_apdu_buffer[OFFSET_P1], G_io_apdu_buffer[OFFSET_P2], G_io_apdu_buffer + OFFSET_CDATA, G_io_apdu_buffer[OFFSET_LC], flags, tx); break; case INS_SIGN: handle_sign(G_io_apdu_buffer[OFFSET_P1], G_io_apdu_buffer[OFFSET_P2], G_io_apdu_buffer + OFFSET_CDATA, G_io_apdu_buffer[OFFSET_LC], flags); break; case INS_GET_APP_CONFIGURATION: handle_app_configuration(tx); break; default: THROW(0x6D00); break; } } CATCH_OTHER(e) { switch (e & 0xF000u) { case 0x6000: // Wipe the transaction context and report the exception sw = e; reset_transaction_context(); break; case 0x9000: // All is well sw = e; break; default: // Internal error, wipe the transaction context and report the exception sw = 0x6800u | (e & 0x7FFu); reset_transaction_context(); break; } // Unexpected exception => report G_io_apdu_buffer[*tx] = sw >> 8u; G_io_apdu_buffer[*tx + 1] = sw; *tx += 2; } FINALLY { } } END_TRY }
osdnk/rainbow-list
ios/UltraFastAbstractComponentWrapper.h
<filename>ios/UltraFastAbstractComponentWrapper.h // // UltraFastComponentWrapper.h // Pods // // Created by <NAME> on 10/10/2021. // #import <React/RCTView.h> #import <React/RCTViewManager.h> #import "RecyclerRow.h" @interface UltraFastAbstractComponentWrapperManager: RCTViewManager @end @interface UltraFastAbstractComponentWrapper: RCTView @property (nonatomic) NSString* binding; @property (nonatomic) RecyclerRow* boundRow; -(void)notifyNewData:(NSInteger)index; @end
osdnk/rainbow-list
ios/CellStorage.h
<gh_stars>1-10 // // CellStorage.h // Pods // // Created by <NAME> on 06/10/2021. // #import <React/RCTViewManager.h> #import <React/RCTView.h> #import "RecyclerRow.h" #import <React/RCTEventDispatcher.h> @interface CellStorageManager : RCTViewManager @end @class ReusableCell; @interface CellStorage: RCTView @property CGRect initialRect; @property (nonatomic) NSString* type; @property(nonatomic, copy) RCTDirectEventBlock onMoreRowsNeeded; - (RecyclerRow *) getFirstAvailableRow; - (void) dequeueView:(ReusableCell*)cell; - (void) enqueueForView:(ReusableCell *)cell; - (void) notifyNeedMoreCells; - (void) notifyNewViewAvailable; - (instancetype) initWithBridge:(RCTBridge*)bridge; @end
osdnk/rainbow-list
ios/RecyclerController.h
<gh_stars>1-10 // // RecyclerController.h // react-native-multithreading // // Created by <NAME> on 06/10/2021. // #import <Foundation/Foundation.h> #import <React/RCTView.h> #import "CellStorage.h" #import "StickyGridCollectionViewLayout.h" @interface RecyclerController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, StickyGridCollectionViewLayoutDelegate> { UICollectionView *_collectionView; } @property (nonatomic) NSMutableDictionary<NSString*, CellStorage *> *cellStorages; @property (nonatomic) UIRefreshControl* refreshControl; @property (class, nonatomic) NSMutableDictionary<NSNumber*, RecyclerController*>* lists; + (void)notifyNewData:(int)listId; - (void)notifyNewData; @end @interface SizeableView: RCTView @property(nonatomic, copy) RCTDirectEventBlock onRefresh; @property(nonatomic) BOOL isRefreshing; @property (nonatomic) NSNumber* identifier; // TODO osdnk dealloc @property (nonatomic, strong) RecyclerController* controller; @end @interface ReusableCell: UICollectionViewCell @property (nonatomic) NSString* type; @property (nonatomic) NSInteger index; @property (nonatomic) RecyclerController* controller; - (void)recycle:(NSInteger)index; - (void)notifyNewViewAvailable; @end
osdnk/rainbow-list
ios/RecyclerRowWrapper.h
// // RecyclerRowWrapper.h // Pods // // Created by <NAME> on 06/10/2021. // #import <React/RCTViewManager.h> #import <React/RCTView.h> @interface RecyclerRowWrapper : RCTView @property(nonatomic) BOOL reparented; @end @interface RecyclerRowWrapperManager : RCTViewManager @end
osdnk/rainbow-list
ios/RecyclerList.h
<reponame>osdnk/rainbow-list<gh_stars>1-10 // // RecyclerList.h // Pods // // Created by <NAME> on 06/10/2021. // #import <React/RCTViewManager.h> #import "RecyclerController.h" @interface RecyclerListManager : RCTViewManager @end
osdnk/rainbow-list
ios/events/OnRecycle.h
<gh_stars>1-10 // // OnRecycle.h // Pods // // Created by <NAME> on 10/10/2021. // #import <React/RCTEventDispatcher.h> #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface RCTOnRecycleEvent : NSObject <RCTEvent> - (instancetype)initWithReactTag:(NSNumber *)reactTag position:(NSInteger)position prevPosition:(NSInteger)prevPosition; - (instancetype)initWithReactTag:(NSNumber *)reactTag cells:(NSInteger)cells;; @end
osdnk/rainbow-list
ios/UltraFastTextWrapper.h
// // RecyclerRow.h // Pods // // Created by <NAME> on 06/10/2021. // #import "UltraFastAbstractComponentWrapper.h" @interface UltraFastTextWrapperManager:UltraFastAbstractComponentWrapperManager @end @interface UltraFastTextWrapper:UltraFastAbstractComponentWrapper @end
osdnk/rainbow-list
ios/RecyclerRow.h
<reponame>osdnk/rainbow-list<filename>ios/RecyclerRow.h // // RecyclerRow.h // Pods // // Created by <NAME> on 06/10/2021. // #import <React/RCTViewManager.h> #import <React/RCTView.h> #import <React/RCTBridge.h> @interface RecyclerRowManager : RCTViewManager @end @class UltraFastAbstractComponentWrapper; @class SizeableView; @interface RecyclerRow : RCTView @property(nonatomic, copy) RCTDirectEventBlock onRecycle; @property(nonatomic) SizeableView* config; -(void)recycle:(NSInteger)index; -(instancetype)initWithBridge:(RCTBridge*)bridge; -(void)registerUltraFastComponent:(UltraFastAbstractComponentWrapper*)component; @end
osdnk/rainbow-list
ios/StickyGridCollectionViewLayout.h
// // StickyGridCollectionViewLayout.h // Pods // // Created by <NAME> on 11/10/2021. // #import <UIKit/UIKit.h> @protocol StickyGridCollectionViewLayoutDelegate - (BOOL)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout isNeedStickyForIndexPath:(NSIndexPath *)indexPath; @end @interface StickyGridCollectionViewLayout : UICollectionViewFlowLayout @property (nonatomic, weak) id<StickyGridCollectionViewLayoutDelegate> delegate; @end
osdnk/rainbow-list
ios/UltimateList.h
#import <React/RCTBridgeModule.h> #import "rainbow-me-ultimate-list.h" @interface UltimateList : NSObject <RCTBridgeModule> @end
thompsonsed/pycoalescence
pycoalescence/necsim/lib/LandscapeMetricsCalculator.h
<gh_stars>0 // This file is part of necsim project which is released under MIT license. // See file **LICENSE.txt** or visit https://opensource.org/licenses/MIT) for full license details /** * @author <NAME> * @file LandscapeMetricsCalculator.h * @brief Contains the LandscapeMetricsCalculator class for calculating landscape metrics. * * @copyright <a href="https://opensource.org/licenses/MIT"> MIT Licence.</a> */ #include<algorithm> #include <vector> #include <numeric> #include "../necsim/Map.h" #include "../necsim/Cell.h" #ifndef MEAN_DISTANCE_MEANDISTANCECALCULATOR_H #define MEAN_DISTANCE_MEANDISTANCECALCULATOR_H using namespace necsim; /** * @brief Calculates a variety of landscape metrics from an imported tif file. */ class LandscapeMetricsCalculator : public Map<double> { vector<Cell> all_cells; bool has_imported_map; public: LandscapeMetricsCalculator() : all_cells(), has_imported_map(false) { }; virtual ~LandscapeMetricsCalculator() { }; /** * @brief Imports the matrix from a csv file. * * @throws runtime_error: if type detection for the filename fails. * @param filename the file to import. */ void importMap(const string &filename); /** * @brief Calculates the mean distance between nearest neighbours on a Map. * @return the mean distance between every cell and its nearest neighbour */ double calculateMNN(); /** * @brief Checks if the minimum distance between cells is a new minimum. * @param home_cell the cell to check the distance from * @param x the x coordinate of the new location * @param y the y coordinate of the new location * @param min_distance the previous minimum distance */ void checkMinDistance(Cell &home_cell, const long &x, const long &y, double &min_distance); /** * @brief Determines the distance to the nearest neighbour of a cell. * @param row * @param col * @return */ double findNearestNeighbourDistance(const long &row, const long &col); /** * @brief Creates a list containing all habitat cells in the landscape. * List is stored in all_cells. */ void createCellList(); /** * @brief Calculates the clumpiness metric, which measures the degree to which the focal habitat is aggregated or * clumped given its total area. * @return the clumpiness metric */ double calculateClumpiness(); /** * @brief Calculates the number of adjacencies in the landscape. * * Adjacencies are habitat cells that are directly next to each other. Note that this uses the "double=count" * method. * @return the number of adjacent cells in the landscape. */ unsigned long calculateNoAdjacencies(); /** * @brief Calculates the minimum bounding perimeter for square cells on a landscape. * @return the minimum bounding perimeter for cells on a landscape */ double calculateMinPerimeter(); }; #endif //MEAN_DISTANCE_MEANDISTANCECALCULATOR_H
thompsonsed/pycoalescence
pycoalescence/necsim/lib/PyLogger.h
// This file is part of necsim project which is released under MIT license. // See file **LICENSE.txt** or visit https://opensource.org/licenses/MIT) for full license details /** * @author <NAME> * @file PyLogger.h * @brief Routines for controlling logger from C++ to Python. * @copyright <a href="https://opensource.org/licenses/MIT">MIT Licence.</a> */ #ifndef NECSIM_PYLOGGER_H #define NECSIM_PYLOGGER_H #ifndef PYTHON_COMPILE #define PYTHON_COMPILE #endif #include <Python.h> #include <string> #include <sstream> #include "../necsim/Logger.h" namespace necsim { class PyLogger : public Logger { private: PyObject* py_logger; PyObject* py_log_function; bool logger_set; bool log_function_set; public: /** * @brief Default constructor for PyLogger. */ PyLogger() : Logger::Logger(), py_logger(nullptr), py_log_function(nullptr), logger_set(false), log_function_set(false) { } /** * @brief Safely deletes the Python references. */ ~PyLogger() override { Py_CLEAR(py_logger); Py_CLEAR(py_log_function); } /** * @brief Sets the logger object * @param logger the log object that is written out to */ void setLogger(PyObject* logger); /** * @brief Sets the logger function * @param log_function the function that will be used for writing out logs */ void setLogFunction(PyObject* log_function); /** * @brief Checks if the logger has been setup. * @return true if the logger object and the logger function have been set */ bool isSetup(); /** * @brief Writes a message to the log object with level 20. * @param message the message to write out */ void writeInfo(string message) override; /** * @brief Writes a message to the log object with level 30. * @param message the message to write out */ void writeWarning(string message) override; /** * @brief Writes a message to the log object with level 40. * @param message the message to write out */ void writeError(string message) override; /** * @brief Writes a message to the log object with level 50. * @param message the message to write out */ void writeCritical(string message) override; //#ifdef DEBUG /** * @brief Writes a message to the log object with the supplied leve * @param level the logging level to write out at * @param message the message to write out */ void write(const int &level, string message); /** * @brief Writes a message to the log object with the supplied leve * @param level the logging level to write out at * @param message the message to write out */ void write(const int &level, std::stringstream &message); //#endif // DEBUG }; } #endif // NECSIM_PYLOGGER_H
thompsonsed/pycoalescence
pycoalescence/necsim/lib/PyLogging.h
<gh_stars>0 //This file is part of necsim project which is released under MIT license. //See file **LICENSE.txt** or visit https://opensource.org/licenses/MIT) for full license details. /** * @author <NAME> * @file PyLogging.h * @brief Routines for writing to Python logging module. * @copyright <a href="https://opensource.org/licenses/MIT">MIT Licence.</a> */ #ifndef PYLOGGING_H #define PYLOGGING_H #include "Python.h" #include <string> #include "../necsim/LogFile.h" #include "PyLogger.h" namespace necsim { /** * @brief Generates the global logger object and adds the logger and log functions to the Python logger. * * Each call to getGlobalLogger should be matched by a call to removeGlobalLogger * @param logger the Python logger object to use * @param log_function the Python logging function to use */ void setGlobalLogger(PyObject* logger, PyObject* log_function); /** * @brief Safely deletes the global logger object. */ void removeGlobalLogger(); } #endif // PYLOGGING_H
Soluto/react-native-branch-deep-linking
native-tests/ios/Pods/Headers/Public/Branch-SDK/Branch/BranchOpenRequest.h
<gh_stars>1-10 // // BranchOpenRequest.h // Branch-TestBed // // Created by <NAME> on 5/26/15. // Copyright (c) 2015 Branch Metrics. All rights reserved. // #import "BNCServerRequest.h" #import "Branch.h" @interface BranchOpenRequest : BNCServerRequest @property (copy) callbackWithStatus callback; + (void) waitForOpenResponseLock; + (void) releaseOpenResponseLock; + (void) setWaitNeededForOpenResponseLock; - (id)initWithCallback:(callbackWithStatus)callback; - (id)initWithCallback:(callbackWithStatus)callback isInstall:(BOOL)isInstall; @end
Soluto/react-native-branch-deep-linking
native-tests/ios/Pods/Headers/Public/Branch-SDK/Branch/BranchInstallRequest.h
<reponame>Soluto/react-native-branch-deep-linking // // BranchInstallRequest.h // Branch-TestBed // // Created by <NAME> on 5/26/15. // Copyright (c) 2015 Branch Metrics. All rights reserved. // #import "BranchOpenRequest.h" @interface BranchInstallRequest : BranchOpenRequest - (NSString *)getActionName; @end
minhkstn/lsquic
src/liblsquic/lsquic_trans_params.c
/* Copyright (c) 2017 - 2020 LiteSpeed Technologies Inc. See LICENSE. */ /* * lsquic_trans_params.c */ #include <assert.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stddef.h> #include <stdint.h> #include <string.h> #ifndef WIN32 #include <arpa/inet.h> #include <sys/socket.h> #else #include "vc_compat.h" #include "Ws2tcpip.h" #endif #include "lsquic_byteswap.h" #include "lsquic_int_types.h" #include "lsquic_types.h" #include "lsquic_version.h" #include "lsquic_sizes.h" #include "lsquic_trans_params.h" #include "lsquic_util.h" #include "lsquic_varint.h" #define LSQUIC_LOGGER_MODULE LSQLM_TRAPA #include "lsquic_logger.h" static enum transport_param_id tpi_val_2_enum (uint64_t tpi_val) { switch (tpi_val) { case 0: return TPI_ORIGINAL_DEST_CID; case 1: return TPI_MAX_IDLE_TIMEOUT; case 2: return TPI_STATELESS_RESET_TOKEN; case 3: return TPI_MAX_UDP_PAYLOAD_SIZE; case 4: return TPI_INIT_MAX_DATA; case 5: return TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL; case 6: return TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE; case 7: return TPI_INIT_MAX_STREAM_DATA_UNI; case 8: return TPI_INIT_MAX_STREAMS_BIDI; case 9: return TPI_INIT_MAX_STREAMS_UNI; case 10: return TPI_ACK_DELAY_EXPONENT; case 11: return TPI_MAX_ACK_DELAY; case 12: return TPI_DISABLE_ACTIVE_MIGRATION; case 13: return TPI_PREFERRED_ADDRESS; case 14: return TPI_ACTIVE_CONNECTION_ID_LIMIT; case 15: return TPI_INITIAL_SOURCE_CID; case 16: return TPI_RETRY_SOURCE_CID; #if LSQUIC_TEST_QUANTUM_READINESS case 0xC37: return TPI_QUANTUM_READINESS; #endif case 0x1057: return TPI_LOSS_BITS; case 0xDE1A: return TPI_MIN_ACK_DELAY; case 0x7157: return TPI_TIMESTAMPS; default: return INT_MAX; } } static const unsigned enum_2_tpi_val[LAST_TPI + 1] = { [TPI_ORIGINAL_DEST_CID] = 0x0, [TPI_MAX_IDLE_TIMEOUT] = 0x1, [TPI_STATELESS_RESET_TOKEN] = 0x2, [TPI_MAX_UDP_PAYLOAD_SIZE] = 0x3, [TPI_INIT_MAX_DATA] = 0x4, [TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL] = 0x5, [TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE] = 0x6, [TPI_INIT_MAX_STREAM_DATA_UNI] = 0x7, [TPI_INIT_MAX_STREAMS_BIDI] = 0x8, [TPI_INIT_MAX_STREAMS_UNI] = 0x9, [TPI_ACK_DELAY_EXPONENT] = 0xA, [TPI_MAX_ACK_DELAY] = 0xB, [TPI_DISABLE_ACTIVE_MIGRATION] = 0xC, [TPI_PREFERRED_ADDRESS] = 0xD, [TPI_ACTIVE_CONNECTION_ID_LIMIT] = 0xE, [TPI_INITIAL_SOURCE_CID] = 0xF, [TPI_RETRY_SOURCE_CID] = 0x10, #if LSQUIC_TEST_QUANTUM_READINESS [TPI_QUANTUM_READINESS] = 0xC37, #endif [TPI_LOSS_BITS] = 0x1057, [TPI_MIN_ACK_DELAY] = 0xDE1A, [TPI_TIMESTAMPS] = 0x7157, }; const char * const lsquic_tpi2str[LAST_TPI + 1] = { [TPI_ORIGINAL_DEST_CID] = "original_destination_connection_id", [TPI_MAX_IDLE_TIMEOUT] = "max_idle_timeout", [TPI_STATELESS_RESET_TOKEN] = "stateless_reset_token", [TPI_MAX_UDP_PAYLOAD_SIZE] = "max_udp_payload_size", [TPI_INIT_MAX_DATA] = "init_max_data", [TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL] = "init_max_stream_data_bidi_local", [TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE] = "init_max_stream_data_bidi_remote", [TPI_INIT_MAX_STREAM_DATA_UNI] = "init_max_stream_data_uni", [TPI_INIT_MAX_STREAMS_BIDI] = "init_max_streams_bidi", [TPI_INIT_MAX_STREAMS_UNI] = "init_max_streams_uni", [TPI_ACK_DELAY_EXPONENT] = "ack_delay_exponent", [TPI_MAX_ACK_DELAY] = "max_ack_delay", [TPI_DISABLE_ACTIVE_MIGRATION] = "disable_active_migration", [TPI_PREFERRED_ADDRESS] = "preferred_address", [TPI_ACTIVE_CONNECTION_ID_LIMIT] = "active_connection_id_limit", [TPI_INITIAL_SOURCE_CID] = "initial_source_connection_id", [TPI_RETRY_SOURCE_CID] = "retry_source_connection_id", #if LSQUIC_TEST_QUANTUM_READINESS [TPI_QUANTUM_READINESS] = "quantum_readiness", #endif [TPI_LOSS_BITS] = "loss_bits", [TPI_MIN_ACK_DELAY] = "min_ack_delay", [TPI_TIMESTAMPS] = "timestamps", }; #define tpi2str lsquic_tpi2str static const uint64_t def_vals[MAX_NUM_WITH_DEF_TPI + 1] = { [TPI_MAX_UDP_PAYLOAD_SIZE] = TP_DEF_MAX_UDP_PAYLOAD_SIZE, [TPI_ACK_DELAY_EXPONENT] = TP_DEF_ACK_DELAY_EXP, [TPI_INIT_MAX_STREAMS_UNI] = TP_DEF_INIT_MAX_STREAMS_UNI, [TPI_INIT_MAX_STREAMS_BIDI] = TP_DEF_INIT_MAX_STREAMS_BIDI, [TPI_INIT_MAX_DATA] = TP_DEF_INIT_MAX_DATA, [TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL] = TP_DEF_INIT_MAX_STREAM_DATA_BIDI_LOCAL, [TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE] = TP_DEF_INIT_MAX_STREAM_DATA_BIDI_REMOTE, [TPI_INIT_MAX_STREAM_DATA_UNI] = TP_DEF_INIT_MAX_STREAM_DATA_UNI, [TPI_MAX_IDLE_TIMEOUT] = TP_DEF_MAX_IDLE_TIMEOUT, [TPI_MAX_ACK_DELAY] = TP_DEF_MAX_ACK_DELAY, [TPI_ACTIVE_CONNECTION_ID_LIMIT] = TP_DEF_ACTIVE_CONNECTION_ID_LIMIT, }; static const uint64_t max_vals[MAX_NUMERIC_TPI + 1] = { /* We don't enforce the maximum practical UDP payload value of 65527, as * it is not required by the spec and is not necessary. */ [TPI_MAX_UDP_PAYLOAD_SIZE] = VINT_MAX_VALUE, [TPI_ACK_DELAY_EXPONENT] = VINT_MAX_VALUE, [TPI_INIT_MAX_STREAMS_UNI] = VINT_MAX_VALUE, [TPI_INIT_MAX_STREAMS_BIDI] = VINT_MAX_VALUE, [TPI_INIT_MAX_DATA] = VINT_MAX_VALUE, [TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL] = VINT_MAX_VALUE, [TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE] = VINT_MAX_VALUE, [TPI_INIT_MAX_STREAM_DATA_UNI] = VINT_MAX_VALUE, [TPI_MAX_IDLE_TIMEOUT] = VINT_MAX_VALUE, [TPI_MAX_ACK_DELAY] = TP_MAX_MAX_ACK_DELAY, [TPI_ACTIVE_CONNECTION_ID_LIMIT] = VINT_MAX_VALUE, [TPI_LOSS_BITS] = 1, [TPI_MIN_ACK_DELAY] = (1u << 24) - 1u, }; static const uint64_t min_vals[MAX_NUMERIC_TPI + 1] = { /* On the other hand, we do enforce the lower bound. */ [TPI_MAX_UDP_PAYLOAD_SIZE] = 1200, [TPI_MIN_ACK_DELAY] = 1, [TPI_ACTIVE_CONNECTION_ID_LIMIT] = 2, }; static size_t preferred_address_size (const struct transport_params *params) { return sizeof(params->tp_preferred_address.ipv4_addr) + sizeof(params->tp_preferred_address.ipv4_port) + sizeof(params->tp_preferred_address.ipv6_addr) + sizeof(params->tp_preferred_address.ipv6_port) + 1 + params->tp_preferred_address.cid.len + sizeof(params->tp_preferred_address.srst) ; } int lsquic_tp_has_pref_ipv4 (const struct transport_params *params) { return (params->tp_set & (1 << TPI_PREFERRED_ADDRESS)) && params->tp_preferred_address.ipv4_port && !lsquic_is_zero(params->tp_preferred_address.ipv4_addr, sizeof(params->tp_preferred_address.ipv4_addr)); } int lsquic_tp_has_pref_ipv6 (const struct transport_params *params) { return (params->tp_set & (1 << TPI_PREFERRED_ADDRESS)) && params->tp_preferred_address.ipv6_port && !lsquic_is_zero(params->tp_preferred_address.ipv6_addr, sizeof(params->tp_preferred_address.ipv6_addr)); } static size_t update_cid_bits (unsigned bits[][3], enum transport_param_id tpi, const lsquic_cid_t *cid) { bits[tpi][0] = vint_val2bits(enum_2_tpi_val[tpi]); #if __GNUC__ #pragma GCC diagnostic ignored "-Wunknown-pragmas" #if __clang__ #pragma GCC diagnostic ignored "-Wtautological-constant-out-of-range-compare" #else #pragma GCC diagnostic ignored "-Wtype-limits" #endif #endif bits[tpi][1] = vint_val2bits(cid->len); #if __GNUC__ #pragma GCC diagnostic pop #pragma GCC diagnostic pop #endif return (1u << bits[tpi][0]) + (1u << bits[tpi][1]) + cid->len; } int lsquic_tp_encode (const struct transport_params *params, int is_server, unsigned char *const buf, size_t bufsz) { unsigned char *p; size_t need; uint16_t u16; enum transport_param_id tpi; unsigned set; unsigned bits[LAST_TPI + 1][3 /* ID, length, value */]; need = 0; set = params->tp_set; /* Will turn bits off for default values */ if (set & (1 << TPI_INITIAL_SOURCE_CID)) need += update_cid_bits(bits, TPI_INITIAL_SOURCE_CID, &params->tp_initial_source_cid); if (is_server) { if (set & (1 << TPI_ORIGINAL_DEST_CID)) need += update_cid_bits(bits, TPI_ORIGINAL_DEST_CID, &params->tp_original_dest_cid); if (set & (1 << TPI_RETRY_SOURCE_CID)) need += update_cid_bits(bits, TPI_RETRY_SOURCE_CID, &params->tp_retry_source_cid); if (set & (1 << TPI_STATELESS_RESET_TOKEN)) { bits[TPI_STATELESS_RESET_TOKEN][0] = vint_val2bits(enum_2_tpi_val[TPI_STATELESS_RESET_TOKEN]); bits[TPI_STATELESS_RESET_TOKEN][1] = vint_val2bits(sizeof(params->tp_stateless_reset_token)); need += (1 << bits[TPI_STATELESS_RESET_TOKEN][0]) + (1 << bits[TPI_STATELESS_RESET_TOKEN][1]) + sizeof(params->tp_stateless_reset_token); } if (set & (1 << TPI_PREFERRED_ADDRESS)) { bits[TPI_PREFERRED_ADDRESS][0] = vint_val2bits(enum_2_tpi_val[TPI_PREFERRED_ADDRESS]); bits[TPI_PREFERRED_ADDRESS][1] = vint_val2bits( preferred_address_size(params)); need += (1 << bits[TPI_PREFERRED_ADDRESS][0]) + (1 << bits[TPI_PREFERRED_ADDRESS][1]) + preferred_address_size(params); } } #if LSQUIC_TEST_QUANTUM_READINESS else if (set & (1 << TPI_QUANTUM_READINESS)) { bits[TPI_QUANTUM_READINESS][0] = vint_val2bits(enum_2_tpi_val[TPI_QUANTUM_READINESS]); bits[TPI_QUANTUM_READINESS][1] = vint_val2bits(QUANTUM_READY_SZ); need += (1 << bits[TPI_QUANTUM_READINESS][0]) + (1 << bits[TPI_QUANTUM_READINESS][1]) + QUANTUM_READY_SZ; } #endif for (tpi = 0; tpi <= MAX_NUMERIC_TPI; ++tpi) if (set & (1 << tpi)) { if (tpi > MAX_NUM_WITH_DEF_TPI || params->tp_numerics[tpi] != def_vals[tpi]) { if (params->tp_numerics[tpi] >= min_vals[tpi] && params->tp_numerics[tpi] <= max_vals[tpi]) { bits[tpi][0] = vint_val2bits(enum_2_tpi_val[tpi]); bits[tpi][2] = vint_val2bits(params->tp_numerics[tpi]); bits[tpi][1] = vint_val2bits(bits[tpi][2]); need += (1 << bits[tpi][0]) + (1 << bits[tpi][1]) + (1 << bits[tpi][2]); } else if (params->tp_numerics[tpi] > max_vals[tpi]) { LSQ_DEBUG("numeric value of %s is too large (%"PRIu64" vs " "maximum of %"PRIu64")", tpi2str[tpi], params->tp_numerics[tpi], max_vals[tpi]); return -1; } else { LSQ_DEBUG("numeric value of %s is too small (%"PRIu64" vs " "minimum " "of %"PRIu64")", tpi2str[tpi], params->tp_numerics[tpi], min_vals[tpi]); return -1; } } else set &= ~(1 << tpi); /* Don't write default value */ } for (; tpi <= MAX_EMPTY_TPI; ++tpi) if (set & (1 << tpi)) { bits[tpi][0] = vint_val2bits(enum_2_tpi_val[tpi]); need += (1 << bits[tpi][0]) + 1 /* Zero length byte */; } if (need > bufsz || need > UINT16_MAX) { errno = ENOBUFS; return -1; } p = buf; #define WRITE_TO_P(src, len) do { \ memcpy(p, src, len); \ p += len; \ } while (0) #if __BYTE_ORDER == __LITTLE_ENDIAN #define WRITE_UINT_TO_P(val, width) do { \ u##width = bswap_##width(val); \ WRITE_TO_P(&u##width, sizeof(u##width)); \ } while (0) #else #define WRITE_UINT_TO_P(val, width) do { \ u##width = val; \ WRITE_TO_P(&u##width, sizeof(u##width)); \ } while (0) #endif for (tpi = 0; tpi <= LAST_TPI; ++tpi) if (set & (1 << tpi)) { vint_write(p, enum_2_tpi_val[tpi], bits[tpi][0], 1 << bits[tpi][0]); p += 1 << bits[tpi][0]; switch (tpi) { case TPI_MAX_IDLE_TIMEOUT: case TPI_MAX_UDP_PAYLOAD_SIZE: case TPI_INIT_MAX_DATA: case TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL: case TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE: case TPI_INIT_MAX_STREAM_DATA_UNI: case TPI_INIT_MAX_STREAMS_BIDI: case TPI_INIT_MAX_STREAMS_UNI: case TPI_ACK_DELAY_EXPONENT: case TPI_MAX_ACK_DELAY: case TPI_ACTIVE_CONNECTION_ID_LIMIT: case TPI_LOSS_BITS: case TPI_MIN_ACK_DELAY: vint_write(p, 1 << bits[tpi][2], bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; vint_write(p, params->tp_numerics[tpi], bits[tpi][2], 1 << bits[tpi][2]); p += 1 << bits[tpi][2]; break; case TPI_ORIGINAL_DEST_CID: case TPI_INITIAL_SOURCE_CID: case TPI_RETRY_SOURCE_CID: vint_write(p, params->tp_cids[TP_CID_IDX(tpi)].len, bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; WRITE_TO_P(params->tp_cids[TP_CID_IDX(tpi)].idbuf, params->tp_cids[TP_CID_IDX(tpi)].len); break; case TPI_STATELESS_RESET_TOKEN: vint_write(p, sizeof(params->tp_stateless_reset_token), bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; WRITE_TO_P(params->tp_stateless_reset_token, sizeof(params->tp_stateless_reset_token)); break; case TPI_PREFERRED_ADDRESS: vint_write(p, preferred_address_size(params), bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; WRITE_TO_P(&params->tp_preferred_address.ipv4_addr, sizeof(params->tp_preferred_address.ipv4_addr)); WRITE_UINT_TO_P(params->tp_preferred_address.ipv4_port, 16); WRITE_TO_P(&params->tp_preferred_address.ipv6_addr, sizeof(params->tp_preferred_address.ipv6_addr)); WRITE_UINT_TO_P(params->tp_preferred_address.ipv6_port, 16); *p++ = params->tp_preferred_address.cid.len; WRITE_TO_P(params->tp_preferred_address.cid.idbuf, params->tp_preferred_address.cid.len); WRITE_TO_P(params->tp_preferred_address.srst, sizeof(params->tp_preferred_address.srst)); break; case TPI_DISABLE_ACTIVE_MIGRATION: case TPI_TIMESTAMPS: *p++ = 0; break; #if LSQUIC_TEST_QUANTUM_READINESS case TPI_QUANTUM_READINESS: vint_write(p, QUANTUM_READY_SZ, bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; memset(p, 'Q', QUANTUM_READY_SZ); p += QUANTUM_READY_SZ; break; #endif } } assert(buf + need == p); return (int) (p - buf); #undef WRITE_TO_P #undef WRITE_UINT_TO_P } int lsquic_tp_decode (const unsigned char *const buf, size_t bufsz, int is_server, struct transport_params *params) { const unsigned char *p, *end, *q; uint64_t len, param_id; uint16_t tlen; enum transport_param_id tpi; unsigned set_of_ids; int s; p = buf; end = buf + bufsz; *params = TP_INITIALIZER(); #define EXPECT_LEN(expected_len) do { \ if (expected_len != len) \ return -1; \ } while (0) #define EXPECT_AT_LEAST(expected_len) do { \ if ((expected_len) > (uintptr_t) (p + len - q)) \ return -1; \ } while (0) set_of_ids = 0; while (p < end) { s = vint_read(p, end, &param_id); if (s < 0) return -1; p += s; s = vint_read(p, end, &len); if (s < 0) return -1; p += s; if ((ptrdiff_t) len > end - p) return -1; tpi = tpi_val_2_enum(param_id); if (tpi <= LAST_TPI) { if (set_of_ids & (1 << tpi)) return -1; set_of_ids |= 1 << tpi; } switch (tpi) { case TPI_MAX_IDLE_TIMEOUT: case TPI_MAX_UDP_PAYLOAD_SIZE: case TPI_INIT_MAX_DATA: case TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL: case TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE: case TPI_INIT_MAX_STREAM_DATA_UNI: case TPI_INIT_MAX_STREAMS_BIDI: case TPI_INIT_MAX_STREAMS_UNI: case TPI_ACK_DELAY_EXPONENT: case TPI_MAX_ACK_DELAY: case TPI_ACTIVE_CONNECTION_ID_LIMIT: case TPI_LOSS_BITS: case TPI_MIN_ACK_DELAY: switch (len) { case 1: case 2: case 4: case 8: s = vint_read(p, p + len, &params->tp_numerics[tpi]); if (s == (int) len) { if (params->tp_numerics[tpi] > max_vals[tpi]) { LSQ_DEBUG("numeric value of %s is too large " "(%"PRIu64" vs maximum of %"PRIu64, tpi2str[tpi], params->tp_numerics[tpi], max_vals[tpi]); return -1; } else if (params->tp_numerics[tpi] < min_vals[tpi]) { LSQ_DEBUG("numeric value of %s is too small " "(%"PRIu64" vs minimum of %"PRIu64, tpi2str[tpi], params->tp_numerics[tpi], min_vals[tpi]); return -1; } break; } else { LSQ_DEBUG("cannot read the value of numeric transport " "param %s of length %"PRIu64, tpi2str[tpi], len); return -1; } default: LSQ_DEBUG("invalid length=%"PRIu64" for numeric transport " "parameter %s", len, tpi2str[tpi]); return -1; } break; case TPI_DISABLE_ACTIVE_MIGRATION: case TPI_TIMESTAMPS: EXPECT_LEN(0); break; case TPI_STATELESS_RESET_TOKEN: /* Client MUST not include reset token, * see [draft-ietf-quic-transport-11], Section 6.4.1 */ if (!is_server) return -1; EXPECT_LEN(sizeof(params->tp_stateless_reset_token)); memcpy(params->tp_stateless_reset_token, p, sizeof(params->tp_stateless_reset_token)); break; case TPI_ORIGINAL_DEST_CID: case TPI_RETRY_SOURCE_CID: /* [draft-ietf-quic-transport-28] Section 18.2: " A client MUST NOT include any server-only transport parameter: " original_destination_connection_id, preferred_address, " retry_source_connection_id, or stateless_reset_token. */ if (!is_server) return -1; /* fallthru */ case TPI_INITIAL_SOURCE_CID: if (len > MAX_CID_LEN) return -1; memcpy(params->tp_cids[TP_CID_IDX(tpi)].idbuf, p, len); params->tp_cids[TP_CID_IDX(tpi)].len = len; break; case TPI_PREFERRED_ADDRESS: /* Client MUST not include preferred address, * see [draft-ietf-quic-transport-12], Section 6.4.1 */ if (!is_server) return -1; q = p; EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv4_addr)); memcpy(params->tp_preferred_address.ipv4_addr, q, sizeof(params->tp_preferred_address.ipv4_addr)); q += sizeof(params->tp_preferred_address.ipv4_addr); EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv4_port)); READ_UINT(params->tp_preferred_address.ipv4_port, 16, q, 2); q += 2; EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv6_addr)); memcpy(params->tp_preferred_address.ipv6_addr, q, sizeof(params->tp_preferred_address.ipv6_addr)); q += sizeof(params->tp_preferred_address.ipv6_addr); EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv6_port)); READ_UINT(params->tp_preferred_address.ipv6_port, 16, q, 2); q += 2; EXPECT_AT_LEAST(1); tlen = *q; q += 1; if (tlen > MAX_CID_LEN) { LSQ_DEBUG("preferred server address contains invalid " "CID length of %"PRIu16" bytes", tlen); return -1; } EXPECT_AT_LEAST(tlen); memcpy(params->tp_preferred_address.cid.idbuf, q, tlen); params->tp_preferred_address.cid.len = tlen; q += tlen; EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.srst)); memcpy(params->tp_preferred_address.srst, q, sizeof(params->tp_preferred_address.srst)); q += sizeof(params->tp_preferred_address.srst); if (q != p + len) return -1; break; default: /* Do nothing: skip this transport parameter */ break; } p += len; if (tpi <= LAST_TPI) { params->tp_set |= 1 << tpi; params->tp_decoded |= 1 << tpi; } } if (p != end) return -1; if ((params->tp_set & (1 << TPI_MIN_ACK_DELAY)) && params->tp_numerics[TPI_MIN_ACK_DELAY] > params->tp_numerics[TPI_MAX_ACK_DELAY] * 1000) { LSQ_DEBUG("min_ack_delay (%"PRIu64" usec) is larger than " "max_ack_delay (%"PRIu64" ms)", params->tp_numerics[TPI_MIN_ACK_DELAY], params->tp_numerics[TPI_MAX_ACK_DELAY]); return -1; } return (int) (end - buf); #undef EXPECT_LEN } void lsquic_tp_to_str (const struct transport_params *params, char *buf, size_t sz) { char *const end = buf + sz; int nw; enum transport_param_id tpi; char tok_str[sizeof(params->tp_stateless_reset_token) * 2 + 1]; char addr_str[INET6_ADDRSTRLEN]; for (tpi = 0; tpi <= MAX_NUMERIC_TPI; ++tpi) if (params->tp_set & (1 << tpi)) { nw = snprintf(buf, end - buf, "%.*s%s: %"PRIu64, (buf + sz > end) << 1, "; ", tpi2str[tpi], params->tp_numerics[tpi]); buf += nw; if (buf >= end) return; } for (; tpi <= MAX_EMPTY_TPI; ++tpi) if (params->tp_set & (1 << tpi)) { nw = snprintf(buf, end - buf, "%.*s%s", (buf + sz > end) << 1, "; ", tpi2str[tpi]); buf += nw; if (buf >= end) return; } #if LSQUIC_TEST_QUANTUM_READINESS if (params->tp_set & (1 << TPI_QUANTUM_READINESS)) { nw = snprintf(buf, end - buf, "%.*s%s", (buf + sz > end) << 1, "; ", tpi2str[TPI_QUANTUM_READINESS]); buf += nw; if (buf >= end) return; } #endif if (params->tp_set & (1 << TPI_STATELESS_RESET_TOKEN)) { lsquic_hexstr(params->tp_stateless_reset_token, sizeof(params->tp_stateless_reset_token), tok_str, sizeof(tok_str)); nw = snprintf(buf, end - buf, "; stateless_reset_token: %s", tok_str); buf += nw; if (buf >= end) return; } for (tpi = FIRST_TP_CID; tpi <= LAST_TP_CID; ++tpi) if (params->tp_set & (1 << tpi)) { char cidbuf_[MAX_CID_LEN * 2 + 1]; nw = snprintf(buf, end - buf, "; %s: %"CID_FMT, tpi2str[tpi], CID_BITS(&params->tp_cids[TP_CID_IDX(tpi)])); buf += nw; if (buf >= end) return; } if (lsquic_tp_has_pref_ipv4(params)) { if (inet_ntop(AF_INET, params->tp_preferred_address.ipv4_addr, addr_str, sizeof(addr_str))) { nw = snprintf(buf, end - buf, "; IPv4 preferred address: %s:%u", addr_str, params->tp_preferred_address.ipv4_port); buf += nw; if (buf >= end) return; } } if (lsquic_tp_has_pref_ipv6(params)) { if (inet_ntop(AF_INET6, params->tp_preferred_address.ipv6_addr, addr_str, sizeof(addr_str))) { nw = snprintf(buf, end - buf, "; IPv6 preferred address: %s:%u", addr_str, params->tp_preferred_address.ipv6_port); buf += nw; if (buf >= end) return; } } } int lsquic_tp_encode_27 (const struct transport_params *params, int is_server, unsigned char *const buf, size_t bufsz) { unsigned char *p; size_t need; uint16_t u16; enum transport_param_id tpi; unsigned set; unsigned bits[LAST_TPI + 1][3 /* ID, length, value */]; need = 0; set = params->tp_set; /* Will turn bits off for default values */ if (is_server) { if (set & (1 << TPI_ORIGINAL_DEST_CID)) { bits[TPI_ORIGINAL_DEST_CID][0] = vint_val2bits(enum_2_tpi_val[TPI_ORIGINAL_DEST_CID]); #if __GNUC__ #pragma GCC diagnostic ignored "-Wunknown-pragmas" #if __clang__ #pragma GCC diagnostic ignored "-Wtautological-constant-out-of-range-compare" #else #pragma GCC diagnostic ignored "-Wtype-limits" #endif #endif bits[TPI_ORIGINAL_DEST_CID][1] = vint_val2bits(params->tp_original_dest_cid.len); #if __GNUC__ #pragma GCC diagnostic pop #pragma GCC diagnostic pop #endif need += (1 << bits[TPI_ORIGINAL_DEST_CID][0]) + (1 << bits[TPI_ORIGINAL_DEST_CID][1]) + params->tp_original_dest_cid.len; } if (set & (1 << TPI_STATELESS_RESET_TOKEN)) { bits[TPI_STATELESS_RESET_TOKEN][0] = vint_val2bits(enum_2_tpi_val[TPI_STATELESS_RESET_TOKEN]); bits[TPI_STATELESS_RESET_TOKEN][1] = vint_val2bits(sizeof(params->tp_stateless_reset_token)); need += (1 << bits[TPI_STATELESS_RESET_TOKEN][0]) + (1 << bits[TPI_STATELESS_RESET_TOKEN][1]) + sizeof(params->tp_stateless_reset_token); } if (set & (1 << TPI_PREFERRED_ADDRESS)) { bits[TPI_PREFERRED_ADDRESS][0] = vint_val2bits(enum_2_tpi_val[TPI_PREFERRED_ADDRESS]); bits[TPI_PREFERRED_ADDRESS][1] = vint_val2bits( preferred_address_size(params)); need += (1 << bits[TPI_PREFERRED_ADDRESS][0]) + (1 << bits[TPI_PREFERRED_ADDRESS][1]) + preferred_address_size(params); } } #if LSQUIC_TEST_QUANTUM_READINESS else if (set & (1 << TPI_QUANTUM_READINESS)) { bits[TPI_QUANTUM_READINESS][0] = vint_val2bits(enum_2_tpi_val[TPI_QUANTUM_READINESS]); bits[TPI_QUANTUM_READINESS][1] = vint_val2bits(QUANTUM_READY_SZ); need += (1 << bits[TPI_QUANTUM_READINESS][0]) + (1 << bits[TPI_QUANTUM_READINESS][1]) + QUANTUM_READY_SZ; } #endif for (tpi = 0; tpi <= MAX_NUMERIC_TPI; ++tpi) if (set & (1 << tpi)) { if (tpi > MAX_NUM_WITH_DEF_TPI || params->tp_numerics[tpi] != def_vals[tpi]) { if (params->tp_numerics[tpi] >= min_vals[tpi] && params->tp_numerics[tpi] <= max_vals[tpi]) { bits[tpi][0] = vint_val2bits(enum_2_tpi_val[tpi]); bits[tpi][2] = vint_val2bits(params->tp_numerics[tpi]); bits[tpi][1] = vint_val2bits(bits[tpi][2]); need += (1 << bits[tpi][0]) + (1 << bits[tpi][1]) + (1 << bits[tpi][2]); } else if (params->tp_numerics[tpi] > max_vals[tpi]) { LSQ_DEBUG("numeric value of %s is too large (%"PRIu64" vs " "maximum of %"PRIu64")", tpi2str[tpi], params->tp_numerics[tpi], max_vals[tpi]); return -1; } else { LSQ_DEBUG("numeric value of %s is too small (%"PRIu64" vs " "minimum " "of %"PRIu64")", tpi2str[tpi], params->tp_numerics[tpi], min_vals[tpi]); return -1; } } else set &= ~(1 << tpi); /* Don't write default value */ } for (; tpi <= MAX_EMPTY_TPI; ++tpi) if (set & (1 << tpi)) { bits[tpi][0] = vint_val2bits(enum_2_tpi_val[tpi]); need += (1 << bits[tpi][0]) + 1 /* Zero length byte */; } if (need > bufsz || need > UINT16_MAX) { errno = ENOBUFS; return -1; } p = buf; #define WRITE_TO_P(src, len) do { \ memcpy(p, src, len); \ p += len; \ } while (0) #if __BYTE_ORDER == __LITTLE_ENDIAN #define WRITE_UINT_TO_P(val, width) do { \ u##width = bswap_##width(val); \ WRITE_TO_P(&u##width, sizeof(u##width)); \ } while (0) #else #define WRITE_UINT_TO_P(val, width) do { \ u##width = val; \ WRITE_TO_P(&u##width, sizeof(u##width)); \ } while (0) #endif for (tpi = 0; tpi <= LAST_TPI; ++tpi) if (set & (1 << tpi)) { vint_write(p, enum_2_tpi_val[tpi], bits[tpi][0], 1 << bits[tpi][0]); p += 1 << bits[tpi][0]; switch (tpi) { case TPI_MAX_IDLE_TIMEOUT: case TPI_MAX_UDP_PAYLOAD_SIZE: case TPI_INIT_MAX_DATA: case TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL: case TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE: case TPI_INIT_MAX_STREAM_DATA_UNI: case TPI_INIT_MAX_STREAMS_BIDI: case TPI_INIT_MAX_STREAMS_UNI: case TPI_ACK_DELAY_EXPONENT: case TPI_MAX_ACK_DELAY: case TPI_ACTIVE_CONNECTION_ID_LIMIT: case TPI_LOSS_BITS: case TPI_MIN_ACK_DELAY: vint_write(p, 1 << bits[tpi][2], bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; vint_write(p, params->tp_numerics[tpi], bits[tpi][2], 1 << bits[tpi][2]); p += 1 << bits[tpi][2]; break; case TPI_INITIAL_SOURCE_CID: case TPI_RETRY_SOURCE_CID: assert(0); return -1; case TPI_ORIGINAL_DEST_CID: vint_write(p, params->tp_original_dest_cid.len, bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; WRITE_TO_P(params->tp_original_dest_cid.idbuf, params->tp_original_dest_cid.len); break; case TPI_STATELESS_RESET_TOKEN: vint_write(p, sizeof(params->tp_stateless_reset_token), bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; WRITE_TO_P(params->tp_stateless_reset_token, sizeof(params->tp_stateless_reset_token)); break; case TPI_PREFERRED_ADDRESS: vint_write(p, preferred_address_size(params), bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; WRITE_TO_P(&params->tp_preferred_address.ipv4_addr, sizeof(params->tp_preferred_address.ipv4_addr)); WRITE_UINT_TO_P(params->tp_preferred_address.ipv4_port, 16); WRITE_TO_P(&params->tp_preferred_address.ipv6_addr, sizeof(params->tp_preferred_address.ipv6_addr)); WRITE_UINT_TO_P(params->tp_preferred_address.ipv6_port, 16); *p++ = params->tp_preferred_address.cid.len; WRITE_TO_P(params->tp_preferred_address.cid.idbuf, params->tp_preferred_address.cid.len); WRITE_TO_P(params->tp_preferred_address.srst, sizeof(params->tp_preferred_address.srst)); break; case TPI_DISABLE_ACTIVE_MIGRATION: case TPI_TIMESTAMPS: *p++ = 0; break; #if LSQUIC_TEST_QUANTUM_READINESS case TPI_QUANTUM_READINESS: vint_write(p, QUANTUM_READY_SZ, bits[tpi][1], 1 << bits[tpi][1]); p += 1 << bits[tpi][1]; memset(p, 'Q', QUANTUM_READY_SZ); p += QUANTUM_READY_SZ; break; #endif } } assert(buf + need == p); return (int) (p - buf); #undef WRITE_TO_P #undef WRITE_UINT_TO_P } int lsquic_tp_decode_27 (const unsigned char *const buf, size_t bufsz, int is_server, struct transport_params *params) { const unsigned char *p, *end, *q; uint64_t len, param_id; uint16_t tlen; enum transport_param_id tpi; unsigned set_of_ids; int s; p = buf; end = buf + bufsz; *params = TP_INITIALIZER(); #define EXPECT_LEN(expected_len) do { \ if (expected_len != len) \ return -1; \ } while (0) #define EXPECT_AT_LEAST(expected_len) do { \ if ((expected_len) > (uintptr_t) (p + len - q)) \ return -1; \ } while (0) set_of_ids = 0; while (p < end) { s = vint_read(p, end, &param_id); if (s < 0) return -1; p += s; s = vint_read(p, end, &len); if (s < 0) return -1; p += s; if ((ptrdiff_t) len > end - p) return -1; tpi = tpi_val_2_enum(param_id); if (tpi <= LAST_TPI) { if (set_of_ids & (1 << tpi)) return -1; set_of_ids |= 1 << tpi; } switch (tpi) { case TPI_MAX_IDLE_TIMEOUT: case TPI_MAX_UDP_PAYLOAD_SIZE: case TPI_INIT_MAX_DATA: case TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL: case TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE: case TPI_INIT_MAX_STREAM_DATA_UNI: case TPI_INIT_MAX_STREAMS_BIDI: case TPI_INIT_MAX_STREAMS_UNI: case TPI_ACK_DELAY_EXPONENT: case TPI_MAX_ACK_DELAY: case TPI_ACTIVE_CONNECTION_ID_LIMIT: case TPI_LOSS_BITS: case TPI_MIN_ACK_DELAY: switch (len) { case 1: case 2: case 4: case 8: s = vint_read(p, p + len, &params->tp_numerics[tpi]); if (s == (int) len) { if (params->tp_numerics[tpi] > max_vals[tpi]) { LSQ_DEBUG("numeric value of %s is too large " "(%"PRIu64" vs maximum of %"PRIu64, tpi2str[tpi], params->tp_numerics[tpi], max_vals[tpi]); return -1; } else if (params->tp_numerics[tpi] < min_vals[tpi]) { LSQ_DEBUG("numeric value of %s is too small " "(%"PRIu64" vs minimum of %"PRIu64, tpi2str[tpi], params->tp_numerics[tpi], min_vals[tpi]); return -1; } break; } else { LSQ_DEBUG("cannot read the value of numeric transport " "param %s of length %"PRIu64, tpi2str[tpi], len); return -1; } default: LSQ_DEBUG("invalid length=%"PRIu64" for numeric transport " "parameter %s", len, tpi2str[tpi]); return -1; } break; case TPI_DISABLE_ACTIVE_MIGRATION: case TPI_TIMESTAMPS: EXPECT_LEN(0); break; case TPI_STATELESS_RESET_TOKEN: /* Client MUST not include reset token, * see [draft-ietf-quic-transport-11], Section 6.4.1 */ if (!is_server) return -1; EXPECT_LEN(sizeof(params->tp_stateless_reset_token)); memcpy(params->tp_stateless_reset_token, p, sizeof(params->tp_stateless_reset_token)); break; case TPI_ORIGINAL_DEST_CID: /* Client MUST not original connecti ID, * see [draft-ietf-quic-transport-15], Section 6.6.1 */ if (!is_server) return -1; if (len > MAX_CID_LEN) return -1; memcpy(params->tp_original_dest_cid.idbuf, p, len); params->tp_original_dest_cid.len = len; break; case TPI_PREFERRED_ADDRESS: /* Client MUST not include preferred address, * see [draft-ietf-quic-transport-12], Section 6.4.1 */ if (!is_server) return -1; q = p; EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv4_addr)); memcpy(params->tp_preferred_address.ipv4_addr, q, sizeof(params->tp_preferred_address.ipv4_addr)); q += sizeof(params->tp_preferred_address.ipv4_addr); EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv4_port)); READ_UINT(params->tp_preferred_address.ipv4_port, 16, q, 2); q += 2; EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv6_addr)); memcpy(params->tp_preferred_address.ipv6_addr, q, sizeof(params->tp_preferred_address.ipv6_addr)); q += sizeof(params->tp_preferred_address.ipv6_addr); EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.ipv6_port)); READ_UINT(params->tp_preferred_address.ipv6_port, 16, q, 2); q += 2; EXPECT_AT_LEAST(1); tlen = *q; q += 1; if (tlen > MAX_CID_LEN) { LSQ_DEBUG("preferred server address contains invalid " "CID length of %"PRIu16" bytes", tlen); return -1; } EXPECT_AT_LEAST(tlen); memcpy(params->tp_preferred_address.cid.idbuf, q, tlen); params->tp_preferred_address.cid.len = tlen; q += tlen; EXPECT_AT_LEAST(sizeof(params->tp_preferred_address.srst)); memcpy(params->tp_preferred_address.srst, q, sizeof(params->tp_preferred_address.srst)); q += sizeof(params->tp_preferred_address.srst); if (q != p + len) return -1; break; default: /* Do nothing: skip this transport parameter */ break; } p += len; if (tpi <= LAST_TPI) { params->tp_set |= 1 << tpi; params->tp_decoded |= 1 << tpi; } } if (p != end) return -1; if ((params->tp_set & (1 << TPI_MIN_ACK_DELAY)) && params->tp_numerics[TPI_MIN_ACK_DELAY] > params->tp_numerics[TPI_MAX_ACK_DELAY] * 1000) { LSQ_DEBUG("min_ack_delay (%"PRIu64" usec) is larger than " "max_ack_delay (%"PRIu64" ms)", params->tp_numerics[TPI_MIN_ACK_DELAY], params->tp_numerics[TPI_MAX_ACK_DELAY]); return -1; } return (int) (end - buf); #undef EXPECT_LEN } void lsquic_tp_to_str_27 (const struct transport_params *params, char *buf, size_t sz) { char *const end = buf + sz; int nw; enum transport_param_id tpi; char tok_str[sizeof(params->tp_stateless_reset_token) * 2 + 1]; char addr_str[INET6_ADDRSTRLEN]; for (tpi = 0; tpi <= MAX_NUMERIC_TPI; ++tpi) if (params->tp_set & (1 << tpi)) { nw = snprintf(buf, end - buf, "%.*s%s: %"PRIu64, (buf + sz > end) << 1, "; ", tpi2str[tpi], params->tp_numerics[tpi]); buf += nw; if (buf >= end) return; } for (; tpi <= MAX_EMPTY_TPI; ++tpi) if (params->tp_set & (1 << tpi)) { nw = snprintf(buf, end - buf, "%.*s%s", (buf + sz > end) << 1, "; ", tpi2str[tpi]); buf += nw; if (buf >= end) return; } #if LSQUIC_TEST_QUANTUM_READINESS if (params->tp_set & (1 << TPI_QUANTUM_READINESS)) { nw = snprintf(buf, end - buf, "%.*s%s", (buf + sz > end) << 1, "; ", tpi2str[TPI_QUANTUM_READINESS]); buf += nw; if (buf >= end) return; } #endif if (params->tp_set & (1 << TPI_STATELESS_RESET_TOKEN)) { lsquic_hexstr(params->tp_stateless_reset_token, sizeof(params->tp_stateless_reset_token), tok_str, sizeof(tok_str)); nw = snprintf(buf, end - buf, "; stateless_reset_token: %s", tok_str); buf += nw; if (buf >= end) return; } if (params->tp_set & (1 << TPI_ORIGINAL_DEST_CID)) { char cidbuf_[MAX_CID_LEN * 2 + 1]; nw = snprintf(buf, end - buf, "; original DCID (ODCID): %"CID_FMT, CID_BITS(&params->tp_original_dest_cid)); buf += nw; if (buf >= end) return; } if (lsquic_tp_has_pref_ipv4(params)) { if (inet_ntop(AF_INET, params->tp_preferred_address.ipv4_addr, addr_str, sizeof(addr_str))) { nw = snprintf(buf, end - buf, "; IPv4 preferred address: %s:%u", addr_str, params->tp_preferred_address.ipv4_port); buf += nw; if (buf >= end) return; } } if (lsquic_tp_has_pref_ipv6(params)) { if (inet_ntop(AF_INET6, params->tp_preferred_address.ipv6_addr, addr_str, sizeof(addr_str))) { nw = snprintf(buf, end - buf, "; IPv6 preferred address: %s:%u", addr_str, params->tp_preferred_address.ipv6_port); buf += nw; if (buf >= end) return; } } }
minhkstn/lsquic
src/liblsquic/lsquic_enc_sess_ietf.c
/* Copyright (c) 2017 - 2020 LiteSpeed Technologies Inc. See LICENSE. */ /* * lsquic_enc_sess_ietf.c -- Crypto session for IETF QUIC */ #include <assert.h> #include <errno.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <sys/queue.h> #if LSQUIC_PREFERRED_ADDR #include <arpa/inet.h> #endif #include <openssl/chacha.h> #include <openssl/hkdf.h> #include <openssl/rand.h> #include <openssl/ssl.h> #include "fiu-local.h" #include "lsquic_types.h" #include "lsquic_hkdf.h" #include "lsquic.h" #include "lsquic_int_types.h" #include "lsquic_sizes.h" #include "lsquic_hash.h" #include "lsquic_conn.h" #include "lsquic_enc_sess.h" #include "lsquic_parse.h" #include "lsquic_mm.h" #include "lsquic_engine_public.h" #include "lsquic_packet_common.h" #include "lsquic_packet_out.h" #include "lsquic_packet_ietf.h" #include "lsquic_packet_in.h" #include "lsquic_util.h" #include "lsquic_byteswap.h" #include "lsquic_ev_log.h" #include "lsquic_trans_params.h" #include "lsquic_version.h" #include "lsquic_ver_neg.h" #include "lsquic_frab_list.h" #include "lsquic_tokgen.h" #include "lsquic_ietf.h" #include "lsquic_alarmset.h" #if __GNUC__ # define UNLIKELY(cond) __builtin_expect(cond, 0) #else # define UNLIKELY(cond) cond #endif #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LSQUIC_LOGGER_MODULE LSQLM_HANDSHAKE #define LSQUIC_LOG_CONN_ID lsquic_conn_log_cid(enc_sess->esi_conn) #include "lsquic_logger.h" #define KEY_LABEL "quic key" #define KEY_LABEL_SZ (sizeof(KEY_LABEL) - 1) #define IV_LABEL "quic iv" #define IV_LABEL_SZ (sizeof(IV_LABEL) - 1) #define PN_LABEL "quic hp" #define PN_LABEL_SZ (sizeof(PN_LABEL) - 1) #define N_HSK_PAIRS (N_ENC_LEVS - 1) static const struct alpn_map { enum lsquic_version version; const unsigned char *alpn; } s_h3_alpns[] = { { LSQVER_ID27, (unsigned char *) "\x05h3-27", }, { LSQVER_ID28, (unsigned char *) "\x05h3-28", }, { LSQVER_ID29, (unsigned char *) "\x05h3-29", }, { LSQVER_VERNEG, (unsigned char *) "\x05h3-29", }, }; struct enc_sess_iquic; struct crypto_ctx; struct crypto_ctx_pair; struct header_prot; static const int s_log_seal_and_open; static char s_str[0x1000]; static const SSL_QUIC_METHOD cry_quic_method; static int s_idx = -1; static int setup_handshake_keys (struct enc_sess_iquic *, const lsquic_cid_t *); static void free_handshake_keys (struct enc_sess_iquic *); static struct stack_st_X509 * iquic_esf_get_server_cert_chain (enc_session_t *); static void maybe_drop_SSL (struct enc_sess_iquic *); static void no_sess_ticket (enum alarm_id alarm_id, void *ctx, lsquic_time_t expiry, lsquic_time_t now); #define SAMPLE_SZ 16 typedef void (*gen_hp_mask_f)(struct enc_sess_iquic *, struct header_prot *, unsigned rw, const unsigned char *sample, unsigned char *mask, size_t sz); #define CHACHA20_KEY_LENGTH 32 struct header_prot { gen_hp_mask_f hp_gen_mask; enum enc_level hp_enc_level; enum { HP_CAN_READ = 1 << 0, HP_CAN_WRITE = 1 << 1, } hp_flags; union { EVP_CIPHER_CTX cipher_ctx[2]; /* AES */ unsigned char buf[2][CHACHA20_KEY_LENGTH]; /* ChaCha */ } hp_u; }; #define header_prot_inited(hp_, rw_) ((hp_)->hp_flags & (1 << (rw_))) struct crypto_ctx { enum { YK_INITED = 1 << 0, } yk_flags; EVP_AEAD_CTX yk_aead_ctx; unsigned yk_key_sz; unsigned yk_iv_sz; unsigned char yk_key_buf[EVP_MAX_KEY_LENGTH]; unsigned char yk_iv_buf[EVP_MAX_IV_LENGTH]; }; struct crypto_ctx_pair { lsquic_packno_t ykp_thresh; struct crypto_ctx ykp_ctx[2]; /* client, server */ }; /* [draft-ietf-quic-tls-12] Section 5.3.6 */ static int init_crypto_ctx (struct crypto_ctx *crypto_ctx, const EVP_MD *md, const EVP_AEAD *aead, const unsigned char *secret, size_t secret_sz, enum evp_aead_direction_t dir) { crypto_ctx->yk_key_sz = EVP_AEAD_key_length(aead); crypto_ctx->yk_iv_sz = EVP_AEAD_nonce_length(aead); if (crypto_ctx->yk_key_sz > sizeof(crypto_ctx->yk_key_buf) || crypto_ctx->yk_iv_sz > sizeof(crypto_ctx->yk_iv_buf)) { return -1; } lsquic_qhkdf_expand(md, secret, secret_sz, KEY_LABEL, KEY_LABEL_SZ, crypto_ctx->yk_key_buf, crypto_ctx->yk_key_sz); lsquic_qhkdf_expand(md, secret, secret_sz, IV_LABEL, IV_LABEL_SZ, crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz); if (!EVP_AEAD_CTX_init_with_direction(&crypto_ctx->yk_aead_ctx, aead, crypto_ctx->yk_key_buf, crypto_ctx->yk_key_sz, IQUIC_TAG_LEN, dir)) return -1; crypto_ctx->yk_flags |= YK_INITED; return 0; } static void cleanup_crypto_ctx (struct crypto_ctx *crypto_ctx) { if (crypto_ctx->yk_flags & YK_INITED) { EVP_AEAD_CTX_cleanup(&crypto_ctx->yk_aead_ctx); crypto_ctx->yk_flags &= ~YK_INITED; } } #define HP_BATCH_SIZE 8 struct enc_sess_iquic { struct lsquic_engine_public *esi_enpub; struct lsquic_conn *esi_conn; void **esi_streams; const struct crypto_stream_if *esi_cryst_if; const struct ver_neg *esi_ver_neg; SSL *esi_ssl; /* These are used for forward encryption key phase 0 and 1 */ struct header_prot esi_hp; struct crypto_ctx_pair esi_pairs[2]; /* These are used during handshake. There are three of them. * esi_hsk_pairs and esi_hsk_hps are allocated and freed * together. */ struct crypto_ctx_pair * esi_hsk_pairs; struct header_prot *esi_hsk_hps; lsquic_packno_t esi_max_packno[N_PNS]; lsquic_cid_t esi_odcid; lsquic_cid_t esi_rscid; /* Retry SCID */ lsquic_cid_t esi_iscid; /* Initial SCID */ unsigned esi_key_phase; enum { ESI_INITIALIZED = 1 << 0, ESI_LOG_SECRETS = 1 << 1, ESI_HANDSHAKE_OK = 1 << 2, ESI_ODCID = 1 << 3, ESI_ON_WRITE = 1 << 4, ESI_SERVER = 1 << 5, ESI_USE_SSL_TICKET = 1 << 6, ESI_HAVE_PEER_TP = 1 << 7, ESI_ALPN_CHECKED = 1 << 8, ESI_CACHED_INFO = 1 << 9, ESI_HSK_CONFIRMED= 1 << 10, ESI_WANT_TICKET = 1 << 11, ESI_RECV_QL_BITS = 1 << 12, ESI_SEND_QL_BITS = 1 << 13, ESI_RSCID = 1 << 14, ESI_ISCID = 1 << 15, ESI_RETRY = 1 << 16, /* Connection was retried */ } esi_flags; enum enc_level esi_last_w; unsigned esi_trasec_sz; char *esi_hostname; void *esi_keylog_handle; #ifndef NDEBUG char *esi_sni_bypass; #endif const unsigned char *esi_alpn; unsigned char *esi_zero_rtt_buf; size_t esi_zero_rtt_sz; /* Need MD and AEAD for key rotation */ const EVP_MD *esi_md; const EVP_AEAD *esi_aead; struct { const char *cipher_name; int alg_bits; } esi_cached_info; /* Secrets are kept for key rotation */ unsigned char esi_traffic_secrets[2][EVP_MAX_KEY_LENGTH]; /* We never use the first two levels, so it seems we could reduce the * memory requirement here at the cost of adding some code. */ struct frab_list esi_frals[N_ENC_LEVS]; struct transport_params esi_peer_tp; struct lsquic_alarmset *esi_alset; unsigned esi_max_streams_uni; unsigned esi_hp_batch_idx; unsigned esi_hp_batch_packno_len[HP_BATCH_SIZE]; unsigned esi_hp_batch_packno_off[HP_BATCH_SIZE]; struct lsquic_packet_out * esi_hp_batch_packets[HP_BATCH_SIZE]; unsigned char esi_hp_batch_samples[HP_BATCH_SIZE][SAMPLE_SZ]; }; static void gen_hp_mask_aes (struct enc_sess_iquic *enc_sess, struct header_prot *hp, unsigned rw, const unsigned char *sample, unsigned char *mask, size_t sz) { int out_len; if (EVP_EncryptUpdate(&hp->hp_u.cipher_ctx[rw], mask, &out_len, sample, sz)) assert(out_len >= (int) sz); else { LSQ_WARN("cannot generate hp mask, error code: %"PRIu32, ERR_get_error()); enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn, "cannot generate hp mask, error code: %"PRIu32, ERR_get_error()); } } static void gen_hp_mask_chacha20 (struct enc_sess_iquic *enc_sess, struct header_prot *hp, unsigned rw, const unsigned char *sample, unsigned char *mask, size_t sz) { const uint8_t *nonce; uint32_t counter; #if __BYTE_ORDER == __LITTLE_ENDIAN memcpy(&counter, sample, sizeof(counter)); #else #error TODO: support non-little-endian machines #endif nonce = sample + sizeof(counter); CRYPTO_chacha_20(mask, (unsigned char [5]) { 0, 0, 0, 0, 0, }, 5, hp->hp_u.buf[rw], nonce, counter); } static void apply_hp (struct enc_sess_iquic *enc_sess, struct header_prot *hp, unsigned char *dst, const unsigned char *mask, unsigned packno_off, unsigned packno_len) { char mask_str[5 * 2 + 1]; LSQ_DEBUG("apply header protection using mask %s", HEXSTR(mask, 5, mask_str)); if (enc_sess->esi_flags & ESI_SEND_QL_BITS) dst[0] ^= (0x7 | ((dst[0] >> 7) << 3)) & mask[0]; else dst[0] ^= (0xF | (((dst[0] & 0x80) == 0) << 4)) & mask[0]; switch (packno_len) { case 4: dst[packno_off + 3] ^= mask[4]; /* fall-through */ case 3: dst[packno_off + 2] ^= mask[3]; /* fall-through */ case 2: dst[packno_off + 1] ^= mask[2]; /* fall-through */ default: dst[packno_off + 0] ^= mask[1]; } } static void apply_hp_immediately (struct enc_sess_iquic *enc_sess, struct header_prot *hp, struct lsquic_packet_out *packet_out, unsigned packno_off, unsigned packno_len) { unsigned char mask[SAMPLE_SZ]; hp->hp_gen_mask(enc_sess, hp, 1, packet_out->po_enc_data + packno_off + 4, mask, SAMPLE_SZ); apply_hp(enc_sess, hp, packet_out->po_enc_data, mask, packno_off, packno_len); #ifndef NDEBUG packet_out->po_lflags |= POL_HEADER_PROT; #endif } static void flush_hp_batch (struct enc_sess_iquic *enc_sess) { unsigned i; unsigned char mask[HP_BATCH_SIZE][SAMPLE_SZ]; enc_sess->esi_hp.hp_gen_mask(enc_sess, &enc_sess->esi_hp, 1, (unsigned char *) enc_sess->esi_hp_batch_samples, (unsigned char *) mask, enc_sess->esi_hp_batch_idx * SAMPLE_SZ); for (i = 0; i < enc_sess->esi_hp_batch_idx; ++i) { apply_hp(enc_sess, &enc_sess->esi_hp, enc_sess->esi_hp_batch_packets[i]->po_enc_data, mask[i], enc_sess->esi_hp_batch_packno_off[i], enc_sess->esi_hp_batch_packno_len[i]); #ifndef NDEBUG enc_sess->esi_hp_batch_packets[i]->po_lflags |= POL_HEADER_PROT; #endif } enc_sess->esi_hp_batch_idx = 0; } static void apply_hp_batch (struct enc_sess_iquic *enc_sess, struct header_prot *hp, struct lsquic_packet_out *packet_out, unsigned packno_off, unsigned packno_len) { memcpy(enc_sess->esi_hp_batch_samples[enc_sess->esi_hp_batch_idx], packet_out->po_enc_data + packno_off + 4, SAMPLE_SZ); enc_sess->esi_hp_batch_packno_off[enc_sess->esi_hp_batch_idx] = packno_off; enc_sess->esi_hp_batch_packno_len[enc_sess->esi_hp_batch_idx] = packno_len; enc_sess->esi_hp_batch_packets[enc_sess->esi_hp_batch_idx] = packet_out; ++enc_sess->esi_hp_batch_idx; if (enc_sess->esi_hp_batch_idx == HP_BATCH_SIZE) flush_hp_batch(enc_sess); } static lsquic_packno_t decode_packno (lsquic_packno_t max_packno, lsquic_packno_t packno, unsigned shift) { lsquic_packno_t candidates[3], epoch_delta; int64_t diffs[3]; unsigned min;; epoch_delta = 1ULL << shift; candidates[1] = (max_packno & ~(epoch_delta - 1)) + packno; candidates[0] = candidates[1] - epoch_delta; candidates[2] = candidates[1] + epoch_delta; diffs[0] = llabs((int64_t) candidates[0] - (int64_t) max_packno); diffs[1] = llabs((int64_t) candidates[1] - (int64_t) max_packno); diffs[2] = llabs((int64_t) candidates[2] - (int64_t) max_packno); min = diffs[1] < diffs[0]; if (diffs[2] < diffs[min]) min = 2; return candidates[min]; } static lsquic_packno_t strip_hp (struct enc_sess_iquic *enc_sess, struct header_prot *hp, const unsigned char *iv, unsigned char *dst, unsigned packno_off, unsigned *packno_len) { enum packnum_space pns; lsquic_packno_t packno; unsigned shift; unsigned char mask[SAMPLE_SZ]; char mask_str[5 * 2 + 1]; hp->hp_gen_mask(enc_sess, hp, 0, iv, mask, SAMPLE_SZ); LSQ_DEBUG("strip header protection using mask %s", HEXSTR(mask, 5, mask_str)); if (enc_sess->esi_flags & ESI_RECV_QL_BITS) dst[0] ^= (0x7 | ((dst[0] >> 7) << 3)) & mask[0]; else dst[0] ^= (0xF | (((dst[0] & 0x80) == 0) << 4)) & mask[0]; packno = 0; shift = 0; *packno_len = 1 + (dst[0] & 3); switch (*packno_len) { case 4: dst[packno_off + 3] ^= mask[4]; packno |= dst[packno_off + 3]; shift += 8; /* fall-through */ case 3: dst[packno_off + 2] ^= mask[3]; packno |= (unsigned) dst[packno_off + 2] << shift; shift += 8; /* fall-through */ case 2: dst[packno_off + 1] ^= mask[2]; packno |= (unsigned) dst[packno_off + 1] << shift; shift += 8; /* fall-through */ default: dst[packno_off + 0] ^= mask[1]; packno |= (unsigned) dst[packno_off + 0] << shift; shift += 8; } pns = lsquic_enclev2pns[hp->hp_enc_level]; return decode_packno(enc_sess->esi_max_packno[pns], packno, shift); } static int gen_trans_params (struct enc_sess_iquic *enc_sess, unsigned char *buf, size_t bufsz) { const struct lsquic_engine_settings *const settings = &enc_sess->esi_enpub->enp_settings; struct transport_params params; const enum lsquic_version version = enc_sess->esi_conn->cn_version; int len; memset(&params, 0, sizeof(params)); if (version > LSQVER_ID27) { params.tp_initial_source_cid = *CN_SCID(enc_sess->esi_conn); params.tp_set |= 1 << TPI_INITIAL_SOURCE_CID; } if (enc_sess->esi_flags & ESI_SERVER) { const struct lsquic_conn *const lconn = enc_sess->esi_conn; params.tp_set |= 1 << TPI_STATELESS_RESET_TOKEN; lsquic_tg_generate_sreset(enc_sess->esi_enpub->enp_tokgen, CN_SCID(lconn), params.tp_stateless_reset_token); if (enc_sess->esi_flags & ESI_ODCID) { params.tp_original_dest_cid = enc_sess->esi_odcid; params.tp_set |= 1 << TPI_ORIGINAL_DEST_CID; } #if LSQUIC_PREFERRED_ADDR char addr_buf[INET6_ADDRSTRLEN + 6 /* port */ + 1]; const char *s, *colon; struct lsquic_conn *conn; struct conn_cid_elem *cce; unsigned seqno; s = getenv("LSQUIC_PREFERRED_ADDR4"); if (s && strlen(s) < sizeof(addr_buf) && (colon = strchr(s, ':'))) { strncpy(addr_buf, s, colon - s); addr_buf[colon - s] = '\0'; inet_pton(AF_INET, addr_buf, params.tp_preferred_address.ipv4_addr); params.tp_preferred_address.ipv4_port = atoi(colon + 1); params.tp_set |= 1 << TPI_PREFERRED_ADDRESS; } s = getenv("LSQUIC_PREFERRED_ADDR6"); if (s && strlen(s) < sizeof(addr_buf) && (colon = strrchr(s, ':'))) { strncpy(addr_buf, s, colon - s); addr_buf[colon - s] = '\0'; inet_pton(AF_INET6, addr_buf, params.tp_preferred_address.ipv6_addr); params.tp_preferred_address.ipv6_port = atoi(colon + 1); params.tp_set |= 1 << TPI_PREFERRED_ADDRESS; } conn = enc_sess->esi_conn; if ((params.tp_set & (1 << TPI_PREFERRED_ADDRESS)) && (1 << conn->cn_n_cces) - 1 != conn->cn_cces_mask) { seqno = 0; for (cce = lconn->cn_cces; cce < END_OF_CCES(lconn); ++cce) { if (lconn->cn_cces_mask & (1 << (cce - lconn->cn_cces))) { if ((cce->cce_flags & CCE_SEQNO) && cce->cce_seqno > seqno) seqno = cce->cce_seqno; } else break; } if (cce == END_OF_CCES(lconn)) { goto cant_use_prefaddr; } cce->cce_seqno = seqno + 1; cce->cce_flags = CCE_SEQNO; lsquic_generate_cid(&cce->cce_cid, enc_sess->esi_enpub->enp_settings.es_scid_len); /* Don't add to hash: migration must not start until *after* * handshake is complete. */ conn->cn_cces_mask |= 1 << (cce - conn->cn_cces); params.tp_preferred_address.cid = cce->cce_cid; lsquic_tg_generate_sreset(enc_sess->esi_enpub->enp_tokgen, &params.tp_preferred_address.cid, params.tp_preferred_address.srst); } else { cant_use_prefaddr: params.tp_set &= ~(1 << TPI_PREFERRED_ADDRESS); } #endif } #if LSQUIC_TEST_QUANTUM_READINESS else { const char *s = getenv("LSQUIC_TEST_QUANTUM_READINESS"); if (s && atoi(s)) params.tp_set |= 1 << TPI_QUANTUM_READINESS; } #endif params.tp_init_max_data = settings->es_init_max_data; params.tp_init_max_stream_data_bidi_local = settings->es_init_max_stream_data_bidi_local; params.tp_init_max_stream_data_bidi_remote = settings->es_init_max_stream_data_bidi_remote; params.tp_init_max_stream_data_uni = settings->es_init_max_stream_data_uni; params.tp_init_max_streams_uni = enc_sess->esi_max_streams_uni; params.tp_init_max_streams_bidi = settings->es_init_max_streams_bidi; params.tp_ack_delay_exponent = TP_DEF_ACK_DELAY_EXP; params.tp_max_idle_timeout = settings->es_idle_timeout * 1000; params.tp_max_ack_delay = TP_DEF_MAX_ACK_DELAY; params.tp_active_connection_id_limit = MAX_IETF_CONN_DCIDS; params.tp_set |= (1 << TPI_INIT_MAX_DATA) | (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL) | (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE) | (1 << TPI_INIT_MAX_STREAM_DATA_UNI) | (1 << TPI_INIT_MAX_STREAMS_UNI) | (1 << TPI_INIT_MAX_STREAMS_BIDI) | (1 << TPI_ACK_DELAY_EXPONENT) | (1 << TPI_MAX_IDLE_TIMEOUT) | (1 << TPI_MAX_ACK_DELAY) | (1 << TPI_ACTIVE_CONNECTION_ID_LIMIT) ; if (settings->es_max_udp_payload_size_rx) { params.tp_max_udp_payload_size = settings->es_max_udp_payload_size_rx; params.tp_set |= 1 << TPI_MAX_UDP_PAYLOAD_SIZE; } if (!settings->es_allow_migration) params.tp_set |= 1 << TPI_DISABLE_ACTIVE_MIGRATION; if (settings->es_ql_bits) { params.tp_loss_bits = settings->es_ql_bits - 1; params.tp_set |= 1 << TPI_LOSS_BITS; } if (settings->es_delayed_acks) { params.tp_numerics[TPI_MIN_ACK_DELAY] = 10000; /* TODO: make into a constant? make configurable? */ params.tp_set |= 1 << TPI_MIN_ACK_DELAY; } if (settings->es_timestamps) params.tp_set |= 1 << TPI_TIMESTAMPS; len = (version == LSQVER_ID27 ? lsquic_tp_encode_27 : lsquic_tp_encode)( &params, enc_sess->esi_flags & ESI_SERVER, buf, bufsz); if (len >= 0) { char str[MAX_TP_STR_SZ]; LSQ_DEBUG("generated transport parameters buffer of %d bytes", len); LSQ_DEBUG("%s", ((version == LSQVER_ID27 ? lsquic_tp_to_str_27 : lsquic_tp_to_str)(&params, str, sizeof(str)), str)); } else LSQ_WARN("cannot generate transport parameters: %d", errno); return len; } /* * Format: * uint32_t lsquic_ver_tag_t * uint32_t encoder version * uint32_t ticket_size * uint8_t ticket_buf[ ticket_size ] * uint32_t trapa_size * uint8_t trapa_buf[ trapa_size ] */ #define ZERO_RTT_VERSION 1 #if __BYTE_ORDER == __LITTLE_ENDIAN #define READ_NUM(var_, ptr_) do { \ memcpy(&var_, ptr_, sizeof(var_)); \ var_ = bswap_32(var_); \ ptr_ += sizeof(var_); \ } while (0) #else #define READ_NUM(var_, ptr_) do { \ memcpy(&var_, ptr_, sizeof(var_)); \ ptr_ += sizeof(var_); \ } while (0) #endif static SSL_SESSION * maybe_create_SSL_SESSION (struct enc_sess_iquic *enc_sess, const SSL_CTX *ssl_ctx) { SSL_SESSION *ssl_session; lsquic_ver_tag_t ver_tag; enum lsquic_version quic_ver; uint32_t rtt_ver, ticket_sz, trapa_sz; const unsigned char *ticket_buf, *trapa_buf, *p; const unsigned char *const end = enc_sess->esi_zero_rtt_buf + enc_sess->esi_zero_rtt_sz; if (enc_sess->esi_zero_rtt_sz < sizeof(ver_tag) + sizeof(rtt_ver) + sizeof(ticket_sz)) { LSQ_DEBUG("rtt buf too short"); return NULL; } p = enc_sess->esi_zero_rtt_buf; memcpy(&ver_tag, p, sizeof(ver_tag)); p += sizeof(ver_tag); quic_ver = lsquic_tag2ver(ver_tag); if (quic_ver != enc_sess->esi_ver_neg->vn_ver) { LSQ_DEBUG("negotiated version %s does not match that in the zero-rtt " "info buffer", lsquic_ver2str[enc_sess->esi_ver_neg->vn_ver]); return NULL; } READ_NUM(rtt_ver, p); if (rtt_ver != ZERO_RTT_VERSION) { LSQ_DEBUG("cannot use zero-rtt buffer: encoded using %"PRIu32", " "while current version is %u", rtt_ver, ZERO_RTT_VERSION); return NULL; } READ_NUM(ticket_sz, p); if (p + ticket_sz > end) { LSQ_WARN("truncated ticket buffer"); return NULL; } ticket_buf = p; p += ticket_sz; if (p + sizeof(trapa_sz) > end) { LSQ_WARN("too short to read trapa size"); return NULL; } READ_NUM(trapa_sz, p); if (p + trapa_sz > end) { LSQ_WARN("truncated trapa buffer"); return NULL; } trapa_buf = p; p += trapa_sz; assert(p == end); (void) /* TODO */ trapa_buf; ssl_session = SSL_SESSION_from_bytes(ticket_buf, ticket_sz, ssl_ctx); if (!ssl_session) { LSQ_WARN("SSL_SESSION could not be parsed out"); return NULL; } LSQ_INFO("instantiated SSL_SESSION from serialized buffer"); return ssl_session; } static void init_frals (struct enc_sess_iquic *enc_sess) { struct frab_list *fral; for (fral = enc_sess->esi_frals; fral < enc_sess->esi_frals + sizeof(enc_sess->esi_frals) / sizeof(enc_sess->esi_frals[0]); ++fral) lsquic_frab_list_init(fral, 0x100, NULL, NULL, NULL); } static enc_session_t * iquic_esfi_create_client (const char *hostname, struct lsquic_engine_public *enpub, struct lsquic_conn *lconn, const lsquic_cid_t *dcid, const struct ver_neg *ver_neg, void *crypto_streams[4], const struct crypto_stream_if *cryst_if, const unsigned char *zero_rtt, size_t zero_rtt_sz, struct lsquic_alarmset *alset, unsigned max_streams_uni) { struct enc_sess_iquic *enc_sess; fiu_return_on("enc_sess_ietf/create_client", NULL); enc_sess = calloc(1, sizeof(*enc_sess)); if (!enc_sess) return NULL; if (hostname) { enc_sess->esi_hostname = strdup(hostname); if (!enc_sess->esi_hostname) { free(enc_sess); return NULL; } } else enc_sess->esi_hostname = NULL; enc_sess->esi_enpub = enpub; enc_sess->esi_streams = crypto_streams; enc_sess->esi_cryst_if = cryst_if; enc_sess->esi_conn = lconn; enc_sess->esi_ver_neg = ver_neg; enc_sess->esi_odcid = *dcid; enc_sess->esi_flags |= ESI_ODCID; LSQ_DEBUGC("created client, DCID: %"CID_FMT, CID_BITS(dcid)); { const char *log; log = getenv("LSQUIC_LOG_SECRETS"); if (log) { if (atoi(log)) enc_sess->esi_flags |= ESI_LOG_SECRETS; LSQ_DEBUG("will %slog secrets", atoi(log) ? "" : "not "); } } init_frals(enc_sess); if (0 != setup_handshake_keys(enc_sess, dcid)) { free(enc_sess); return NULL; } /* Have to wait until the call to init_client() -- this is when the * result of version negotiation is known. */ if (zero_rtt && zero_rtt_sz) { enc_sess->esi_zero_rtt_buf = malloc(zero_rtt_sz); if (enc_sess->esi_zero_rtt_buf) { memcpy(enc_sess->esi_zero_rtt_buf, zero_rtt, zero_rtt_sz); enc_sess->esi_zero_rtt_sz = zero_rtt_sz; } else enc_sess->esi_zero_rtt_sz = 0; } else { enc_sess->esi_zero_rtt_buf = NULL; enc_sess->esi_zero_rtt_sz = 0; } if (enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info) enc_sess->esi_flags |= ESI_WANT_TICKET; enc_sess->esi_alset = alset; lsquic_alarmset_init_alarm(enc_sess->esi_alset, AL_SESS_TICKET, no_sess_ticket, enc_sess); enc_sess->esi_max_streams_uni = max_streams_uni; return enc_sess; } static void iquic_esfi_set_streams (enc_session_t *enc_session_p, void *(crypto_streams)[4], const struct crypto_stream_if *cryst_if) { struct enc_sess_iquic *const enc_sess = enc_session_p; enc_sess->esi_streams = crypto_streams; enc_sess->esi_cryst_if = cryst_if; } static enc_session_t * iquic_esfi_create_server (struct lsquic_engine_public *enpub, struct lsquic_conn *lconn, const lsquic_cid_t *first_dcid, void *(crypto_streams)[4], const struct crypto_stream_if *cryst_if, const struct lsquic_cid *odcid, const struct lsquic_cid *iscid ) { struct enc_sess_iquic *enc_sess; enc_sess = calloc(1, sizeof(*enc_sess)); if (!enc_sess) return NULL; #ifndef NDEBUG enc_sess->esi_sni_bypass = getenv("LSQUIC_SNI_BYPASS"); #endif enc_sess->esi_flags = ESI_SERVER; enc_sess->esi_streams = crypto_streams; enc_sess->esi_cryst_if = cryst_if; enc_sess->esi_enpub = enpub; enc_sess->esi_conn = lconn; if (odcid) { enc_sess->esi_odcid = *odcid; enc_sess->esi_flags |= ESI_ODCID; } enc_sess->esi_iscid = *iscid; enc_sess->esi_flags |= ESI_ISCID; init_frals(enc_sess); { const char *log; log = getenv("LSQUIC_LOG_SECRETS"); if (log) { if (atoi(log)) enc_sess->esi_flags |= ESI_LOG_SECRETS; LSQ_DEBUG("will %slog secrets", atoi(log) ? "" : "not "); } } if (0 != setup_handshake_keys(enc_sess, first_dcid)) { free(enc_sess); return NULL; } enc_sess->esi_max_streams_uni = enpub->enp_settings.es_init_max_streams_uni; return enc_sess; } static const char *const rw2str[] = { "read", "write", }; typedef char evp_aead_enum_has_expected_values[ (int) evp_aead_open == 0 && (int) evp_aead_seal == 1 ? 1 : -1]; #define rw2dir(rw_) ((enum evp_aead_direction_t) (rw_)) static void log_crypto_ctx (const struct enc_sess_iquic *enc_sess, const struct crypto_ctx *ctx, const char *name, int rw) { char hexbuf[EVP_MAX_MD_SIZE * 2 + 1]; LSQ_DEBUG("%s %s key: %s", name, rw2str[rw], HEXSTR(ctx->yk_key_buf, ctx->yk_key_sz, hexbuf)); LSQ_DEBUG("%s %s iv: %s", name, rw2str[rw], HEXSTR(ctx->yk_iv_buf, ctx->yk_iv_sz, hexbuf)); } static void log_crypto_pair (const struct enc_sess_iquic *enc_sess, const struct crypto_ctx_pair *pair, const char *name) { log_crypto_ctx(enc_sess, &pair->ykp_ctx[0], name, 0); log_crypto_ctx(enc_sess, &pair->ykp_ctx[1], name, 1); } /* [draft-ietf-quic-tls-12] Section 5.3.2 */ static int setup_handshake_keys (struct enc_sess_iquic *enc_sess, const lsquic_cid_t *cid) { const EVP_MD *const md = EVP_sha256(); const EVP_AEAD *const aead = EVP_aead_aes_128_gcm(); /* [draft-ietf-quic-tls-12] Section 5.6.1: AEAD_AES_128_GCM implies * 128-bit AES-CTR. */ const EVP_CIPHER *const cipher = EVP_aes_128_ecb(); struct crypto_ctx_pair *pair; struct header_prot *hp; size_t hsk_secret_sz, key_len; unsigned cliser, i; unsigned char hsk_secret[EVP_MAX_MD_SIZE]; unsigned char secret[2][SHA256_DIGEST_LENGTH]; /* client, server */ unsigned char key[2][EVP_MAX_KEY_LENGTH]; char hexbuf[EVP_MAX_MD_SIZE * 2 + 1]; if (!enc_sess->esi_hsk_pairs) { enc_sess->esi_hsk_pairs = calloc(N_HSK_PAIRS, sizeof(enc_sess->esi_hsk_pairs[0])); enc_sess->esi_hsk_hps = calloc(N_HSK_PAIRS, sizeof(enc_sess->esi_hsk_hps[0])); if (!(enc_sess->esi_hsk_pairs && enc_sess->esi_hsk_hps)) { free(enc_sess->esi_hsk_pairs); free(enc_sess->esi_hsk_hps); return -1; } } pair = &enc_sess->esi_hsk_pairs[ENC_LEV_CLEAR]; pair->ykp_thresh = IQUIC_INVALID_PACKNO; hp = &enc_sess->esi_hsk_hps[ENC_LEV_CLEAR]; HKDF_extract(hsk_secret, &hsk_secret_sz, md, cid->idbuf, cid->len, enc_sess->esi_conn->cn_version < LSQVER_ID29 ? HSK_SALT_PRE29 : HSK_SALT, HSK_SALT_SZ); if (enc_sess->esi_flags & ESI_LOG_SECRETS) { LSQ_DEBUG("handshake salt: %s", HEXSTR(HSK_SALT, HSK_SALT_SZ, hexbuf)); LSQ_DEBUG("handshake secret: %s", HEXSTR(hsk_secret, hsk_secret_sz, hexbuf)); } lsquic_qhkdf_expand(md, hsk_secret, hsk_secret_sz, CLIENT_LABEL, CLIENT_LABEL_SZ, secret[0], sizeof(secret[0])); lsquic_qhkdf_expand(md, hsk_secret, hsk_secret_sz, SERVER_LABEL, SERVER_LABEL_SZ, secret[1], sizeof(secret[1])); if (enc_sess->esi_flags & ESI_LOG_SECRETS) { LSQ_DEBUG("client handshake secret: %s", HEXSTR(secret[0], sizeof(secret[0]), hexbuf)); LSQ_DEBUG("server handshake secret: %s", HEXSTR(secret[1], sizeof(secret[1]), hexbuf)); } cliser = !!(enc_sess->esi_flags & ESI_SERVER); if (0 != init_crypto_ctx(&pair->ykp_ctx[!cliser], md, aead, secret[0], sizeof(secret[0]), rw2dir(!cliser))) goto err; if (0 != init_crypto_ctx(&pair->ykp_ctx[cliser], md, aead, secret[1], sizeof(secret[1]), rw2dir(cliser))) goto err; hp->hp_gen_mask = gen_hp_mask_aes; hp->hp_enc_level = ENC_LEV_CLEAR; key_len = EVP_AEAD_key_length(aead); lsquic_qhkdf_expand(md, secret[!cliser], sizeof(secret[0]), PN_LABEL, PN_LABEL_SZ, key[0], key_len); lsquic_qhkdf_expand(md, secret[cliser], sizeof(secret[0]), PN_LABEL, PN_LABEL_SZ, key[1], key_len); if (enc_sess->esi_flags & ESI_LOG_SECRETS) { log_crypto_pair(enc_sess, pair, "handshake"); LSQ_DEBUG("read handshake hp: %s", HEXSTR(key[0], key_len, hexbuf)); LSQ_DEBUG("write handshake hp: %s", HEXSTR(key[1], key_len, hexbuf)); } for (i = 0; i < 2; ++i) { EVP_CIPHER_CTX_init(&hp->hp_u.cipher_ctx[i]); if (EVP_EncryptInit_ex(&hp->hp_u.cipher_ctx[i], cipher, NULL, key[i], 0)) hp->hp_flags |= 1 << i; else { LSQ_ERROR("%s: cannot initialize cipher %u", __func__, i); goto err; } } return 0; err: cleanup_crypto_ctx(&pair->ykp_ctx[0]); cleanup_crypto_ctx(&pair->ykp_ctx[1]); return -1; } static void cleanup_hp (struct header_prot *hp) { unsigned rw; if (hp->hp_gen_mask == gen_hp_mask_aes) for (rw = 0; rw < 2; ++rw) if (hp->hp_flags & (1 << rw)) (void) EVP_CIPHER_CTX_cleanup(&hp->hp_u.cipher_ctx[rw]); } static void free_handshake_keys (struct enc_sess_iquic *enc_sess) { struct crypto_ctx_pair *pair; unsigned i; if (enc_sess->esi_hsk_pairs) { assert(enc_sess->esi_hsk_hps); for (pair = enc_sess->esi_hsk_pairs; pair < enc_sess->esi_hsk_pairs + N_HSK_PAIRS; ++pair) { cleanup_crypto_ctx(&pair->ykp_ctx[0]); cleanup_crypto_ctx(&pair->ykp_ctx[1]); } free(enc_sess->esi_hsk_pairs); enc_sess->esi_hsk_pairs = NULL; for (i = 0; i < N_HSK_PAIRS; ++i) cleanup_hp(&enc_sess->esi_hsk_hps[i]); free(enc_sess->esi_hsk_hps); enc_sess->esi_hsk_hps = NULL; } else assert(!enc_sess->esi_hsk_hps); } static void keylog_callback (const SSL *ssl, const char *line) { struct enc_sess_iquic *enc_sess; enc_sess = SSL_get_ex_data(ssl, s_idx); if (enc_sess->esi_keylog_handle) enc_sess->esi_enpub->enp_kli->kli_log_line( enc_sess->esi_keylog_handle, line); } static void maybe_setup_key_logging (struct enc_sess_iquic *enc_sess) { if (enc_sess->esi_enpub->enp_kli) { enc_sess->esi_keylog_handle = enc_sess->esi_enpub->enp_kli->kli_open( enc_sess->esi_enpub->enp_kli_ctx, enc_sess->esi_conn); LSQ_DEBUG("SSL keys %s be logged", enc_sess->esi_keylog_handle ? "will" : "will not"); } } static enum ssl_verify_result_t verify_server_cert_callback (SSL *ssl, uint8_t *out_alert) { struct enc_sess_iquic *enc_sess; struct stack_st_X509 *chain; int s; enc_sess = SSL_get_ex_data(ssl, s_idx); chain = SSL_get_peer_cert_chain(ssl); if (!chain) { LSQ_ERROR("cannot get peer chain"); return ssl_verify_invalid; } EV_LOG_CERT_CHAIN(LSQUIC_LOG_CONN_ID, chain); if (enc_sess->esi_enpub->enp_verify_cert) { s = enc_sess->esi_enpub->enp_verify_cert( enc_sess->esi_enpub->enp_verify_ctx, chain); return s == 0 ? ssl_verify_ok : ssl_verify_invalid; } else return ssl_verify_ok; } static int iquic_lookup_cert (SSL *ssl, void *arg) { struct enc_sess_iquic *const enc_sess = arg; const struct network_path *path; const char *server_name; SSL_CTX *ssl_ctx; server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); #ifndef NDEBUG if (!server_name) server_name = enc_sess->esi_sni_bypass; #endif if (!server_name) { LSQ_DEBUG("cert lookup: server name is not set"); /* SNI is required in HTTP/3 */ if (enc_sess->esi_enpub->enp_flags & ENPUB_HTTP) return 1; } path = enc_sess->esi_conn->cn_if->ci_get_path(enc_sess->esi_conn, NULL); ssl_ctx = enc_sess->esi_enpub->enp_lookup_cert( enc_sess->esi_enpub->enp_cert_lu_ctx, NP_LOCAL_SA(path), server_name); if (ssl_ctx) { if (SSL_set_SSL_CTX(enc_sess->esi_ssl, ssl_ctx)) { LSQ_DEBUG("looked up cert for %s", server_name ? server_name : "<no SNI>"); if (enc_sess->esi_enpub->enp_kli) SSL_CTX_set_keylog_callback(ssl_ctx, keylog_callback); SSL_set_verify(enc_sess->esi_ssl, SSL_CTX_get_verify_mode(ssl_ctx), NULL); SSL_set_verify_depth(enc_sess->esi_ssl, SSL_CTX_get_verify_depth(ssl_ctx)); SSL_clear_options(enc_sess->esi_ssl, SSL_get_options(enc_sess->esi_ssl)); SSL_set_options(enc_sess->esi_ssl, SSL_CTX_get_options(ssl_ctx) & ~SSL_OP_NO_TLSv1_3); return 1; } else { LSQ_WARN("cannot set SSL_CTX"); return 0; } } else { LSQ_DEBUG("could not look up cert for %s", server_name ? server_name : "<no SNI>"); return 0; } } static void iquic_esf_set_conn (enc_session_t *enc_session_p, struct lsquic_conn *lconn) { struct enc_sess_iquic *const enc_sess = enc_session_p; enc_sess->esi_conn = lconn; LSQ_DEBUG("updated conn reference"); } static int iquic_esfi_init_server (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; const struct alpn_map *am; int transpa_len; SSL_CTX *ssl_ctx = NULL; union { char errbuf[ERR_ERROR_STRING_BUF_LEN]; unsigned char trans_params[sizeof(struct transport_params)]; } u; if (enc_sess->esi_enpub->enp_alpn) enc_sess->esi_alpn = enc_sess->esi_enpub->enp_alpn; else if (enc_sess->esi_enpub->enp_flags & ENPUB_HTTP) { for (am = s_h3_alpns; am < s_h3_alpns + sizeof(s_h3_alpns) / sizeof(s_h3_alpns[0]); ++am) if (am->version == enc_sess->esi_conn->cn_version) goto ok; LSQ_ERROR("version %s has no matching ALPN", lsquic_ver2str[enc_sess->esi_conn->cn_version]); return -1; ok: enc_sess->esi_alpn = am->alpn; } ssl_ctx = enc_sess->esi_enpub->enp_get_ssl_ctx( lsquic_conn_get_peer_ctx(enc_sess->esi_conn, NULL)); if (!ssl_ctx) { LSQ_ERROR("fetching SSL context associated with peer context failed"); return -1; } enc_sess->esi_ssl = SSL_new(ssl_ctx); if (!enc_sess->esi_ssl) { LSQ_ERROR("cannot create SSL object: %s", ERR_error_string(ERR_get_error(), u.errbuf)); return -1; } if (!(SSL_set_quic_method(enc_sess->esi_ssl, &cry_quic_method))) { LSQ_INFO("could not set stream method"); return -1; } /* TODO: set to transport parameter string instead of the constant string */ if (!SSL_set_quic_early_data_context(enc_sess->esi_ssl, (unsigned char *) "lsquic", 6)) { LSQ_INFO("could not set early data context"); return -1; } maybe_setup_key_logging(enc_sess); transpa_len = gen_trans_params(enc_sess, u.trans_params, sizeof(u.trans_params)); if (transpa_len < 0) return -1; if (1 != SSL_set_quic_transport_params(enc_sess->esi_ssl, u.trans_params, transpa_len)) { LSQ_ERROR("cannot set QUIC transport params: %s", ERR_error_string(ERR_get_error(), u.errbuf)); return -1; } SSL_clear_options(enc_sess->esi_ssl, SSL_OP_NO_TLSv1_3); SSL_set_cert_cb(enc_sess->esi_ssl, iquic_lookup_cert, enc_sess); SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess); SSL_set_accept_state(enc_sess->esi_ssl); LSQ_DEBUG("initialized server enc session"); enc_sess->esi_flags |= ESI_INITIALIZED; return 0; } #if __BYTE_ORDER == __LITTLE_ENDIAN #define WRITE_NUM(var_, val_, ptr_) do { \ var_ = (val_); \ var_ = bswap_32(var_); \ memcpy((ptr_), &var_, sizeof(var_)); \ ptr_ += sizeof(var_); \ } while (0) #else #define WRITE_NUM(var_, val_, ptr_) do { \ var_ = (val_); \ memcpy((ptr_), &var_, sizeof(var_)); \ ptr_ += sizeof(var_); \ } while (0) #endif static int iquic_new_session_cb (SSL *ssl, SSL_SESSION *session) { struct enc_sess_iquic *enc_sess; uint32_t num; unsigned char *p, *buf; uint8_t *ticket_buf; size_t ticket_sz; lsquic_ver_tag_t tag; const uint8_t *trapa_buf; size_t trapa_sz, buf_sz; enc_sess = SSL_get_ex_data(ssl, s_idx); assert(enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info); SSL_get_peer_quic_transport_params(enc_sess->esi_ssl, &trapa_buf, &trapa_sz); if (!(trapa_buf + trapa_sz)) { LSQ_WARN("no transport parameters: cannot generate zero-rtt info"); return 0; } if (trapa_sz > UINT32_MAX) { LSQ_WARN("trapa size too large: %zu", trapa_sz); return 0; } if (!SSL_SESSION_to_bytes(session, &ticket_buf, &ticket_sz)) { LSQ_INFO("could not serialize new session"); return 0; } if (ticket_sz > UINT32_MAX) { LSQ_WARN("ticket size too large: %zu", ticket_sz); OPENSSL_free(ticket_buf); return 0; } buf_sz = sizeof(tag) + sizeof(uint32_t) + sizeof(uint32_t) + ticket_sz + sizeof(uint32_t) + trapa_sz; buf = malloc(buf_sz); if (!buf) { OPENSSL_free(ticket_buf); LSQ_WARN("%s: malloc failed", __func__); return 0; } p = buf; tag = lsquic_ver2tag(enc_sess->esi_conn->cn_version); memcpy(p, &tag, sizeof(tag)); p += sizeof(tag); WRITE_NUM(num, ZERO_RTT_VERSION, p); WRITE_NUM(num, ticket_sz, p); memcpy(p, ticket_buf, ticket_sz); p += ticket_sz; WRITE_NUM(num, trapa_sz, p); memcpy(p, trapa_buf, trapa_sz); p += trapa_sz; assert(buf + buf_sz == p); OPENSSL_free(ticket_buf); LSQ_DEBUG("generated %zu bytes of zero-rtt buffer", buf_sz); enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info(enc_sess->esi_conn, buf, buf_sz); free(buf); enc_sess->esi_flags &= ~ESI_WANT_TICKET; lsquic_alarmset_unset(enc_sess->esi_alset, AL_SESS_TICKET); return 0; } static int init_client (struct enc_sess_iquic *const enc_sess) { SSL_CTX *ssl_ctx; SSL_SESSION *ssl_session; const struct alpn_map *am; int transpa_len; char errbuf[ERR_ERROR_STRING_BUF_LEN]; #define hexbuf errbuf /* This is a dual-purpose buffer */ unsigned char trans_params[0x80 #if LSQUIC_TEST_QUANTUM_READINESS + 4 + QUANTUM_READY_SZ #endif ]; if (enc_sess->esi_enpub->enp_alpn) enc_sess->esi_alpn = enc_sess->esi_enpub->enp_alpn; else if (enc_sess->esi_enpub->enp_flags & ENPUB_HTTP) { for (am = s_h3_alpns; am < s_h3_alpns + sizeof(s_h3_alpns) / sizeof(s_h3_alpns[0]); ++am) if (am->version == enc_sess->esi_ver_neg->vn_ver) goto ok; LSQ_ERROR("version %s has no matching ALPN", lsquic_ver2str[enc_sess->esi_ver_neg->vn_ver]); return -1; ok: enc_sess->esi_alpn = am->alpn; } LSQ_DEBUG("Create new SSL_CTX"); ssl_ctx = SSL_CTX_new(TLS_method()); if (!ssl_ctx) { LSQ_ERROR("cannot create SSL context: %s", ERR_error_string(ERR_get_error(), errbuf)); goto err; } SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION); SSL_CTX_set_default_verify_paths(ssl_ctx); SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT); if (enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info) SSL_CTX_sess_set_new_cb(ssl_ctx, iquic_new_session_cb); if (enc_sess->esi_enpub->enp_kli) SSL_CTX_set_keylog_callback(ssl_ctx, keylog_callback); if (enc_sess->esi_enpub->enp_verify_cert || LSQ_LOG_ENABLED_EXT(LSQ_LOG_DEBUG, LSQLM_EVENT) || LSQ_LOG_ENABLED_EXT(LSQ_LOG_DEBUG, LSQLM_QLOG)) SSL_CTX_set_custom_verify(ssl_ctx, SSL_VERIFY_PEER, verify_server_cert_callback); SSL_CTX_set_early_data_enabled(ssl_ctx, 1); transpa_len = gen_trans_params(enc_sess, trans_params, sizeof(trans_params)); if (transpa_len < 0) { goto err; } enc_sess->esi_ssl = SSL_new(ssl_ctx); if (!enc_sess->esi_ssl) { LSQ_ERROR("cannot create SSL object: %s", ERR_error_string(ERR_get_error(), errbuf)); goto err; } if (!(SSL_set_quic_method(enc_sess->esi_ssl, &cry_quic_method))) { LSQ_INFO("could not set stream method"); goto err; } maybe_setup_key_logging(enc_sess); if (1 != SSL_set_quic_transport_params(enc_sess->esi_ssl, trans_params, transpa_len)) { LSQ_ERROR("cannot set QUIC transport params: %s", ERR_error_string(ERR_get_error(), errbuf)); goto err; } if (enc_sess->esi_alpn && 0 != SSL_set_alpn_protos(enc_sess->esi_ssl, enc_sess->esi_alpn, enc_sess->esi_alpn[0] + 1)) { LSQ_ERROR("cannot set ALPN: %s", ERR_error_string(ERR_get_error(), errbuf)); goto err; } if (1 != SSL_set_tlsext_host_name(enc_sess->esi_ssl, enc_sess->esi_hostname)) { LSQ_ERROR("cannot set hostname: %s", ERR_error_string(ERR_get_error(), errbuf)); goto err; } free(enc_sess->esi_hostname); enc_sess->esi_hostname = NULL; if (enc_sess->esi_zero_rtt_buf) { ssl_session = maybe_create_SSL_SESSION(enc_sess, ssl_ctx); if (ssl_session) { if (SSL_set_session(enc_sess->esi_ssl, ssl_session)) enc_sess->esi_flags |= ESI_USE_SSL_TICKET; else LSQ_WARN("cannot set session"); } } SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess); SSL_set_connect_state(enc_sess->esi_ssl); SSL_CTX_free(ssl_ctx); LSQ_DEBUG("initialized client enc session"); enc_sess->esi_flags |= ESI_INITIALIZED; return 0; err: if (ssl_ctx) SSL_CTX_free(ssl_ctx); return -1; #undef hexbuf } struct crypto_params { const EVP_AEAD *aead; const EVP_MD *md; const EVP_CIPHER *hp; gen_hp_mask_f gen_hp_mask; }; static int get_crypto_params (const struct enc_sess_iquic *enc_sess, const SSL_CIPHER *cipher, struct crypto_params *params) { unsigned key_sz, iv_sz; uint32_t id; id = SSL_CIPHER_get_id(cipher); LSQ_DEBUG("Negotiated cipher ID is 0x%"PRIX32, id); /* RFC 8446, Appendix B.4 */ switch (id) { case 0x03000000 | 0x1301: /* TLS_AES_128_GCM_SHA256 */ params->md = EVP_sha256(); params->aead = EVP_aead_aes_128_gcm(); params->hp = EVP_aes_128_ecb(); params->gen_hp_mask = gen_hp_mask_aes; break; case 0x03000000 | 0x1302: /* TLS_AES_256_GCM_SHA384 */ params->md = EVP_sha384(); params->aead = EVP_aead_aes_256_gcm(); params->hp = EVP_aes_256_ecb(); params->gen_hp_mask = gen_hp_mask_aes; break; case 0x03000000 | 0x1303: /* TLS_CHACHA20_POLY1305_SHA256 */ params->md = EVP_sha256(); params->aead = EVP_aead_chacha20_poly1305(); params->hp = NULL; params->gen_hp_mask = gen_hp_mask_chacha20; break; default: /* TLS_AES_128_CCM_SHA256 and TLS_AES_128_CCM_8_SHA256 are not * supported by BoringSSL (grep for \b0x130[45]\b). */ LSQ_DEBUG("unsupported cipher 0x%"PRIX32, id); return -1; } key_sz = EVP_AEAD_key_length(params->aead); if (key_sz > EVP_MAX_KEY_LENGTH) { LSQ_DEBUG("key size %u is too large", key_sz); return -1; } iv_sz = EVP_AEAD_nonce_length(params->aead); if (iv_sz < 8) iv_sz = 8; /* [draft-ietf-quic-tls-11], Section 5.3 */ if (iv_sz > EVP_MAX_IV_LENGTH) { LSQ_DEBUG("iv size %u is too large", iv_sz); return -1; } /* FIXME: figure out why this duplicate check is here and either fix it * or get rid of it. */ if (key_sz > EVP_MAX_KEY_LENGTH) { LSQ_DEBUG("PN size %u is too large", key_sz); return -1; } return 0; } static int get_peer_transport_params (struct enc_sess_iquic *enc_sess) { struct transport_params *const trans_params = &enc_sess->esi_peer_tp; const uint8_t *params_buf; size_t bufsz; char *params_str; const enum lsquic_version version = enc_sess->esi_conn->cn_version; SSL_get_peer_quic_transport_params(enc_sess->esi_ssl, &params_buf, &bufsz); if (!params_buf) { LSQ_DEBUG("no peer transport parameters"); return -1; } LSQ_DEBUG("have peer transport parameters (%zu bytes)", bufsz); if (0 > (version == LSQVER_ID27 ? lsquic_tp_decode_27 : lsquic_tp_decode)(params_buf, bufsz, !(enc_sess->esi_flags & ESI_SERVER), trans_params)) { if (LSQ_LOG_ENABLED(LSQ_LOG_DEBUG)) { params_str = lsquic_mm_get_4k(&enc_sess->esi_enpub->enp_mm); if (params_str) { lsquic_hexdump(params_buf, bufsz, params_str, 0x1000); LSQ_DEBUG("could not parse peer transport parameters " "(%zd bytes):\n%s", bufsz, params_str); lsquic_mm_put_4k(&enc_sess->esi_enpub->enp_mm, params_str); } else LSQ_DEBUG("could not parse peer transport parameters " "(%zd bytes)", bufsz); } return -1; } const lsquic_cid_t *const cids[LAST_TPI + 1] = { [TP_CID_IDX(TPI_ORIGINAL_DEST_CID)] = enc_sess->esi_flags & ESI_ODCID ? &enc_sess->esi_odcid : NULL, [TP_CID_IDX(TPI_RETRY_SOURCE_CID)] = enc_sess->esi_flags & ESI_RSCID ? &enc_sess->esi_rscid : NULL, [TP_CID_IDX(TPI_INITIAL_SOURCE_CID)] = enc_sess->esi_flags & ESI_ISCID ? &enc_sess->esi_iscid : NULL, }; unsigned must_have, must_not_have = 0; if (version > LSQVER_ID27) { must_have = 1 << TPI_INITIAL_SOURCE_CID; if (enc_sess->esi_flags & ESI_SERVER) must_not_have |= 1 << TPI_ORIGINAL_DEST_CID; else must_have |= 1 << TPI_ORIGINAL_DEST_CID; if ((enc_sess->esi_flags & (ESI_RETRY|ESI_SERVER)) == ESI_RETRY) must_have |= 1 << TPI_RETRY_SOURCE_CID; else must_not_have |= 1 << TPI_RETRY_SOURCE_CID; } else if ((enc_sess->esi_flags & (ESI_RETRY|ESI_SERVER)) == ESI_RETRY) must_have = 1 << TPI_ORIGINAL_DEST_CID; else must_have = 0; enum transport_param_id tpi; for (tpi = FIRST_TP_CID; tpi <= LAST_TP_CID; ++tpi) { if (!(must_have & (1 << tpi))) continue; if (!(trans_params->tp_set & (1 << tpi))) { LSQ_DEBUG("server did not produce %s", lsquic_tpi2str[tpi]); return -1; } if (!cids[TP_CID_IDX(tpi)]) { LSQ_WARN("do not have CID %s for checking", lsquic_tpi2str[tpi]); return -1; } if (LSQUIC_CIDS_EQ(cids[TP_CID_IDX(tpi)], &trans_params->tp_cids[TP_CID_IDX(tpi)])) LSQ_DEBUG("%s values match", lsquic_tpi2str[tpi]); else { if (LSQ_LOG_ENABLED(LSQ_LOG_DEBUG)) { char cidbuf[2][MAX_CID_LEN * 2 + 1]; LSQ_DEBUG("server provided %s %"CID_FMT" that does not " "match ours %"CID_FMT, lsquic_tpi2str[tpi], CID_BITS_B(&trans_params->tp_cids[TP_CID_IDX(tpi)], cidbuf[0]), CID_BITS_B(cids[TP_CID_IDX(tpi)], cidbuf[1])); } return -1; } } for (tpi = FIRST_TP_CID; tpi <= LAST_TP_CID; ++tpi) if (must_not_have & (1 << tpi) & trans_params->tp_set) { LSQ_DEBUG("server transport parameters unexpectedly contain %s", lsquic_tpi2str[tpi]); return -1; } if ((trans_params->tp_set & (1 << TPI_LOSS_BITS)) && enc_sess->esi_enpub->enp_settings.es_ql_bits) { const unsigned our_loss_bits = enc_sess->esi_enpub->enp_settings.es_ql_bits - 1; switch ((our_loss_bits << 1) | trans_params->tp_loss_bits) { case (0 << 1) | 0: LSQ_DEBUG("both sides only tolerate QL bits: don't enable them"); break; case (0 << 1) | 1: LSQ_DEBUG("peer sends QL bits, we receive them"); enc_sess->esi_flags |= ESI_RECV_QL_BITS; break; case (1 << 1) | 0: LSQ_DEBUG("we send QL bits, peer receives them"); enc_sess->esi_flags |= ESI_SEND_QL_BITS; break; default/*1 << 1) | 1*/: LSQ_DEBUG("enable sending and receiving QL bits"); enc_sess->esi_flags |= ESI_RECV_QL_BITS; enc_sess->esi_flags |= ESI_SEND_QL_BITS; break; } } else LSQ_DEBUG("no QL bits"); return 0; } static int maybe_get_peer_transport_params (struct enc_sess_iquic *enc_sess) { int s; if (enc_sess->esi_flags & ESI_HAVE_PEER_TP) return 0; s = get_peer_transport_params(enc_sess); if (s == 0) enc_sess->esi_flags |= ESI_HAVE_PEER_TP; return s; } static enum iquic_handshake_status iquic_esfi_handshake (struct enc_sess_iquic *enc_sess) { int s, err; enum lsquic_hsk_status hsk_status; char errbuf[ERR_ERROR_STRING_BUF_LEN]; s = SSL_do_handshake(enc_sess->esi_ssl); if (s <= 0) { err = SSL_get_error(enc_sess->esi_ssl, s); switch (err) { case SSL_ERROR_WANT_READ: LSQ_DEBUG("retry read"); return IHS_WANT_READ; case SSL_ERROR_WANT_WRITE: LSQ_DEBUG("retry write"); return IHS_WANT_WRITE; case SSL_ERROR_EARLY_DATA_REJECTED: LSQ_DEBUG("early data rejected"); hsk_status = LSQ_HSK_0RTT_FAIL; goto err; /* fall through */ default: LSQ_DEBUG("handshake: %s", ERR_error_string(err, errbuf)); hsk_status = LSQ_HSK_FAIL; goto err; } } if (SSL_in_early_data(enc_sess->esi_ssl)) { LSQ_DEBUG("in early data"); if (enc_sess->esi_flags & ESI_SERVER) LSQ_DEBUG("TODO"); else return IHS_WANT_READ; } hsk_status = LSQ_HSK_OK; LSQ_DEBUG("handshake reported complete"); EV_LOG_HSK_COMPLETED(LSQUIC_LOG_CONN_ID); /* The ESI_USE_SSL_TICKET flag indicates if the client attempted 0-RTT. * If the handshake is complete, and the client attempted 0-RTT, it * must have succeeded. */ if (enc_sess->esi_flags & ESI_USE_SSL_TICKET) { hsk_status = LSQ_HSK_0RTT_OK; EV_LOG_ZERO_RTT(LSQUIC_LOG_CONN_ID); } if (0 != maybe_get_peer_transport_params(enc_sess)) { hsk_status = LSQ_HSK_FAIL; goto err; } enc_sess->esi_flags |= ESI_HANDSHAKE_OK; enc_sess->esi_conn->cn_if->ci_hsk_done(enc_sess->esi_conn, hsk_status); return IHS_STOP; /* XXX: what else can come on the crypto stream? */ err: LSQ_DEBUG("handshake failed"); enc_sess->esi_conn->cn_if->ci_hsk_done(enc_sess->esi_conn, hsk_status); return IHS_STOP; } static enum iquic_handshake_status iquic_esfi_post_handshake (struct enc_sess_iquic *enc_sess) { int s; s = SSL_process_quic_post_handshake(enc_sess->esi_ssl); LSQ_DEBUG("SSL_process_quic_post_handshake() returned %d", s); if (s == 1) return IHS_WANT_READ; else { enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn, "post-handshake error, code %d", s); return IHS_STOP; } } static struct transport_params * iquic_esfi_get_peer_transport_params (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; if (0 == maybe_get_peer_transport_params(enc_sess)) return &enc_sess->esi_peer_tp; else return NULL; } static void iquic_esfi_destroy (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; struct frab_list *fral; LSQ_DEBUG("iquic_esfi_destroy"); for (fral = enc_sess->esi_frals; fral < enc_sess->esi_frals + sizeof(enc_sess->esi_frals) / sizeof(enc_sess->esi_frals[0]); ++fral) lsquic_frab_list_cleanup(fral); if (enc_sess->esi_keylog_handle) enc_sess->esi_enpub->enp_kli->kli_close(enc_sess->esi_keylog_handle); if (enc_sess->esi_ssl) SSL_free(enc_sess->esi_ssl); free_handshake_keys(enc_sess); cleanup_hp(&enc_sess->esi_hp); free(enc_sess->esi_zero_rtt_buf); free(enc_sess->esi_hostname); free(enc_sess); } /* See [draft-ietf-quic-tls-14], Section 4 */ static const enum enc_level hety2el[] = { [HETY_NOT_SET] = ENC_LEV_FORW, [HETY_VERNEG] = 0, [HETY_INITIAL] = ENC_LEV_CLEAR, [HETY_RETRY] = 0, [HETY_HANDSHAKE] = ENC_LEV_INIT, [HETY_0RTT] = ENC_LEV_EARLY, }; static const enum enc_level pns2enc_level[] = { [PNS_INIT] = ENC_LEV_CLEAR, [PNS_HSK] = ENC_LEV_INIT, [PNS_APP] = ENC_LEV_FORW, }; static enum enc_packout iquic_esf_encrypt_packet (enc_session_t *enc_session_p, const struct lsquic_engine_public *enpub, struct lsquic_conn *lconn_UNUSED, struct lsquic_packet_out *packet_out) { struct enc_sess_iquic *const enc_sess = enc_session_p; struct lsquic_conn *const lconn = enc_sess->esi_conn; unsigned char *dst; const struct crypto_ctx_pair *pair; const struct crypto_ctx *crypto_ctx; struct header_prot *hp; enum enc_level enc_level; unsigned char nonce_buf[ sizeof(crypto_ctx->yk_iv_buf) + 8 ]; unsigned char *nonce, *begin_xor; lsquic_packno_t packno; size_t out_sz, dst_sz; int header_sz; int ipv6; unsigned packno_off, packno_len; enum packnum_space pns; char errbuf[ERR_ERROR_STRING_BUF_LEN]; pns = lsquic_packet_out_pns(packet_out); /* TODO Obviously, will need more logic for 0-RTT */ enc_level = pns2enc_level[ pns ]; if (enc_level == ENC_LEV_FORW) { pair = &enc_sess->esi_pairs[ enc_sess->esi_key_phase ]; crypto_ctx = &pair->ykp_ctx[ 1 ]; hp = &enc_sess->esi_hp; } else if (enc_sess->esi_hsk_pairs) { pair = &enc_sess->esi_hsk_pairs[ enc_level ]; crypto_ctx = &pair->ykp_ctx[ 1 ]; hp = &enc_sess->esi_hsk_hps[ enc_level ]; } else { LSQ_WARN("no keys for encryption level %s", lsquic_enclev2str[enc_level]); return ENCPA_BADCRYPT; } if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED))) { LSQ_WARN("encrypt crypto context at level %s not initialized", lsquic_enclev2str[enc_level]); return ENCPA_BADCRYPT; } if (packet_out->po_data_sz < 3) { /* [draft-ietf-quic-tls-20] Section 5.4.2 */ enum packno_bits bits = lsquic_packet_out_packno_bits(packet_out); unsigned len = iquic_packno_bits2len(bits); if (packet_out->po_data_sz + len < 4) { len = 4 - packet_out->po_data_sz - len; memset(packet_out->po_data + packet_out->po_data_sz, 0, len); packet_out->po_data_sz += len; packet_out->po_frame_types |= QUIC_FTBIT_PADDING; LSQ_DEBUG("padded packet %"PRIu64" with %u bytes of PADDING", packet_out->po_packno, len); } } dst_sz = lconn->cn_pf->pf_packout_size(lconn, packet_out); ipv6 = NP_IS_IPv6(packet_out->po_path); dst = enpub->enp_pmi->pmi_allocate(enpub->enp_pmi_ctx, packet_out->po_path->np_peer_ctx, dst_sz, ipv6); if (!dst) { LSQ_DEBUG("could not allocate memory for outgoing packet of size %zd", dst_sz); return ENCPA_NOMEM; } /* Align nonce so we can perform XOR safely in one shot: */ begin_xor = nonce_buf + sizeof(nonce_buf) - 8; begin_xor = (unsigned char *) ((uintptr_t) begin_xor & ~0x7); nonce = begin_xor - crypto_ctx->yk_iv_sz + 8; memcpy(nonce, crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz); packno = packet_out->po_packno; if (s_log_seal_and_open) LSQ_DEBUG("seal: iv: %s; packno: 0x%"PRIX64, HEXSTR(crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz, s_str), packno); #if __BYTE_ORDER == __LITTLE_ENDIAN packno = bswap_64(packno); #endif *((uint64_t *) begin_xor) ^= packno; /* TODO: have this call return packno_off and packno_len to avoid * another function call. */ header_sz = lconn->cn_pf->pf_gen_reg_pkt_header(lconn, packet_out, dst, dst_sz); if (header_sz < 0) goto err; if (enc_level == ENC_LEV_FORW) dst[0] |= enc_sess->esi_key_phase << 2; if (s_log_seal_and_open) { LSQ_DEBUG("seal: nonce (%u bytes): %s", crypto_ctx->yk_iv_sz, HEXSTR(nonce, crypto_ctx->yk_iv_sz, s_str)); LSQ_DEBUG("seal: ad (%u bytes): %s", header_sz, HEXSTR(dst, header_sz, s_str)); LSQ_DEBUG("seal: in (%u bytes): %s", packet_out->po_data_sz, HEXSTR(packet_out->po_data, packet_out->po_data_sz, s_str)); } if (!EVP_AEAD_CTX_seal(&crypto_ctx->yk_aead_ctx, dst + header_sz, &out_sz, dst_sz - header_sz, nonce, crypto_ctx->yk_iv_sz, packet_out->po_data, packet_out->po_data_sz, dst, header_sz)) { LSQ_WARN("cannot seal packet #%"PRIu64": %s", packet_out->po_packno, ERR_error_string(ERR_get_error(), errbuf)); goto err; } assert(out_sz == dst_sz - header_sz); lconn->cn_pf->pf_packno_info(lconn, packet_out, &packno_off, &packno_len); #ifndef NDEBUG const unsigned sample_off = packno_off + 4; assert(sample_off + IQUIC_TAG_LEN <= dst_sz); #endif packet_out->po_enc_data = dst; packet_out->po_enc_data_sz = dst_sz; packet_out->po_sent_sz = dst_sz; packet_out->po_flags &= ~PO_IPv6; packet_out->po_flags |= PO_ENCRYPTED|PO_SENT_SZ|(ipv6 << POIPv6_SHIFT); lsquic_packet_out_set_enc_level(packet_out, enc_level); lsquic_packet_out_set_kp(packet_out, enc_sess->esi_key_phase); if (enc_level == ENC_LEV_FORW && hp->hp_gen_mask != gen_hp_mask_chacha20) apply_hp_batch(enc_sess, hp, packet_out, packno_off, packno_len); else apply_hp_immediately(enc_sess, hp, packet_out, packno_off, packno_len); return ENCPA_OK; err: enpub->enp_pmi->pmi_return(enpub->enp_pmi_ctx, packet_out->po_path->np_peer_ctx, dst, ipv6); return ENCPA_BADCRYPT; } static void iquic_esf_flush_encryption (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; if (enc_sess->esi_hp_batch_idx) { LSQ_DEBUG("flush header protection application, count: %u", enc_sess->esi_hp_batch_idx); flush_hp_batch(enc_sess); } } static struct ku_label { const char *str; uint8_t len; } select_ku_label (const struct enc_sess_iquic *enc_sess) { return (struct ku_label) { "quic ku", 7, }; } static enum dec_packin iquic_esf_decrypt_packet (enc_session_t *enc_session_p, struct lsquic_engine_public *enpub, const struct lsquic_conn *lconn, struct lsquic_packet_in *packet_in) { struct enc_sess_iquic *const enc_sess = enc_session_p; unsigned char *dst; struct crypto_ctx_pair *pair; struct header_prot *hp; struct crypto_ctx *crypto_ctx = NULL; unsigned char nonce_buf[ sizeof(crypto_ctx->yk_iv_buf) + 8 ]; unsigned char *nonce, *begin_xor; unsigned sample_off, packno_len, key_phase; enum enc_level enc_level; enum packnum_space pns; lsquic_packno_t packno; size_t out_sz; enum dec_packin dec_packin; int s; const size_t dst_sz = packet_in->pi_data_sz; unsigned char new_secret[EVP_MAX_KEY_LENGTH]; struct crypto_ctx crypto_ctx_buf; char secret_str[EVP_MAX_KEY_LENGTH * 2 + 1]; char errbuf[ERR_ERROR_STRING_BUF_LEN]; dst = lsquic_mm_get_packet_in_buf(&enpub->enp_mm, dst_sz); if (!dst) { LSQ_WARN("cannot allocate memory to copy incoming packet data"); dec_packin = DECPI_NOMEM; goto err; } enc_level = hety2el[packet_in->pi_header_type]; if (enc_level == ENC_LEV_FORW) hp = &enc_sess->esi_hp; else if (enc_sess->esi_hsk_pairs) hp = &enc_sess->esi_hsk_hps[ enc_level ]; else hp = NULL; if (UNLIKELY(!(hp && header_prot_inited(hp, 0)))) { LSQ_DEBUG("header protection for level %u not initialized yet", enc_level); dec_packin = DECPI_NOT_YET; goto err; } /* Decrypt packet number. After this operation, packet_in is adjusted: * the packet number becomes part of the header. */ sample_off = packet_in->pi_header_sz + 4; if (sample_off + IQUIC_TAG_LEN > packet_in->pi_data_sz) { LSQ_INFO("packet data is too short: %hu bytes", packet_in->pi_data_sz); dec_packin = DECPI_TOO_SHORT; goto err; } memcpy(dst, packet_in->pi_data, sample_off); packet_in->pi_packno = packno = strip_hp(enc_sess, hp, packet_in->pi_data + sample_off, dst, packet_in->pi_header_sz, &packno_len); if (enc_level == ENC_LEV_FORW) { key_phase = (dst[0] & 0x04) > 0; pair = &enc_sess->esi_pairs[ key_phase ]; if (key_phase == enc_sess->esi_key_phase) { crypto_ctx = &pair->ykp_ctx[ 0 ]; /* Checked by header_prot_inited() above */ assert(crypto_ctx->yk_flags & YK_INITED); } else if (!is_valid_packno( enc_sess->esi_pairs[enc_sess->esi_key_phase].ykp_thresh) || packet_in->pi_packno > enc_sess->esi_pairs[enc_sess->esi_key_phase].ykp_thresh) { const struct ku_label kl = select_ku_label(enc_sess); lsquic_qhkdf_expand(enc_sess->esi_md, enc_sess->esi_traffic_secrets[0], enc_sess->esi_trasec_sz, kl.str, kl.len, new_secret, enc_sess->esi_trasec_sz); if (enc_sess->esi_flags & ESI_LOG_SECRETS) LSQ_DEBUG("key phase changed to %u, will try decrypting using " "new secret %s", key_phase, HEXSTR(new_secret, enc_sess->esi_trasec_sz, secret_str)); else LSQ_DEBUG("key phase changed to %u, will try decrypting using " "new secret", key_phase); crypto_ctx = &crypto_ctx_buf; crypto_ctx->yk_flags = 0; s = init_crypto_ctx(crypto_ctx, enc_sess->esi_md, enc_sess->esi_aead, new_secret, enc_sess->esi_trasec_sz, evp_aead_open); if (s != 0) { LSQ_ERROR("could not init open crypto ctx (key phase)"); dec_packin = DECPI_BADCRYPT; goto err; } } else { crypto_ctx = &pair->ykp_ctx[ 0 ]; if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED))) { LSQ_DEBUG("supposedly older context is not initialized (key " "phase: %u)", key_phase); dec_packin = DECPI_BADCRYPT; goto err; } } } else { key_phase = 0; assert(enc_sess->esi_hsk_pairs); pair = &enc_sess->esi_hsk_pairs[ enc_level ]; crypto_ctx = &pair->ykp_ctx[ 0 ]; if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED))) { LSQ_WARN("decrypt crypto context at level %s not initialized", lsquic_enclev2str[enc_level]); dec_packin = DECPI_BADCRYPT; goto err; } } if (s_log_seal_and_open) LSQ_DEBUG("open: iv: %s; packno: 0x%"PRIX64, HEXSTR(crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz, s_str), packno); /* Align nonce so we can perform XOR safely in one shot: */ begin_xor = nonce_buf + sizeof(nonce_buf) - 8; begin_xor = (unsigned char *) ((uintptr_t) begin_xor & ~0x7); nonce = begin_xor - crypto_ctx->yk_iv_sz + 8; memcpy(nonce, crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz); #if __BYTE_ORDER == __LITTLE_ENDIAN packno = bswap_64(packno); #endif *((uint64_t *) begin_xor) ^= packno; packet_in->pi_header_sz += packno_len; if (s_log_seal_and_open) { LSQ_DEBUG("open: nonce (%u bytes): %s", crypto_ctx->yk_iv_sz, HEXSTR(nonce, crypto_ctx->yk_iv_sz, s_str)); LSQ_DEBUG("open: ad (%u bytes): %s", packet_in->pi_header_sz, HEXSTR(dst, packet_in->pi_header_sz, s_str)); LSQ_DEBUG("open: in (%u bytes): %s", packet_in->pi_data_sz - packet_in->pi_header_sz, HEXSTR(packet_in->pi_data + packet_in->pi_header_sz, packet_in->pi_data_sz - packet_in->pi_header_sz, s_str)); } if (!EVP_AEAD_CTX_open(&crypto_ctx->yk_aead_ctx, dst + packet_in->pi_header_sz, &out_sz, dst_sz - packet_in->pi_header_sz, nonce, crypto_ctx->yk_iv_sz, packet_in->pi_data + packet_in->pi_header_sz, packet_in->pi_data_sz - packet_in->pi_header_sz, dst, packet_in->pi_header_sz)) { LSQ_INFO("cannot open packet #%"PRIu64": %s", packet_in->pi_packno, ERR_error_string(ERR_get_error(), errbuf)); dec_packin = DECPI_BADCRYPT; goto err; } if (enc_sess->esi_flags & ESI_SEND_QL_BITS) { packet_in->pi_flags |= PI_LOG_QL_BITS; if (dst[0] & 0x10) packet_in->pi_flags |= PI_SQUARE_BIT; if (dst[0] & 0x08) packet_in->pi_flags |= PI_LOSS_BIT; } else if (dst[0] & (0x0C << (packet_in->pi_header_type == HETY_NOT_SET))) { LSQ_DEBUG("reserved bits are not set to zero"); dec_packin = DECPI_VIOLATION; goto err; } if (crypto_ctx == &crypto_ctx_buf) { LSQ_DEBUG("decryption in the new key phase %u successful, rotate " "keys", key_phase); const struct ku_label kl = select_ku_label(enc_sess); pair->ykp_thresh = packet_in->pi_packno; pair->ykp_ctx[ 0 ] = crypto_ctx_buf; memcpy(enc_sess->esi_traffic_secrets[ 0 ], new_secret, enc_sess->esi_trasec_sz); lsquic_qhkdf_expand(enc_sess->esi_md, enc_sess->esi_traffic_secrets[1], enc_sess->esi_trasec_sz, kl.str, kl.len, new_secret, enc_sess->esi_trasec_sz); memcpy(enc_sess->esi_traffic_secrets[1], new_secret, enc_sess->esi_trasec_sz); s = init_crypto_ctx(&pair->ykp_ctx[1], enc_sess->esi_md, enc_sess->esi_aead, new_secret, enc_sess->esi_trasec_sz, evp_aead_seal); if (s != 0) { LSQ_ERROR("could not init seal crypto ctx (key phase)"); cleanup_crypto_ctx(&pair->ykp_ctx[1]); /* This is a severe error, abort connection */ enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn, "crypto ctx failure during key phase shift"); dec_packin = DECPI_BADCRYPT; goto err; } if (enc_sess->esi_flags & ESI_LOG_SECRETS) log_crypto_pair(enc_sess, pair, "updated"); enc_sess->esi_key_phase = key_phase; } packet_in->pi_data_sz = packet_in->pi_header_sz + out_sz; if (packet_in->pi_flags & PI_OWN_DATA) lsquic_mm_put_packet_in_buf(&enpub->enp_mm, packet_in->pi_data, packet_in->pi_data_sz); packet_in->pi_data = dst; packet_in->pi_flags |= PI_OWN_DATA | PI_DECRYPTED | (enc_level << PIBIT_ENC_LEV_SHIFT); EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "decrypted packet %"PRIu64, packet_in->pi_packno); pns = lsquic_enclev2pns[enc_level]; if (packet_in->pi_packno > enc_sess->esi_max_packno[pns]) enc_sess->esi_max_packno[pns] = packet_in->pi_packno; if (is_valid_packno(pair->ykp_thresh) && packet_in->pi_packno > pair->ykp_thresh) pair->ykp_thresh = packet_in->pi_packno; return DECPI_OK; err: if (crypto_ctx == &crypto_ctx_buf) cleanup_crypto_ctx(crypto_ctx); if (dst) lsquic_mm_put_packet_in_buf(&enpub->enp_mm, dst, dst_sz); EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "could not decrypt packet (type %s, " "number %"PRIu64")", lsquic_hety2str[packet_in->pi_header_type], packet_in->pi_packno); return dec_packin; } static int iquic_esf_global_init (int flags) { s_idx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); if (s_idx >= 0) { LSQ_LOG1(LSQ_LOG_DEBUG, "SSL extra data index: %d", s_idx); return 0; } else { LSQ_LOG1(LSQ_LOG_ERROR, "%s: could not select index", __func__); return -1; } } static void iquic_esf_global_cleanup (void) { } static void * copy_X509 (void *cert) { X509_up_ref(cert); return cert; } static struct stack_st_X509 * iquic_esf_get_server_cert_chain (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; STACK_OF(X509) *chain; if (enc_sess->esi_ssl) { chain = SSL_get_peer_cert_chain(enc_sess->esi_ssl); return (struct stack_st_X509 *) sk_deep_copy((const _STACK *) chain, sk_X509_call_copy_func, copy_X509, sk_X509_call_free_func, (void(*)(void*))X509_free); } else return NULL; } static const char * iquic_esf_cipher (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; const SSL_CIPHER *cipher; if (enc_sess->esi_flags & ESI_CACHED_INFO) return enc_sess->esi_cached_info.cipher_name; else if (enc_sess->esi_ssl) { cipher = SSL_get_current_cipher(enc_sess->esi_ssl); return SSL_CIPHER_get_name(cipher); } else { LSQ_WARN("SSL session is not set"); return "null"; } } static int iquic_esf_keysize (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; const SSL_CIPHER *cipher; uint32_t id; if (enc_sess->esi_flags & ESI_CACHED_INFO) return enc_sess->esi_cached_info.alg_bits / 8; else if (enc_sess->esi_ssl) { cipher = SSL_get_current_cipher(enc_sess->esi_ssl); id = SSL_CIPHER_get_id(cipher); /* RFC 8446, Appendix B.4 */ switch (id) { case 0x03000000 | 0x1301: /* TLS_AES_128_GCM_SHA256 */ return 128 / 8; case 0x03000000 | 0x1302: /* TLS_AES_256_GCM_SHA384 */ return 256 / 8; case 0x03000000 | 0x1303: /* TLS_CHACHA20_POLY1305_SHA256 */ return 256 / 8; default: return -1; } } else { LSQ_WARN("SSL session is not set"); return -1; } } static int iquic_esf_alg_keysize (enc_session_t *enc_session_p) { /* Modeled on SslConnection::getEnv() */ return iquic_esf_keysize(enc_session_p); } static int iquic_esf_zero_rtt_enabled (enc_session_t *enc_session_p) { struct enc_sess_iquic *const enc_sess = enc_session_p; return enc_sess->esi_zero_rtt_buf != NULL; } static void iquic_esfi_set_iscid (enc_session_t *enc_session_p, const struct lsquic_packet_in *packet_in) { struct enc_sess_iquic *const enc_sess = enc_session_p; if (!(enc_sess->esi_flags & ESI_ISCID)) { lsquic_scid_from_packet_in(packet_in, &enc_sess->esi_iscid); enc_sess->esi_flags |= ESI_ISCID; LSQ_DEBUGC("set ISCID to %"CID_FMT, CID_BITS(&enc_sess->esi_iscid)); } } static int iquic_esfi_reset_dcid (enc_session_t *enc_session_p, const lsquic_cid_t *old_dcid, const lsquic_cid_t *new_dcid) { struct enc_sess_iquic *const enc_sess = enc_session_p; struct crypto_ctx_pair *pair; enc_sess->esi_odcid = *old_dcid; enc_sess->esi_rscid = *new_dcid; enc_sess->esi_flags |= ESI_ODCID|ESI_RSCID|ESI_RETRY; /* Free previous handshake keys */ assert(enc_sess->esi_hsk_pairs); pair = &enc_sess->esi_hsk_pairs[ENC_LEV_CLEAR]; cleanup_crypto_ctx(&pair->ykp_ctx[0]); cleanup_crypto_ctx(&pair->ykp_ctx[1]); if (0 == setup_handshake_keys(enc_sess, new_dcid)) { LSQ_INFOC("reset DCID to %"CID_FMT, CID_BITS(new_dcid)); return 0; } else return -1; } static void iquic_esfi_handshake_confirmed (enc_session_t *sess) { struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *) sess; if (!(enc_sess->esi_flags & ESI_HSK_CONFIRMED)) { LSQ_DEBUG("handshake has been confirmed"); enc_sess->esi_flags |= ESI_HSK_CONFIRMED; maybe_drop_SSL(enc_sess); } } static int iquic_esfi_in_init (enc_session_t *sess) { struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *) sess; int in_init; if (enc_sess->esi_ssl) { in_init = SSL_in_init(enc_sess->esi_ssl); LSQ_DEBUG("in_init: %d", in_init); return in_init; } else { LSQ_DEBUG("no SSL object, in_init: 0"); return 0; } } static int iquic_esfi_data_in (enc_session_t *sess, enum enc_level enc_level, const unsigned char *buf, size_t len) { struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *) sess; int s; size_t str_sz; char str[MAX(1500 * 5, ERR_ERROR_STRING_BUF_LEN)]; if (!enc_sess->esi_ssl) return -1; s = SSL_provide_quic_data(enc_sess->esi_ssl, (enum ssl_encryption_level_t) enc_level, buf, len); if (!s) { LSQ_WARN("SSL_provide_quic_data returned false: %s", ERR_error_string(ERR_get_error(), str)); return -1; } LSQ_DEBUG("provided %zu bytes of %u-level data to SSL", len, enc_level); str_sz = lsquic_hexdump(buf, len, str, sizeof(str)); LSQ_DEBUG("\n%.*s", (int) str_sz, str); s = SSL_do_handshake(enc_sess->esi_ssl); LSQ_DEBUG("do_handshake returns %d", s); return 0; } static void iquic_esfi_shake_stream (enc_session_t *sess, struct lsquic_stream *stream, const char *what); const struct enc_session_funcs_iquic lsquic_enc_session_iquic_ietf_v1 = { .esfi_create_client = iquic_esfi_create_client, .esfi_destroy = iquic_esfi_destroy, .esfi_get_peer_transport_params = iquic_esfi_get_peer_transport_params, .esfi_reset_dcid = iquic_esfi_reset_dcid, .esfi_init_server = iquic_esfi_init_server, .esfi_set_iscid = iquic_esfi_set_iscid, .esfi_set_streams = iquic_esfi_set_streams, .esfi_create_server = iquic_esfi_create_server, .esfi_shake_stream = iquic_esfi_shake_stream, .esfi_handshake_confirmed = iquic_esfi_handshake_confirmed, .esfi_in_init = iquic_esfi_in_init, .esfi_data_in = iquic_esfi_data_in, }; const struct enc_session_funcs_common lsquic_enc_session_common_ietf_v1 = { .esf_encrypt_packet = iquic_esf_encrypt_packet, .esf_decrypt_packet = iquic_esf_decrypt_packet, .esf_flush_encryption= iquic_esf_flush_encryption, .esf_global_cleanup = iquic_esf_global_cleanup, .esf_global_init = iquic_esf_global_init, .esf_tag_len = IQUIC_TAG_LEN, .esf_get_server_cert_chain = iquic_esf_get_server_cert_chain, .esf_cipher = iquic_esf_cipher, .esf_keysize = iquic_esf_keysize, .esf_alg_keysize = iquic_esf_alg_keysize, .esf_is_zero_rtt_enabled = iquic_esf_zero_rtt_enabled, .esf_set_conn = iquic_esf_set_conn, }; static const struct enc_session_funcs_common lsquic_enc_session_common_ietf_v1_no_flush = { .esf_encrypt_packet = iquic_esf_encrypt_packet, .esf_decrypt_packet = iquic_esf_decrypt_packet, .esf_global_cleanup = iquic_esf_global_cleanup, .esf_global_init = iquic_esf_global_init, .esf_tag_len = IQUIC_TAG_LEN, .esf_get_server_cert_chain = iquic_esf_get_server_cert_chain, .esf_cipher = iquic_esf_cipher, .esf_keysize = iquic_esf_keysize, .esf_alg_keysize = iquic_esf_alg_keysize, .esf_is_zero_rtt_enabled = iquic_esf_zero_rtt_enabled, .esf_set_conn = iquic_esf_set_conn, }; static void cache_info (struct enc_sess_iquic *enc_sess) { const SSL_CIPHER *cipher; cipher = SSL_get_current_cipher(enc_sess->esi_ssl); enc_sess->esi_cached_info.cipher_name = SSL_CIPHER_get_name(cipher); SSL_CIPHER_get_bits(cipher, &enc_sess->esi_cached_info.alg_bits); enc_sess->esi_flags |= ESI_CACHED_INFO; } static void drop_SSL (struct enc_sess_iquic *enc_sess) { LSQ_DEBUG("drop SSL object"); if (enc_sess->esi_conn->cn_if->ci_drop_crypto_streams) enc_sess->esi_conn->cn_if->ci_drop_crypto_streams( enc_sess->esi_conn); cache_info(enc_sess); SSL_free(enc_sess->esi_ssl); enc_sess->esi_ssl = NULL; free_handshake_keys(enc_sess); } static void maybe_drop_SSL (struct enc_sess_iquic *enc_sess) { /* We rely on the following BoringSSL property: it writes new session * tickets before marking handshake as complete. In this case, the new * session tickets have either been successfully written to crypto stream, * in which case we can close it, or (unlikely) they are buffered in the * frab list. */ if ((enc_sess->esi_flags & (ESI_HSK_CONFIRMED|ESI_HANDSHAKE_OK)) == (ESI_HSK_CONFIRMED|ESI_HANDSHAKE_OK) && enc_sess->esi_ssl && lsquic_frab_list_empty(&enc_sess->esi_frals[ENC_LEV_FORW])) { if ((enc_sess->esi_flags & (ESI_SERVER|ESI_WANT_TICKET)) != ESI_WANT_TICKET) drop_SSL(enc_sess); else if (enc_sess->esi_alset && !lsquic_alarmset_is_set(enc_sess->esi_alset, AL_SESS_TICKET)) { LSQ_DEBUG("no session ticket: delay dropping SSL object"); lsquic_alarmset_set(enc_sess->esi_alset, AL_SESS_TICKET, /* Wait up to two seconds for session tickets */ lsquic_time_now() + 2000000); } } } static void no_sess_ticket (enum alarm_id alarm_id, void *ctx, lsquic_time_t expiry, lsquic_time_t now) { struct enc_sess_iquic *enc_sess = ctx; LSQ_DEBUG("no session tickets forthcoming -- drop SSL"); drop_SSL(enc_sess); } typedef char enums_have_the_same_value[ (int) ssl_encryption_initial == (int) ENC_LEV_CLEAR && (int) ssl_encryption_early_data == (int) ENC_LEV_EARLY && (int) ssl_encryption_handshake == (int) ENC_LEV_INIT && (int) ssl_encryption_application == (int) ENC_LEV_FORW ? 1 : -1]; static int set_secret (SSL *ssl, enum ssl_encryption_level_t level, const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len, int rw) { struct enc_sess_iquic *enc_sess; struct crypto_ctx_pair *pair; struct header_prot *hp; struct crypto_params crypa; int have_alpn; const unsigned char *alpn; unsigned alpn_len; size_t key_len; const enum enc_level enc_level = (enum enc_level) level; unsigned char key[EVP_MAX_KEY_LENGTH]; char errbuf[ERR_ERROR_STRING_BUF_LEN]; #define hexbuf errbuf enc_sess = SSL_get_ex_data(ssl, s_idx); if (!enc_sess) return 0; if ((enc_sess->esi_flags & (ESI_ALPN_CHECKED|ESI_SERVER)) == ESI_SERVER && enc_sess->esi_alpn) { enc_sess->esi_flags |= ESI_ALPN_CHECKED; SSL_get0_alpn_selected(enc_sess->esi_ssl, &alpn, &alpn_len); have_alpn = alpn && alpn_len == enc_sess->esi_alpn[0] && 0 == memcmp(alpn, enc_sess->esi_alpn + 1, alpn_len); if (have_alpn) LSQ_DEBUG("Selected ALPN %.*s", (int) alpn_len, (char *) alpn); else { LSQ_INFO("No ALPN is selected: send fatal alert"); SSL_send_fatal_alert(ssl, ALERT_NO_APPLICATION_PROTOCOL); return 0; } } if (0 != get_crypto_params(enc_sess, cipher, &crypa)) return 0; /* if (enc_sess->esi_flags & ESI_SERVER) secrets[0] = read_secret, secrets[1] = write_secret; else secrets[0] = write_secret, secrets[1] = read_secret; */ if (enc_level < ENC_LEV_FORW) { assert(enc_sess->esi_hsk_pairs); pair = &enc_sess->esi_hsk_pairs[enc_level]; hp = &enc_sess->esi_hsk_hps[enc_level]; } else { pair = &enc_sess->esi_pairs[0]; hp = &enc_sess->esi_hp; enc_sess->esi_trasec_sz = secret_len; memcpy(enc_sess->esi_traffic_secrets[rw], secret, secret_len); enc_sess->esi_md = crypa.md; enc_sess->esi_aead = crypa.aead; if (!(hp->hp_flags & (HP_CAN_READ|HP_CAN_WRITE)) && crypa.aead == EVP_aead_chacha20_poly1305()) { LSQ_DEBUG("turn off header protection batching (chacha not " "supported)"); enc_sess->esi_conn->cn_esf_c = &lsquic_enc_session_common_ietf_v1_no_flush; } } pair->ykp_thresh = IQUIC_INVALID_PACKNO; if (enc_sess->esi_flags & ESI_LOG_SECRETS) LSQ_DEBUG("set %s secret for level %u: %s", rw2str[rw], enc_level, HEXSTR(secret, secret_len, hexbuf)); else LSQ_DEBUG("set %s for level %u", rw2str[rw], enc_level); if (0 != init_crypto_ctx(&pair->ykp_ctx[rw], crypa.md, crypa.aead, secret, secret_len, rw2dir(rw))) goto err; if (pair->ykp_ctx[!rw].yk_flags & YK_INITED) { /* Sanity check that the two sides end up with the same header * protection logic, as they should. */ assert(hp->hp_gen_mask == crypa.gen_hp_mask); } else { hp->hp_enc_level = enc_level; hp->hp_gen_mask = crypa.gen_hp_mask; } key_len = EVP_AEAD_key_length(crypa.aead); if (hp->hp_gen_mask == gen_hp_mask_aes) { lsquic_qhkdf_expand(crypa.md, secret, secret_len, PN_LABEL, PN_LABEL_SZ, key, key_len); EVP_CIPHER_CTX_init(&hp->hp_u.cipher_ctx[rw]); if (!EVP_EncryptInit_ex(&hp->hp_u.cipher_ctx[rw], crypa.hp, NULL, key, 0)) { LSQ_ERROR("cannot initialize cipher on level %u", enc_level); goto err; } } else lsquic_qhkdf_expand(crypa.md, secret, secret_len, PN_LABEL, PN_LABEL_SZ, hp->hp_u.buf[rw], key_len); hp->hp_flags |= 1 << rw; if (enc_sess->esi_flags & ESI_LOG_SECRETS) { log_crypto_ctx(enc_sess, &pair->ykp_ctx[rw], "new", rw); LSQ_DEBUG("%s hp: %s", rw2str[rw], HEXSTR(hp->hp_gen_mask == gen_hp_mask_aes ? key : hp->hp_u.buf[rw], key_len, hexbuf)); } return 1; err: cleanup_crypto_ctx(&pair->ykp_ctx[0]); cleanup_crypto_ctx(&pair->ykp_ctx[1]); return 0; #undef hexbuf } static int cry_sm_set_read_secret (SSL *ssl, enum ssl_encryption_level_t level, const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len) { return set_secret(ssl, level, cipher, secret, secret_len, 0); } static int cry_sm_set_write_secret (SSL *ssl, enum ssl_encryption_level_t level, const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len) { return set_secret(ssl, level, cipher, secret, secret_len, 1); } static int cry_sm_write_message (SSL *ssl, enum ssl_encryption_level_t level, const uint8_t *data, size_t len) { struct enc_sess_iquic *enc_sess; void *stream; ssize_t nw; enc_sess = SSL_get_ex_data(ssl, s_idx); if (!enc_sess) return 0; stream = enc_sess->esi_streams[level]; if (!stream) return 0; /* The frab list logic is only applicable on the client. XXX This is * likely to change when support for key updates is added. */ if (enc_sess->esi_flags & (ESI_ON_WRITE|ESI_SERVER)) nw = enc_sess->esi_cryst_if->csi_write(stream, data, len); else { LSQ_DEBUG("not in on_write event: buffer in a frab list"); if (0 == lsquic_frab_list_write(&enc_sess->esi_frals[level], data, len)) { if (!lsquic_frab_list_empty(&enc_sess->esi_frals[level])) enc_sess->esi_cryst_if->csi_wantwrite(stream, 1); nw = len; } else nw = -1; } if (nw >= 0 && (size_t) nw == len) { enc_sess->esi_last_w = (enum enc_level) level; LSQ_DEBUG("wrote %zu bytes to stream at encryption level %u", len, level); maybe_drop_SSL(enc_sess); return 1; } else { LSQ_INFO("could not write %zu bytes: returned %zd", len, nw); return 0; } } static int cry_sm_flush_flight (SSL *ssl) { struct enc_sess_iquic *enc_sess; void *stream; unsigned level; int s; enc_sess = SSL_get_ex_data(ssl, s_idx); if (!enc_sess) return 0; level = enc_sess->esi_last_w; stream = enc_sess->esi_streams[level]; if (!stream) return 0; if (lsquic_frab_list_empty(&enc_sess->esi_frals[level])) { s = enc_sess->esi_cryst_if->csi_flush(stream); return s == 0; } else /* Frab list will get flushed */ /* TODO: add support for recording flush points in frab list. */ return 1; } static int cry_sm_send_alert (SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert) { struct enc_sess_iquic *enc_sess; enc_sess = SSL_get_ex_data(ssl, s_idx); if (!enc_sess) return 0; LSQ_INFO("got alert %"PRIu8, alert); enc_sess->esi_conn->cn_if->ci_tls_alert(enc_sess->esi_conn, alert); return 1; } static const SSL_QUIC_METHOD cry_quic_method = { .set_read_secret = cry_sm_set_read_secret, .set_write_secret = cry_sm_set_write_secret, .add_handshake_data = cry_sm_write_message, .flush_flight = cry_sm_flush_flight, .send_alert = cry_sm_send_alert, }; static lsquic_stream_ctx_t * chsk_ietf_on_new_stream (void *stream_if_ctx, struct lsquic_stream *stream) { struct enc_sess_iquic *const enc_sess = stream_if_ctx; enum enc_level enc_level; enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream); if (enc_level != ENC_LEV_CLEAR) { LSQ_DEBUG("skip initialization of stream at level %u", enc_level); goto end; } if ( (enc_sess->esi_flags & ESI_SERVER) == 0 && 0 != init_client(enc_sess)) { LSQ_WARN("enc session could not be initialized"); return NULL; } enc_sess->esi_cryst_if->csi_wantwrite(stream, 1); LSQ_DEBUG("handshake stream created successfully"); end: return stream_if_ctx; } static lsquic_stream_ctx_t * shsk_ietf_on_new_stream (void *stream_if_ctx, struct lsquic_stream *stream) { struct enc_sess_iquic *const enc_sess = stream_if_ctx; enum enc_level enc_level; enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream); LSQ_DEBUG("on_new_stream called on level %u", enc_level); enc_sess->esi_cryst_if->csi_wantread(stream, 1); return stream_if_ctx; } static void chsk_ietf_on_close (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx) { struct enc_sess_iquic *const enc_sess = (struct enc_sess_iquic *) ctx; if (enc_sess && enc_sess->esi_cryst_if) LSQ_DEBUG("crypto stream level %u is closed", (unsigned) enc_sess->esi_cryst_if->csi_enc_level(stream)); } static const char *const ihs2str[] = { [IHS_WANT_READ] = "want read", [IHS_WANT_WRITE] = "want write", [IHS_STOP] = "stop", }; static void iquic_esfi_shake_stream (enc_session_t *sess, struct lsquic_stream *stream, const char *what) { struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *)sess; enum iquic_handshake_status st; enum enc_level enc_level; int write; if (0 == (enc_sess->esi_flags & ESI_HANDSHAKE_OK)) st = iquic_esfi_handshake(enc_sess); else st = iquic_esfi_post_handshake(enc_sess); enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream); LSQ_DEBUG("enc level %s after %s: %s", lsquic_enclev2str[enc_level], what, ihs2str[st]); switch (st) { case IHS_WANT_READ: write = !lsquic_frab_list_empty(&enc_sess->esi_frals[enc_level]); enc_sess->esi_cryst_if->csi_wantwrite(stream, write); enc_sess->esi_cryst_if->csi_wantread(stream, 1); break; case IHS_WANT_WRITE: enc_sess->esi_cryst_if->csi_wantwrite(stream, 1); enc_sess->esi_cryst_if->csi_wantread(stream, 0); break; default: assert(st == IHS_STOP); write = !lsquic_frab_list_empty(&enc_sess->esi_frals[enc_level]); enc_sess->esi_cryst_if->csi_wantwrite(stream, write); enc_sess->esi_cryst_if->csi_wantread(stream, 0); break; } LSQ_DEBUG("Exit shake_stream"); maybe_drop_SSL(enc_sess); } struct readf_ctx { struct enc_sess_iquic *enc_sess; enum enc_level enc_level; int err; }; static size_t readf_cb (void *ctx, const unsigned char *buf, size_t len, int fin) { struct readf_ctx *const readf_ctx = (void *) ctx; struct enc_sess_iquic *const enc_sess = readf_ctx->enc_sess; int s; size_t str_sz; char str[MAX(1500 * 5, ERR_ERROR_STRING_BUF_LEN)]; s = SSL_provide_quic_data(enc_sess->esi_ssl, (enum ssl_encryption_level_t) readf_ctx->enc_level, buf, len); if (s) { LSQ_DEBUG("provided %zu bytes of %u-level data to SSL", len, readf_ctx->enc_level); str_sz = lsquic_hexdump(buf, len, str, sizeof(str)); LSQ_DEBUG("\n%.*s", (int) str_sz, str); return len; } else { LSQ_WARN("SSL_provide_quic_data returned false: %s", ERR_error_string(ERR_get_error(), str)); readf_ctx->err++; return 0; } } static size_t discard_cb (void *ctx, const unsigned char *buf, size_t len, int fin) { return len; } static void chsk_ietf_on_read (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx) { struct enc_sess_iquic *const enc_sess = (void *) ctx; enum enc_level enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream); struct readf_ctx readf_ctx = { enc_sess, enc_level, 0, }; ssize_t nread; if (enc_sess->esi_ssl) { nread = enc_sess->esi_cryst_if->csi_readf(stream, readf_cb, &readf_ctx); if (!(nread < 0 || readf_ctx.err)) iquic_esfi_shake_stream((enc_session_t *)enc_sess, stream, "on_read"); else enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn, "shaking stream failed: nread: %zd, err: %d, SSL err: %"PRIu32, nread, readf_ctx.err, ERR_get_error()); } else { /* This branch is reached when we don't want TLS ticket and drop * the SSL object before we process TLS tickets that have been * already received and waiting in the incoming stream buffer. */ nread = enc_sess->esi_cryst_if->csi_readf(stream, discard_cb, NULL); lsquic_stream_wantread(stream, 0); LSQ_DEBUG("no SSL object: discard %zd bytes of SSL data", nread); } } static void maybe_write_from_fral (struct enc_sess_iquic *enc_sess, struct lsquic_stream *stream) { enum enc_level enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream); struct frab_list *const fral = &enc_sess->esi_frals[enc_level]; struct lsquic_reader reader = { .lsqr_read = lsquic_frab_list_read, .lsqr_size = lsquic_frab_list_size, .lsqr_ctx = fral, }; ssize_t nw; if (lsquic_frab_list_empty(fral)) return; nw = lsquic_stream_writef(stream, &reader); if (nw >= 0) { LSQ_DEBUG("wrote %zd bytes to stream from frab list", nw); (void) lsquic_stream_flush(stream); if (lsquic_frab_list_empty(fral)) lsquic_stream_wantwrite(stream, 0); } else { enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn, "cannot write to stream: %s", strerror(errno)); lsquic_stream_wantwrite(stream, 0); } } static void chsk_ietf_on_write (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx) { struct enc_sess_iquic *const enc_sess = (void *) ctx; maybe_write_from_fral(enc_sess, stream); enc_sess->esi_flags |= ESI_ON_WRITE; iquic_esfi_shake_stream(enc_sess, stream, "on_write"); enc_sess->esi_flags &= ~ESI_ON_WRITE; } const struct lsquic_stream_if lsquic_cry_sm_if = { .on_new_stream = chsk_ietf_on_new_stream, .on_read = chsk_ietf_on_read, .on_write = chsk_ietf_on_write, .on_close = chsk_ietf_on_close, }; const struct lsquic_stream_if lsquic_mini_cry_sm_if = { .on_new_stream = shsk_ietf_on_new_stream, .on_read = chsk_ietf_on_read, .on_write = chsk_ietf_on_write, .on_close = chsk_ietf_on_close, }; const unsigned char *const lsquic_retry_key_buf[N_IETF_RETRY_VERSIONS] = { /* [draft-ietf-quic-tls-25] Section 5.8 */ (unsigned char *) "\x4d\x32\xec\xdb\x2a\x21\x33\xc8\x41\xe4\x04\x3d\xf2\x7d\x44\x30", /* [draft-ietf-quic-tls-29] Section 5.8 */ (unsigned char *) "\xcc\xce\x18\x7e\xd0\x9a\x09\xd0\x57\x28\x15\x5a\x6c\xb9\x6b\xe1", }; const unsigned char *const lsquic_retry_nonce_buf[N_IETF_RETRY_VERSIONS] = { /* [draft-ietf-quic-tls-25] Section 5.8 */ (unsigned char *) "\x4d\x16\x11\xd0\x55\x13\xa5\x52\xc5\x87\xd5\x75", /* [draft-ietf-quic-tls-29] Section 5.8 */ (unsigned char *) "\xe5\x49\x30\xf9\x7f\x21\x36\xf0\x53\x0a\x8c\x1c", };
minhkstn/lsquic
bin/http_client.c
<reponame>minhkstn/lsquic /* Copyright (c) 2017 - 2020 LiteSpeed Technologies Inc. See LICENSE. */ /* * http_client.c -- A simple HTTP/QUIC client */ #ifndef WIN32 #include <arpa/inet.h> #include <netinet/in.h> #else #include <Windows.h> #include <WinSock2.h> #include <io.h> #include <stdlib.h> #include <getopt.h> #define STDOUT_FILENO 1 #define random rand #pragma warning(disable:4996) //POSIX name deprecated #endif #include <assert.h> #include <errno.h> #include <inttypes.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/queue.h> #ifndef WIN32 #include <unistd.h> #include <sys/types.h> #include <dirent.h> #include <limits.h> #endif #include <sys/stat.h> #include <fcntl.h> #include <event2/event.h> #include <math.h> #include <stdbool.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/x509.h> #include "lsquic.h" #include "test_common.h" #include "prog.h" #include "../src/liblsquic/lsquic_logger.h" #include "../src/liblsquic/lsquic_int_types.h" #include "../src/liblsquic/lsquic_util.h" /* include directly for reset_stream testing */ #include "../src/liblsquic/lsquic_varint.h" #include "../src/liblsquic/lsquic_hq.h" #include "../src/liblsquic/lsquic_sfcw.h" #include "../src/liblsquic/lsquic_hash.h" #include "../src/liblsquic/lsquic_stream.h" /* include directly for retire_cid testing */ #include "../src/liblsquic/lsquic_conn.h" #include "lsxpack_header.h" #include <time.h> #define MIN(a, b) ((a) <= (b) ? (a) : (b)) #define MAX(a, b) ((a) >= (b) ? (a) : (b)) /* This is used to exercise generating and sending of priority frames */ static int randomly_reprioritize_streams; static int s_display_cert_chain; /* If this file descriptor is open, the client will accept server push and * dump the contents here. See -u flag. */ static int promise_fd = -1; /* Set to true value to use header bypass. This means that the use code * creates header set via callbacks and then fetches it by calling * lsquic_stream_get_hset() when the first "on_read" event is called. */ static int g_header_bypass; static int s_discard_response; // Minh ADD-S #define NUM_SEGMENTS 12 #define MAX_SEGMENT_ID 500 #define MAX_LAYER_ID 4 // 1 BL + 3 ELs #define TRUE true #define FALSE false const int MINH_BITRATE_SET[NUM_SEGMENTS][MAX_LAYER_ID] = { {3359, 4866, 7219, 7578}, {4203, 6239, 8736, 9298}, {4686, 7015, 8882, 9346}, {5130, 7610, 9515, 9367}, {5489, 8138, 10025, 9402}, {5539, 8144, 9749, 8883}, {6555, 9671, 11094, 9259}, {6102, 8744, 9644, 7926}, {3803, 5362, 7978, 7256}, {3137, 4506, 8590, 10603}, {2024, 2846, 6278, 9392}, {2013, 2885, 5742, 8159} }; //Kbps const int MINH_SUM_BITRATE_SET[NUM_SEGMENTS][MAX_LAYER_ID] = { {3359, 8225, 15444, 23022}, {4203, 10442, 19177, 28475}, {4686, 11702, 20584, 29929}, {5130, 12740, 22255, 31622}, {5489, 13627, 23652, 33054}, {5539, 13682, 23432, 32315}, {6555, 16226, 27320, 36579}, {6102, 14846, 24490, 32417}, {3803, 9165, 17143, 24399}, {3137, 7643, 16233, 26836}, {2024, 4871, 11148, 20541}, {2013, 4898, 10641, 18800} }; //Kbps char* MINH_PATH_SET[NUM_SEGMENTS][MAX_LAYER_ID] = { {"/file-420K", "/file-608K", "/file-902K", "/file-947K"}, //1 {"/file-525K", "/file-780K", "/file-1092K", "/file-1162K"}, //2 {"/file-586K", "/file-877K", "/file-1110K", "/file-1168K"}, //3 {"/file-641K", "/file-951K", "/file-1189K", "/file-1171K"}, //4 {"/file-686K", "/file-1017K", "/file-1253K", "/file-1175K"}, //5 {"/file-692K", "/file-1018K", "/file-1219K", "/file-1110K"}, //6 {"/file-819K", "/file-1209K", "/file-1387K", "/file-1157K"}, //7 {"/file-763K", "/file-1093K", "/file-1206K", "/file-991K"}, //8 {"/file-475K", "/file-670K", "/file-997K", "/file-907K"}, //9 {"/file-392K", "/file-563K", "/file-1074K", "/file-1325K"}, //10 {"/file-253K", "/file-356K", "/file-785K", "/file-1174K"}, //11 {"/file-252K", "/file-361K", "/file-718K", "/file-1020K"} //12 }; // MINH_BITRATE_SET/8 #define MINH_BUFFER_SIZE 20000 //15000 //20000 //10000 //5000 #define MINH_REBUF_THRESHOLD_EXIT 15000 //10000 //15000 //6000 // 3000 #define MINH_SD 1000 const int hung_max_seg_id_consideration = 200; const int RETRANS_BUFF_TRIGGER_ON = MINH_BUFFER_SIZE/2; const int RETRANS_BUFF_THRES = MINH_BUFFER_SIZE/4; const int THETA = MINH_BUFFER_SIZE/4; // estimated buffer > THETA int retrans_seg_id_recorder [MAX_SEGMENT_ID]; unsigned terminate_stream_id_recorder [MAX_SEGMENT_ID]; lsquic_time_t streaming_start_time; static int minh_client_seg = 0; static int minh_retrans_seg = -1; static double minh_cur_buf = 0; // in milisecon static double minh_throughput = 0; // in Kbps static double estimated_throughput = 0; static bool minh_rebuf = TRUE; static bool retrans_check = FALSE; static bool set_prior_check = FALSE; static bool minh_retrans_trigger = FALSE; // static bool minh_retrans_extension = TRUE; static bool retransmitting = FALSE; static bool termination_check = FALSE; static bool stall_while_downloading = FALSE; static bool retrans_enable = FALSE; static char* next_path = "/file-5000K"; static char* retrans_path; static unsigned terminate_seg_id = 0; static int terminate_num = 0; static int priority_next = 2; static int priority_retrans = 8; static int retrans_num = 0; static int retrans_seg_id = 0; static int cur_layer_id = 1; static unsigned long downloaded_bytes_2on_close = 0; static unsigned long retrans_stream_id = 0; static unsigned long next_stream_id = 0; static long double last_stall_start_time = 0; static long double stall_duration_before_update = 0; static long double last_update_time = 0; static double start_play_time = 0; static int sum_stall_num = 0; static double sum_stall_duration = 0; static double sum_avg_quality = 0; static int sum_switch_num = 0; static double sum_avg_switch = 0; enum ABR {AGG, CURSOR, BACKFILLING}; static enum ABR minh_ABR; // MINH SVC_Cursor_ABR Parameters -S static int cursor_quality_cursor = 1; static int cursor_segment_cursor = 0; static double cursor_improvement_timer = 0; // MINH SVC_Cursor_ABR Parameters -E struct Seg_layers // a stream = 1 layer { int bitrate; unsigned long stream_id; double throughput; double buffer; long double start_download_time; long double end_download_time; long double download_time; }; struct Segments { int num_layers; struct Seg_layers layer[MAX_LAYER_ID]; }; struct lsquic_stream_ctx { lsquic_stream_t *stream; struct http_client_ctx *client_ctx; const char *path; enum { HEADERS_SENT = (1 << 0), PROCESSED_HEADERS = 1 << 1, } sh_flags; lsquic_time_t sh_created; lsquic_time_t sh_ttfb; unsigned count; struct lsquic_reader reader; }; struct Segments segment[MAX_SEGMENT_ID]; // static void // delay( int milli_seconds) // { // // long pause; // // clock_t now,then; // // pause = milli_seconds*(CLOCKS_PER_SEC/1000); // // now = then = clock(); // // while( (now-then) < pause ) // // now = clock(); // long double target_time = lsquic_time_now()+ milli_seconds*1000; // while (lsquic_time_now() < target_time) // ; // } static void minh_get_est_throughput(){ estimated_throughput = minh_throughput; } static void minh_AGG_ABR(){ printf("\tINVOKED %s\n", __func__); printf("\t\tLast seg: %d \tLast_layer_id = %d\n", minh_client_seg, cur_layer_id); if (minh_rebuf && minh_cur_buf >= MINH_REBUF_THRESHOLD_EXIT) // stop rebuffering { printf("stop rebuffering\n"); if (minh_client_seg > MINH_REBUF_THRESHOLD_EXIT/MINH_SD && minh_client_seg < hung_max_seg_id_consideration) { sum_stall_duration += (long double)(lsquic_time_now() - streaming_start_time) / 1000 - last_stall_start_time; //ms printf("\t\tstall duration so far: %.3f\n", sum_stall_duration); stall_duration_before_update = 0; } else if (minh_client_seg < hung_max_seg_id_consideration) { start_play_time = (long double)(lsquic_time_now() - streaming_start_time) / 1000; printf("Start play video\n"); } minh_rebuf = false; } if (minh_cur_buf < MINH_SD || minh_rebuf) // still or start rebuffering ==> go to the next segment and choose BL { if (!minh_rebuf) // start rebuff { if (minh_client_seg < hung_max_seg_id_consideration) sum_stall_num++; minh_rebuf = true; //minh_cur_buf = 0; last_stall_start_time = (long double)(lsquic_time_now() - streaming_start_time) / 1000 - stall_duration_before_update; printf("\t\tRebuffer_Start at %.3Lf\n", last_stall_start_time); } cur_layer_id = 1; minh_client_seg ++; segment[minh_client_seg].num_layers = 1; } else // normal { if (cur_layer_id == segment[minh_client_seg].num_layers) // go to next request. { minh_client_seg ++; cur_layer_id = 1; int tmp_num_layers = 1; int i; for (i = MAX_LAYER_ID; i >=1; i--){ if ( MINH_SUM_BITRATE_SET[minh_client_seg % 12][i-1] < 0.9 *estimated_throughput){ tmp_num_layers = i; printf("\t\tSeg: %d \tbitrate: %d \test_thrp: %.1f\n", minh_client_seg, MINH_SUM_BITRATE_SET[minh_client_seg % 12][i-1], 0.9 *estimated_throughput); break; } } segment[minh_client_seg].num_layers = tmp_num_layers; // if (minh_cur_buf > MINH_BUFFER_SIZE && minh_client_seg < hung_max_seg_id_consideration){ // printf("\t\t======== SLEEP: cur_buf: %.1f an sleep in %.1f ms\n", minh_cur_buf, (minh_cur_buf - MINH_BUFFER_SIZE)); // // usleep((minh_cur_buf - MINH_BUFFER_SIZE + 1000)*1000); // delay (minh_cur_buf - MINH_BUFFER_SIZE); // // minh_cur_buf = MINH_BUFFER_SIZE-1000; //co can phai tinh lai minh_curbuf? // } } else{ cur_layer_id ++; } printf("\t\tNext seg: %d. num_layers: %d. Layer id: %d\n", minh_client_seg, segment[minh_client_seg].num_layers, cur_layer_id); } segment[minh_client_seg].layer[cur_layer_id-1].bitrate = MINH_BITRATE_SET[minh_client_seg % 12][cur_layer_id-1]; // segment[minh_client_seg].layer[cur_layer_id-1].start_download_time = lsquic_time_now(); next_path = MINH_PATH_SET[minh_client_seg % 12][cur_layer_id-1]; } static void minh_SVC_cursor_ABR(){ // minh_client_seg <==> cursor_segment_cursor printf("\tINVOKED %s\n", __func__); printf("\t\tLast seg: %d \tLast_layer_id = %d\n", minh_client_seg, cur_layer_id); if (minh_rebuf && minh_cur_buf >= MINH_REBUF_THRESHOLD_EXIT) // stop rebuffering { if (minh_client_seg > MINH_REBUF_THRESHOLD_EXIT/MINH_SD && minh_client_seg < hung_max_seg_id_consideration) { sum_stall_duration += (long double)(lsquic_time_now() - streaming_start_time) / 1000 - last_stall_start_time; //ms printf("\t\tstall duration so far: %.3f\n", sum_stall_duration); stall_duration_before_update = 0; } minh_rebuf = false; } if (minh_cur_buf < MINH_SD || minh_rebuf) // still or start rebuffering ==> go to the next segment and choose BL { if (!minh_rebuf) // start rebuff { if (minh_client_seg < hung_max_seg_id_consideration) sum_stall_num++; minh_rebuf = true; // minh_cur_buf = 0; last_stall_start_time = (long double)(lsquic_time_now() - streaming_start_time) / 1000 - stall_duration_before_update; printf("\t\tRebuffer_Start at %.3Lf\n", last_stall_start_time); } cur_layer_id = 1; minh_client_seg ++; segment[minh_client_seg].num_layers = 1; } else // normal { int first_buffered_segmet = cursor_segment_cursor - (int)minh_cur_buf/MINH_SD + 1; static int last_buffered_segment = 0; double t_avai_next_layer = (cursor_segment_cursor -(last_buffered_segment+1))*MINH_SD + minh_cur_buf; // segment cursor tang khi if (MINH_BITRATE_SET[minh_client_seg % 12][cursor_quality_cursor-1]*MINH_SD/estimated_throughput > t_avai_next_layer || // time download > available time. segment[last_buffered_segment].num_layers == cursor_quality_cursor) // num_layers ++ if a layer of corresponding segment is downloaded { cursor_segment_cursor ++; if (MINH_BITRATE_SET[minh_client_seg % 12][cursor_quality_cursor-1]*MINH_SD/estimated_throughput > t_avai_next_layer) { cursor_quality_cursor = MIN(1, cursor_quality_cursor-1); // quality cursor decreased cursor_improvement_timer = 0; // improvement timer is reset. } } if (segment[last_buffered_segment].layer[cursor_quality_cursor-1].bitrate != 0 && //all lower layers are downloaded cursor_improvement_timer == 0) // improvement timer is timed out { cursor_quality_cursor ++; last_buffered_segment = first_buffered_segmet; // linh tinh thoi } } minh_client_seg = cursor_segment_cursor; next_path = MINH_PATH_SET[minh_client_seg % 12][0]; } static void minh_SVC_backfilling_ABR(){ // printf("INVOKED %s\n", __func__); // printf("Last seg: %d \tLast_layer_id = %d\n", minh_client_seg, cur_layer_id); // if (minh_rebuf && minh_cur_buf >= MINH_REBUF_THRESHOLD_EXIT) // stop rebuffering // { // if (minh_client_seg > MINH_REBUF_THRESHOLD_EXIT/MINH_SD && minh_client_seg < 300) // { // sum_stall_duration += (long double)(lsquic_time_now() - streaming_start_time) / 1000 - // last_stall_start_time; //ms // printf("stall duration so far: %.3f\n", sum_stall_duration); // stall_duration_before_update = 0; // } // minh_rebuf = false; // } // if (minh_cur_buf < MINH_SD || minh_rebuf) // still or start rebuffering ==> go to the next segment and choose BL // { // if (!minh_rebuf) // start rebuff // { // if (minh_client_seg < 300) // sum_stall_num++; // minh_rebuf = true; // minh_cur_buf = 0; // last_stall_start_time = (long double)(lsquic_time_now() - streaming_start_time) / 1000 - stall_duration_before_update; // printf("Rebuffer_Start at %.3Lf\n", last_stall_start_time); // } // cur_layer_id = 1; // minh_client_seg ++; // segment[minh_client_seg].num_layers = 1; // } // else //normal // { // backfilling_considering_segment_id = minh_client_seg; // if ((int) minh_cur_buf/1000 < MINH_BUFFER_SIZE) // not all BLs are downloaded // { // } // } } static void minh_retransmission_technique(){ printf("\tINVOKED %s\n", __func__); // trigger retrans if (estimated_throughput > MINH_SUM_BITRATE_SET[minh_client_seg % 12][segment[minh_client_seg].num_layers-1] && minh_client_seg*MINH_SD > MINH_REBUF_THRESHOLD_EXIT && minh_cur_buf >= RETRANS_BUFF_TRIGGER_ON) { minh_retrans_trigger = TRUE; printf("--- TRIGGER ON ---\n"); } else //if (minh_cur_buf < RETRANS_BUFF_THRES) { minh_retrans_trigger = FALSE; // printf("--- Cannot trigger retrans: %.0f: %d: %.0f\n", // estimated_throughput - MINH_SUM_BITRATE_SET[minh_client_seg % 12][segment[minh_client_seg].num_layers-1], // minh_client_seg*MINH_SD > MINH_REBUF_THRESHOLD_EXIT, // minh_cur_buf - RETRANS_BUFF_TRIGGER_ON); } // if retrans is ON if (minh_retrans_trigger){ printf("-------------------- RETRANS. IS ENABLE ----------------------\n"); if (cur_layer_id == 1) // just jump to the next segment. ??? Chi check retrans trong truong hop nay? { // find the highest gap amplitude int i; int m_gap_amplitude = 0; int m_retrans_seg_id = 0; bool found_a_gap = FALSE; for (i = minh_client_seg - (int) minh_cur_buf/MINH_SD + 1; i < minh_client_seg; i++) { if (i == minh_client_seg-1) { if (segment[i-1].num_layers - segment[i].num_layers > m_gap_amplitude) { m_gap_amplitude = segment[i-1].num_layers - segment[i].num_layers; m_retrans_seg_id = i; found_a_gap = TRUE; // printf("# layers of current segment:%d\n", segment[i].num_layers); // printf("# layers of previous segment:%d\n", segment[i-1].num_layers); } } else { if (segment[i-1].num_layers - segment[i].num_layers > m_gap_amplitude || segment[i+1].num_layers - segment[i].num_layers > m_gap_amplitude) { m_gap_amplitude = MAX(segment[i-1].num_layers - segment[i].num_layers, segment[i+1].num_layers - segment[i].num_layers); m_retrans_seg_id = i; found_a_gap = TRUE; // printf("# layers of latter segment:%d\n", segment[i+1].num_layers); // printf("# layers of current segment:%d\n", segment[i].num_layers); // printf("# layers of previous segment:%d\n", segment[i-1].num_layers); } } if(found_a_gap && i < hung_max_seg_id_consideration) { // tinh t^a, T^R, B^e int next_all_rate = MINH_SUM_BITRATE_SET[minh_client_seg % 12][segment[minh_client_seg].num_layers-1]; int retrans_rate = MINH_BITRATE_SET[m_retrans_seg_id % 12][segment[m_retrans_seg_id].num_layers]; double t_avai = (m_retrans_seg_id -minh_client_seg)*MINH_SD + minh_cur_buf; double retrans_throughput = MINH_SD*retrans_rate / t_avai; double estimated_buffer = minh_cur_buf + MINH_SD*(1 - (next_all_rate + retrans_rate)/estimated_throughput); if (retrans_throughput < estimated_throughput && estimated_buffer > THETA) { retrans_path = MINH_PATH_SET[m_retrans_seg_id % 12][segment[m_retrans_seg_id].num_layers]; double division_factor = MAX(retrans_throughput/256, (estimated_throughput-retrans_throughput)/256); assert(division_factor != 0); priority_retrans = MAX((int) retrans_throughput / division_factor, 1); priority_next = MAX((int) (estimated_throughput-retrans_throughput) / division_factor, 1); // printf("MINH-2: priority_retrans: %d, priority_next: %d\n", priority_retrans, priority_next); assert(priority_retrans >= 1 && priority_retrans <= 256 && priority_next >= 1 && priority_next <= 256); retrans_check = TRUE; retransmitting = TRUE; minh_retrans_seg ++; // printf("MINH-2; minh_retrans_seg: %d\n", minh_retrans_seg); retrans_seg_id = m_retrans_seg_id; retrans_seg_id_recorder[minh_retrans_seg] = m_retrans_seg_id; retrans_num ++; printf("[RETRANS # %d] info: seg %d \tnew layer: %d \tt_avai: %.0f \tPri_retrans: %d \tPri_next: %d\n", retrans_num, i, segment[m_retrans_seg_id].num_layers +1,t_avai, priority_retrans, priority_next); break; } } } if (!retrans_check) { printf("After sanning, cannot find any layer to retransmit\n"); } } } else { printf("-------------------- CANNOT RETRANS ----------------------\n"); } } static void minh_update_stats(lsquic_stream_t *stream, lsquic_stream_ctx_t *st_h, int m_segment_id, bool retrans_layer){ long double m_dowload_time = (long double) (lsquic_time_now()- st_h->sh_created)/1000; //ms // long double m_update_diff_time = (long double)(lsquic_time_now()-last_update_time)/1000; int layer_id = 0; last_update_time = lsquic_time_now(); if (m_segment_id == 0){segment[m_segment_id].num_layers = 1;} if (retrans_layer) // this layer is retransmitted { if (lsquic_stream_id(stream) == terminate_seg_id) // TERMINIATE layer { printf("\tTERMINATION: this segment was requested for termination\n"); return; } else // retrans successfully { segment[m_segment_id].num_layers ++; layer_id = segment[m_segment_id].num_layers; segment[m_segment_id].layer[layer_id-1].stream_id = lsquic_stream_id(stream); } double temp_buf = minh_client_seg*MINH_SD + sum_stall_duration + start_play_time - (long double) (lsquic_time_now() - streaming_start_time)/1000; if (temp_buf < 0) // rebuffering before update { stall_while_downloading = TRUE; stall_duration_before_update = -temp_buf; minh_cur_buf = 0; // printf("\tRebuffering while downloading. Duration: %Lf\n", stall_duration_before_update); } else{ minh_cur_buf = temp_buf; } // printf("\t***Note: Update stats: retransmitted layer\n"); } else // this layer is current/next segment { layer_id = cur_layer_id; if (minh_rebuf) { printf("Update: still rebuffering\n"); minh_cur_buf += MINH_SD; } else if (layer_id == 1) // this is the first layer of current segment { double temp_buf = (minh_client_seg+1)*MINH_SD + sum_stall_duration + start_play_time - (long double) (lsquic_time_now() - streaming_start_time)/1000; // if (minh_cur_buf + MINH_SD - m_update_diff_time < 0) // rebuffering before update if (temp_buf < 0) { stall_while_downloading = TRUE; stall_duration_before_update = - temp_buf ; //(minh_cur_buf + MINH_SD - m_update_diff_time); minh_cur_buf = 0; printf("\tRebuffering while downloading. Duration: %.3Lf ms\n", stall_duration_before_update); } else { // double minh_cur_buf_1 = minh_cur_buf + MINH_SD - m_update_diff_time; minh_cur_buf = temp_buf; //(minh_client_seg+1)*MINH_SD + sum_stall_duration + start_play_time // - (long double) (lsquic_time_now() - streaming_start_time)/1000; //minh_cur_buf + MINH_SD - m_update_diff_time; // printf("\tDiff in 2 ways BL: %.1f: Old (%.1f) -> New (%.1f) \n", // minh_cur_buf_1 - minh_cur_buf, minh_cur_buf_1, minh_cur_buf); } } else { double temp_buf = (minh_client_seg+1)*MINH_SD + sum_stall_duration + start_play_time - (long double) (lsquic_time_now() - streaming_start_time)/1000; // if (minh_cur_buf - m_update_diff_time < 0) // rebuffering before update if (temp_buf < 0) { stall_while_downloading = TRUE; stall_duration_before_update = -temp_buf; //(minh_cur_buf - m_update_diff_time); minh_cur_buf = 0; // printf("\tRebuffering while downloading. Duration: %Lf\n", stall_duration_before_update); } else{ // minh_cur_buf = minh_cur_buf - m_update_diff_time; // double minh_cur_buf_1 = minh_cur_buf - m_update_diff_time; minh_cur_buf = temp_buf; //(minh_client_seg+1)*MINH_SD + sum_stall_duration + start_play_time // - (long double) (lsquic_time_now() - streaming_start_time)/1000; //minh_cur_buf + MINH_SD - m_update_diff_time; // printf("\tDiff in 2 ways EL: %.1f: Old (%.1f) -> New (%.1f) \n", // minh_cur_buf_1 - minh_cur_buf, minh_cur_buf_1, minh_cur_buf); } } } if ((downloaded_bytes_2on_close)*8.0/m_dowload_time > 65000) minh_throughput = minh_throughput; else minh_throughput = (downloaded_bytes_2on_close)*8.0/m_dowload_time; minh_get_est_throughput(); // recorder segment[m_segment_id].layer[layer_id-1].bitrate = MINH_BITRATE_SET[m_segment_id % 12][layer_id-1]; segment[m_segment_id].layer[layer_id-1].throughput = minh_throughput; segment[m_segment_id].layer[layer_id-1].buffer = minh_cur_buf; segment[m_segment_id].layer[layer_id-1].download_time = m_dowload_time; segment[m_segment_id].layer[layer_id-1].start_download_time = (long double) (st_h->sh_created - streaming_start_time)/1000; segment[m_segment_id].layer[layer_id-1].end_download_time = (long double) (lsquic_time_now() - streaming_start_time)/1000; downloaded_bytes_2on_close = 0; printf("[%.1Lf] Update stats: Segment %d Layer_id (1-4) %d current buff %.0f ms \tthroughput %.3f kbps in %.0Lf ms. Estimate throughput: %.3f\n", segment[m_segment_id].layer[layer_id-1].end_download_time, m_segment_id, layer_id, minh_cur_buf, minh_throughput, m_dowload_time, estimated_throughput); } // static void // minh_terminate_stream(lsquic_stream_t *stream, lsquic_stream_ctx_t *st_h){ // long double inst_download_time = (long double) (lsquic_time_now() - st_h->sh_created)/1000000; // double inst_buf = (minh_cur_buf - inst_buf) > 0 ? // minh_cur_buf - inst_buf : // 0; // printf("instant buffer = %.3f of stream id: %"PRIu64"\n", inst_buf, lsquic_stream_id(stream)); // } // Minh ADD-E struct sample_stats { unsigned n; unsigned long min, max; unsigned long sum; /* To calculate mean */ unsigned long sum_X2; /* To calculate stddev */ }; static struct sample_stats s_stat_to_conn, /* Time to connect */ s_stat_ttfb, s_stat_req; /* From TTFB to EOS */ static unsigned s_stat_conns_ok, s_stat_conns_failed; static unsigned long s_stat_downloaded_bytes; static void update_sample_stats (struct sample_stats *stats, unsigned long val) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); LSQ_DEBUG("%s: %p: %lu", __func__, stats, val); if (stats->n) { if (val < stats->min) stats->min = val; else if (val > stats->max) stats->max = val; } else { stats->min = val; stats->max = val; } stats->sum += val; stats->sum_X2 += val * val; ++stats->n; } // static void // calc_sample_stats (const struct sample_stats *stats, // long double *mean_p, long double *stddev_p) // { // // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); // unsigned long mean, tmp; // if (stats->n) // { // mean = stats->sum / stats->n; // *mean_p = (long double) mean; // if (stats->n > 1) // { // tmp = stats->sum_X2 - stats->n * mean * mean; // tmp /= stats->n - 1; // *stddev_p = sqrtl((long double) tmp); // } // else // *stddev_p = 0; // } // else // { // *mean_p = 0; // *stddev_p = 0; // } // } #ifdef WIN32 static char * strndup(const char *s, size_t n) { char *copy; copy = malloc(n + 1); if (copy) { memcpy(copy, s, n); copy[n] = '\0'; } return copy; } #endif struct lsquic_conn_ctx; struct path_elem { TAILQ_ENTRY(path_elem) next_pe; const char *path; }; struct http_client_ctx { TAILQ_HEAD(, lsquic_conn_ctx) conn_ctxs; const char *hostname; const char *method; const char *payload; char payload_size[20]; /* hcc_path_elems holds a list of paths which are to be requested from * the server. Each new request gets the next path from the list (the * iterator is stored in hcc_cur_pe); when the end is reached, the * iterator wraps around. */ TAILQ_HEAD(, path_elem) hcc_path_elems; struct path_elem *hcc_cur_pe; unsigned hcc_total_n_reqs; unsigned hcc_reqs_per_conn; unsigned hcc_concurrency; unsigned hcc_cc_reqs_per_conn; unsigned hcc_n_open_conns; unsigned hcc_reset_after_nbytes; unsigned hcc_retire_cid_after_nbytes; char *hcc_zero_rtt_file_name; enum { HCC_SKIP_0RTT = (1 << 0), HCC_SEEN_FIN = (1 << 1), HCC_ABORT_ON_INCOMPLETE = (1 << 2), } hcc_flags; struct prog *prog; const char *qif_file; FILE *qif_fh; }; struct lsquic_conn_ctx { TAILQ_ENTRY(lsquic_conn_ctx) next_ch; lsquic_conn_t *conn; struct http_client_ctx *client_ctx; lsquic_time_t ch_created; unsigned ch_n_reqs; /* This number gets decremented as streams are closed and * incremented as push promises are accepted. */ unsigned ch_n_cc_streams; /* This number is incremented as streams are opened * and decremented as streams are closed. It should * never exceed hcc_cc_reqs_per_conn in client_ctx. */ enum { CH_ZERO_RTT_SAVED = 1 << 0, } ch_flags; }; struct hset_elem { STAILQ_ENTRY(hset_elem) next; struct lsxpack_header xhdr; }; STAILQ_HEAD(hset, hset_elem); static void hset_dump (const struct hset *, FILE *); static void hset_destroy (void *hset); static void display_cert_chain (lsquic_conn_t *); static void create_connections (struct http_client_ctx *client_ctx) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); size_t len; FILE *file; unsigned char zero_rtt[0x2000]; if (0 == (client_ctx->hcc_flags & HCC_SKIP_0RTT) && client_ctx->hcc_zero_rtt_file_name) { file = fopen(client_ctx->hcc_zero_rtt_file_name, "rb"); if (!file) { LSQ_DEBUG("cannot open %s for reading: %s", client_ctx->hcc_zero_rtt_file_name, strerror(errno)); goto no_file; } len = fread(zero_rtt, 1, sizeof(zero_rtt), file); if (0 == len && !feof(file)) LSQ_WARN("error reading %s: %s", client_ctx->hcc_zero_rtt_file_name, strerror(errno)); fclose(file); LSQ_INFO("create connection zero_rtt %zu bytes", len); } else no_file: len = 0; while (client_ctx->hcc_n_open_conns < client_ctx->hcc_concurrency && client_ctx->hcc_total_n_reqs > 0) if (0 != prog_connect(client_ctx->prog, len ? zero_rtt : NULL, len)) { LSQ_ERROR("connection failed"); exit(EXIT_FAILURE); } } static void create_streams (struct http_client_ctx *client_ctx, lsquic_conn_ctx_t *conn_h) { printf("\n====================== CREATE STREAM ==================================================================\n"); #if 0 while (conn_h->ch_n_reqs - conn_h->ch_n_cc_streams && conn_h->ch_n_cc_streams < client_ctx->hcc_cc_reqs_per_conn) { lsquic_conn_make_stream(conn_h->conn); conn_h->ch_n_cc_streams++; } #else if (retrans_check){ client_ctx->hcc_cc_reqs_per_conn = 2; } while (conn_h->ch_n_reqs - conn_h->ch_n_cc_streams && conn_h->ch_n_cc_streams < client_ctx->hcc_cc_reqs_per_conn) { lsquic_conn_make_stream(conn_h->conn); conn_h->ch_n_cc_streams++; } #endif } static lsquic_conn_ctx_t * http_client_on_new_conn (void *stream_if_ctx, lsquic_conn_t *conn) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); struct http_client_ctx *client_ctx = stream_if_ctx; lsquic_conn_ctx_t *conn_h = calloc(1, sizeof(*conn_h)); conn_h->conn = conn; conn_h->client_ctx = client_ctx; conn_h->ch_n_reqs = MIN(client_ctx->hcc_total_n_reqs, client_ctx->hcc_reqs_per_conn); client_ctx->hcc_total_n_reqs -= conn_h->ch_n_reqs; TAILQ_INSERT_TAIL(&client_ctx->conn_ctxs, conn_h, next_ch); ++conn_h->client_ctx->hcc_n_open_conns; if (!TAILQ_EMPTY(&client_ctx->hcc_path_elems)) create_streams(client_ctx, conn_h); conn_h->ch_created = lsquic_time_now(); return conn_h; } struct create_another_conn_or_stop_ctx { struct event *event; struct http_client_ctx *client_ctx; }; static void create_another_conn_or_stop (evutil_socket_t sock, short events, void *ctx) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); struct create_another_conn_or_stop_ctx *const cacos = ctx; struct http_client_ctx *const client_ctx = cacos->client_ctx; event_del(cacos->event); event_free(cacos->event); free(cacos); create_connections(client_ctx); if (0 == client_ctx->hcc_n_open_conns) { LSQ_INFO("All connections are closed: stop engine"); prog_stop(client_ctx->prog); } } static void http_client_on_conn_closed (lsquic_conn_t *conn) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); lsquic_conn_ctx_t *conn_h = lsquic_conn_get_ctx(conn); struct create_another_conn_or_stop_ctx *cacos; enum LSQUIC_CONN_STATUS status; struct event_base *eb; char errmsg[80]; status = lsquic_conn_status(conn, errmsg, sizeof(errmsg)); LSQ_INFO("Connection closed. Status: %d. Message: %s", status, errmsg[0] ? errmsg : "<not set>"); if (conn_h->client_ctx->hcc_flags & HCC_ABORT_ON_INCOMPLETE) { if (!(conn_h->client_ctx->hcc_flags & HCC_SEEN_FIN)) abort(); } TAILQ_REMOVE(&conn_h->client_ctx->conn_ctxs, conn_h, next_ch); --conn_h->client_ctx->hcc_n_open_conns; cacos = calloc(1, sizeof(*cacos)); if (!cacos) { LSQ_ERROR("cannot allocate cacos"); exit(1); } eb = prog_eb(conn_h->client_ctx->prog); cacos->client_ctx = conn_h->client_ctx; cacos->event = event_new(eb, -1, 0, create_another_conn_or_stop, cacos); if (!cacos->event) { LSQ_ERROR("cannot allocate event"); exit(1); } if (0 != event_add(cacos->event, NULL)) { LSQ_ERROR("cannot add cacos event"); exit(1); } event_active(cacos->event, 0, 0); free(conn_h); } static int hsk_status_ok (enum lsquic_hsk_status status) { return status == LSQ_HSK_OK || status == LSQ_HSK_0RTT_OK; } static void http_client_on_hsk_done (lsquic_conn_t *conn, enum lsquic_hsk_status status) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); lsquic_conn_ctx_t *conn_h = lsquic_conn_get_ctx(conn); struct http_client_ctx *client_ctx = conn_h->client_ctx; if (hsk_status_ok(status)) LSQ_INFO("handshake success %s", status == LSQ_HSK_0RTT_OK ? "with 0-RTT" : ""); else if (status == LSQ_HSK_FAIL) LSQ_INFO("handshake failed"); else if (status == LSQ_HSK_0RTT_FAIL) { LSQ_INFO("handshake failed because of 0-RTT, will retry without it"); client_ctx->hcc_flags |= HCC_SKIP_0RTT; ++client_ctx->hcc_concurrency; ++client_ctx->hcc_total_n_reqs; } else assert(0); if (hsk_status_ok(status) && s_display_cert_chain) display_cert_chain(conn); if (hsk_status_ok(status)) { conn_h = lsquic_conn_get_ctx(conn); ++s_stat_conns_ok; update_sample_stats(&s_stat_to_conn, lsquic_time_now() - conn_h->ch_created); if (TAILQ_EMPTY(&client_ctx->hcc_path_elems)) { LSQ_INFO("no paths mode: close connection"); lsquic_conn_close(conn_h->conn); } } else ++s_stat_conns_failed; } static void http_client_on_zero_rtt_info (lsquic_conn_t *conn, const unsigned char *buf, size_t bufsz) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); lsquic_conn_ctx_t *const conn_h = lsquic_conn_get_ctx(conn); struct http_client_ctx *const client_ctx = conn_h->client_ctx; FILE *file; size_t nw; assert(client_ctx->hcc_zero_rtt_file_name); /* Our client is rather limited: only one file and only one ticket per * connection can be saved. */ if (conn_h->ch_flags & CH_ZERO_RTT_SAVED) { LSQ_DEBUG("zero-rtt already saved for this connection"); return; } file = fopen(client_ctx->hcc_zero_rtt_file_name, "wb"); if (!file) { LSQ_WARN("cannot open %s for writing: %s", client_ctx->hcc_zero_rtt_file_name, strerror(errno)); return; } nw = fwrite(buf, 1, bufsz, file); if (nw == bufsz) { LSQ_DEBUG("wrote %zd bytes of zero-rtt information to %s", nw, client_ctx->hcc_zero_rtt_file_name); conn_h->ch_flags |= CH_ZERO_RTT_SAVED; } else LSQ_WARN("error: fwrite(%s) returns %zd instead of %zd: %s", client_ctx->hcc_zero_rtt_file_name, nw, bufsz, strerror(errno)); fclose(file); } // struct lsquic_stream_ctx { // lsquic_stream_t *stream; // struct http_client_ctx *client_ctx; // const char *path; // enum { // HEADERS_SENT = (1 << 0), // PROCESSED_HEADERS = 1 << 1, // } sh_flags; // lsquic_time_t sh_created; // lsquic_time_t sh_ttfb; // unsigned count; // struct lsquic_reader reader; // }; static lsquic_stream_ctx_t * http_client_on_new_stream (void *stream_if_ctx, lsquic_stream_t *stream) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); // minh_client_seg ++; const int pushed = lsquic_stream_is_pushed(stream); if (pushed) { LSQ_INFO("not accepting server push"); lsquic_stream_refuse_push(stream); return NULL; } lsquic_stream_ctx_t *st_h = calloc(1, sizeof(*st_h)); st_h->stream = stream; st_h->client_ctx = stream_if_ctx; st_h->sh_created = lsquic_time_now(); // Minh [retransmission] MOD-S #if 0 if (st_h->client_ctx->hcc_cur_pe) { // printf("\t[MINH] info: 1 st_h->client_ctx->hcc_cur_pe->next_pe: %s\n", st_h->client_ctx->hcc_cur_pe->path); st_h->client_ctx->hcc_cur_pe = TAILQ_NEXT( st_h->client_ctx->hcc_cur_pe, next_pe); if (!st_h->client_ctx->hcc_cur_pe){ /* Wrap around */ // printf("\t[MINH] info: 2 st_h->client_ctx->hcc_cur_pe: %s\n", st_h->client_ctx->hcc_cur_pe); st_h->client_ctx->hcc_cur_pe = TAILQ_FIRST(&st_h->client_ctx->hcc_path_elems); } } else{ st_h->client_ctx->hcc_cur_pe = TAILQ_FIRST( &st_h->client_ctx->hcc_path_elems); } #else if (!retrans_check){ st_h->path = next_path; next_stream_id = lsquic_stream_id(stream); segment[minh_client_seg].layer[cur_layer_id-1].stream_id = next_stream_id; printf("path = NEXT path: %s in stream_id: %"PRIu64"\n", st_h->path, next_stream_id); printf("\t[MINH] info: Segment %d \tLayer %d \tAt time: %.0Lf ms\n", minh_client_seg, cur_layer_id, (long double)(lsquic_time_now() - streaming_start_time) / 1000); struct http_client_ctx *const client_ctx = st_h->client_ctx; client_ctx->hcc_cc_reqs_per_conn = 1; } else { st_h->path = retrans_path; retrans_stream_id = lsquic_stream_id(stream); segment[retrans_seg_id].layer[segment[retrans_seg_id].num_layers].stream_id = retrans_stream_id; printf("path = RETRANS path: %s in stream_id: %"PRIu64"\n", st_h->path, retrans_stream_id); printf("\t[MINH] info: Segment %d \tLayer %d \tAt time: %.0Lf ms\n", retrans_seg_id, segment[retrans_seg_id].num_layers+1, (long double)(lsquic_time_now() - streaming_start_time) / 1000); retrans_check = false; } #endif // Minh [retransmission] MOD-E if (st_h->client_ctx->payload) { st_h->reader.lsqr_read = test_reader_read; st_h->reader.lsqr_size = test_reader_size; st_h->reader.lsqr_ctx = create_lsquic_reader_ctx(st_h->client_ctx->payload); if (!st_h->reader.lsqr_ctx) exit(1); } else st_h->reader.lsqr_ctx = NULL; // printf("\t[MINH] info: Segment %d \tLayer %d \tAt time: %.0Lf ms\n", // minh_client_seg, cur_layer_id, (long double)(lsquic_time_now() - streaming_start_time) / 1000); lsquic_stream_wantwrite(stream, 1); if (set_prior_check){ if (st_h->path == retrans_path){ printf("PRIORITY_retrans\n"); lsquic_stream_set_priority(stream, priority_retrans); } else{ printf("PRIORITY_next\n"); lsquic_stream_set_priority(stream, priority_next); set_prior_check = false; } } return st_h; } static void send_headers (lsquic_stream_ctx_t *st_h) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); const char *hostname = st_h->client_ctx->hostname; if (!hostname) hostname = st_h->client_ctx->prog->prog_hostname; struct lsxpack_header headers_arr[7]; #define V(v) (v), strlen(v) lsxpack_header_set_ptr(&headers_arr[0], V(":method"), V(st_h->client_ctx->method)); lsxpack_header_set_ptr(&headers_arr[1], V(":scheme"), V("https")); lsxpack_header_set_ptr(&headers_arr[2], V(":path"), V(st_h->path)); lsxpack_header_set_ptr(&headers_arr[3], V(":authority"), V(hostname)); lsxpack_header_set_ptr(&headers_arr[4], V("user-agent"), V(st_h->client_ctx->prog->prog_settings.es_ua)); /* The following headers only gets sent if there is request payload: */ lsxpack_header_set_ptr(&headers_arr[5], V("content-type"), V("application/octet-stream")); lsxpack_header_set_ptr(&headers_arr[6], V("content-length"), V( st_h->client_ctx->payload_size)); lsquic_http_headers_t headers = { .count = sizeof(headers_arr) / sizeof(headers_arr[0]), .headers = headers_arr, }; if (!st_h->client_ctx->payload) headers.count -= 2; if (0 != lsquic_stream_send_headers(st_h->stream, &headers, st_h->client_ctx->payload == NULL)) { LSQ_ERROR("cannot send headers: %s", strerror(errno)); exit(1); } } /* This is here to exercise lsquic_conn_get_server_cert_chain() API */ static void display_cert_chain (lsquic_conn_t *conn) { STACK_OF(X509) *chain; X509_NAME *name; X509 *cert; unsigned i; char buf[100]; chain = lsquic_conn_get_server_cert_chain(conn); if (!chain) { LSQ_WARN("could not get server certificate chain"); return; } for (i = 0; i < sk_X509_num(chain); ++i) { cert = sk_X509_value(chain, i); name = X509_get_subject_name(cert); LSQ_INFO("cert #%u: name: %s", i, X509_NAME_oneline(name, buf, sizeof(buf))); X509_free(cert); } sk_X509_free(chain); } static void http_client_on_write (lsquic_stream_t *stream, lsquic_stream_ctx_t *st_h) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); ssize_t nw; if (st_h->sh_flags & HEADERS_SENT) { if (st_h->client_ctx->payload && test_reader_size(st_h->reader.lsqr_ctx) > 0) { nw = lsquic_stream_writef(stream, &st_h->reader); if (nw < 0) { LSQ_ERROR("write error: %s", strerror(errno)); exit(1); } if (test_reader_size(st_h->reader.lsqr_ctx) > 0) { lsquic_stream_wantwrite(stream, 1); } else { lsquic_stream_shutdown(stream, 1); lsquic_stream_wantread(stream, 1); } } else { lsquic_stream_shutdown(stream, 1); lsquic_stream_wantread(stream, 1); } } else { st_h->sh_flags |= HEADERS_SENT; send_headers(st_h); } } static size_t discard (void *ctx, const unsigned char *buf, size_t sz, int fin) { return sz; } static void http_client_on_read (lsquic_stream_t *stream, lsquic_stream_ctx_t *st_h) { // printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); struct http_client_ctx *const client_ctx = st_h->client_ctx; struct hset *hset; ssize_t nread; unsigned old_prio, new_prio; unsigned char buf[0x200]; unsigned nreads = 0; #ifdef WIN32 srand(GetTickCount()); #endif do { if (g_header_bypass && !(st_h->sh_flags & PROCESSED_HEADERS)) { hset = lsquic_stream_get_hset(stream); if (!hset) { LSQ_ERROR("could not get header set from stream"); exit(2); } st_h->sh_ttfb = lsquic_time_now(); update_sample_stats(&s_stat_ttfb, st_h->sh_ttfb - st_h->sh_created); if (s_discard_response) LSQ_DEBUG("discard response: do not dump headers"); else hset_dump(hset, stdout); hset_destroy(hset); st_h->sh_flags |= PROCESSED_HEADERS; } else if (nread = (s_discard_response ? lsquic_stream_readf(stream, discard, NULL) : lsquic_stream_read(stream, buf, sizeof(buf))), nread > 0) { // Termination -S if (retransmitting) { static int count_retrans = 0; static int count_next = 0; if (lsquic_stream_id(stream) == retrans_stream_id) { double inst_buf = minh_cur_buf - (long double) (lsquic_time_now() - last_update_time)/1000; double t_avai = retrans_seg_id*MINH_SD + sum_stall_duration + start_play_time - (long double) (lsquic_time_now() - streaming_start_time)/1000;//(retrans_seg_id -minh_client_seg)*MINH_SD + inst_buf; // in millisecond if (t_avai < 100 || inst_buf < RETRANS_BUFF_THRES) { printf("[MONITOR] inst_buf %.0f, t_avai %.0f\n", inst_buf, t_avai); lsquic_stream_reset(stream, 0x1); printf("========================= TERMINATION STREAM ID %"PRIu64" = SEGMENT %d ==============================\n", retrans_stream_id, retrans_seg_id); termination_check = TRUE; terminate_seg_id = lsquic_stream_id(stream); terminate_stream_id_recorder[terminate_num] = terminate_seg_id; terminate_num ++; break; } else { if (count_retrans == 5) { count_retrans = 0; lsquic_stream_set_priority(stream, priority_retrans); } else { count_retrans ++; } } } else{ if (count_next == 5) { count_next = 0; lsquic_stream_set_priority(stream, priority_next); } else { count_next ++; } } } // Termination -E // s_stat_downloaded_bytes += nread; stream->sm_cont_len += nread; downloaded_bytes_2on_close += nread; if (!g_header_bypass && !(st_h->sh_flags & PROCESSED_HEADERS)) { /* First read is assumed to be the first byte */ st_h->sh_ttfb = lsquic_time_now(); update_sample_stats(&s_stat_ttfb, st_h->sh_ttfb - st_h->sh_created); st_h->sh_flags |= PROCESSED_HEADERS; } if (randomly_reprioritize_streams && (st_h->count++ & 0x3F) == 0) { old_prio = lsquic_stream_priority(stream); new_prio = 1 + (random() & 0xFF); #ifndef NDEBUG const int s = #endif lsquic_stream_set_priority(stream, new_prio); assert(s == 0); LSQ_DEBUG("changed stream %"PRIu64" priority from %u to %u", lsquic_stream_id(stream), old_prio, new_prio); } } else if (0 == nread) { update_sample_stats(&s_stat_req, lsquic_time_now() - st_h->sh_ttfb); client_ctx->hcc_flags |= HCC_SEEN_FIN; lsquic_stream_shutdown(stream, 0); break; } else if (client_ctx->prog->prog_settings.es_rw_once && EWOULDBLOCK == errno) { LSQ_NOTICE("emptied the buffer in 'once' mode"); break; } else if (lsquic_stream_is_rejected(stream)) { LSQ_NOTICE("stream was rejected"); lsquic_stream_close(stream); break; } else { LSQ_ERROR("could not read: %s", strerror(errno)); exit(2); } } while (client_ctx->prog->prog_settings.es_rw_once && nreads++ < 3 /* Emulate just a few reads */); } // static void // minh_submit_request(){ // struct path_elem *pe; // pe = calloc(1, sizeof(*pe)); // pe->path = "/file-50K"; // TAILQ_INSERT_TAIL(&client_ctx.hcc_path_elems, pe, next_pe); // } static void http_client_on_close (lsquic_stream_t *stream, lsquic_stream_ctx_t *st_h) { unsigned long stream_id = lsquic_stream_id(stream); printf("\n\t******************* CLOSE STREAM ***************\n"); printf("\t[MINH] closed stream id: %"PRIu64" \tpath: %s \tAt time : %.0Lf ms \n", stream_id, st_h->path, (long double) (lsquic_time_now() - streaming_start_time)/1000); const int pushed = lsquic_stream_is_pushed(stream); if (pushed) { assert(NULL == st_h); return; } LSQ_INFO("%s called", __func__); struct http_client_ctx *const client_ctx = st_h->client_ctx; lsquic_conn_t *conn = lsquic_stream_conn(stream); lsquic_conn_ctx_t *conn_h; TAILQ_FOREACH(conn_h, &client_ctx->conn_ctxs, next_ch) if (conn_h->conn == conn) break; assert(conn_h); --conn_h->ch_n_reqs; --conn_h->ch_n_cc_streams; // Minh [retransmission] ADD-S if (retrans_stream_id == stream_id) // retransmit successfully (NO termination) { if (!termination_check) { printf("RETRANSMIT SUCCESSFULLY\n"); minh_update_stats(stream, st_h, retrans_seg_id, TRUE); } else { printf("RETRANSMIT FAILED\n"); termination_check = FALSE; } retransmitting = FALSE; } else if (next_stream_id == stream_id) { printf("\tThis is NEXT layer\n"); // cur_layer_id ++; // nen cho vao minh_AGG minh_update_stats(stream, st_h, minh_client_seg, FALSE); // call ABR if (minh_ABR == AGG) { minh_AGG_ABR(); } else if (minh_ABR == CURSOR) { minh_SVC_cursor_ABR(); } else if (minh_ABR == BACKFILLING) { minh_SVC_backfilling_ABR(); } // call retransmission if enable if (retrans_enable && !retransmitting) { minh_retransmission_technique(); } if (minh_cur_buf > MINH_BUFFER_SIZE && minh_client_seg < hung_max_seg_id_consideration){ printf("\t\t======== SLEEP: cur_buf: %.1f an sleep in %.1f ms\n", minh_cur_buf, (minh_cur_buf - MINH_BUFFER_SIZE)); usleep((minh_cur_buf - MINH_BUFFER_SIZE)*1000); // delay (minh_cur_buf - MINH_BUFFER_SIZE); // minh_cur_buf = MINH_BUFFER_SIZE-1000; //co can phai tinh lai minh_curbuf? } } else { printf("SOMETHING WRONG IN CLOSE STREAM\n"); exit(1); } // Minh [retransmission] ADD-E if (0 == conn_h->ch_n_reqs) { LSQ_INFO("all requests completed, closing connection"); lsquic_conn_close(conn_h->conn); } else { LSQ_INFO("%u active stream, %u request remain, creating %u new stream", conn_h->ch_n_cc_streams, conn_h->ch_n_reqs - conn_h->ch_n_cc_streams, MIN((conn_h->ch_n_reqs - conn_h->ch_n_cc_streams), (client_ctx->hcc_cc_reqs_per_conn - conn_h->ch_n_cc_streams))); create_streams(client_ctx, conn_h); } if (st_h->reader.lsqr_ctx) destroy_lsquic_reader_ctx(st_h->reader.lsqr_ctx); free(st_h); } static struct lsquic_stream_if http_client_if = { .on_new_conn = http_client_on_new_conn, .on_conn_closed = http_client_on_conn_closed, .on_new_stream = http_client_on_new_stream, .on_read = http_client_on_read, .on_write = http_client_on_write, .on_close = http_client_on_close, .on_hsk_done = http_client_on_hsk_done, }; static void usage (const char *prog) { const char *const slash = strrchr(prog, '/'); if (slash) prog = slash + 1; printf( "Usage: %s [opts]\n" "\n" "Options:\n" " -p PATH Path to request. May be specified more than once. If no\n" " path is specified, the connection is closed as soon as\n" " handshake succeeds.\n" " -n CONNS Number of concurrent connections. Defaults to 1.\n" " -r NREQS Total number of requests to send. Defaults to 1.\n" " -R MAXREQS Maximum number of requests per single connection. Some\n" " connections will have fewer requests than this.\n" " -w CONCUR Number of concurrent requests per single connection.\n" " Defaults to 1.\n" " -M METHOD Method. Defaults to GET.\n" " -P PAYLOAD Name of the file that contains payload to be used in the\n" " request. This adds two more headers to the request:\n" " content-type: application/octet-stream and\n" " content-length\n" " -K Discard server response\n" " -I Abort on incomplete reponse from server\n" " -4 Prefer IPv4 when resolving hostname\n" " -6 Prefer IPv6 when resolving hostname\n" " -0 FILE Provide RTT info file (reading or writing)\n" #ifndef WIN32 " -C DIR Certificate store. If specified, server certificate will\n" " be verified.\n" #endif " -a Display server certificate chain after successful handshake.\n" " -b N_BYTES Send RESET_STREAM frame after the client has read n bytes.\n" " -t Print stats to stdout.\n" " -T FILE Print stats to FILE. If FILE is -, print stats to stdout.\n" " -q FILE QIF mode: issue requests from the QIF file and validate\n" " server responses.\n" " -e TOKEN Hexadecimal string representing resume token.\n" , prog); } #ifndef WIN32 static X509_STORE *store; /* Windows does not have regex... */ static int ends_in_pem (const char *s) { int len; len = strlen(s); return len >= 4 && 0 == strcasecmp(s + len - 4, ".pem"); } static X509 * file2cert (const char *path) { X509 *cert = NULL; BIO *in; in = BIO_new(BIO_s_file()); if (!in) goto end; if (BIO_read_filename(in, path) <= 0) goto end; cert = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL); end: BIO_free(in); return cert; } static int init_x509_cert_store (const char *path) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); struct dirent *ent; X509 *cert; DIR *dir; char file_path[NAME_MAX]; int ret; dir = opendir(path); if (!dir) { LSQ_WARN("Cannot open directory `%s': %s", path, strerror(errno)); return -1; } store = X509_STORE_new(); while ((ent = readdir(dir))) { if (ends_in_pem(ent->d_name)) { ret = snprintf(file_path, sizeof(file_path), "%s/%s", path, ent->d_name); if (ret < 0) { LSQ_WARN("file_path formatting error %s", strerror(errno)); continue; } else if ((unsigned)ret >= sizeof(file_path)) { LSQ_WARN("file_path was truncated %s", strerror(errno)); continue; } cert = file2cert(file_path); if (cert) { if (1 != X509_STORE_add_cert(store, cert)) LSQ_WARN("could not add cert from %s", file_path); } else LSQ_WARN("could not read cert from %s", file_path); } } (void) closedir(dir); return 0; } static int verify_server_cert (void *ctx, STACK_OF(X509) *chain) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); X509_STORE_CTX store_ctx; X509 *cert; int ver; if (!store) { if (0 != init_x509_cert_store(ctx)) return -1; } cert = sk_X509_shift(chain); X509_STORE_CTX_init(&store_ctx, store, cert, chain); ver = X509_verify_cert(&store_ctx); X509_STORE_CTX_cleanup(&store_ctx); if (ver != 1) LSQ_WARN("could not verify server certificate"); return ver == 1 ? 0 : -1; } #endif static void * hset_create (void *hsi_ctx, lsquic_stream_t *stream, int is_push_promise) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); struct hset *hset; if (s_discard_response) return (void *) 1; else if ((hset = malloc(sizeof(*hset)))) { STAILQ_INIT(hset); return hset; } else return NULL; } static struct lsxpack_header * hset_prepare_decode (void *hset_p, struct lsxpack_header *xhdr, size_t req_space) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); struct hset *const hset = hset_p; struct hset_elem *el; char *buf; if (0 == req_space) req_space = 0x100; if (req_space > LSXPACK_MAX_STRLEN) { LSQ_WARN("requested space for header is too large: %zd bytes", req_space); return NULL; } if (!xhdr) { buf = malloc(req_space); if (!buf) { LSQ_WARN("cannot allocate buf of %zd bytes", req_space); return NULL; } el = malloc(sizeof(*el)); if (!el) { LSQ_WARN("cannot allocate hset_elem"); free(buf); return NULL; } STAILQ_INSERT_TAIL(hset, el, next); lsxpack_header_prepare_decode(&el->xhdr, buf, 0, req_space); } else { el = (struct hset_elem *) ((char *) xhdr - offsetof(struct hset_elem, xhdr)); if (req_space <= xhdr->val_len) { LSQ_ERROR("requested space is smaller than already allocated"); return NULL; } buf = realloc(el->xhdr.buf, req_space); if (!buf) { LSQ_WARN("cannot reallocate hset buf"); return NULL; } el->xhdr.buf = buf; el->xhdr.val_len = req_space; } return &el->xhdr; } static int hset_add_header (void *hset_p, struct lsxpack_header *xhdr) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); unsigned name_len, value_len; /* Not much to do: the header value are in xhdr */ if (xhdr) { name_len = xhdr->name_len; value_len = xhdr->val_len; s_stat_downloaded_bytes += name_len + value_len + 4; /* ": \r\n" */ } else s_stat_downloaded_bytes += 2; /* \r\n "*/ return 0; } static void hset_destroy (void *hset_p) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); struct hset *hset = hset_p; struct hset_elem *el, *next; if (!s_discard_response) { for (el = STAILQ_FIRST(hset); el; el = next) { next = STAILQ_NEXT(el, next); free(el->xhdr.buf); free(el); } free(hset); } } static void hset_dump (const struct hset *hset, FILE *out) { printf("\t[MINH] info: %s:%s():%d\n", __FILE__, __func__, __LINE__); const struct hset_elem *el; STAILQ_FOREACH(el, hset, next) if (el->xhdr.flags & (LSXPACK_HPACK_IDX|LSXPACK_QPACK_IDX)) fprintf(out, "%.*s (%s static table idx %u): %.*s\n", (int) el->xhdr.name_len, lsxpack_header_get_name(&el->xhdr), el->xhdr.flags & LSXPACK_HPACK_IDX ? "hpack" : "qpack", el->xhdr.flags & LSXPACK_HPACK_IDX ? el->xhdr.hpack_index : el->xhdr.qpack_index, (int) el->xhdr.val_len, lsxpack_header_get_value(&el->xhdr)); else fprintf(out, "%.*s: %.*s\n", (int) el->xhdr.name_len, lsxpack_header_get_name(&el->xhdr), (int) el->xhdr.val_len, lsxpack_header_get_value(&el->xhdr)); fprintf(out, "\n"); fflush(out); } /* These are basic and for illustration purposes only. You will want to * do your own verification by doing something similar to what is done * in src/liblsquic/lsquic_http1x_if.c */ static const struct lsquic_hset_if header_bypass_api = { .hsi_create_header_set = hset_create, .hsi_prepare_decode = hset_prepare_decode, .hsi_process_header = hset_add_header, .hsi_discard_header_set = hset_destroy, }; // static void // display_stat (FILE *out, const struct sample_stats *stats, const char *name) // { // long double mean, stddev; // calc_sample_stats(stats, &mean, &stddev); // fprintf(out, "%s: n: %u; min: %.2Lf ms; max: %.2Lf ms; mean: %.2Lf ms; " // "sd: %.2Lf ms\n", name, stats->n, (long double) stats->min / 1000, // (long double) stats->max / 1000, mean / 1000, stddev / 1000); // } static lsquic_conn_ctx_t * qif_client_on_new_conn (void *stream_if_ctx, lsquic_conn_t *conn) { lsquic_conn_make_stream(conn); return stream_if_ctx; } static void qif_client_on_conn_closed (lsquic_conn_t *conn) { struct http_client_ctx *client_ctx = (void *) lsquic_conn_get_ctx(conn); LSQ_INFO("connection is closed: stop engine"); prog_stop(client_ctx->prog); } struct qif_stream_ctx { int reqno; struct lsquic_http_headers headers; char *qif_str; size_t qif_sz; size_t qif_off; char *resp_str; /* qif_sz allocated */ size_t resp_off; /* Read so far */ enum { QSC_HEADERS_SENT = 1 << 0, QSC_GOT_HEADERS = 1 << 1, } flags; }; // #define MAX(a, b) ((a) > (b) ? (a) : (b)) lsquic_stream_ctx_t * qif_client_on_new_stream (void *stream_if_ctx, lsquic_stream_t *stream) { struct http_client_ctx *const client_ctx = stream_if_ctx; FILE *const fh = client_ctx->qif_fh; struct qif_stream_ctx *ctx; struct lsxpack_header *header; static int reqno; size_t nalloc; int i; char *end, *tab, *line; char line_buf[0x1000]; ctx = calloc(1, sizeof(*ctx)); if (!ctx) { perror("calloc"); exit(1); } ctx->reqno = reqno++; nalloc = 0; while ((line = fgets(line_buf, sizeof(line_buf), fh))) { end = strchr(line, '\n'); if (!end) { fprintf(stderr, "no newline\n"); exit(1); } if (end == line) break; if (*line == '#') continue; tab = strchr(line, '\t'); if (!tab) { fprintf(stderr, "no TAB\n"); exit(1); } if (nalloc + (end + 1 - line) > ctx->qif_sz) { if (nalloc) nalloc = MAX(nalloc * 2, nalloc + (end + 1 - line)); else nalloc = end + 1 - line; ctx->qif_str = realloc(ctx->qif_str, nalloc); if (!ctx->qif_str) { perror("realloc"); exit(1); } } memcpy(ctx->qif_str + ctx->qif_sz, line, end + 1 - line); ctx->headers.headers = realloc(ctx->headers.headers, sizeof(ctx->headers.headers[0]) * (ctx->headers.count + 1)); if (!ctx->headers.headers) { perror("realloc"); exit(1); } header = &ctx->headers.headers[ctx->headers.count++]; lsxpack_header_set_ptr(header, (void *) ctx->qif_sz, tab - line, (void *) (ctx->qif_sz + (tab - line + 1)), end - tab - 1); ctx->qif_sz += end + 1 - line; } for (i = 0; i < ctx->headers.count; ++i) { ctx->headers.headers[i].buf = ctx->qif_str + (uintptr_t) ctx->headers.headers[i].buf; ctx->headers.headers[i].name_ptr = ctx->qif_str + (uintptr_t) ctx->headers.headers[i].name_ptr; } lsquic_stream_wantwrite(stream, 1); if (!line) { LSQ_DEBUG("Input QIF file ends; close file handle"); fclose(client_ctx->qif_fh); client_ctx->qif_fh = NULL; } return (void *) ctx; } static void qif_client_on_write (struct lsquic_stream *stream, lsquic_stream_ctx_t *h) { struct qif_stream_ctx *const ctx = (void *) h; size_t towrite; ssize_t nw; if (ctx->flags & QSC_HEADERS_SENT) { towrite = ctx->qif_sz - ctx->qif_off; nw = lsquic_stream_write(stream, ctx->qif_str + ctx->qif_off, towrite); if (nw >= 0) { LSQ_DEBUG("wrote %zd bytes to stream", nw); ctx->qif_off += nw; if (ctx->qif_off == (size_t) nw) { lsquic_stream_shutdown(stream, 1); lsquic_stream_wantread(stream, 1); LSQ_DEBUG("finished writing request %d", ctx->reqno); } } else { LSQ_ERROR("cannot write to stream: %s", strerror(errno)); lsquic_stream_wantwrite(stream, 0); lsquic_conn_abort(lsquic_stream_conn(stream)); } } else { if (0 == lsquic_stream_send_headers(stream, &ctx->headers, 0)) { ctx->flags |= QSC_HEADERS_SENT; LSQ_DEBUG("sent headers"); } else { LSQ_ERROR("cannot send headers: %s", strerror(errno)); lsquic_stream_wantwrite(stream, 0); lsquic_conn_abort(lsquic_stream_conn(stream)); } } } static void qif_client_on_read (struct lsquic_stream *stream, lsquic_stream_ctx_t *h) { struct qif_stream_ctx *const ctx = (void *) h; struct hset *hset; ssize_t nr; unsigned char buf[1]; LSQ_DEBUG("reading response to request %d", ctx->reqno); if (!(ctx->flags & QSC_GOT_HEADERS)) { hset = lsquic_stream_get_hset(stream); if (!hset) { LSQ_ERROR("could not get header set from stream"); exit(2); } LSQ_DEBUG("got header set for response %d", ctx->reqno); hset_dump(hset, stdout); hset_destroy(hset); ctx->flags |= QSC_GOT_HEADERS; } else { if (!ctx->resp_str) { ctx->resp_str = malloc(ctx->qif_sz); if (!ctx->resp_str) { perror("malloc"); exit(1); } } if (ctx->resp_off < ctx->qif_sz) { nr = lsquic_stream_read(stream, ctx->resp_str + ctx->resp_off, ctx->qif_sz - ctx->resp_off); if (nr > 0) { ctx->resp_off += nr; LSQ_DEBUG("read %zd bytes of reponse %d", nr, ctx->reqno); } else if (nr == 0) { LSQ_INFO("response %d too short", ctx->reqno); LSQ_WARN("response %d FAIL", ctx->reqno); lsquic_stream_shutdown(stream, 0); } else { LSQ_ERROR("error reading from stream"); lsquic_stream_wantread(stream, 0); lsquic_conn_abort(lsquic_stream_conn(stream)); } } else { /* Collect EOF */ nr = lsquic_stream_read(stream, buf, sizeof(buf)); if (nr == 0) { if (0 == memcmp(ctx->qif_str, ctx->resp_str, ctx->qif_sz)) LSQ_INFO("response %d OK", ctx->reqno); else LSQ_WARN("response %d FAIL", ctx->reqno); lsquic_stream_shutdown(stream, 0); } else if (nr > 0) { LSQ_INFO("response %d too long", ctx->reqno); LSQ_WARN("response %d FAIL", ctx->reqno); lsquic_stream_shutdown(stream, 0); } else { LSQ_ERROR("error reading from stream"); lsquic_stream_shutdown(stream, 0); lsquic_conn_abort(lsquic_stream_conn(stream)); } } } } static void qif_client_on_close (struct lsquic_stream *stream, lsquic_stream_ctx_t *h) { struct lsquic_conn *conn = lsquic_stream_conn(stream); struct http_client_ctx *client_ctx = (void *) lsquic_conn_get_ctx(conn); struct qif_stream_ctx *const ctx = (void *) h; free(ctx->qif_str); free(ctx->resp_str); free(ctx->headers.headers); free(ctx); if (client_ctx->qif_fh) lsquic_conn_make_stream(conn); else lsquic_conn_close(conn); } const struct lsquic_stream_if qif_client_if = { .on_new_conn = qif_client_on_new_conn, .on_conn_closed = qif_client_on_conn_closed, .on_new_stream = qif_client_on_new_stream, .on_read = qif_client_on_read, .on_write = qif_client_on_write, .on_close = qif_client_on_close, }; int main (int argc, char **argv) { int opt, s, was_empty; FILE *stats_fh = NULL; // long double elapsed; struct http_client_ctx client_ctx; struct stat st; struct path_elem *pe; struct sport_head sports; struct prog prog; const char *token = NULL; TAILQ_INIT(&sports); memset(&client_ctx, 0, sizeof(client_ctx)); TAILQ_INIT(&client_ctx.hcc_path_elems); TAILQ_INIT(&client_ctx.conn_ctxs); client_ctx.method = "GET"; client_ctx.hcc_concurrency = 1; client_ctx.hcc_cc_reqs_per_conn = 1; client_ctx.hcc_reqs_per_conn = 1; client_ctx.hcc_total_n_reqs = 1; client_ctx.hcc_reset_after_nbytes = 0; client_ctx.hcc_retire_cid_after_nbytes = 0; client_ctx.prog = &prog; #ifdef WIN32 WSADATA wsd; WSAStartup(MAKEWORD(2, 2), &wsd); #endif prog_init(&prog, LSENG_HTTP, &sports, &http_client_if, &client_ctx); while (-1 != (opt = getopt(argc, argv, PROG_OPTS "46Br:R:IKu:EP:M:n:w:H:p:0:q:e:hatT:b:d:A:Z" #ifndef WIN32 "C:" #endif ))) { switch (opt) { case 'a': ++s_display_cert_chain; break; case '4': case '6': prog.prog_ipver = opt - '0'; break; case 'B': g_header_bypass = 1; prog.prog_api.ea_hsi_if = &header_bypass_api; prog.prog_api.ea_hsi_ctx = NULL; break; case 'I': client_ctx.hcc_flags |= HCC_ABORT_ON_INCOMPLETE; break; case 'K': ++s_discard_response; break; case 'u': /* Accept p<U>sh promise */ promise_fd = open(optarg, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (promise_fd < 0) { perror("open"); exit(1); } prog.prog_settings.es_support_push = 1; /* Pokes into prog */ break; case 'E': /* E: randomly reprioritize str<E>ams. Now, that's * pretty random. :) */ randomly_reprioritize_streams = 1; break; case 'n': client_ctx.hcc_concurrency = atoi(optarg); break; case 'w': client_ctx.hcc_cc_reqs_per_conn = atoi(optarg); break; case 'P': client_ctx.payload = optarg; if (0 != stat(optarg, &st)) { perror("stat"); exit(2); } sprintf(client_ctx.payload_size, "%jd", (intmax_t) st.st_size); break; case 'M': client_ctx.method = optarg; break; case 'r': client_ctx.hcc_total_n_reqs = atoi(optarg); break; case 'R': client_ctx.hcc_reqs_per_conn = atoi(optarg); break; case 'H': client_ctx.hostname = optarg; prog.prog_hostname = optarg; /* Pokes into prog */ break; case 'p': pe = calloc(1, sizeof(*pe)); pe->path = optarg; TAILQ_INSERT_TAIL(&client_ctx.hcc_path_elems, pe, next_pe); break; case 'h': usage(argv[0]); prog_print_common_options(&prog, stdout); exit(0); case 'q': client_ctx.qif_file = optarg; break; case 'e': if (TAILQ_EMPTY(&sports)) token = optarg; else sport_set_token(TAILQ_LAST(&sports, sport_head), optarg); break; #ifndef WIN32 case 'C': prog.prog_api.ea_verify_cert = verify_server_cert; prog.prog_api.ea_verify_ctx = optarg; break; #endif case 't': stats_fh = stdout; break; case 'T': if (0 == strcmp(optarg, "-")) stats_fh = stdout; else { stats_fh = fopen(optarg, "w"); if (!stats_fh) { perror("fopen"); exit(1); } } break; case 'b': client_ctx.hcc_reset_after_nbytes = atoi(optarg); break; case 'd': client_ctx.hcc_retire_cid_after_nbytes = atoi(optarg); break; case '0': http_client_if.on_zero_rtt_info = http_client_on_zero_rtt_info; client_ctx.hcc_zero_rtt_file_name = optarg; break; // MINH [retransmission] ADD-S case 'A': // choose ABR if (strcmp(optarg, "AGG") == 0) { minh_ABR = AGG; printf("~~~ AGG ABR~~~\n"); } else if (strcmp(optarg, "CURSOR") == 0) { minh_ABR = CURSOR; printf("~~~ SVC_CURSOR ABR~~~\n"); } else if (strcmp(optarg, "BACKFILLING") == 0) { minh_ABR = BACKFILLING; printf("~~~ SVC_BACKFILLING ABR~~~\n"); } else { printf("No ABR available\n"); exit(1); } break; // case 'z': case 'Z': // enable retransmisison printf("~~~ENABLE RETRANSMISSION\n"); retrans_enable = TRUE; break; // MINH [retransmission] ADD-E default: if (0 != prog_set_opt(&prog, opt, optarg)) exit(1); } } client_ctx.hcc_reqs_per_conn = 1000; printf("~~~DUMMYNET starts\n"); if (system("./complex_4g.sh &")) {printf("ERROR Cannot start DummyNet\n"); exit(1);}; #if LSQUIC_CONN_STATS prog.prog_api.ea_stats_fh = stats_fh; #endif prog.prog_settings.es_ua = LITESPEED_ID; if (client_ctx.qif_file) { client_ctx.qif_fh = fopen(client_ctx.qif_file, "r"); if (!client_ctx.qif_fh) { fprintf(stderr, "Cannot open %s for reading: %s\n", client_ctx.qif_file, strerror(errno)); exit(1); } LSQ_NOTICE("opened QIF file %s for reading\n", client_ctx.qif_file); prog.prog_api.ea_stream_if = &qif_client_if; g_header_bypass = 1; prog.prog_api.ea_hsi_if = &header_bypass_api; prog.prog_api.ea_hsi_ctx = NULL; } else if (TAILQ_EMPTY(&client_ctx.hcc_path_elems)) { fprintf(stderr, "Specify at least one path using -p option\n"); exit(1); } streaming_start_time = lsquic_time_now(); was_empty = TAILQ_EMPTY(&sports); if (0 != prog_prep(&prog)) { LSQ_ERROR("could not prep"); exit(EXIT_FAILURE); } if (!(client_ctx.hostname || prog.prog_hostname)) { fprintf(stderr, "Specify hostname (used for SNI and :authority) via " "-H option\n"); exit(EXIT_FAILURE); } if (was_empty && token) sport_set_token(TAILQ_LAST(&sports, sport_head), token); if (client_ctx.qif_file) { if (0 != prog_connect(&prog, NULL, 0)) { LSQ_ERROR("connection failed"); exit(EXIT_FAILURE); } } else create_connections(&client_ctx); LSQ_DEBUG("entering event loop"); s = prog_run(&prog); // if (stats_fh) // { // elapsed = (long double) (lsquic_time_now() - streaming_start_time) / 1000000; // fprintf(stats_fh, "\noverall statistics as calculated by %s:\n", argv[0]); // display_stat(stats_fh, &s_stat_to_conn, "time for connect"); // display_stat(stats_fh, &s_stat_req, "time for request"); // display_stat(stats_fh, &s_stat_ttfb, "time to 1st byte"); // fprintf(stats_fh, "downloaded %lu application bytes in %.3Lf seconds\n", // s_stat_downloaded_bytes, elapsed); // fprintf(stats_fh, "%.2Lf reqs/sec; %.0Lf bytes/sec\n", // (long double) s_stat_req.n / elapsed, // (long double) s_stat_downloaded_bytes / elapsed); // fprintf(stats_fh, "read handler count %lu\n", prog.prog_read_count); int seg_idx, layer_idx; printf("=======================Streaming session status=======================\n"); printf("StartTime\t EndTime\t SegID\t #Layers\t LayerID\t Bitrate\t Throughput\t Buffer\t StreamID\t DownloadTime\n"); // for ( seg_idx = 0; seg_idx < MAX_SEGMENT_ID && segment[seg_idx].num_layers != 0; seg_idx ++) for ( seg_idx = 0; seg_idx < hung_max_seg_id_consideration; seg_idx ++) { if (seg_idx < hung_max_seg_id_consideration) sum_avg_quality += segment[seg_idx].num_layers; if (seg_idx < hung_max_seg_id_consideration-1 && segment[seg_idx].num_layers > segment[seg_idx+1].num_layers) { sum_switch_num ++; sum_avg_switch += segment[seg_idx].num_layers - segment[seg_idx+1].num_layers; } for (layer_idx = 0; layer_idx < segment[seg_idx].num_layers; layer_idx ++) { if (!segment[seg_idx].layer[layer_idx].throughput){ continue;} // in case of terminated layers printf("%.3Lf\t %.3Lf\t %d\t %d\t %d\t %d\t %.0f\t %.0f\t %"PRIu64"\t %.0Lf\n", segment[seg_idx].layer[layer_idx].start_download_time/1000, segment[seg_idx].layer[layer_idx].end_download_time/1000, seg_idx, segment[seg_idx].num_layers, layer_idx, segment[seg_idx].layer[layer_idx].bitrate, segment[seg_idx].layer[layer_idx].throughput, segment[seg_idx].layer[layer_idx].buffer, segment[seg_idx].layer[layer_idx].stream_id, segment[seg_idx].layer[layer_idx].download_time); } } if (minh_ABR == AGG) { printf("~~~ AGG ABR~~~\n"); } else if (minh_ABR == CURSOR) { printf("~~~ SVC_CURSOR ABR~~~\n"); } else if (minh_ABR == BACKFILLING) { printf("~~~ SVC_BACKFILLING ABR~~~\n"); } else { printf("No ABR available\n"); exit(1); } if (retrans_enable) printf("~~~ENABLE RETRANSMISSION\n"); else printf("~~~RETRANSMISSION is DISABLE\n"); // MINH killall bash ./complex if (system("sudo killall bash ./complex_4g.sh")) {printf("Killed Dummynet\n");}; if (system("sudo cp /home/minh/HTTP3_src/LSQUIC/lsquic/test/http_client.c /home/minh/HTTP3_src/LSQUIC/lsquic/complex_4g.sh /home/minh/HTTP3_src/LSQUIC/lsquic/results/")) {printf("Copied files\n");} // write on file FILE *stats_file, *summary_file; stats_file = fopen("./results/statistics.txt", "w+"); fprintf(stats_file, "StartTime\t EndTime\t SegID\t #Layers\t LayerID\t Bitrate\t Throughput\t Buffer\t StreamID\t DownloadTime\n"); for ( seg_idx = 0; seg_idx < hung_max_seg_id_consideration; seg_idx ++) { for (layer_idx = 0; layer_idx < segment[seg_idx].num_layers; layer_idx ++) { if (!segment[seg_idx].layer[layer_idx].throughput){ continue;} // in case of terminated layers fprintf(stats_file, "%.3Lf\t %.3Lf\t %d\t %d\t %d\t %d\t %.0f\t %.1f\t %"PRIu64"\t %.0Lf\n", segment[seg_idx].layer[layer_idx].start_download_time/1000, segment[seg_idx].layer[layer_idx].end_download_time/1000, seg_idx, segment[seg_idx].num_layers, layer_idx, segment[seg_idx].layer[layer_idx].bitrate, segment[seg_idx].layer[layer_idx].throughput, segment[seg_idx].layer[layer_idx].buffer/1000, segment[seg_idx].layer[layer_idx].stream_id, segment[seg_idx].layer[layer_idx].download_time); } } printf("======================= Writing on files -E =======================\n"); printf("Buffer size: %d \tBuffer exit threshold: %d\n", MINH_BUFFER_SIZE, MINH_REBUF_THRESHOLD_EXIT); summary_file = fopen("./results/summary.txt", "w+"); fprintf(summary_file, "AGG {AGG, CURSOR, BACKFILLING}: %d \tRetrans_enable: %d\n", minh_ABR, retrans_enable); fprintf(summary_file, "Buffer size: %d \tBuffer exit threshold: %d\n", MINH_BUFFER_SIZE, MINH_REBUF_THRESHOLD_EXIT); fprintf(summary_file, "Start play time: %.3f (s)\n", start_play_time/1000); fprintf(summary_file, "- sum_avg_quality = %.2f layers out of %d layers\n", sum_avg_quality/hung_max_seg_id_consideration, MAX_LAYER_ID); fprintf(summary_file, "- sum_switch_num = %d\n", sum_switch_num); fprintf(summary_file, "- sum_avg_switch = %.2f\n", (sum_switch_num > 0) ? sum_avg_switch/sum_switch_num : 0); fprintf(summary_file, "- sum_stall_num = %d\n", sum_stall_num); fprintf(summary_file, "- sum_stall_duration = %.3f s\n", (sum_stall_num > 0) ? sum_stall_duration/1000 : 0); fprintf(summary_file, "- sum_retrans_num = %d\n", retrans_num); fprintf(summary_file, "- sum_terminate_num = %d\n", terminate_num); if (terminate_num > 0) { for (seg_idx = 0; seg_idx < terminate_num; seg_idx ++) { fprintf(summary_file, "terminate stream id: %d\n", terminate_stream_id_recorder[seg_idx]); } } for (seg_idx = 0; seg_idx < retrans_num; seg_idx ++){ fprintf(summary_file, "retrans seg id: %d\n", retrans_seg_id_recorder[seg_idx]); } prog_cleanup(&prog); if (promise_fd >= 0) (void) close(promise_fd); while ((pe = TAILQ_FIRST(&client_ctx.hcc_path_elems))) { TAILQ_REMOVE(&client_ctx.hcc_path_elems, pe, next_pe); free(pe); } if (client_ctx.qif_fh) (void) fclose(client_ctx.qif_fh); exit(0 == s ? EXIT_SUCCESS : EXIT_FAILURE); }
cuponadesk/bGUI
src/helvetica_12.h
const uint8_t Helvetica12pt7bBitmaps[] PROGMEM = { 0xFF, 0xFF, 0xFF, 0xC3, 0xC0, 0xCF, 0x3C, 0xF3, 0xCF, 0x3C, 0xC0, 0x02, 0x30, 0x31, 0x01, 0x98, 0x0C, 0xC0, 0x46, 0x1F, 0xFC, 0x33, 0x01, 0x98, 0x08, 0x80, 0xC4, 0x06, 0x61, 0xFF, 0xC3, 0x10, 0x19, 0x80, 0xCC, 0x04, 0x60, 0x62, 0x00, 0x04, 0x00, 0x80, 0x7C, 0x3F, 0xE6, 0x4D, 0x89, 0xF1, 0x1E, 0x20, 0xE4, 0x0F, 0xE0, 0x7F, 0x02, 0x7C, 0x47, 0x88, 0xF1, 0x1F, 0x27, 0x7F, 0xC3, 0xE0, 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00, 0x60, 0x38, 0x1D, 0x81, 0xE0, 0x67, 0x07, 0x81, 0x9C, 0x1E, 0x0E, 0x30, 0x7C, 0x38, 0xC3, 0xB0, 0xC3, 0x0C, 0xC3, 0x0E, 0x33, 0x8C, 0x19, 0xC6, 0x70, 0x66, 0x19, 0x81, 0x98, 0x66, 0x07, 0x61, 0xD8, 0x0F, 0x83, 0xE0, 0x3C, 0x0F, 0x00, 0xF0, 0x3C, 0x03, 0xC0, 0x70, 0x06, 0x01, 0xC0, 0x70, 0x0E, 0x70, 0x38, 0x60, 0x60, 0xE1, 0xC0, 0xE7, 0x00, 0xCC, 0x01, 0xF8, 0x01, 0xE0, 0x03, 0xC0, 0x07, 0x80, 0x1F, 0x80, 0x73, 0x80, 0xC3, 0x03, 0x87, 0x0E, 0x07, 0x18, 0x0E, 0x70, 0x0E, 0x60, 0x06, 0x70, 0x0E, 0x38, 0x1C, 0x18, 0x18, 0x1C, 0x38, 0x0C, 0x30, 0x0E, 0x70, 0x07, 0xE0, 0x03, 0xC0, 0x03, 0xC0, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0xFF, 0xFF, 0xFF, 0xC0, 0x1C, 0x00, 0xE0, 0x0E, 0x00, 0xE0, 0x0E, 0x00, 0x60, 0x07, 0x00, 0x70, 0x07, 0x00, 0x70, 0x03, 0x00, 0x38, 0x03, 0x80, 0x1F, 0xFF, 0xFF, 0xF8, 0xFF, 0xF1, 0x8C, 0x63, 0x18, 0xC6, 0x31, 0x8C, 0x63, 0x18, 0xC6, 0x31, 0x8F, 0xFC, 0xC0, 0x30, 0x18, 0x04, 0x03, 0x01, 0x80, 0x40, 0x30, 0x18, 0x06, 0x03, 0x00, 0x80, 0x60, 0x30, 0x0C, 0x06, 0x01, 0x00, 0xFF, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0xFF, 0x0C, 0x03, 0x81, 0xE0, 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, 0xC0, 0x70 }; const GFXglyph Helvetica12pt7bGlyphs[] PROGMEM = { { 0, 0, 0, 7, 0, 1 }, // 0x20 ' ' { 0, 2, 17, 7, 3, -16 }, // 0x21 '!' { 5, 6, 7, 8, 1, -16 }, // 0x22 '"' { 11, 13, 17, 13, 0, -16 }, // 0x23 '#' { 39, 11, 20, 13, 1, -17 }, // 0x24 '$' { 67, 19, 16, 21, 1, -15 }, // 0x25 '%' { 105, 14, 17, 16, 1, -16 }, // 0x26 '&' { 135, 2, 7, 4, 2, -16 }, // 0x27 ''' { 137, 5, 22, 8, 2, -16 }, // 0x28 '(' { 151, 5, 22, 8, 1, -16 }, // 0x29 ')' { 165, 7, 7, 9, 1, -16 }, // 0x2A '*' { 172, 12, 12, 14, 1, -11 }, // 0x2B '+' { 190, 2, 5, 7, 2, -1 }, // 0x2C ',' { 192, 6, 2, 8, 1, -6 }, // 0x2D '-' { 194, 2, 2, 7, 2, -1 }, // 0x2E '.' { 195, 7, 17, 7, 0, -16 }, // 0x2F '/' { 210, 11, 16, 13, 1, -15 }, // 0x30 '0' { 232, 6, 16, 13, 2, -15 }, // 0x31 '1' { 244, 11, 16, 13, 1, -15 }, // 0x32 '2' { 266, 11, 16, 13, 1, -15 }, // 0x33 '3' { 288, 11, 16, 13, 1, -15 }, // 0x34 '4' { 310, 11, 16, 13, 1, -15 }, // 0x35 '5' { 332, 11, 16, 13, 1, -15 }, // 0x36 '6' { 354, 11, 16, 13, 1, -15 }, // 0x37 '7' { 376, 11, 16, 13, 1, -15 }, // 0x38 '8' { 398, 11, 16, 13, 1, -15 }, // 0x39 '9' { 420, 2, 13, 7, 3, -12 }, // 0x3A ':' { 424, 2, 16, 7, 3, -12 }, // 0x3B ';' { 428, 14, 13, 14, 0, -12 }, // 0x3C '<' { 451, 12, 7, 14, 1, -9 }, // 0x3D '=' { 462, 14, 13, 14, 0, -12 }, // 0x3E '>' { 485, 10, 17, 13, 2, -16 }, // 0x3F '?' { 507, 18, 17, 24, 3, -16 }, // 0x40 '@' { 546, 15, 17, 16, 0, -16 }, // 0x41 'A' { 578, 13, 17, 16, 2, -16 }, // 0x42 'B' { 606, 15, 17, 17, 1, -16 }, // 0x43 'C' { 638, 14, 17, 17, 2, -16 }, // 0x44 'D' { 668, 12, 17, 16, 2, -16 }, // 0x45 'E' { 694, 12, 17, 14, 2, -16 }, // 0x46 'F' { 720, 16, 17, 18, 1, -16 }, // 0x47 'G' { 754, 13, 17, 17, 2, -16 }, // 0x48 'H' { 782, 3, 17, 7, 2, -16 }, // 0x49 'I' { 789, 10, 17, 12, 0, -16 }, // 0x4A 'J' { 811, 14, 17, 16, 2, -16 }, // 0x4B 'K' { 841, 11, 17, 13, 2, -16 }, // 0x4C 'L' { 865, 16, 17, 20, 2, -16 }, // 0x4D 'M' { 899, 13, 17, 17, 2, -16 }, // 0x4E 'N' { 927, 16, 17, 18, 1, -16 }, // 0x4F 'O' { 961, 13, 17, 16, 2, -16 }, // 0x50 'P' { 989, 16, 18, 18, 1, -16 }, // 0x51 'Q' { 1025, 14, 17, 17, 2, -16 }, // 0x52 'R' { 1055, 14, 17, 16, 1, -16 }, // 0x53 'S' { 1085, 14, 17, 14, 0, -16 }, // 0x54 'T' { 1115, 13, 17, 17, 2, -16 }, // 0x55 'U' { 1143, 14, 17, 16, 1, -16 }, // 0x56 'V' { 1173, 22, 17, 22, 0, -16 }, // 0x57 'W' { 1220, 15, 17, 16, 0, -16 }, // 0x58 'X' { 1252, 16, 17, 16, 0, -16 }, // 0x59 'Y' { 1286, 13, 17, 14, 1, -16 }, // 0x5A 'Z' { 1314, 5, 22, 7, 1, -16 }, // 0x5B '[' { 1328, 9, 17, 7, -1, -16 }, // 0x5C '\' { 1348, 4, 22, 7, 1, -16 }, // 0x5D ']' { 1359, 10, 10, 11, 1, -16 }, // 0x5E '^' { 1372, 13, 1, 13, 0, 3 }, // 0x5F '_' { 1374, 5, 3, 8, 0, -16 }, // 0x60 '`' { 1376, 12, 13, 13, 1, -12 }, // 0x61 'a' { 1396, 11, 17, 13, 1, -16 }, // 0x62 'b' { 1420, 10, 13, 12, 1, -12 }, // 0x63 'c' { 1437, 11, 17, 13, 1, -16 }, // 0x64 'd' { 1461, 11, 13, 13, 1, -12 }, // 0x65 'e' { 1479, 6, 17, 7, 0, -16 }, // 0x66 'f' { 1492, 10, 18, 13, 1, -12 }, // 0x67 'g' { 1515, 10, 17, 13, 2, -16 }, // 0x68 'h' { 1537, 2, 17, 5, 2, -16 }, // 0x69 'i' { 1542, 4, 22, 5, 0, -16 }, // 0x6A 'j' { 1553, 11, 17, 12, 1, -16 }, // 0x6B 'k' { 1577, 2, 17, 5, 2, -16 }, // 0x6C 'l' { 1582, 16, 13, 20, 2, -12 }, // 0x6D 'm' { 1608, 10, 13, 13, 2, -12 }, // 0x6E 'n' { 1625, 11, 13, 13, 1, -12 }, // 0x6F 'o' { 1643, 11, 18, 13, 1, -12 }, // 0x70 'p' { 1668, 11, 18, 13, 1, -12 }, // 0x71 'q' { 1693, 6, 13, 8, 2, -12 }, // 0x72 'r' { 1703, 10, 13, 12, 1, -12 }, // 0x73 's' { 1720, 6, 16, 7, 0, -15 }, // 0x74 't' { 1732, 10, 13, 13, 1, -12 }, // 0x75 'u' { 1749, 12, 13, 12, 0, -12 }, // 0x76 'v' { 1769, 17, 13, 17, 0, -12 }, // 0x77 'w' { 1797, 11, 13, 12, 0, -12 }, // 0x78 'x' { 1815, 11, 18, 12, 0, -12 }, // 0x79 'y' { 1840, 10, 13, 12, 1, -12 }, // 0x7A 'z' { 1857, 7, 22, 8, 0, -16 }, // 0x7B '{' { 1877, 2, 17, 6, 2, -16 }, // 0x7C '|' { 1882, 8, 22, 8, 0, -16 }, // 0x7D '}' { 1904, 14, 5, 14, 0, -8 } }; // 0x7E '~' const GFXfont Helvetica12pt7b PROGMEM = { (uint8_t *)Helvetica12pt7bBitmaps, (GFXglyph *)Helvetica12pt7bGlyphs, 0x20, 0x7E, 24 }; // Approx. 2585 bytes
cuponadesk/bGUI
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 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x01, 0xF0, 0x1F, 0x03, 0xE0, 0xFC, 0x0F, 0x00, 0xFC, 0x03, 0xE0, 0x1F, 0x01, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xFF, 0x0F, 0xF0, 0x7F, 0x01, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF8, 0x0F, 0xC0, 0xFE, 0x0F, 0xF0, 0x1F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xFC, 0x07, 0xF0, 0x0F, 0x07, 0xF0, 0xFC, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0x00, 0xF0, 0x1F, 0x0F, 0xF0, 0xFE, 0x0F, 0xC0, 0xF8, 0x00, 0x00, 0x01, 0x0F, 0x80, 0x67, 0xFE, 0x3B, 0xFF, 0xFF, 0xFF, 0xFF, 0xB8, 0x7F, 0xC4, 0x03, 0xE2, 0x00, 0x00 }; const GFXglyph Helvetica20pt7bGlyphs[] PROGMEM = { { 0, 0, 0, 11, 0, 1 }, // 0x20 ' ' { 0, 5, 28, 11, 3, -27 }, // 0x21 '!' { 18, 11, 11, 17, 3, -27 }, // 0x22 '"' { 34, 19, 27, 22, 1, -26 }, // 0x23 '#' { 99, 20, 36, 22, 1, -31 }, // 0x24 '$' { 189, 33, 29, 39, 3, -27 }, // 0x25 '%' { 309, 25, 28, 25, 1, -27 }, // 0x26 '&' { 397, 4, 11, 11, 3, -27 }, // 0x27 ''' { 403, 9, 35, 11, 2, -27 }, // 0x28 '(' { 443, 9, 35, 11, 0, -27 }, // 0x29 ')' { 483, 13, 12, 14, 1, -27 }, // 0x2A '*' { 503, 20, 20, 23, 2, -19 }, // 0x2B '+' { 553, 5, 11, 11, 3, -4 }, // 0x2C ',' { 560, 11, 4, 15, 2, -12 }, // 0x2D '-' { 566, 5, 5, 11, 3, -4 }, // 0x2E '.' { 570, 16, 28, 14, -1, -27 }, // 0x2F '/' { 626, 19, 28, 22, 1, -27 }, // 0x30 '0' { 693, 12, 27, 22, 2, -26 }, // 0x31 '1' { 734, 18, 28, 22, 2, -27 }, // 0x32 '2' { 797, 19, 28, 22, 1, -27 }, // 0x33 '3' { 864, 19, 27, 22, 1, -26 }, // 0x34 '4' { 929, 19, 27, 22, 1, -26 }, // 0x35 '5' { 994, 19, 28, 22, 1, -27 }, // 0x36 '6' { 1061, 19, 27, 22, 1, -26 }, // 0x37 '7' { 1126, 19, 28, 22, 1, -27 }, // 0x38 '8' { 1193, 19, 28, 22, 1, -27 }, // 0x39 '9' { 1260, 5, 20, 11, 3, -19 }, // 0x3A ':' { 1273, 5, 26, 11, 3, -19 }, // 0x3B ';' { 1290, 20, 20, 23, 2, -19 }, // 0x3C '<' { 1340, 20, 12, 23, 2, -15 }, // 0x3D '=' { 1370, 20, 20, 23, 2, -19 }, // 0x3E '>' { 1420, 18, 28, 22, 2, -27 }, // 0x3F '?' { 1483, 27, 28, 31, 2, -27 }, // 0x40 '@' { 1578, 26, 28, 26, 0, -27 }, // 0x41 'A' { 1669, 23, 28, 27, 3, -27 }, // 0x42 'B' { 1750, 26, 28, 28, 1, -27 }, // 0x43 'C' { 1841, 24, 28, 28, 3, -27 }, // 0x44 'D' { 1925, 20, 28, 25, 3, -27 }, // 0x45 'E' { 1995, 19, 28, 23, 3, -27 }, // 0x46 'F' { 2062, 25, 28, 30, 2, -27 }, // 0x47 'G' { 2150, 22, 28, 28, 3, -27 }, // 0x48 'H' { 2227, 5, 28, 11, 3, -27 }, // 0x49 'I' { 2245, 17, 28, 21, 1, -27 }, // 0x4A 'J' { 2305, 24, 28, 27, 3, -27 }, // 0x4B 'K' { 2389, 19, 28, 22, 3, -27 }, // 0x4C 'L' { 2456, 29, 28, 35, 3, -27 }, // 0x4D 'M' { 2558, 22, 28, 28, 3, -27 }, // 0x4E 'N' { 2635, 27, 28, 30, 1, -27 }, // 0x4F 'O' { 2730, 22, 28, 26, 3, -27 }, // 0x50 'P' { 2807, 27, 31, 30, 1, -27 }, // 0x51 'Q' { 2912, 24, 28, 27, 3, -27 }, // 0x52 'R' { 2996, 23, 28, 25, 1, -27 }, // 0x53 'S' { 3077, 23, 28, 23, 0, -27 }, // 0x54 'T' { 3158, 23, 28, 28, 3, -27 }, // 0x55 'U' { 3239, 24, 28, 24, 0, -27 }, // 0x56 'V' { 3323, 37, 28, 37, 0, -27 }, // 0x57 'W' { 3453, 25, 28, 25, 0, -27 }, // 0x58 'X' { 3541, 26, 28, 25, 0, -27 }, // 0x59 'Y' { 3632, 23, 28, 25, 1, -27 }, // 0x5A 'Z' { 3713, 9, 35, 12, 3, -27 }, // 0x5B '[' { 3753, 16, 28, 14, -1, -27 }, // 0x5C '\' { 3809, 9, 35, 12, 0, -27 }, // 0x5D ']' { 3849, 17, 14, 23, 3, -26 }, // 0x5E '^' { 3879, 20, 2, 20, 0, 4 }, // 0x5F '_' { 3884, 9, 6, 9, -1, -28 }, // 0x60 '`' { 3891, 20, 20, 22, 1, -19 }, // 0x61 'a' { 3941, 20, 28, 24, 2, -27 }, // 0x62 'b' { 4011, 19, 20, 22, 1, -19 }, // 0x63 'c' { 4059, 20, 28, 24, 1, -27 }, // 0x64 'd' { 4129, 20, 20, 22, 1, -19 }, // 0x65 'e' { 4179, 12, 28, 12, 0, -27 }, // 0x66 'f' { 4221, 20, 27, 23, 1, -19 }, // 0x67 'g' { 4289, 18, 28, 22, 2, -27 }, // 0x68 'h' { 4352, 5, 28, 9, 2, -27 }, // 0x69 'i' { 4370, 8, 35, 9, -1, -27 }, // 0x6A 'j' { 4405, 19, 28, 21, 2, -27 }, // 0x6B 'k' { 4472, 5, 28, 9, 2, -27 }, // 0x6C 'l' { 4490, 30, 20, 34, 2, -19 }, // 0x6D 'm' { 4565, 18, 20, 22, 2, -19 }, // 0x6E 'n' { 4610, 21, 20, 23, 1, -19 }, // 0x6F 'o' { 4663, 20, 27, 24, 2, -19 }, // 0x70 'p' { 4731, 20, 27, 24, 1, -19 }, // 0x71 'q' { 4799, 12, 20, 14, 2, -19 }, // 0x72 'r' { 4829, 18, 20, 20, 1, -19 }, // 0x73 's' { 4874, 12, 26, 13, 0, -25 }, // 0x74 't' { 4913, 18, 20, 22, 2, -19 }, // 0x75 'u' { 4958, 20, 20, 20, 0, -19 }, // 0x76 'v' { 5008, 29, 20, 30, 1, -19 }, // 0x77 'w' { 5081, 21, 20, 21, 0, -19 }, // 0x78 'x' { 5134, 20, 27, 20, 0, -19 }, // 0x79 'y' { 5202, 18, 20, 20, 1, -19 }, // 0x7A 'z' { 5247, 12, 35, 12, 0, -27 }, // 0x7B '{' { 5300, 4, 39, 9, 2, -30 }, // 0x7C '|' { 5320, 12, 35, 12, 0, -27 }, // 0x7D '}' { 5373, 18, 8, 23, 3, -13 } }; // 0x7E '~' const GFXfont Helvetica20pt7b PROGMEM = { (uint8_t *)Helvetica20pt7bBitmaps, (GFXglyph *)Helvetica20pt7bGlyphs, 0x20, 0x7E, 48 }; // Approx. 6063 bytes
cuponadesk/bGUI
src/progress.h
<reponame>cuponadesk/bGUI<filename>src/progress.h template <typename T> struct Progress : Element { Monitor<T> * _linked; T * max; using Element::set; Progress() { } void set(const Monitor<T> & n) { Serial.printf("Creating new linked.\n"); _linked = new Monitor<T>(n); } void set( T * t) { max = t; } void draw(Adafruit_ILI9341 * etft) const override { Serial.println("Drawing Progress."); float tmp = _linked->_l; tmp = tmp / *max; tmp = tmp*(_w-2.0); tmp = (tmp<6 ? 6 : tmp); const Element * local = this; Serial.printf("Linked: %i Max: %i Bar length:%i\n", _linked->_l, *max, tmp); uint16_t x1 = LIST_HEIGHT * 1562 / 10000, x2 = LIST_HEIGHT - LIST_HEIGHT * 1875 / 10000, y1 = LIST_HEIGHT / 2, y2 = LIST_HEIGHT * 1250 / 10000, y3 = LIST_HEIGHT - LIST_HEIGHT * 1250 / 10000; Serial.printf("%i %i %i\n", this->_x, this->_y, this->_w); Serial.printf("%i %i %i %i %i\n", x1, y1, x2, y2, x2, y3); Serial.printf("%i %i %i %i %i\n", (this->_x + this->_w) - x1, y1, (this->_x + this->_w) - x2, y2, (this->_x + this->_w) - x2, y3); //TEXT BOX Serial.printf("%i %i %i %i", this->_x + LIST_HEIGHT + LIST_HEIGHT * 625 / 10000, this->_y + LIST_HEIGHT * 625 / 10000, this->_w - ( LIST_HEIGHT + LIST_HEIGHT * 625 / 10000)*2, LIST_HEIGHT - LIST_HEIGHT * 625 / 10000); etft->fillRoundRect(this->_x, this->_y, this->_w, LIST_HEIGHT, LIST_CORNER_RADIUS, LIST_TEXT_BACKGROUND_COLOR); etft->fillRoundRect(this->_x+1, this->_y+1, tmp, LIST_HEIGHT-2, LIST_CORNER_RADIUS, LIST_ARROW_COLOR); etft->drawRoundRect(this->_x, this->_y, this->_w, LIST_HEIGHT, LIST_CORNER_RADIUS, LIST_OUTLINE_COLOR); // tft->fillRoundRect(this->_x + LIST_HEIGHT + LIST_HEIGHT * 625 / 10000, this->_y + LIST_HEIGHT * 625 / 10000, this->_w - ( LIST_HEIGHT + LIST_HEIGHT * 625 / 10000)*2, LIST_HEIGHT - LIST_HEIGHT * 625 / 10000, LIST_CORNER_RADIUS, LIST_TEXT_BACKGROUND_COLOR);\ // // Serial.println("Progress done."); } bool changed() override { // Serial.println(" for change."); if(*_linked->_p!=_linked->_l) { _linked->_l = *_linked->_p; return true; } return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { ; } };
cuponadesk/bGUI
src/numpad.h
<gh_stars>0 #define NUMPAD_BMP "numpad.bmp" #define NUMPAD_TEXT_COLOR 0x0000 #define NUMPAD_BACKGROUND_COLOR 0xFFFF #define NUMPAD_CURSOR_X 12 #define NUMPAD_CURSOR_Y 31 #define DOUBLE_NUMPAD 1 #define DOUBLE_NUMPAD_NO_NEG 2 #define DOUBLE_NUMPAD_NEG_ONLY 3 #define INT_NUMPAD 4 #define INT_NUMPAD_NO_NEG 5 #define INT_NUMPAD_NEG_ONLY 6 class Numpad { const char keyboardLayout[4][3] = { { '7', '8', '9'}, { '4', '5', '6'}, { '1', '2', '3'}, { '-', '0', '.'} }; static Numpad *n_instance; bool _visible =false; bool _draw_text =false; bool _draw_numpad = false; Adafruit_ILI9341 * _tft; const GFXfont * _font; std::string _local; Numpad() { } public: bool start = false; uint8_t _type; double * _linkedD, linkedDoubleMin, linkedDoubleMax; int32_t * _linkedI, linkedIntMin, linkedIntMax; void setup(Adafruit_ILI9341 * s, const GFXfont * f) { _tft=s; _font=f; } void touch(uint16_t x, uint16_t y, uint16_t z) { if(z > 5 ) { int8_t key_row=-1, key_col=-1; if(x>4 && x < 76) key_col = 0; else if(x>84 && x < 155) key_col = 1; else if(x>164 && x < 235) key_col = 2; if(y>68 && y < 115) key_row = 0; else if(y>122 && y < 168) key_row = 1; else if(y>176 && y < 222) key_row = 2; else if(y>230 && y < 276) key_row = 3; else if(y>283 && y < 316) { key_col= -1; key_row= 4; if(x> 2 && x< 52) key_col= 0; else if(x> 70 && x< 168) key_col= 1; else if( x> 186 && x< 236) key_col= 2; } Serial.printf("%i %i %i\n", key_col, key_row, _type); if(key_row == 4 && ( key_col==0 || key_col ==2 )) { _visible=false; start=false; _draw_text=true; if(key_col) { if(_type < 4) { Serial.println("Here in double."); *_linkedD = strtod(_local.c_str(), NULL); } else { Serial.println("Here in int."); if( atoi(_local.c_str()) < linkedIntMin) { Serial.println("Here in min."); make_std_string(linkedIntMin, &_local); _visible=true; start=true; // return; } else if( atoi(_local.c_str()) > linkedIntMax) { make_std_string(linkedIntMax, &_local); _visible=true; start=true; // return; } else *_linkedI = atoi(_local.c_str()); } } } else if(key_col == 1 && key_row == 4 && _local.length()>0)//backspace { _local.pop_back(); _draw_text=true; } else if(key_col!=-1&&key_row!=-1) { if(key_row == 3 && (key_col == 0 || key_col ==2)) { Serial.printf("Attempting to insert. Row %i Col %i Type %i\n", key_row, key_col, _type); if(key_col== 0 && _type!= 2 && _type!= 5) { std::string tmp {"-"}; tmp += _local; _local = tmp; } else if(key_col==2 && _type< 4) { _local += "."; } _draw_text=true; } else _local+=keyboardLayout[key_row][key_col]; _draw_text=true; } if(_draw_text==true) { if(_type < 4) { if( strtod(_local.c_str(), NULL) > linkedDoubleMax) _local= linkedDoubleMax; else if ( strtod(_local.c_str(), NULL) < linkedDoubleMin) _local= linkedDoubleMin; } else { // Serial.printf("Atoi: %i",atoi(_local.c_str())); // if( atoi(_local.c_str()) > linkedIntMax) // make_std_string(linkedIntMax, &_local); // else if( atoi(_local.c_str()) < linkedIntMin) // make_std_string(linkedIntMin, &_local); } } } std::string tmp {}; make_std_string(atoi(_local.c_str()),&tmp); if(_local!=tmp && _local!="-" && _local!="") { _draw_text=true; _local = tmp; } } void draw() { if(_draw_numpad) { drawBMP(_tft, 0,0,NUMPAD_BMP); _draw_numpad=false; } if(_draw_text) { Serial.printf("Drawing text %s\n", _local.c_str()); _tft->fillRect(5,12,225,46,0xFFFF); drawText(_tft, NUMPAD_CURSOR_X, NUMPAD_CURSOR_Y, 0, _local.c_str(), MIDDLE_LEFT, _font, false, NUMPAD_TEXT_COLOR, NUMPAD_BACKGROUND_COLOR ); // Serial.printf("%i %i %i %i\n", x1,y1,w,h); _draw_text=false; } } static Numpad *instance() { if (!n_instance) n_instance = new Numpad; return n_instance; } bool active() { if(!_visible && start!=_visible) { _visible = true; _draw_numpad = true; _draw_text = true; if(_type < 4) { make_std_string(*_linkedD, &_local); } else { make_std_string(*_linkedI, &_local); } } if(_visible) { // Serial.println("Keyboard active."); return true; } return false; } }; // Allocating and initializing GlobalClass's // static data member. The pointer is being // allocated - not the object inself. Numpad *Numpad::n_instance = 0;
cuponadesk/bGUI
src/textarea.h
<reponame>cuponadesk/bGUI<gh_stars>0 template <typename T> struct Textarea : Element { Monitor<T> * _linked; using Element::set; void set(const Monitor<T> & n) { Serial.printf("Creating new linked.\n"); _linked = new Monitor<T>(n); } void draw(Adafruit_ILI9341 * etft) const override { Serial.println("Drawing Text Area."); const Element * local = this; uint16_t x1 = LIST_HEIGHT * 1562 / 10000, x2 = LIST_HEIGHT - LIST_HEIGHT * 1875 / 10000, y1 = LIST_HEIGHT / 2, y2 = LIST_HEIGHT * 1250 / 10000, y3 = LIST_HEIGHT - LIST_HEIGHT * 1250 / 10000; Serial.printf("%i %i %i\n", this->_x, this->_y, this->_w); Serial.printf("%i %i %i %i %i\n", x1, y1, x2, y2, x2, y3); Serial.printf("%i %i %i %i %i\n", (this->_x + this->_w) - x1, y1, (this->_x + this->_w) - x2, y2, (this->_x + this->_w) - x2, y3); //TEXT BOX Serial.printf("%i %i %i %i", this->_x + LIST_HEIGHT + LIST_HEIGHT * 625 / 10000, this->_y + LIST_HEIGHT * 625 / 10000, this->_w - ( LIST_HEIGHT + LIST_HEIGHT * 625 / 10000)*2, LIST_HEIGHT - LIST_HEIGHT * 625 / 10000); etft->fillRoundRect(this->_x, this->_y, this->_w, LIST_HEIGHT, LIST_CORNER_RADIUS, LIST_TEXT_BACKGROUND_COLOR); etft->drawRoundRect(this->_x, this->_y, this->_w, LIST_HEIGHT, LIST_CORNER_RADIUS, LIST_OUTLINE_COLOR); // tft->fillRoundRect(this->_x + LIST_HEIGHT + LIST_HEIGHT * 625 / 10000, this->_y + LIST_HEIGHT * 625 / 10000, this->_w - ( LIST_HEIGHT + LIST_HEIGHT * 625 / 10000)*2, LIST_HEIGHT - LIST_HEIGHT * 625 / 10000, LIST_CORNER_RADIUS, LIST_TEXT_BACKGROUND_COLOR); int16_t availTextWidth = this->_w - 16; Serial.printf("\nAvailable text space %i %i %i\n", availTextWidth, this->_x+availTextWidth/2, this->_y+y2); std::string temp {}; make_std_string(_linked->_l, &temp); Serial.printf("Text: %s\n", temp.c_str()); drawText(etft, this->_x + (this->_w/2), this->_y+ LIST_HEIGHT/2, availTextWidth, temp.c_str(), MIDDLE_CENTER, SMALL_FONT, 0, LIST_TEXT_COLOR, LIST_TEXT_BACKGROUND_COLOR); Serial.println("lkasdjf"); } bool changed() override { // Serial.println(" for change."); if(*_linked->_p!=_linked->_l) { _linked->_l = *_linked->_p; return true; } return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { ; } };
cuponadesk/bGUI
src/keyboard.h
<gh_stars>0 class barKey { #define KEYBOARD_LOWERCASE_BMP "keylow.bmp" #define KEYBOARD_UPPERCASE_BMP "keyupp.bmp" #define KEYBOARD_TEXT_COLOR 0x0000 #define KEYBOARD_BACKGROUND_COLOR 0xFFFF #define KEYBOARD_CURSOR_X 12 #define KEYBOARD_CURSOR_Y 31 private: barKey(){ }; const char keyboardLayout[2][7][7] = { { { '1', '2', '3', '4', '5', '-', '='}, { '6', '7', '8', '9', '0', ',', '.'}, { 'a', 'b', 'c', 'd', 'e', 'f', 'g'}, { 'h', 'i', 'j', 'k', 'l', 'm', 'n'}, { 'o', 'p', 'q', 'r', 's', 't', 'u'}, { 0, 'v', 'w', 'x', 'y', 'z', 0 }, { 0, ' ', 0, 0, 0, 0, 0 }}, { { '!', '@', '#', '$', '%', '-', '+'}, { '^', '&', '*', '(', ')', '?', '/'}, { 'A', 'B', 'C', 'D', 'E', 'F', 'G'}, { 'H', 'I', 'J', 'K', 'L', 'M', 'N'}, { 'O', 'P', 'Q', 'R', 'S', 'T', 'U'}, { 0, 'V', 'W', 'X', 'Y', 'Z', 0 }, { 0, ' ', 0, 0, 0, 0, 0 }} }; char loca_text[MAX_STRING_LENGTH+1]; char * linked_variable; bool shift=false, active=false, draw_keyboard = false, draw_text=false; uint16_t max_text_height; Adafruit_ILI9341 * tft; const GFXfont *font; public: bool visible=false; void begin(Adafruit_ILI9341 * tft, const GFXfont * font) { tft = tft; font = font; int16_t x1, y1; uint16_t w,h; tft->setTextWrap(false); char displayText[] = "QWTYGB?()ygq"; tft->getTextBounds(displayText, 0, 0, &x1, &y1, &w, &h); Serial.printf("%i %i %i %ip\n", x1,y1,w,h); max_text_height=h; } void activate(char * linked_variable) { Serial.printf("Got text:%s\n",linked_variable); shift = false; visible = true; draw_keyboard = true; draw_text=true; linked_variable=linked_variable; strncpy(loca_text, linked_variable,MAX_STRING_LENGTH); } bool active() { return visible; } void draw() { if(draw_keyboard) { if(shift) tft->drawBMP(0,0,KEYBOARD_UPPERCASE_BMP); else tft->drawBMP(0,0,KEYBOARD_LOWERCASE_BMP); draw_keyboard=false; } if(draw_text) { Serial.printf("Drawing text %s\n", loca_text); int16_t x1, y1; uint16_t w, h; tft->setTextWrap(false); tft->setFont(font); tft->getTextBounds(loca_text, 0, 0, &x1, &y1, &w, &h); tft->setTextColor(KEYBOARD_TEXT_COLOR); tft->fillRect(KEYBOARD_CURSOR_X-x1, 10, 232-KEYBOARD_CURSOR_X-x1,45, KEYBOARD_BACKGROUND_COLOR); tft->setCursor(KEYBOARD_CURSOR_X-x1, 40); Serial.printf("%i %i %i %i\n", x1,y1,w,h); tft->print(loca_text); draw_text=false; } } void touch(int16_t x, int16_t y, int16_t z) { if(z > 5) { int8_t key_row=-1, key_col=-1; if(x>2 && x < 33) key_col = 0; else if(x>36 && x < 67) key_col = 1; else if(x>70 && x < 101) key_col = 2; else if(x>104 && x < 135) key_col = 3; else if(x>138 && x < 169) key_col = 4; else if(x>172 && x < 204) key_col = 5; else if(x>207 && x < 238) key_col = 6; if(y>61 && y < 94) key_row = 0; else if(y>97 && y < 130) key_row = 1; else if(y>135 && y < 168) key_row = 2; else if(y>171 && y < 204) key_row = 3; else if(y>207 && y < 240) key_row = 4; else if(y>243 && y < 276) key_row = 5; else if(y>282 && y < 315) { key_col = -1; key_row = 6; if(x > 2 && x < 52) { key_col=0; } if(x > 70 && x < 169) { key_col=1; } else if(x > 186 && x < 235) { key_col=2; } } Serial.printf("%i %i\n", key_col, key_row); if(key_row == 6 && (key_col==0 || key_col ==2 )) { visible=false; if(key_col) { strncpy(linked_variable,loca_text,MAX_STRING_LENGTH); } } else if(key_col ==0 && key_row ==5) //shift { shift = !shift; draw_keyboard=true; draw_text = true; } else if(key_col == 6 && key_row == 5 && strlen(loca_text)>0)//backspace { loca_text[strlen(loca_text)-1]='\0'; draw_text=true; } else if(key_col!=-1&&key_row!=-1) { if(strlen(loca_text)<MAX_STRING_LENGTH) { loca_text[strlen(loca_text)]=keyboardLayout[shift][key_row][key_col]; loca_text[strlen(loca_text)]='\0'; draw_text=true; } } } } };
cuponadesk/bGUI
src/bargui.h
<gh_stars>0 #ifndef _BARGUI_ #define _BARGUI_ #include "gui_settings.h" enum shape_name : uint8_t { point = 0, line =1, triangle=3, rectangle=4, polygon=5}; //templated setter for many types template <typename T> struct Setter { T _i; Setter(const T & i) : _i(i) { } operator T() const {return _i;} }; //setter for each parameter //0x0103 First two digits aka 01 means window number // Second two digits aka 03 reference unique item number template <typename T> struct Monitor { T _l; T * _p = nullptr; Monitor() { _p=nullptr; } Monitor(T * l) : _p(l), _l(*l) { } operator T() const { return *_p;} bool changed() { if(*_p!=_l) { _l = *_p; return true; } return false; } Monitor operator=(const Monitor * b){ _p = b->_p; _l = b->_l; } Monitor operator=(const Monitor & b) { *_p = b._l; _l = b._l; } Monitor operator=(const T * t) { _p = t; _l = *t; } void set(const T * t) { _p = t; _l = *_p; } }; struct ID : Setter<uint16_t> { using Setter::Setter; }; struct X : Setter<int16_t> { using Setter::Setter; }; struct Y : Setter<int16_t> { using Setter::Setter; }; struct W : Setter<uint16_t> { using Setter::Setter; }; struct H : Setter<uint16_t> { using Setter::Setter; }; struct Hidden : Setter<uint8_t> { using Setter::Setter; }; struct Disabled : Setter<uint8_t> { using Setter::Setter; }; struct Func : Setter<void (*)()> { using Setter::Setter;}; struct MaxWidth : Setter<uint16_t> { using Setter::Setter; }; struct Align : Setter<uint8_t> {using Setter::Setter; }; struct Color : Setter<uint16_t> { using Setter::Setter; }; struct Words : Setter<std::string> { using Setter::Setter; }; struct BMP : Setter<std::string> { using Setter::Setter; }; struct BGColor : Setter<uint16_t> { using Setter::Setter; }; struct Font : Setter<const GFXfont * > { using Setter::Setter; }; struct Wrap : Setter<bool> {using Setter::Setter; }; struct Shape : Setter<shape_name> {using Setter::Setter;}; struct TextWrap { bool _textWrap {false}; void set(const Wrap & w) { _textWrap = w; } }; struct BackgroundColor { uint16_t _bgColor {DEFAULT_BACKGROUND_COLOR}; void set(const BGColor & c) { _bgColor = c; } }; struct DisplayColor { uint16_t _color {DEFAULT_TEXT_COLOR}; void set(const Color & c) { _color = c; } }; struct DisplayFont { const GFXfont * _font {DEFAULT_TEXT_FONT}; void set(const Font & f) { _font = f; } }; struct Alignment { uint8_t _align {DEFAULT_TEXT_ALIGN}; void set(const Align & a) { _align = a; } }; struct DisplayText : DisplayFont, BackgroundColor, DisplayColor, Alignment, TextWrap { std::string _displayString {}; using DisplayFont::set; using BackgroundColor::set; using DisplayColor::set; using Alignment::set; using TextWrap::set; void set(const Words & w) { _displayString = w; } }; struct Bitmap { std::string _bmp {""}; void set(const BMP & b) { _bmp = b; } }; struct Action { void (*_callbackFunc)() = nullptr; void set(const Func & f) { Serial.printf("New callback\n" ); _callbackFunc = f; } }; struct Element { uint16_t _id; int16_t _x, _y; uint16_t _w {0}, _h {0}; bool _hidden {false}, _disabled {false}; virtual void draw(Adafruit_ILI9341 * _tft ) const { } virtual bool changed() { } virtual void touch(uint16_t x, uint16_t y,uint16_t z){ } virtual ~Element() { } int16_t xPos() { return _x; } void set(const ID & n ) { _id = n; } void set(const X & x) { _x = x; } void set (const Y & y) { _y = y; } void set (const W & w) { _w = w; } void set (const H & h) { _h = h; } void set (const Hidden & hidden) { _hidden = hidden; } void set (const Disabled & d) { _disabled = d; } }; #define BUFFPIXEL 60 static uint16_t read16(File &f) { uint16_t result; ((uint8_t *)&result)[0] = f.read(); // LSB ((uint8_t *)&result)[1] = f.read(); // MSB return result; } static uint32_t read32(File &f) { uint32_t result; ((uint8_t *)&result)[0] = f.read(); // LSB ((uint8_t *)&result)[1] = f.read(); ((uint8_t *)&result)[2] = f.read(); ((uint8_t *)&result)[3] = f.read(); // MSB return result; } static void drawBMP( Adafruit_ILI9341 * tft, int16_t x, int16_t y, const std::string * bFile) { char filename[12]; strncpy(filename, bFile->c_str(), 12); File bmpFile; int bmpWidth, bmpHeight; // W+H in pixels uint8_t bmpDepth; // Bit depth (currently must be 24) uint32_t bmpImageoffset; // Start of image data in file uint32_t rowSize; // Not always = bmpWidth; may have padding uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer boolean goodBmp = false; // Set to true on valid header parse boolean flip = true; // BMP is stored bottom-to-top int w, h, row, col, x2, y2, bx1, by1; uint8_t r, g, b; uint32_t pos = 0, startTime = millis(); uint16_t _width = tft->width(); uint16_t _height = tft->height(); if((x >= _width) || (y >= _height)) return; Serial.println(); Serial.print(F("Loading image '")); Serial.print(filename); Serial.println('\''); // Open requested file on SD card if ((bmpFile = SD.open(filename)) == NULL) { Serial.print(F("File not found")); return; } // Parse BMP header if(read16(bmpFile) == 0x4D42) { // BMP signature Serial.print(F("File size: ")); Serial.println(read32(bmpFile)); (void)read32(bmpFile); // Read & ignore creator bytes bmpImageoffset = read32(bmpFile); // Start of image data Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC); // Read DIB header Serial.print(F("Header size: ")); Serial.println(read32(bmpFile)); bmpWidth = read32(bmpFile); bmpHeight = read32(bmpFile); if(read16(bmpFile) == 1) { // # planes -- must be '1' bmpDepth = read16(bmpFile); // bits per pixel Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth); if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed goodBmp = true; // Supported BMP format -- proceed! Serial.print(F("Image size: ")); Serial.print(bmpWidth); Serial.print('x'); Serial.println(bmpHeight); // BMP rows are padded (if needed) to 4-byte boundary rowSize = (bmpWidth * 3 + 3) & ~3; // If bmpHeight is negative, image is in top-down order. // This is not canon but has been observed in the wild. if(bmpHeight < 0) { bmpHeight = -bmpHeight; flip = false; } // Crop area to be loaded x2 = x + bmpWidth - 1;// Lower-right corner y2 = y + bmpHeight - 1; if((x2 >= 0) && (y2 >= 0)) { // On screen? w = bmpWidth; // Width/height of section to load/display h = bmpHeight; bx1 = by1 = 0; // UL coordinate in BMP file if(x < 0) { // Clip left bx1 = -x; x = 0; w = x2 + 1; } if(y < 0) { // Clip top by1 = -y; y = 0; h = y2 + 1; } if(x2 >= _width) w = _width - x; // Clip right if(y2 >= _height) h = _height - y; // Clip bottom // Set TFT address window to clipped image bounds tft->startWrite(); // Requires start/end transaction now tft->setAddrWindow(x, y, w, h); for (row=0; row<h; row++) { // For each scanline... // Seek to start of scan line. It might seem labor- // intensive to be doing this on every line, but this // method covers a lot of gritty details like cropping // and scanline padding. Also, the seek only takes // place if the file position actually needs to change // (avoids a lot of cluster math in SD library). if(flip) // Bitmap is stored bottom-to-top order (normal BMP) pos = bmpImageoffset + (bmpHeight - 1 - (row + by1)) * rowSize; else // Bitmap is stored top-to-bottom pos = bmpImageoffset + (row + by1) * rowSize; pos += bx1 * 3; // Factor in starting column (bx1) if(bmpFile.position() != pos) { // Need seek? tft->endWrite(); // End TFT transaction bmpFile.seek(pos); buffidx = sizeof(sdbuffer); // Force buffer reload tft->startWrite(); // Start new TFT transaction } for (col=0; col<w; col++) { // For each pixel... // Time to read more pixel data? if (buffidx >= sizeof(sdbuffer)) { // Indeed tft->endWrite(); // End TFT transaction bmpFile.read(sdbuffer, sizeof(sdbuffer)); buffidx = 0; // Set index to beginning tft->startWrite(); // Start new TFT transaction } // Convert pixel from BMP to TFT format, push to display b = sdbuffer[buffidx++]; g = sdbuffer[buffidx++]; r = sdbuffer[buffidx++]; tft->writePixel(tft->color565(r,g,b)); } // end pixel } // end scanline tft->endWrite(); // End last TFT transaction } // end onscreen Serial.print(F("Loaded in ")); Serial.print(millis() - startTime); Serial.println(" ms"); } // end goodBmp } } bmpFile.close(); if(!goodBmp) Serial.println(F("BMP format not recognized.")); } static void drawBMP(Adafruit_ILI9341 * tft, int16_t x, int16_t y, const char * bFile) { std::string temp = bFile; drawBMP(tft, x, y, &temp); } static uint16_t getTextWidth(Adafruit_ILI9341 * etft, const std::string * str, const GFXfont * font) { Serial.printf("Getting text width %s\n", str->c_str()); char buff[32] = {}; sprintf(buff, "%s", str->c_str()); int16_t x1, y1; uint16_t w, h; etft->setTextWrap(false); etft->setFont(font); etft->getTextBounds(buff, 0, 0, &x1, &y1, &w, &h); return w; } void drawText(Adafruit_GFX * tft, const int16_t & x, const int16_t & y, uint16_t const & width, const char * displayText, const uint8_t & align, const GFXfont * textSize, const bool text_wrap, const uint16_t & color, const uint16_t & bgColor ) { Serial.printf("Drawing text %s\n", displayText); int16_t x1, y1; uint16_t w, h, max_height, accender_height; tft->setTextWrap(text_wrap); tft->setFont(textSize); tft->getTextBounds("YgAqQa", 0, 0, &x1, &y1, &w, &max_height); tft->getTextBounds("Yt", 0, 0, &x1, &y1, &w, &accender_height); uint8_t newLen = strlen(displayText)+1; char tmpTxt[newLen]; strncpy(tmpTxt,displayText, strlen(displayText)); tmpTxt[strlen(displayText)]='\0'; tft->getTextBounds(tmpTxt, 0, 0, &x1, &y1, &w, &h); if (w > width && width) { do { tmpTxt[strlen(tmpTxt) - 4] = '.'; tmpTxt[strlen(tmpTxt) - 3] = '.'; tmpTxt[strlen(tmpTxt) - 2] = '\0'; tft->getTextBounds(tmpTxt, 0, 0, &x1, &y1, &w, &h); } while (w > width && strlen(tmpTxt) > 2); } Serial.println(max_height); Serial.println(accender_height); Serial.println(h); switch (align) { case TOP_LEFT: case MIDDLE_LEFT: case BOTTOM_LEFT: x1 = x; break; case TOP_CENTER: case MIDDLE_CENTER: case BOTTOM_CENTER: x1 = x - w / 2; break; case TOP_RIGHT: case MIDDLE_RIGHT: case BOTTOM_RIGHT: x1 = x - w; break; } switch (align) { case TOP_LEFT: case TOP_CENTER: case TOP_RIGHT: y1 = y + accender_height; break; case MIDDLE_LEFT: case MIDDLE_CENTER: case MIDDLE_RIGHT: y1 = y + accender_height/2; break; case BOTTOM_LEFT: case BOTTOM_CENTER: case BOTTOM_RIGHT: y1 = y - max_height - accender_height; break; } tft->setTextColor(color); if (bgColor != 0xabcd) { tft->fillRect(x1, y1-accender_height, w, max_height, bgColor); } Serial.printf("x1: %i, y1: %i, tmpTxt: %s\n", x1, y1, tmpTxt); tft->setCursor(x1, y1); tft->print(tmpTxt); } void drawText(Adafruit_GFX * tft, const int16_t & x, const int16_t & y, uint16_t const & width, const int32_t &displayText, const uint8_t & align, const GFXfont * textSize, const bool text_wrap, const uint16_t & color, const uint16_t & bgColor ) { char temp[12]; sprintf(temp, "%d", displayText ); drawText(tft, x, y, width, temp, align, textSize, text_wrap, color, bgColor ); } void drawText(Adafruit_GFX * tft, const int16_t & x, const int16_t & y, uint16_t const & width, const double &displayText, const uint8_t & align, const GFXfont * textSize, const bool text_wrap, const uint16_t & color, const uint16_t & bgColor ) { char temp[12]; sprintf(temp, "%0.2f", displayText ); drawText(tft, x, y, width, temp, align, textSize, text_wrap, color, bgColor ); } static void make_std_string(const int32_t & i, std::string * str) { char temp[12] {}; itoa(i, temp, 10); *str = std::string(temp); } static void make_std_string(const double & d, std::string * str) { char temp[12] {}; sprintf(temp,"%f",d); *str = std::string(temp); } static void make_std_string( std::string s, std::string * str) { *str = s; } // template <typename T> // class ElementList // { // private: // template <typename S> // struct ElementPtr { // S * _node; // T * _next=null; // }; // // ElementPtr<T> * _first = nullptr; // template <typename R> // void add(R * r) // { // if(_first==nullptr) // _first->_n // temp-> // } // // } struct Scene { bool _drawAll; std::vector<Element *> v; uint8_t _curWin, window; Adafruit_ILI9341 * _tft; uint32_t refreshInterval {0}, nextUpdate {0}, currentTime {0}; void begin(Adafruit_ILI9341 * tft) { _tft = tft; } int win() { return _curWin; } void drawAll(const bool & b) { _drawAll = b; } void setWindow(uint8_t window) { _drawAll=true; this->window = window; } void draw() { currentTime=millis(); if(nextUpdate > currentTime && _drawAll==false ) return; nextUpdate=currentTime+refreshInterval; uint16_t bg=0x0000; for (auto& f : v) { if(_curWin == f->_id >> 8 && (f->changed() || _drawAll) && f->_hidden==false) { Serial.printf("Item id: %i >>8: %i\n", f->_id, f->_id>>8); f->draw(_tft); } } drawAll(false); } void touch(const TS_Point * loc) { for (auto& f : v) { if(_curWin == f->_id >> 8 && f->_disabled==false) { // Serial.printf("ID: %o\n", f->_id); if(loc->x >= f->_x && loc->x <= f->_x+f->_w && loc->y >= f->_y && loc->y <= f->_y+f->_h && loc->z> 0 ) { f->touch(loc->x-f->_x, loc->y-f->_y, loc->z); } } } if(_curWin!=window) { _curWin=window; } } Element * getItemByID(const uint16_t & id) { for( const auto& f : v) { if(f->_id == id) return f; } } //here we go, this is the standard function with recursion template<typename T, typename S, typename ... Args> void apply(T& t, const S & setter, Args&& ... args) { t.set(setter); apply(t, std::forward<Args>(args) ...); } //this terminates the recursion template<typename T, typename S> void apply(T& t, const S & setter) { t.set(setter); } //this is for the empty args call template<typename T> void apply(T&) { Serial.printf("Warning: no parameters set for an object\n"); } //here is the interface function template<typename T, typename ... Args> T * add(Args&& ... args ) { T * t(new T()); apply(*t, std::forward<Args>(args) ...); Serial.printf("t's old address: %i\n", &t); v.emplace_back(t); Serial.printf("t's new address: %i v.back address %i\n",&t, &v.back()); return t; } }; #include "newkeyboard.h" #include "numpad.h" #include "checkbox.h" #include "radio.h" #include "background.h" #include "text.h" #include "button.h" #include "invisible.h" #include "list.h" #include "textarea.h" #include "progress.h" #endif
cuponadesk/bGUI
src/radio.h
<filename>src/radio.h #include "bargui.h" #define RADIO_RADIUS 14 #define RADIO_FULL_COLOR 0x3CDE #define RADIO_EMPTY_COLOR 0xFFFF #define RADIO_OUTLINE_COLOR 0xB596 template <typename T> struct Radio : Element { Monitor<T> * _linked = nullptr; T _local={}; T _touchValue; using Element::set; Radio() { _w = RADIO_RADIUS*2; _h = RADIO_RADIUS*2; _linked = new Monitor<T>(&_local); } void set(const Monitor<T> & n) { Serial.printf("Creating new linked.\n"); delete _linked; _linked = new Monitor<T>(n); } void set(const T & t){ _touchValue = t; } void draw(Adafruit_ILI9341 * etft) const override { const Element * local = this; Serial.println("Drawing Radio"); Serial.printf("Draw Radio x: %i y: %i state: %i\n", local->_x, local->_y, *_linked ==_touchValue); // etft->fillRoundRect( local->_x, local->_y+2, CHECK_WIDTH, CHECK_HEIGHT, CHECK_CORNER_RADIUS, SHADOW_COLOR_1); Serial.println("Made it here."); if (_linked->_l == _touchValue) etft->fillCircle( local->_x+RADIO_RADIUS, local->_y+RADIO_RADIUS, RADIO_RADIUS, RADIO_FULL_COLOR); else { etft->fillCircle( local->_x+RADIO_RADIUS, local->_y+RADIO_RADIUS, RADIO_RADIUS, RADIO_EMPTY_COLOR); etft->drawCircle( local->_x+RADIO_RADIUS, local->_y+RADIO_RADIUS, RADIO_RADIUS, RADIO_OUTLINE_COLOR); etft->drawCircle( local->_x+RADIO_RADIUS, local->_y+RADIO_RADIUS, RADIO_RADIUS-1, RADIO_OUTLINE_COLOR); } } bool changed() override { // Serial.println("Checking for change."); if(*_linked->_p!=_linked->_l) { _linked->_l = *_linked->_p; return true; } return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { if(z>5) { Serial.printf("Doing touch at %i %i %i\n", x, y, z); *_linked->_p = _touchValue; } } };
cuponadesk/bGUI
src/bar_touch.h
#include <Adafruit_STMPE610.h> #ifndef BARTOUCH_H #define BARTOUCH_H #define TS_MINX 3656 #define TS_MAXX 375 #define TS_MINY 300 #define TS_MAXY 3800 // Touch screen stuff #define MIN_TOUCH_LENGTH 50 #define TOUCH_SENSE_DELAY 25 #define TOUCH_END_TIMEOUT 200 #define REFRESH_RATE 20 #define LEFT_TO_RIGHT_SWIPE 1 #define RIGHT_TO_LEFT_SWIPE 2 #define TOP_TO_BOTTOM_SWIPE 3 #define BOTTOM_TO_TOP_SWIPE 4 #define SCREEN_PRESSED 5 #define LOCKOUT_AFTER_TOUCH 250 class barTouch { public: barTouch(Adafruit_STMPE610 * ts); TS_Point getTouch(); private: Adafruit_STMPE610 * _ts; uint32_t currentTime = 0; uint32_t _touchStart = 0; uint32_t _touchEnd = 0; uint32_t _lastTouchRefresh = 0; uint32_t _touchLockout = 500; uint16_t maxX = TS_MAXX, maxY = TS_MAXY, minX = TS_MINX, minY = TS_MINY; TS_Point _touchStartLocation; TS_Point _touchEndLocation; }; #endif
cuponadesk/bGUI
src/button.h
#define BUTTON_HEIGHT 34 #define BUTTON_RADIUS 3 #define BUTTON_TEXT_COLOR 0x0000 #define BUTTON_BG_COLOR 0xFFFF #define BUTTON_OUTLINE_COLOR 0xB596 #define BUTTON_FONT &Helvetica10pt7b template <typename T> struct Button : Element, DisplayText, Bitmap, Action { std::vector<Monitor<T> * > _linked {}; std::vector<T> _touchValue; using Element::set; using DisplayText::set; using Bitmap::set; using Action::set; void set(const Monitor<T> & n) { Serial.printf("Creating new linked.\n"); Monitor<T> * temp = new Monitor<T>(n); _linked.push_back(temp); } void set(const T & t){ _touchValue.push_back(t); } void set(const MaxWidth & w) { _w = w; } void draw(Adafruit_ILI9341 * etft) const override { const Element * local = this; uint16_t textWidth; uint16_t displayHeight; if(local->_h == 0) { displayHeight=BUTTON_HEIGHT; } else { displayHeight=local->_w; } if(local->_w == 0) { uint16_t textWidth = getTextWidth(etft, &_displayString, BUTTON_FONT); } Serial.println("Drawing Button"); Serial.printf("Draw Button x: %i y: %i width: %i\n", local->_x, local->_y, local->_w); Serial.println("Made it here."); if(_bmp!="") drawBMP(etft, local->_x, local->_y, &_bmp); else { etft->fillRoundRect( local->_x, local->_y, local->_w, displayHeight, BUTTON_RADIUS, _bgColor); etft->drawRoundRect( local->_x, local->_y, local->_w, displayHeight, BUTTON_RADIUS, BUTTON_OUTLINE_COLOR); etft->drawRoundRect( local->_x+1, local->_y+1, local->_w-2, displayHeight-2, BUTTON_RADIUS, BUTTON_OUTLINE_COLOR); } if(_displayString!="") drawText(etft, local->_x+(local->_w/2)-5, local->_y+(displayHeight/2), _w - 10, (char *)_displayString.c_str(), MIDDLE_CENTER, BUTTON_FONT, false, _color, _bgColor ); } bool changed() override { // Serial.println(" for change."); return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { if(z>5) { Serial.printf("Doing touch at %i %i %i\n", x, y, z); for(uint8_t x=0; x< _linked.size()&&_touchValue.size(); x++) *_linked[x]->_p = _touchValue[x]; Serial.println("Button Values Finished."); Serial.printf("Callback: %i equals? %i\n", _callbackFunc, (_callbackFunc==nullptr)); if(_callbackFunc!=nullptr) _callbackFunc(); Serial.println("Callback finished."); } } };
cuponadesk/bGUI
src/checkbox.h
#define CHECK_WIDTH 28 #define CHECK_HEIGHT 28 #define CHECK_CORNER_RADIUS 3 #define CHECK_FULL_COLOR 0x3CDE #define CHECK_EMPTY_COLOR 0xFFFF #define CHECK_OUTLINE_COLOR 0xB596 template <typename T> struct Checkbox : Element, Monitor<T> { Monitor<T> * _linked = nullptr; T _touchValue {}, _local {}; using Element::set; Checkbox() { _h=CHECK_HEIGHT; _w=CHECK_WIDTH; _linked = new Monitor<T>(&_local); } operator T() const { return *_linked->_p; } void set(const Monitor<T> & n) { Serial.printf("Creating new linked.\n"); if(_linked!=nullptr) delete _linked; _linked = new Monitor<T>(n); } void set(const T & t){ _touchValue = t; } void draw(Adafruit_ILI9341 * etft) const override { const Element * local = this; Serial.println("Drawing Checkbox"); Serial.printf("Draw Check x: %i y: %i state: %i\n", local->_x, local->_y, *_linked->_p); // etft->fillRoundRect( local->_x, local->_y+2, CHECK_WIDTH, CHECK_HEIGHT, CHECK_CORNER_RADIUS, SHADOW_COLOR_1); Serial.println("Made it here."); if (*_linked->_p) etft->fillRoundRect( local->_x, local->_y, CHECK_WIDTH, CHECK_HEIGHT, CHECK_CORNER_RADIUS, CHECK_FULL_COLOR); else { etft->fillRoundRect( local->_x, local->_y, CHECK_WIDTH, CHECK_HEIGHT, CHECK_CORNER_RADIUS, CHECK_EMPTY_COLOR); etft->drawRoundRect( local->_x, local->_y, CHECK_WIDTH, CHECK_HEIGHT, CHECK_CORNER_RADIUS, CHECK_OUTLINE_COLOR); etft->drawRoundRect( local->_x+1, local->_y+1, CHECK_WIDTH-2, CHECK_HEIGHT-2, CHECK_CORNER_RADIUS, CHECK_OUTLINE_COLOR); } } bool changed() override { // Serial.printf("Checking for checkbox change. %i %i\n",*_linked->_p, _linked->_l); return _linked->changed(); } void touch(uint16_t x, uint16_t y, uint16_t z) { if(z>5) { Serial.printf("Doing touch at %i %i %i\n", x, y, z); if(!*_linked->_p) *_linked->_p = _touchValue; else *_linked->_p = 0; } } };
cuponadesk/bGUI
src/list.h
<filename>src/list.h<gh_stars>0 template <typename T> struct List : Element, DisplayText { Monitor<T> * _linked; std::vector<T> _listOptions; int8_t _linkedIndex; T _local {}; using Element::set; List() { _h = DEFAULT_LIST_HEIGHT; _bgColor = DEFAULT_LIST_TEXT_BACKGROUND_COLOR; _color = DEFAULT_LIST_TEXT_COLOR; } void set(const Monitor<T> & n) { Serial.printf("Creating new linked.\n"); _linked = new Monitor<T>(n); } void set(const T & t){ Serial.println("Adding Option"); _listOptions.push_back(t); Serial.printf("Size: %i\n",_listOptions.size()); } void draw(Adafruit_ILI9341 * etft) const override { Serial.println("Drawing list."); const Element * local = this; uint16_t x1 = _h * 1562 / 10000, x2 = _h - _h * 1875 / 10000, y1 = _h / 2, y2 = _h * 1250 / 10000, y3 = _h - _h * 1250 / 10000; Serial.printf("%i %i %i\n", this->_x, this->_y, this->_w); Serial.printf("%i %i %i %i %i\n", x1, y1, x2, y2, x2, y3); Serial.printf("%i %i %i %i %i\n", (this->_x + this->_w) - x1, y1, (this->_x + this->_w) - x2, y2, (this->_x + this->_w) - x2, y3); //TEXT BOX Serial.printf("%i %i %i %i", this->_x + _h + _h * 625 / 10000, this->_y + _h * 625 / 10000, this->_w - ( _h + _h * 625 / 10000)*2, _h - _h * 625 / 10000); etft->fillRoundRect(this->_x, this->_y, this->_w, _h, LIST_CORNER_RADIUS, _bgColor); etft->drawRoundRect(this->_x, this->_y, this->_w, _h, LIST_CORNER_RADIUS, LIST_OUTLINE_COLOR); // tft->fillRoundRect(this->_x + _h + _h * 625 / 10000, this->_y + _h * 625 / 10000, this->_w - ( _h + _h * 625 / 10000)*2, _h - _h * 625 / 10000, LIST_CORNER_RADIUS, LIST_TEXT_BACKGROUND_COLOR); //LEFT_ARROW etft->fillTriangle(this->_x+x1, this->_y+y1, this->_x+x2, this->_y+y2, this->_x+x2, this->_y+y3, LIST_ARROW_COLOR); etft->drawTriangle(this->_x+x1, this->_y+y1, this->_x+x2, this->_y+y2, this->_x+x2, this->_y+y3, LIST_OUTLINE_COLOR); //RIGHT ARROW etft->fillTriangle((this->_x + this->_w) - x1, y1+this->_y, (this->_x + this->_w) - x2, y2+this->_y, (this->_x + this->_w) - x2, y3+this->_y, LIST_ARROW_COLOR); etft->drawTriangle((this->_x + this->_w) - x1, y1+this->_y, (this->_x + this->_w) - x2, y2+this->_y, (this->_x + this->_w) - x2, y3+this->_y, LIST_OUTLINE_COLOR); int16_t availTextWidth = this->_w - _h * 2 - (_h * 1250 / 10000) * 2; std::string tmp; make_std_string(_linked->_l, &tmp); Serial.printf("\nAvailable text space %i %i %i\n", availTextWidth, this->_x+availTextWidth/2, this->_y+y2); Serial.printf("Text: %s\n", tmp.c_str()); drawText(etft, this->_x + (this->_w/2), this->_y+ _h/2, availTextWidth, tmp.c_str(), MIDDLE_CENTER, SMALL_FONT, 0, _color, _bgColor); Serial.println("lkasdjf"); } bool changed() override { // Serial.println(" for change."); if(*_linked->_p!=_linked->_l) { _linked->_l = *_linked->_p; return true; } return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { if(z>5) { Serial.printf("Doing touch at %i %i %i Index: %i Size: %i\n", x, y, z, _linkedIndex, _listOptions.size()); if(x<_h+8) _linkedIndex--; else if(x>_w-_h-8) _linkedIndex++; if(_linkedIndex<0) _linkedIndex = _listOptions.size()-1; else if(_linkedIndex >= _listOptions.size()) _linkedIndex = 0; if(x<_h+8 && x < _w/2 || x>_w-_h-8 && x > _w/2) *_linked->_p = _listOptions[_linkedIndex]; } } };
cuponadesk/bGUI
src/helvetica_10.h
<gh_stars>0 static const uint8_t Helvetica10pt7bBitmaps[] = { 0x6D, 0xB6, 0xDB, 0x68, 0x7F, 0xC0, 0xDE, 0xF7, 0xBD, 0x80, 0x19, 0x08, 0x84, 0xC6, 0x6F, 0xFF, 0xFC, 0xC8, 0x44, 0xFF, 0xFF, 0xD9, 0x8C, 0xC6, 0x63, 0x20, 0x04, 0x00, 0x80, 0x7C, 0x3F, 0xE6, 0x4C, 0xC9, 0x9D, 0x01, 0xE0, 0x1F, 0x00, 0xF8, 0x13, 0x02, 0x7E, 0x4E, 0xC9, 0xDF, 0xF0, 0xF8, 0x04, 0x00, 0x80, 0x78, 0x18, 0xCC, 0x30, 0xCC, 0x20, 0x84, 0x60, 0xCC, 0xC0, 0xCC, 0x80, 0x79, 0x80, 0x01, 0x1E, 0x03, 0x33, 0x02, 0x33, 0x06, 0x21, 0x04, 0x33, 0x0C, 0x33, 0x18, 0x1E, 0x1E, 0x03, 0xF0, 0x33, 0x87, 0x38, 0x33, 0x03, 0xE0, 0x3C, 0x06, 0x66, 0xC7, 0xCC, 0x3C, 0xC1, 0xCE, 0x3C, 0xFF, 0xE3, 0xE7, 0xFF, 0xC0, 0x19, 0x9C, 0xC6, 0x73, 0x18, 0xC6, 0x31, 0x8E, 0x31, 0x8C, 0x30, 0xC0, 0xC3, 0x18, 0xE3, 0x18, 0xC7, 0x39, 0xCE, 0x63, 0x19, 0xCC, 0x66, 0x00, 0x11, 0x27, 0xF8, 0xC2, 0xCC, 0x80, 0x0C, 0x03, 0x00, 0xC0, 0x30, 0xFF, 0xFF, 0xF0, 0xC0, 0x30, 0x0C, 0x03, 0x00, 0xFF, 0x97, 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6, 5, 5, 9, 2, -13 },// 0x22 '"' { 10, 9, 14, 11, 1, -13 },// 0x23 '#' { 26, 11, 18, 11, 0, -15 },// 0x24 '$' { 51, 16, 14, 20, 2, -13 },// 0x25 '%' { 79, 12, 14, 13, 1, -13 },// 0x26 '&' { 100, 2, 5, 6, 2, -13 },// 0x27 ''' { 102, 5, 18, 6, 1, -13 },// 0x28 '(' { 114, 5, 18, 6, 0, -13 },// 0x29 ')' { 126, 7, 6, 7, 0, -13 },// 0x2A '*' { 132, 10, 10, 12, 1, -9 },// 0x2B '+' { 145, 3, 6, 6, 1, -2 },// 0x2C ',' { 148, 6, 2, 8, 1, -5 },// 0x2D '-' { 150, 3, 3, 6, 1, -2 },// 0x2E '.' { 152, 7, 14, 7, 0, -13 },// 0x2F '/' { 165, 9, 14, 11, 1, -13 },// 0x30 '0' { 181, 6, 14, 11, 1, -13 },// 0x31 '1' { 192, 9, 14, 11, 1, -13 },// 0x32 '2' { 208, 10, 14, 11, 1, -13 },// 0x33 '3' { 226, 10, 14, 11, 0, -13 },// 0x34 '4' { 244, 9, 14, 11, 1, -13 },// 0x35 '5' { 260, 9, 14, 11, 1, -13 },// 0x36 '6' { 276, 9, 14, 11, 1, -13 },// 0x37 '7' { 292, 10, 14, 11, 1, -13 },// 0x38 '8' { 310, 9, 14, 11, 1, -13 },// 0x39 '9' { 326, 3, 10, 6, 1, -9 },// 0x3A ':' { 330, 3, 13, 6, 1, -9 },// 0x3B ';' { 335, 10, 10, 12, 1, -9 },// 0x3C '<' { 348, 10, 6, 12, 1, -7 },// 0x3D '=' { 356, 10, 10, 12, 1, -9 },// 0x3E '>' { 369, 9, 14, 11, 1, -13 },// 0x3F '?' { 385, 14, 14, 16, 1, -13 },// 0x40 '@' { 410, 14, 14, 13, 0, -13 },// 0x41 'A' { 435, 11, 14, 14, 2, -13 },// 0x42 'B' { 455, 13, 14, 14, 1, -13 },// 0x43 'C' { 478, 12, 14, 14, 2, -13 },// 0x44 'D' { 499, 10, 14, 13, 2, -13 },// 0x45 'E' { 517, 9, 14, 12, 2, -13 },// 0x46 'F' { 533, 13, 14, 15, 1, -13 },// 0x47 'G' { 556, 12, 14, 14, 1, -13 },// 0x48 'H' { 577, 2, 14, 6, 2, -13 },// 0x49 'I' { 581, 9, 14, 11, 0, -13 },// 0x4A 'J' { 597, 12, 14, 14, 2, -13 },// 0x4B 'K' { 618, 9, 14, 11, 2, -13 },// 0x4C 'L' { 634, 15, 14, 18, 1, -13 },// 0x4D 'M' { 661, 12, 14, 14, 1, -13 },// 0x4E 'N' { 682, 13, 14, 15, 1, -13 },// 0x4F 'O' { 705, 11, 14, 13, 2, -13 },// 0x50 'P' { 725, 13, 15, 15, 1, -13 },// 0x51 'Q' { 750, 12, 14, 14, 2, -13 },// 0x52 'R' { 771, 11, 14, 13, 1, -13 },// 0x53 'S' { 791, 12, 14, 12, 0, -13 },// 0x54 'T' { 812, 12, 14, 14, 1, -13 },// 0x55 'U' { 833, 12, 14, 12, 0, -13 },// 0x56 'V' { 854, 19, 14, 19, 0, -13 },// 0x57 'W' { 888, 13, 14, 13, 0, -13 },// 0x58 'X' { 911, 13, 14, 13, 0, -13 },// 0x59 'Y' { 934, 12, 14, 13, 0, -13 },// 0x5A 'Z' { 955, 5, 18, 6, 1, -13 },// 0x5B '[' { 967, 7, 14, 7, 0, -13 },// 0x5C '\' { 980, 4, 18, 6, 0, -13 },// 0x5D ']' { 989, 8, 7, 12, 2, -13 },// 0x5E '^' { 996, 10, 2, 10, 0, 2 },// 0x5F '_' { 999, 5, 3, 5, -1, -14 },// 0x60 '`' { 1001, 10, 10, 11, 1, -9 },// 0x61 'a' { 1014, 11, 14, 12, 1, -13 },// 0x62 'b' { 1034, 9, 10, 11, 1, -9 },// 0x63 'c' { 1046, 10, 14, 12, 1, -13 },// 0x64 'd' { 1064, 10, 10, 11, 1, -9 },// 0x65 'e' { 1077, 6, 14, 6, 0, -13 },// 0x66 'f' { 1088, 10, 14, 12, 1, -9 },// 0x67 'g' { 1106, 9, 14, 11, 1, -13 },// 0x68 'h' { 1122, 3, 14, 5, 1, -13 },// 0x69 'i' { 1128, 4, 18, 5, 0, -13 },// 0x6A 'j' { 1137, 10, 14, 11, 1, -13 },// 0x6B 'k' { 1155, 3, 14, 5, 1, -13 },// 0x6C 'l' { 1161, 15, 10, 17, 1, -9 },// 0x6D 'm' { 1180, 9, 10, 11, 1, -9 },// 0x6E 'n' { 1192, 10, 10, 12, 1, -9 },// 0x6F 'o' { 1205, 11, 14, 12, 1, -9 },// 0x70 'p' { 1225, 10, 14, 12, 1, -9 },// 0x71 'q' { 1243, 6, 10, 7, 1, -9 },// 0x72 'r' { 1251, 9, 10, 10, 1, -9 },// 0x73 's' { 1263, 6, 13, 7, 0, -12 },// 0x74 't' { 1273, 9, 10, 11, 1, -9 },// 0x75 'u' { 1285, 10, 10, 10, 0, -9 },// 0x76 'v' { 1298, 15, 10, 16, 0, -9 },// 0x77 'w' { 1317, 11, 10, 11, 0, -9 },// 0x78 'x' { 1331, 10, 14, 10, 0, -9 },// 0x79 'y' { 1349, 10, 10, 10, 0, -9 },// 0x7A 'z' { 1362, 6, 18, 6, 0, -13 },// 0x7B '{' { 1376, 2, 20, 4, 1, -15 },// 0x7C '|' { 1381, 6, 18, 6, 0, -13 },// 0x7D '}' { 1395, 10, 4, 12, 1, -6 } }; // 0x7E '~' static const GFXfont Helvetica10pt7b = { (uint8_t *)Helvetica10pt7bBitmaps, (GFXglyph *)Helvetica10pt7bGlyphs, 0x20, 0x7E, 24 }; // Approx. 2072 bytes
cuponadesk/bGUI
src/invisible.h
template <typename T> struct Invisible : Element { Monitor<T> * _linked=NULL; T _touchValue; void (*_callbackFunc)() = NULL; // void (*functionPtr2)(T); using Element::set; void set(const Monitor<T> & n) { Serial.printf("Creating new linked.\n"); _linked = new Monitor<T>(n); } void set(const T & t){ _touchValue = t; } void set(const Func & f) { Serial.printf("New callback\n" ); _callbackFunc = f; } void draw(Adafruit_ILI9341 * etft) const override { ; } bool changed() override { // Serial.println("Checking for change."); return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { Serial.printf("Doing touch at %i %i %i\n", x, y, z); if(z>5) { if(_linked!=NULL) *_linked->_p = _touchValue; if(_callbackFunc!=NULL) _callbackFunc(); } } };
cuponadesk/bGUI
src/helvetica_14.h
<reponame>cuponadesk/bGUI<gh_stars>0 static const uint8_t Helvetica14pt7bBitmaps[] = { 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0x66, 0x66, 0x00, 0xFF, 0xF0, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0x0C, 0x70, 0x63, 0x03, 0x18, 0x18, 0xC0, 0xC6, 0x06, 0x31, 0xFF, 0xEF, 0xFF, 0x18, 0xC0, 0xC6, 0x06, 0x31, 0xFF, 0xEF, 0xFF, 0x1C, 0x60, 0xC7, 0x06, 0x30, 0x31, 0x81, 0x8C, 0x0C, 0x60, 0x01, 0x00, 0x02, 0x00, 0x04, 0x00, 0x7F, 0x03, 0xFF, 0x8F, 0x27, 0x1C, 0x47, 0x38, 0x8E, 0x71, 0x00, 0xF2, 0x00, 0xFC, 0x00, 0xFE, 0x00, 0x7F, 0x00, 0x3F, 0x00, 0x4F, 0x00, 0x8E, 0xF1, 0x1E, 0xE2, 0x39, 0xC4, 0x73, 0xC9, 0xE3, 0xFF, 0x81, 0xFC, 0x00, 0x40, 0x00, 0x80, 0x01, 0x00, 0x1E, 0x01, 0xC0, 0xFE, 0x03, 0x01, 0x8E, 0x0C, 0x07, 0x0C, 0x18, 0x0E, 0x18, 0x60, 0x1C, 0x30, 0xC0, 0x38, 0x63, 0x00, 0x31, 0xC6, 0x00, 0x7F, 0x18, 0x00, 0x7C, 0x31, 0xE0, 0x00, 0xC7, 0xF0, 0x03, 0x9C, 0x60, 0x06, 0x30, 0xE0, 0x1C, 0x61, 0xC0, 0x30, 0xC3, 0x80, 0xC1, 0x87, 0x01, 0x83, 0x8C, 0x06, 0x03, 0xF8, 0x0C, 0x03, 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x1F, 0x1C, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0xF8, 0xF0, 0xF0, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x1C, 0x1F, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0xF8, 0x38, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1F, 0x0F, 0x0F, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x38, 0xF8, 0xF0, 0x78, 0x1F, 0xE3, 0xC7, 0xF8, 0x1E }; static const GFXglyph Helvetica14pt7bGlyphs[] = { { 0, 0, 0, 8, 0, 1 },// 0x20 ' ' { 0, 4, 19, 8, 2, -18 },// 0x21 '!' { 10, 8, 7, 12, 2, -18 },// 0x22 '"' { 17, 13, 19, 15, 1, -18 },// 0x23 '#' { 48, 15, 25, 15, 0, -21 },// 0x24 '$' { 95, 23, 20, 27, 2, -18 },// 0x25 '%' { 153, 17, 19, 18, 1, -18 },// 0x26 '&' { 194, 3, 7, 8, 2, -18 },// 0x27 ''' { 197, 7, 24, 8, 1, -18 },// 0x28 '(' { 218, 6, 24, 8, 0, -18 },// 0x29 ')' { 236, 9, 8, 10, 1, -18 },// 0x2A '*' { 245, 14, 14, 16, 1, -13 },// 0x2B '+' { 270, 4, 7, 8, 2, -2 },// 0x2C ',' { 274, 8, 3, 11, 1, -8 },// 0x2D '-' { 277, 4, 3, 8, 2, -2 },// 0x2E '.' { 279, 11, 19, 10, -1, -18 },// 0x2F '/' { 306, 13, 19, 15, 1, -18 },// 0x30 '0' { 337, 8, 19, 15, 1, -18 },// 0x31 '1' { 356, 13, 19, 15, 1, -18 },// 0x32 '2' { 387, 13, 19, 15, 1, -18 },// 0x33 '3' { 418, 13, 19, 15, 1, -18 },// 0x34 '4' { 449, 13, 19, 15, 1, -18 },// 0x35 '5' { 480, 13, 19, 15, 1, -18 },// 0x36 '6' { 511, 13, 19, 15, 1, -18 },// 0x37 '7' { 542, 13, 19, 15, 1, -18 },// 0x38 '8' { 573, 13, 19, 15, 1, -18 },// 0x39 '9' { 604, 4, 14, 8, 2, -13 },// 0x3A ':' { 611, 4, 18, 8, 2, -13 },// 0x3B ';' { 620, 14, 14, 16, 1, -13 },// 0x3C '<' { 645, 14, 8, 16, 1, -10 },// 0x3D '=' { 659, 14, 14, 16, 1, -13 },// 0x3E '>' { 684, 13, 19, 15, 1, -18 },// 0x3F '?' { 715, 19, 19, 22, 1, -18 },// 0x40 '@' { 761, 18, 19, 18, 0, -18 },// 0x41 'A' { 804, 16, 19, 19, 2, -18 },// 0x42 'B' { 842, 17, 19, 20, 1, -18 },// 0x43 'C' { 883, 17, 19, 20, 2, -18 },// 0x44 'D' { 924, 14, 19, 17, 2, -18 },// 0x45 'E' { 958, 13, 19, 16, 2, -18 },// 0x46 'F' { 989, 18, 19, 21, 1, -18 },// 0x47 'G' { 1032, 16, 19, 20, 2, -18 },// 0x48 'H' { 1070, 3, 19, 8, 2, -18 },// 0x49 'I' { 1078, 12, 19, 15, 0, -18 },// 0x4A 'J' { 1107, 17, 19, 19, 2, -18 },// 0x4B 'K' { 1148, 13, 19, 16, 2, -18 },// 0x4C 'L' { 1179, 20, 19, 24, 2, -18 },// 0x4D 'M' { 1227, 16, 19, 20, 2, -18 },// 0x4E 'N' { 1265, 19, 19, 21, 1, -18 },// 0x4F 'O' { 1311, 15, 19, 18, 2, -18 },// 0x50 'P' { 1347, 19, 21, 21, 1, -18 },// 0x51 'Q' { 1397, 16, 19, 19, 2, -18 },// 0x52 'R' { 1435, 16, 19, 18, 1, -18 },// 0x53 'S' { 1473, 16, 19, 16, 0, -18 },// 0x54 'T' { 1511, 16, 19, 20, 2, -18 },// 0x55 'U' { 1549, 17, 19, 17, 0, -18 },// 0x56 'V' { 1590, 25, 19, 25, 0, -18 },// 0x57 'W' { 1650, 18, 19, 18, 0, -18 },// 0x58 'X' { 1693, 18, 19, 18, 0, -18 },// 0x59 'Y' { 1736, 15, 19, 17, 1, -18 },// 0x5A 'Z' { 1772, 6, 24, 8, 2, -18 },// 0x5B '[' { 1790, 11, 19, 10, -1, -18 },// 0x5C '\' { 1817, 6, 24, 8, 0, -18 },// 0x5D ']' { 1835, 12, 10, 16, 2, -18 },// 0x5E '^' { 1850, 14, 2, 14, 0, 3 },// 0x5F '_' { 1854, 6, 4, 7, -1, -19 },// 0x60 '`' { 1857, 14, 14, 15, 1, -13 },// 0x61 'a' { 1882, 14, 19, 17, 2, -18 },// 0x62 'b' { 1916, 13, 14, 15, 1, -13 },// 0x63 'c' { 1939, 14, 19, 17, 1, -18 },// 0x64 'd' { 1973, 13, 14, 15, 1, -13 },// 0x65 'e' { 1996, 9, 19, 9, 0, -18 },// 0x66 'f' { 2018, 14, 19, 16, 1, -13 },// 0x67 'g' { 2052, 12, 19, 16, 2, -18 },// 0x68 'h' { 2081, 3, 19, 7, 2, -18 },// 0x69 'i' { 2089, 6, 24, 7, -1, -18 },// 0x6A 'j' { 2107, 13, 19, 15, 2, -18 },// 0x6B 'k' { 2138, 3, 19, 7, 2, -18 },// 0x6C 'l' { 2146, 20, 14, 23, 2, -13 },// 0x6D 'm' { 2181, 12, 14, 16, 2, -13 },// 0x6E 'n' { 2202, 14, 14, 16, 1, -13 },// 0x6F 'o' { 2227, 14, 19, 17, 2, -13 },// 0x70 'p' { 2261, 14, 19, 17, 1, -13 },// 0x71 'q' { 2295, 8, 14, 10, 2, -13 },// 0x72 'r' { 2309, 12, 14, 14, 1, -13 },// 0x73 's' { 2330, 8, 18, 9, 0, -17 },// 0x74 't' { 2348, 12, 14, 16, 2, -13 },// 0x75 'u' { 2369, 14, 14, 14, 0, -13 },// 0x76 'v' { 2394, 21, 14, 21, 0, -13 },// 0x77 'w' { 2431, 14, 14, 15, 0, -13 },// 0x78 'x' { 2456, 14, 19, 14, 0, -13 },// 0x79 'y' { 2490, 12, 14, 14, 1, -13 },// 0x7A 'z' { 2511, 8, 24, 8, 0, -18 },// 0x7B '{' { 2535, 2, 27, 6, 2, -20 },// 0x7C '|' { 2542, 8, 24, 8, 0, -18 },// 0x7D '}' { 2566, 12, 4, 16, 2, -8 } }; // 0x7E '~' static const GFXfont Helvetica14pt7b = { (uint8_t *)Helvetica14pt7bBitmaps, (GFXglyph *)Helvetica14pt7bGlyphs, 0x20, 0x7E, 33 }; // Approx. 3244 bytes
cuponadesk/bGUI
src/background.h
<filename>src/background.h #include "gui_settings.h" struct Background : Element, BackgroundColor, Bitmap { using Bitmap::set; using Element::set; using BackgroundColor::set; auto value()->int { return false; } void draw(Adafruit_ILI9341 * tft) const override { Serial.println("Drawing background."); if (_bmp != "") { Serial.printf("Drawing background bmp %s", _bmp.c_str()); drawBMP(tft, _x, _y, &_bmp); } else { Serial.printf("Fill screen %i\n",_bgColor); tft->fillScreen(_bgColor); Serial.printf("Finished\n"); } } bool changed() { return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { ;// Serial.printf("Doing touch at %i %i %i\n", x, y, z); } };
cuponadesk/bGUI
src/barWifi.h
<reponame>cuponadesk/bGUI<gh_stars>0 #ifndef _BARWIFI_H_ #define _BARWIFI_H_ #include <memory> #include "ESP8266WiFi.h" #define MAX_SSID_LENGTH 32 #define MAX_PASSWORD_LENGTH 32 #define SCAN_LIST_MAX 6 #define RETRY_WAIT 45000 #define ON 1 #define OFF 0 static const char SAVED[] = "SAVED"; class barWifi { public: struct WiFiStation { std::string ssid, pswd=""; int rssi; int8_t enc_type; }; barWifi(); bool * conn, * strAP; wl_status_t begin(uint16_t rom_size); //reads EEPROM flags and sets up wifi. Needs size of eeprom for reading saved wifi crds bool save(const char * name, const char * pass ); //save passed network in eeprom if space available void saveAP(); //saved current ap configuration to eeprom void maintain(); //monitors connection and maintains desired settings const char * saved(uint8_t id = 0); // returns ssid at save location id void keepAlive(bool keepAlive = true); //use saved wifi cred as backup if connection fails void connectOnBoot(bool connect_on_startup = true); //connect on startup flag wl_status_t wifi(bool make_connection); //starts or stops wifi connection wl_status_t wifi(const char * ssid = SAVED, const char * password = SAVED); //set ssid and password for connection wl_status_t accessPoint(bool access_point);//starts or stops access point wl_status_t accessPoint(char * access_point_name, char * access_point_password = "", IPAddress ip = IPAddress(192, 168, 4, 1), IPAddress netmask = IPAddress(255, 255, 255, 0) ); //configures access point wl_status_t status(); //returns status of wifi connection uint8_t getScanned(); //return number of scanned units const char * getScanned(uint8_t slot);//returns name of wifi station in list std::string active();//return network currently connected to private: bool b_keep_alive, b_connect, b_access_point, b_connect_on_boot, b_ap_started, b_part_of_mesh, b_ap_on_boot; wl_status_t m_wifi_status; uint16_t ii_rom_size=512; uint32_t iii_next_connect_attempt=0; IPAddress ip_ap_ip; IPAddress ip_ap_netmask; std::string s_password, s_ssid, s_ap_name, s_ap_pswd; WiFiStation ws_list[SCAN_LIST_MAX],ws_saved[4+1]; void loadEEPROM(char * linked_var, uint16_t start_location, uint8_t read_size); uint8_t loadEEPROM(uint16_t start_location); void writeEEPROM(const char * linked_var, uint16_t start_location, uint8_t write_size); void writeEEPROM(uint8_t value, uint16_t start_location); void scanNetworks(); void load(); void saveHelper(); uint8_t findEmptySlot(); uint8_t alreadySaved(const char * name); wl_status_t connect(); uint8_t findSavedNetwork(); void setFromSaved(uint8_t slot); barWifi::WiFiStation findSaveSlot(uint8_t slot); }; #endif
cuponadesk/bGUI
src/gui_settings.h
#ifndef _GUI_SETTINGS_ #define _GUI_SETTINGS_ #include "helvetica_10.h" #include "helvetica_14.h" #include "helvetica_20.h" #define LARGE_FONT &Helvetica20pt7b #define MEDIUM_FONT &Helvetica14pt7b #define SMALL_FONT &Helvetica10pt7b #define TOP_LEFT 0 #define TOP_CENTER 1 #define TOP_RIGHT 2 #define MIDDLE_LEFT 3 #define MIDDLE_CENTER 4 #define MIDDLE_RIGHT 5 #define BOTTOM_LEFT 6 #define BOTTOM_CENTER 7 #define BOTTOM_RIGHT 8 #define DEFAULT_BACKGROUND_COLOR 0xEF7D #define DEFAULT_ITEM_COLOR 0x3CDE #define DEFAULT_OUTLINE_COLOR 0xB596 #define DEFAULT_ITEM_BACKGROUND_COLOR 0xFFFF #define DEFAULT_TEXT_COLOR 0x0000 #define DEFAULT_TEXT_ALIGN MIDDLE_LEFT #define DEFAULT_TEXT_FONT MEDIUM_FONT #define DEFAULT_LIST_HEIGHT 34 #define LIST_CORNER_RADIUS 3 #define LIST_ARROW_COLOR DEFAULT_ITEM_COLOR #define LIST_OUTLINE_COLOR DEFAULT_OUTLINE_COLOR #define DEFAULT_LIST_TEXT_COLOR DEFAULT_TEXT_COLOR #define DEFAULT_LIST_TEXT_BACKGROUND_COLOR DEFAULT_ITEM_BACKGROUND_COLOR #define LIST_HEIGHT 34 #define LIST_TEXT_COLOR 0x0000 #define LIST_TEXT_BACKGROUND_COLOR 0xFFFF #define LIST_CORNER_RADIUS 3 #define LIST_ARROW_COLOR 0x335D #define LIST_BACKGROUND_COLOR 0xCE79 #define LIST_OUTLINE_COLOR 0xB596 #endif
cuponadesk/bGUI
src/newkeyboard.h
#define KEYBOARD_LOWERCASE_BMP "keylow.bmp" #define KEYBOARD_UPPERCASE_BMP "keyupp.bmp" #define KEYBOARD_TEXT_COLOR 0x0000 #define KEYBOARD_BACKGROUND_COLOR 0xFFFF #define KEYBOARD_CURSOR_X 12 #define KEYBOARD_CURSOR_Y 31 class Keyboard { const char keyboardLayout[2][7][7] = { { { '1', '2', '3', '4', '5', '-', '='}, { '6', '7', '8', '9', '0', ',', '.'}, { 'a', 'b', 'c', 'd', 'e', 'f', 'g'}, { 'h', 'i', 'j', 'k', 'l', 'm', 'n'}, { 'o', 'p', 'q', 'r', 's', 't', 'u'}, { 0, 'v', 'w', 'x', 'y', 'z', 0 }, { 0, ' ', 0, 0, 0, 0, 0 }}, { { '!', '@', '#', '$', '%', '-', '+'}, { '^', '&', '*', '(', ')', '?', '/'}, { 'A', 'B', 'C', 'D', 'E', 'F', 'G'}, { 'H', 'I', 'J', 'K', 'L', 'M', 'N'}, { 'O', 'P', 'Q', 'R', 'S', 'T', 'U'}, { 0, 'V', 'W', 'X', 'Y', 'Z', 0 }, { 0, ' ', 0, 0, 0, 0, 0 }} }; std::string _local = {}; std::string _keyUp = {KEYBOARD_UPPERCASE_BMP}; std::string _keyLo = {KEYBOARD_LOWERCASE_BMP}; static Keyboard *k_instance; bool _visible=false; bool _draw_text=false; bool _draw_keyboard= false; bool _shift = false; Adafruit_ILI9341 * _tft; const GFXfont * _font; Keyboard() { } public: bool start = false; std::string * _linked = NULL; void setup(Adafruit_ILI9341 * s, const GFXfont * f) { _tft=s; _font=f; } void touch(uint16_t x, uint16_t y, uint16_t z) { if(z > 5 ) { int8_t key_row=-1, key_col=-1; if(x>2 && x < 33) key_col = 0; else if(x>36 && x < 67) key_col = 1; else if(x>70 && x < 101) key_col = 2; else if(x>104 && x < 135) key_col = 3; else if(x>138 && x < 169) key_col = 4; else if(x>172 && x < 204) key_col = 5; else if(x>207 && x < 238) key_col = 6; if(y>61 && y < 94) key_row = 0; else if(y>97 && y < 130) key_row = 1; else if(y>135 && y < 168) key_row = 2; else if(y>171 && y < 204) key_row = 3; else if(y>207 && y < 240) key_row = 4; else if(y>243 && y < 276) key_row = 5; else if(y>282 && y < 315) { key_col = -1; key_row = 6; if(x > 2 && x < 52) { key_col=0; } if(x > 70 && x < 169) { key_col=1; } else if(x > 186 && x < 235) { key_col=2; } } Serial.printf("%i %i\n", key_col, key_row); if(key_row == 6 && (key_col==0 || key_col ==2 )) { _visible=false; start=false; if(key_col) { *_linked = _local; } } else if(key_col ==0 && key_row ==5) //shift { _shift = !_shift; _draw_keyboard=true; _draw_text = true; } else if(key_col == 6 && key_row == 5 && _local.length()>0)//backspace { _local.pop_back(); _draw_text=true; } else if(key_col!=-1&&key_row!=-1) { _local+=keyboardLayout[_shift][key_row][key_col]; _draw_text=true; } } } void draw() { if(_draw_keyboard) { if(_shift) drawBMP(_tft, 0,0,&_keyUp); else drawBMP(_tft, 0,0,&_keyLo); _draw_keyboard=false; } if(_draw_text) { Serial.printf("Drawing text %s\n", _local.c_str()); int16_t x1, y1; uint16_t w, h; _tft->setTextWrap(false); _tft->setFont(_font); _tft->getTextBounds((char*)&_local.c_str()[0], 0, 0, &x1, &y1, &w, &h); _tft->setTextColor(KEYBOARD_TEXT_COLOR); _tft->fillRect(KEYBOARD_CURSOR_X-x1, 10, 232-KEYBOARD_CURSOR_X-x1,45, KEYBOARD_BACKGROUND_COLOR); _tft->setCursor(KEYBOARD_CURSOR_X-x1, 40); Serial.printf("%i %i %i %i\n", x1,y1,w,h); _tft->print(_local.c_str()); _draw_text=false; } } static Keyboard *instance() { if (!k_instance) k_instance = new Keyboard; return k_instance; } bool active() { if(!_visible && start!=_visible) { _visible = true; _local = *_linked; _draw_keyboard = true; _draw_text = true; _shift = false; } if(_visible) { // Serial.println("Keyboard active."); return true; } return false; } }; // Allocating and initializing GlobalClass's // static data member. The pointer is being // allocated - not the object inself. Keyboard *Keyboard::k_instance = 0;
cuponadesk/bGUI
src/text.h
#define TEXT_COLOR 0x0000 template <typename T> struct Text : Element, DisplayText { Monitor<T> * _linked=NULL; uint16_t _maxWidth=1000; using Element::set; using DisplayText::set; Text(){ } void set(const Monitor<T> & n) { Serial.printf("Creating new text linked.\n"); _linked = new Monitor<T>(n); } void set(const T & str) { make_std_string(str, &_displayString); Serial.printf("Made string %s\n", _displayString.c_str()); } void set(const MaxWidth & w) { _maxWidth = w; } void draw(Adafruit_ILI9341 * etft) const override { Serial.printf("Drawing Text %s\n", _displayString.c_str()); drawText(etft, _x, _y, _maxWidth, _displayString.c_str(), _align, _font,_textWrap, _color, _bgColor ); } bool changed() override { // Serial.println("Checking for change."); if(_linked==NULL) return false; if(*_linked->_p!=_linked->_l) { _linked->_l = *_linked->_p; make_std_string(_linked->_l,&_displayString); return true; } return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { ; } }; template <typename T> struct Number : Element { Monitor<T> * _linked = NULL; uint16_t _bgColor = 0x0000; uint16_t _maxWidth=1000; uint8_t _align = TOP_LEFT; const GFXfont * _font; uint16_t _textColor = 0x0000; using Element::set; void set(const Monitor<T> & n) { Serial.printf("Creating new text linked.\n"); _linked = new Monitor<T>(n); } void set(const BGColor & c) { _bgColor = c; } void set(const Color & c) { _textColor = c; } void set(const Align & a) { _align=a; } void set(const MaxWidth & w) { _maxWidth = w; } void set(const Font & f) { _font = f; } void draw(Adafruit_ILI9341 * etft) const override { const Element * local = this; Serial.println("Drawing Text"); char buff[64]={}; if(std::is_integral<T>::value) { // temp = std::string(_linked->_l); itoa(_linked->_l, buff, 10); } else if(std::is_floating_point<T>::value) { sprintf(buff,"%f",_linked->_l); } drawText(etft, this->_x, this->_y, _maxWidth, buff, _align, _font, false, _textColor, _bgColor ); return; } bool changed() override { // Serial.println("Checking for change."); if(*_linked->_p!=_linked->_l) { _linked->_l = *_linked->_p; return true; } return false; } void touch(uint16_t x, uint16_t y, uint16_t z) { ; } };
gonzalezjo/terrier
src/include/storage/index/hash_index.h
<filename>src/include/storage/index/hash_index.h #pragma once #include <functional> #include <memory> #include <unordered_set> #include <utility> #include <variant> // NOLINT (Matt): lint thinks this C++17 header is a C header because it only knows C++11 #include <vector> #include "common/managed_pointer.h" #include "libcuckoo/cuckoohash_config.hh" #include "storage/index/index.h" #include "storage/index/index_defs.h" namespace terrier::transaction { class TransactionContext; } template <class Key, class T, class Hash, class KeyEqual, class Allocator, std::size_t SLOT_PER_BUCKET> class cuckoohash_map; namespace terrier::storage::index { template <uint16_t KeySize> class HashKey; template <uint16_t KeySize> class GenericKey; /** * Wrapper around libcuckoo's hash map. The MVCC is logic is similar to our reference index (BwTreeIndex). Much of the * logic here is related to the cuckoohash_map not being a multimap. We get around this by making the value type a * std::variant that can either be a TupleSlot if there's only a single value for a given key, or a std::unordered_set * of TupleSlots if a single key needs to map to multiple TupleSlots. * @tparam KeyType the type of keys stored in the map */ template <typename KeyType> class HashIndex final : public Index { friend class IndexBuilder; private: // TODO(Matt): unclear at the moment if we would want this to be tunable via the SettingsManager. Alternatively, it // might be something that is a per-index hint based on the table size (cardinality?), rather than a global setting static constexpr uint16_t INITIAL_CUCKOOHASH_MAP_SIZE = 256; struct TupleSlotHash; using ValueMap = std::unordered_set<TupleSlot, TupleSlotHash>; using ValueType = std::variant<TupleSlot, ValueMap>; explicit HashIndex(IndexMetadata metadata); const std::unique_ptr< cuckoohash_map<KeyType, ValueType, std::hash<KeyType>, std::equal_to<KeyType>, // NOLINT transparent functors can't figure out template std::allocator<std::pair<const KeyType, ValueType>>, LIBCUCKOO_DEFAULT_SLOT_PER_BUCKET>> hash_map_; mutable common::SpinLatch transaction_context_latch_; // latch used to protect transaction context public: IndexType Type() const final { return IndexType::HASHMAP; } size_t EstimateHeapUsage() const final; bool Insert(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) final; bool InsertUnique(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) final; void Delete(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) final; void ScanKey(const transaction::TransactionContext &txn, const ProjectedRow &key, std::vector<TupleSlot> *value_list) final; uint64_t GetSize() const final; }; extern template class HashIndex<HashKey<8>>; extern template class HashIndex<HashKey<16>>; extern template class HashIndex<HashKey<32>>; extern template class HashIndex<HashKey<64>>; extern template class HashIndex<HashKey<128>>; extern template class HashIndex<HashKey<256>>; extern template class HashIndex<GenericKey<64>>; extern template class HashIndex<GenericKey<128>>; extern template class HashIndex<GenericKey<256>>; } // namespace terrier::storage::index
gonzalezjo/terrier
src/include/settings/settings_defs.h
<reponame>gonzalezjo/terrier // SETTING_<type>(name, description, default_value, min_value, max_value, is_mutable, callback_fn) // Terrier port SETTING_int( port, "Terrier port (default: 15721)", 15721, 1024, 65535, false, terrier::settings::Callbacks::NoOp ) // Preallocated connection handler threads and maximum number of connected clients SETTING_int( connection_thread_count, "Preallocated connection handler threads and maximum number of connected clients (default: 4)", 4, 1, 256, false, terrier::settings::Callbacks::NoOp ) // Path to socket file for Unix domain sockets SETTING_string( uds_file_directory, "The directory for the Unix domain socket (default: /tmp/)", "/tmp/", false, terrier::settings::Callbacks::NoOp ) // RecordBufferSegmentPool size limit SETTING_int( record_buffer_segment_size, "The maximum number of record buffer segments in the system. (default: 100000)", 100000, 1, 100000000, true, terrier::settings::Callbacks::BufferSegmentPoolSizeLimit ) // RecordBufferSegmentPool reuse limit SETTING_int( record_buffer_segment_reuse, "The minimum number of record buffer segments to keep allocated in the system (default: 10000)", 10000, 1, 1000000, true, terrier::settings::Callbacks::BufferSegmentPoolReuseLimit ) // BlockStore for catalog size limit SETTING_int( block_store_size, "The maximum number of storage blocks for the catalog. (default: 100000)", 100000, 1, 1000000, true, terrier::settings::Callbacks::BlockStoreSizeLimit ) // BlockStore for catalog reuse limit SETTING_int( block_store_reuse, "The minimum number of storage blocks for the catalog to keep allocated (default: 1000)", 1000, 1, 1000000, true, terrier::settings::Callbacks::BlockStoreReuseLimit ) // Garbage collector thread interval SETTING_int( gc_interval, "Garbage collector thread interval (us) (default: 1000)", 1000, 1, 10000, false, terrier::settings::Callbacks::NoOp ) // Write ahead logging SETTING_bool( wal_enable, "Whether WAL is enabled (default: true)", true, false, terrier::settings::Callbacks::NoOp ) // Path to log file for WAL SETTING_string( wal_file_path, "The path to the log file for the WAL (default: wal.log)", "wal.log", false, terrier::settings::Callbacks::NoOp ) // Number of buffers log manager can use to buffer logs SETTING_int64( wal_num_buffers, "The number of buffers the log manager uses to buffer logs to hand off to log consumer(s) (default: 100)", 100, 2, 10000, true, terrier::settings::Callbacks::WalNumBuffers ) // Log Serialization interval SETTING_int( wal_serialization_interval, "Log serialization task interval (us) (default: 100)", 100, 1, 10000, false, terrier::settings::Callbacks::NoOp ) // Log file persisting interval SETTING_int( wal_persist_interval, "Log file persisting interval (us) (default: 100)", 100, 1, 10000, false, terrier::settings::Callbacks::NoOp ) // Optimizer timeout SETTING_int(task_execution_timeout, "Maximum allowed length of time (in ms) for task execution step of optimizer, " "assuming one plan has been found (default 5000)", 5000, 1000, 60000, false, terrier::settings::Callbacks::NoOp) // Parallel Execution SETTING_bool( parallel_execution, "Whether parallel execution for scans is enabled", true, true, terrier::settings::Callbacks::NoOp ) // Log file persisting threshold SETTING_int64( wal_persist_threshold, "Log file persisting write threshold (bytes) (default: 1MB)", (1 << 20) /* 1MB */, (1 << 12) /* 4KB */, (1 << 24) /* 16MB */, false, terrier::settings::Callbacks::NoOp ) SETTING_int( extra_float_digits, "Sets the number of digits displayed for floating-point values. (default : 1)", 1, -15, 3, true, terrier::settings::Callbacks::NoOp ) SETTING_bool( metrics, "Metrics sub-system for various components (default: true).", true, false, terrier::settings::Callbacks::NoOp ) SETTING_bool( metrics_logging, "Metrics collection for the Logging component (default: false).", false, true, terrier::settings::Callbacks::MetricsLogging ) SETTING_bool( metrics_transaction, "Metrics collection for the TransactionManager component (default: false).", false, true, terrier::settings::Callbacks::MetricsTransaction ) SETTING_bool( metrics_gc, "Metrics collection for the GarbageCollector component (default: false).", false, true, terrier::settings::Callbacks::MetricsGC ) SETTING_bool( metrics_execution, "Metrics collection for the Execution component (default: false).", false, true, terrier::settings::Callbacks::MetricsExecution ) SETTING_bool( metrics_pipeline, "Metrics collection for the ExecutionEngine pipelines (default: false).", false, true, terrier::settings::Callbacks::MetricsPipeline ) SETTING_bool( metrics_bind_command, "Metrics collection for the bind command.", false, true, terrier::settings::Callbacks::MetricsBindCommand ) SETTING_bool( metrics_execute_command, "Metrics collection for the execute command.", false, true, terrier::settings::Callbacks::MetricsExecuteCommand ) SETTING_bool( use_query_cache, "Extended Query protocol caches physical plans and generated code after first execution. Warning: bugs with DDL changes.", true, false, terrier::settings::Callbacks::NoOp ) SETTING_bool( compiled_query_execution, "Compile queries to native machine code using LLVM, rather than relying on TPL interpretation (default: false).", false, false, terrier::settings::Callbacks::NoOp ) SETTING_string( application_name, "The name of the application (default: NO_NAME)", "NO_NAME", true, terrier::settings::Callbacks::NoOp ) SETTING_string( transaction_isolation, "The default isolation level (default: TRANSACTION_READ_COMMITTED)", "TRANSACTION_READ_COMMITTED", true, terrier::settings::Callbacks::NoOp )
gonzalezjo/terrier
src/include/storage/index/bwtree_index.h
<gh_stars>0 #pragma once #include <functional> #include <memory> #include <utility> #include <vector> #include "common/managed_pointer.h" #include "storage/index/index.h" #include "storage/index/index_defs.h" namespace terrier::transaction { class TransactionContext; } namespace third_party::bwtree { // NOLINT: check censored doesn't like this namespace name template <typename KeyType, typename ValueType, typename KeyComparator, typename KeyEqualityChecker, typename KeyHashFunc, typename ValueEqualityChecker, typename ValueHashFunc> class BwTree; } namespace terrier::storage::index { template <uint8_t KeySize> class CompactIntsKey; template <uint16_t KeySize> class GenericKey; /** * Wrapper around Ziqi's OpenBwTree. * @tparam KeyType the type of keys stored in the BwTree */ template <typename KeyType> class BwTreeIndex final : public Index { friend class IndexBuilder; private: explicit BwTreeIndex(IndexMetadata metadata); const std::unique_ptr<third_party::bwtree::BwTree< KeyType, TupleSlot, std::less<KeyType>, // NOLINT transparent functors can't figure out template std::equal_to<KeyType>, // NOLINT transparent functors can't figure out template std::hash<KeyType>, std::equal_to<TupleSlot>, std::hash<TupleSlot>>> bwtree_; mutable common::SpinLatch transaction_context_latch_; // latch used to protect transaction context public: IndexType Type() const final { return IndexType::BWTREE; } void PerformGarbageCollection() final; size_t EstimateHeapUsage() const final; bool Insert(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) final; bool InsertUnique(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) final; void Delete(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) final; void ScanKey(const transaction::TransactionContext &txn, const ProjectedRow &key, std::vector<TupleSlot> *value_list) final; void ScanAscending(const transaction::TransactionContext &txn, ScanType scan_type, uint32_t num_attrs, ProjectedRow *low_key, ProjectedRow *high_key, uint32_t limit, std::vector<TupleSlot> *value_list) final; void ScanDescending(const transaction::TransactionContext &txn, const ProjectedRow &low_key, const ProjectedRow &high_key, std::vector<TupleSlot> *value_list) final; void ScanLimitDescending(const transaction::TransactionContext &txn, const ProjectedRow &low_key, const ProjectedRow &high_key, std::vector<TupleSlot> *value_list, uint32_t limit) final; uint64_t GetSize() const final; }; extern template class BwTreeIndex<CompactIntsKey<8>>; extern template class BwTreeIndex<CompactIntsKey<16>>; extern template class BwTreeIndex<CompactIntsKey<24>>; extern template class BwTreeIndex<CompactIntsKey<32>>; extern template class BwTreeIndex<GenericKey<64>>; extern template class BwTreeIndex<GenericKey<128>>; extern template class BwTreeIndex<GenericKey<256>>; extern template class BwTreeIndex<GenericKey<512>>; } // namespace terrier::storage::index
SidneyAn/ha
service-mgmt/sm/src/sm_msg.c
// // Copyright (c) 2014-2018 Wind River Systems, Inc. // // SPDX-License-Identifier: Apache-2.0 // #include "sm_msg.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <net/if.h> #include <arpa/inet.h> #include "sm_types.h" #include "sm_debug.h" #include "sm_list.h" #include "sm_selobj.h" #include "sm_uuid.h" #include "sm_sha512.h" #include "sm_hw.h" #include "sm_node_utils.h" #include "sm_db.h" #include "sm_db_service_domain_interfaces.h" #define SM_MSG_VERSION 1 #define SM_MSG_REVISION 1 #define SM_MSG_FLAG_ACK 0x1 #define SM_MSG_MAX_SIZE 1024 #define SM_MSG_BUFFER_MAX_SIZE 4096 #define SM_MSG_MAX_SEQ_DELTA 1000 #if __BYTE_ORDER == __BIG_ENDIAN #define ntohll(x) (x) #define htonll(x) (x) #else # if __BYTE_ORDER == __LITTLE_ENDIAN # define ntohll(x) sm_msg_little_endian_ntohll(x) # define htonll(x) sm_msg_little_endian_htonll(x) # endif #endif #define _MSG_NOT_SENT_TO_TARGET -128 typedef enum { SM_MSG_TYPE_UNKNOWN = 0x0, SM_MSG_TYPE_NODE_HELLO = 0x1, SM_MSG_TYPE_NODE_UPDATE = 0x2, SM_MSG_TYPE_NODE_SWACT = 0x3, SM_MSG_TYPE_NODE_SWACT_ACK = 0x4, SM_MSG_TYPE_SERVICE_DOMAIN_HELLO = 0x5, SM_MSG_TYPE_SERVICE_DOMAIN_PAUSE = 0x6, SM_MSG_TYPE_SERVICE_DOMAIN_EXCHANGE_START = 0x7, SM_MSG_TYPE_SERVICE_DOMAIN_EXCHANGE = 0x8, SM_MSG_TYPE_SERVICE_DOMAIN_MEMBER_REQUEST = 0x9, SM_MSG_TYPE_SERVICE_DOMAIN_MEMBER_UPDATE = 0xa, SM_MSG_MAX, } SmMsgTypeT; typedef struct { uint16_t version; uint16_t revision; uint16_t max_supported_version; uint16_t max_supported_revision; uint16_t msg_len; uint16_t msg_type; uint64_t msg_flags; SmUuidT msg_instance; uint64_t msg_seq_num; char node_name[SM_NODE_NAME_MAX_CHAR]; uint32_t auth_type; uint8_t auth_vector[SM_AUTHENTICATION_VECTOR_MAX_CHAR]; } __attribute__ ((packed)) SmMsgHeaderT; typedef struct { char node_name[SM_NODE_NAME_MAX_CHAR]; char admin_state[SM_NODE_ADMIN_STATE_MAX_CHAR]; char oper_state[SM_NODE_OPERATIONAL_STATE_MAX_CHAR]; char avail_status[SM_NODE_AVAIL_STATUS_MAX_CHAR]; char ready_state[SM_NODE_READY_STATE_MAX_CHAR]; SmUuidT state_uuid; uint32_t uptime; } __attribute__ ((packed)) SmMsgNodeHelloT; typedef struct { char node_name[SM_NODE_NAME_MAX_CHAR]; char admin_state[SM_NODE_ADMIN_STATE_MAX_CHAR]; char oper_state[SM_NODE_OPERATIONAL_STATE_MAX_CHAR]; char avail_status[SM_NODE_AVAIL_STATUS_MAX_CHAR]; char ready_state[SM_NODE_READY_STATE_MAX_CHAR]; SmUuidT old_state_uuid; SmUuidT state_uuid; uint32_t uptime; uint32_t force; } __attribute__ ((packed)) SmMsgNodeUpdateT; typedef struct { SmUuidT request_uuid; char node_name[SM_NODE_NAME_MAX_CHAR]; uint32_t force; } __attribute__ ((packed)) SmMsgNodeSwactT; typedef struct { SmUuidT request_uuid; char node_name[SM_NODE_NAME_MAX_CHAR]; uint32_t force; } __attribute__ ((packed)) SmMsgNodeSwactAckT; typedef struct { char service_domain[SM_SERVICE_DOMAIN_NAME_MAX_CHAR]; char node_name[SM_NODE_NAME_MAX_CHAR]; char orchestration[SM_ORCHESTRATION_MAX_CHAR]; char designation[SM_DESIGNATION_MAX_CHAR]; uint32_t generation; uint32_t priority; uint32_t hello_interval; uint32_t dead_interval; uint32_t wait_interval; uint32_t exchange_interval; char leader[SM_NODE_NAME_MAX_CHAR]; } __attribute__ ((packed)) SmMsgServiceDomainHelloT; typedef struct { char service_domain[SM_SERVICE_DOMAIN_NAME_MAX_CHAR]; char node_name[SM_NODE_NAME_MAX_CHAR]; uint32_t pause_interval; } __attribute__ ((packed)) SmMsgServiceDomainPauseT; typedef struct { char service_domain[SM_SERVICE_DOMAIN_NAME_MAX_CHAR]; char node_name[SM_NODE_NAME_MAX_CHAR]; char exchange_node_name[SM_NODE_NAME_MAX_CHAR]; uint32_t exchange_seq; } __attribute__ ((packed)) SmMsgServiceDomainExchangeStartT; typedef struct { char service_domain[SM_SERVICE_DOMAIN_NAME_MAX_CHAR]; char node_name[SM_NODE_NAME_MAX_CHAR]; char exchange_node_name[SM_NODE_NAME_MAX_CHAR]; uint32_t exchange_seq; int64_t member_id; char member_name[SM_SERVICE_GROUP_NAME_MAX_CHAR]; char member_desired_state[SM_SERVICE_GROUP_STATE_MAX_CHAR]; char member_state[SM_SERVICE_GROUP_STATE_MAX_CHAR]; char member_status[SM_SERVICE_GROUP_STATUS_MAX_CHAR]; char member_condition[SM_SERVICE_GROUP_CONDITION_MAX_CHAR]; int64_t member_health; char reason_text[SM_SERVICE_GROUP_REASON_TEXT_MAX_CHAR]; uint32_t more_members; int64_t last_received_member_id; } __attribute__ ((packed)) SmMsgServiceDomainExchangeT; typedef struct { char service_domain[SM_SERVICE_DOMAIN_NAME_MAX_CHAR]; char node_name[SM_NODE_NAME_MAX_CHAR]; char member_node_name[SM_NODE_NAME_MAX_CHAR]; int64_t member_id; char member_name[SM_SERVICE_GROUP_NAME_MAX_CHAR]; char member_action[SM_SERVICE_GROUP_ACTION_MAX_CHAR]; uint64_t member_action_flags; } __attribute__ ((packed)) SmMsgServiceDomainMemberRequestT; typedef struct { char service_domain[SM_SERVICE_DOMAIN_NAME_MAX_CHAR]; char node_name[SM_NODE_NAME_MAX_CHAR]; char member_node_name[SM_NODE_NAME_MAX_CHAR]; int64_t member_id; char member_name[SM_SERVICE_GROUP_NAME_MAX_CHAR]; char member_desired_state[SM_SERVICE_GROUP_STATE_MAX_CHAR]; char member_state[SM_SERVICE_GROUP_STATE_MAX_CHAR]; char member_status[SM_SERVICE_GROUP_STATUS_MAX_CHAR]; char member_condition[SM_SERVICE_GROUP_CONDITION_MAX_CHAR]; int64_t member_health; char reason_text[SM_SERVICE_GROUP_REASON_TEXT_MAX_CHAR]; } __attribute__ ((packed)) SmMsgServiceDomainMemberUpdateT; typedef struct { SmMsgHeaderT header; union { // Node Messages. SmMsgNodeHelloT node_hello; SmMsgNodeUpdateT node_update; SmMsgNodeSwactT node_swact; SmMsgNodeSwactAckT node_swact_ack; // Service Domain Messages. SmMsgServiceDomainHelloT hello; SmMsgServiceDomainPauseT pause; SmMsgServiceDomainExchangeStartT exchange_start; SmMsgServiceDomainExchangeT exchange; SmMsgServiceDomainMemberRequestT request; SmMsgServiceDomainMemberUpdateT update; char raw_msg[SM_MSG_MAX_SIZE-sizeof(SmMsgHeaderT)]; } u; } __attribute__ ((packed)) SmMsgT; typedef struct { bool inuse; char node_name[SM_NODE_NAME_MAX_CHAR]; SmUuidT msg_instance; uint64_t msg_last_seq_num; } SmMsgPeerNodeInfoT; typedef struct { bool inuse; char interface_name[SM_INTERFACE_NAME_MAX_CHAR]; SmNetworkAddressT network_address; int network_port; SmAuthTypeT auth_type; char auth_key[SM_AUTHENTICATION_KEY_MAX_CHAR]; } SmMsgPeerInterfaceInfoT; static bool _messaging_enabled = false; static char _hostname[SM_NODE_NAME_MAX_CHAR]; static SmUuidT _msg_instance = {0}; static uint64_t _msg_seq_num = 0; static char _tx_control_buffer[SM_MSG_BUFFER_MAX_SIZE] __attribute__((aligned)); static char _tx_buffer[SM_MSG_BUFFER_MAX_SIZE] __attribute__((aligned)); static char _rx_control_buffer[SM_MSG_BUFFER_MAX_SIZE] __attribute__((aligned)); static char _rx_buffer[SM_MSG_BUFFER_MAX_SIZE] __attribute__((aligned)); static SmListT* _callbacks = NULL; static unsigned int _next_free_peer_entry = 0; static SmMsgPeerNodeInfoT _peers[SM_NODE_MAX]; static SmMsgPeerInterfaceInfoT _peer_interfaces[SM_INTERFACE_PEER_MAX]; // Transmit and Receive Statistics static uint64_t _rcvd_total_msgs = 0; static uint64_t _rcvd_msgs_while_disabled = 0; static uint64_t _rcvd_bad_msg_auth = 0; static uint64_t _rcvd_bad_msg_version = 0; static uint64_t _send_node_hello_cnt = 0; static uint64_t _rcvd_node_hello_cnt = 0; static uint64_t _send_node_update_cnt = 0; static uint64_t _rcvd_node_update_cnt = 0; static uint64_t _send_node_swact_cnt = 0; static uint64_t _rcvd_node_swact_cnt = 0; static uint64_t _send_node_swact_ack_cnt = 0; static uint64_t _rcvd_node_swact_ack_cnt = 0; static uint64_t _send_service_domain_hello_cnt = 0; static uint64_t _rcvd_service_domain_hello_cnt = 0; static uint64_t _send_service_domain_pause_cnt = 0; static uint64_t _rcvd_service_domain_pause_cnt = 0; static uint64_t _send_service_domain_exchange_start_cnt = 0; static uint64_t _rcvd_service_domain_exchange_start_cnt = 0; static uint64_t _send_service_domain_exchange_cnt = 0; static uint64_t _rcvd_service_domain_exchange_cnt = 0; static uint64_t _send_service_domain_member_request_cnt = 0; static uint64_t _rcvd_service_domain_member_request_cnt = 0; static uint64_t _send_service_domain_member_update_cnt = 0; static uint64_t _rcvd_service_domain_member_update_cnt = 0; // **************************************************************************** // Messaging - Find Peer Node Info // =============================== static SmMsgPeerNodeInfoT* sm_msg_find_peer_node_info( char node_name[] ) { SmMsgPeerNodeInfoT* entry; unsigned int entry_i; for( entry_i=0; SM_NODE_MAX > entry_i; ++entry_i ) { entry = &(_peers[entry_i]); if( entry->inuse ) { if( 0 == strcmp( node_name, entry->node_name ) ) { return( entry ); } } } return( NULL ); } // **************************************************************************** // **************************************************************************** // Messaging - In Sequence // ======================= static bool sm_msg_in_sequence( char node_name[], SmUuidT msg_instance, uint64_t msg_seq_num ) { bool in_sequence = false; SmMsgPeerNodeInfoT* entry; entry = sm_msg_find_peer_node_info( node_name ); if( NULL == entry ) { // Cheap way of aging out entries when the maximum node limit is // reached. entry = &(_peers[_next_free_peer_entry++]); if( _next_free_peer_entry >= SM_NODE_MAX ) { _next_free_peer_entry = 0; } entry->inuse = true; snprintf( entry->node_name, sizeof(entry->node_name), "%s", node_name ); snprintf( entry->msg_instance, sizeof(entry->msg_instance), "%s", msg_instance ); entry->msg_last_seq_num = msg_seq_num; in_sequence = true; DPRINTFI( "Message instance (%s) for node (%s) set.", msg_instance, node_name ); } else { if( 0 == strcmp( msg_instance, entry->msg_instance ) ) { uint64_t delta; if( msg_seq_num > entry->msg_last_seq_num ) { delta = msg_seq_num- entry->msg_last_seq_num; if( SM_MSG_MAX_SEQ_DELTA < delta ) { DPRINTFI( "Message sequence delta (%" PRIu64 ") too large " "for message instance (%s) from node (%s), " "rcvd_seq=%" PRIu64 ", last_recvd_seq=%" PRIu64 ".", delta, entry->msg_instance, node_name, msg_seq_num, entry->msg_last_seq_num ); } entry->msg_last_seq_num = msg_seq_num; in_sequence = true; } else { delta = entry->msg_last_seq_num - msg_seq_num; if( SM_MSG_MAX_SEQ_DELTA < delta ) { DPRINTFI( "Message sequence delta (%" PRIu64 ") too large " "for message instance (%s) from node (%s), " "rcvd_seq=%" PRIu64 ", last_recvd_seq=%" PRIu64 ".", delta, entry->msg_instance, node_name, msg_seq_num, entry->msg_last_seq_num ); entry->msg_last_seq_num = msg_seq_num; in_sequence = true; } } } else { DPRINTFI( "Message instance (%s) changed for node (%s), now=%s.", entry->msg_instance, node_name, msg_instance ); snprintf( entry->msg_instance, sizeof(entry->msg_instance), "%s", msg_instance ); entry->msg_last_seq_num = msg_seq_num; in_sequence = true; } } return( in_sequence ); } // **************************************************************************** // **************************************************************************** // Messaging - Add Peer Interface // ============================== SmErrorT sm_msg_add_peer_interface( char interface_name[], SmNetworkAddressT* network_address, int network_port, SmAuthTypeT auth_type, char auth_key[] ) { bool found = false; SmMsgPeerInterfaceInfoT* entry; unsigned int entry_i; for( entry_i=0; SM_INTERFACE_PEER_MAX > entry_i; ++entry_i ) { entry = &(_peer_interfaces[entry_i]); if( !(entry->inuse) ) continue; if( 0 != strcmp( interface_name, entry->interface_name ) ) continue; if( network_address->type != entry->network_address.type ) continue; if( SM_NETWORK_TYPE_IPV4 == network_address->type ) { if( network_address->u.ipv4.sin.s_addr == entry->network_address.u.ipv4.sin.s_addr ) { found = true; break; } } else if( SM_NETWORK_TYPE_IPV4_UDP == network_address->type ) { if(( network_address->u.ipv4.sin.s_addr == entry->network_address.u.ipv4.sin.s_addr )&& ( network_port == entry->network_port )) { found = true; break; } } else if( SM_NETWORK_TYPE_IPV6 == network_address->type ) { if( 0 != memcmp( &( network_address->u.ipv6.sin6 ), &( entry->network_address.u.ipv6.sin6 ), sizeof(struct in6_addr) )) { found = true; break; } } else if( SM_NETWORK_TYPE_IPV6_UDP == network_address->type ) { if(( 0 != memcmp( &( network_address->u.ipv6.sin6 ), &( entry->network_address.u.ipv6.sin6 ), sizeof(struct in6_addr) ))&& ( network_port == entry->network_port )) { found = true; break; } } } if( !found ) { for( entry_i=0; SM_INTERFACE_PEER_MAX > entry_i; ++entry_i ) { entry = &(_peer_interfaces[entry_i]); if( !(entry->inuse) ) { entry->inuse = true; snprintf( entry->interface_name, sizeof(entry->interface_name), "%s", interface_name ); memcpy( &(entry->network_address), network_address, sizeof(SmNetworkAddressT) ); entry->network_port = network_port; entry->auth_type = auth_type; memcpy( entry->auth_key, auth_key, SM_AUTHENTICATION_KEY_MAX_CHAR ); break; } } } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Delete Peer Interface // ================================= SmErrorT sm_msg_delete_peer_interface( char interface_name[], SmNetworkAddressT* network_address, int network_port ) { SmMsgPeerInterfaceInfoT* entry; unsigned int entry_i; for( entry_i=0; SM_INTERFACE_PEER_MAX > entry_i; ++entry_i ) { entry = &(_peer_interfaces[entry_i]); if( !(entry->inuse) ) continue; if( 0 != strcmp( interface_name, entry->interface_name ) ) continue; if( network_address->type != entry->network_address.type ) continue; if( SM_NETWORK_TYPE_IPV4 == network_address->type ) { if( network_address->u.ipv4.sin.s_addr == entry->network_address.u.ipv4.sin.s_addr ) { memset( entry, 0, sizeof(SmMsgPeerInterfaceInfoT) ); break; } } else if( SM_NETWORK_TYPE_IPV4_UDP == network_address->type ) { if(( network_address->u.ipv4.sin.s_addr == entry->network_address.u.ipv4.sin.s_addr )&& ( network_port == entry->network_port )) { memset( entry, 0, sizeof(SmMsgPeerInterfaceInfoT) ); break; } } else if( SM_NETWORK_TYPE_IPV6 == network_address->type ) { if( 0 != memcmp( &(network_address->u.ipv6.sin6), &(entry->network_address.u.ipv6.sin6), sizeof(in6_addr) )) { memset( entry, 0, sizeof(SmMsgPeerInterfaceInfoT) ); break; } } else if( SM_NETWORK_TYPE_IPV6_UDP == network_address->type ) { if(( 0 != memcmp( &(network_address->u.ipv6.sin6), &(entry->network_address.u.ipv6.sin6), sizeof(in6_addr) ))&& ( network_port == entry->network_port )) { memset( entry, 0, sizeof(SmMsgPeerInterfaceInfoT) ); break; } } } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Get Peer Interface // ============================== static SmMsgPeerInterfaceInfoT* sm_msg_get_peer_interface( char interface_name[], SmNetworkAddressT* network_address, int network_port ) { SmMsgPeerInterfaceInfoT* entry; in6_addr empty_ipv6_address; unsigned int entry_i; for( entry_i=0; SM_INTERFACE_PEER_MAX > entry_i; ++entry_i ) { entry = &(_peer_interfaces[entry_i]); if( !(entry->inuse) ) continue; if( 0 != strcmp( interface_name, entry->interface_name ) ) continue; if( SM_NETWORK_TYPE_IPV4 == entry->network_address.type ) { if( 0 == entry->network_address.u.ipv4.sin.s_addr ) { return( entry ); } else if( network_address->u.ipv4.sin.s_addr == entry->network_address.u.ipv4.sin.s_addr ) { return( entry ); } } else if( SM_NETWORK_TYPE_IPV4_UDP == entry->network_address.type ) { if( 0 == entry->network_address.u.ipv4.sin.s_addr ) { return( entry ); } else if( -1 == entry->network_port ) { return( entry ); } else if(( network_address->u.ipv4.sin.s_addr == entry->network_address.u.ipv4.sin.s_addr )&& ( network_port == entry->network_port )) { return( entry ); } } else if( SM_NETWORK_TYPE_IPV6 == entry->network_address.type ) { memset( &empty_ipv6_address, 0, sizeof(in6_addr) ); if( 0 == memcmp( &(entry->network_address.u.ipv6.sin6), &(empty_ipv6_address), sizeof(in6_addr) )) { return( entry ); } else if( 0 == memcmp( &(network_address->u.ipv6.sin6), &(entry->network_address.u.ipv6.sin6), sizeof(in6_addr) )) { return( entry ); } } else if( SM_NETWORK_TYPE_IPV6_UDP == entry->network_address.type ) { memset( &empty_ipv6_address, 0, sizeof(in6_addr) ); if( 0 == memcmp( &(entry->network_address.u.ipv6.sin6), &(empty_ipv6_address), sizeof(in6_addr) )) { return( entry ); } else if( -1 == entry->network_port ) { return( entry ); } else if(( 0 == memcmp( &(network_address->u.ipv6.sin6), &(entry->network_address.u.ipv6.sin6), sizeof(in6_addr) ))&& ( network_port == entry->network_port )) { return( entry ); } } } return( NULL ); } // **************************************************************************** // **************************************************************************** // Messaging - Little Endian Network To Host Byte Order For Uint64 // =============================================================== uint64_t sm_msg_little_endian_ntohll( uint64_t i ) { uint32_t tmp; union { uint64_t uint64; struct { uint32_t word0; uint32_t word1; } uint32; } u; u.uint64 = i; u.uint32.word0 = ntohl( u.uint32.word0 ); u.uint32.word1 = ntohl( u.uint32.word1 ); tmp = u.uint32.word0; u.uint32.word0 = u.uint32.word1; u.uint32.word1 = tmp; return( u.uint64 ); } // **************************************************************************** // **************************************************************************** // Messaging - Little Endian Host To Network Byte Order For Uint64 // =============================================================== uint64_t sm_msg_little_endian_htonll( uint64_t i ) { uint32_t tmp; union { uint64_t uint64; struct { uint32_t word0; uint32_t word1; } uint32; } u; u.uint64 = i; u.uint32.word0 = htonl( u.uint32.word0 ); u.uint32.word1 = htonl( u.uint32.word1 ); tmp = u.uint32.word0; u.uint32.word0 = u.uint32.word1; u.uint32.word1 = tmp; return( u.uint64 ); } // **************************************************************************** // **************************************************************************** // Messaging - Enable // ================== void sm_msg_enable( void ) { _messaging_enabled = true; DPRINTFI( "Messaging is now enabled." ); } // **************************************************************************** // **************************************************************************** // Messaging - Disable // =================== void sm_msg_disable( void ) { _messaging_enabled = false; DPRINTFI( "Messaging is now disabled." ); } // **************************************************************************** // **************************************************************************** // Messaging - Register Callbacks // ============================== SmErrorT sm_msg_register_callbacks( SmMsgCallbacksT* callbacks ) { SM_LIST_PREPEND( _callbacks, (SmListEntryDataPtrT) callbacks ); return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Deregister Callbacks // ================================ SmErrorT sm_msg_deregister_callbacks( SmMsgCallbacksT* callbacks ) { SM_LIST_REMOVE( _callbacks, (SmListEntryDataPtrT) callbacks ); return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Increment Sequence Number // ===================================== void sm_msg_increment_seq_num( void ) { ++_msg_seq_num; } // **************************************************************************** // **************************************************************************** // Messaging - Send message from IPv6 source // ========================================== static int sm_msg_sendmsg_src_ipv6( int socket, void* msg, size_t msg_len, int flags, struct sockaddr_in6* dst_addr, struct in6_addr* src_Addr ) { struct msghdr msg_hdr = {}; struct cmsghdr *cmsg; struct in6_pktinfo *pktinfo; struct iovec iov = {msg, msg_len}; memset( &_tx_control_buffer, 0, sizeof(_tx_control_buffer) ); msg_hdr.msg_iov = &iov; msg_hdr.msg_iovlen = 1; msg_hdr.msg_name = dst_addr; msg_hdr.msg_namelen = sizeof(struct sockaddr_in6); msg_hdr.msg_control = _tx_control_buffer; msg_hdr.msg_controllen = CMSG_LEN( sizeof(struct in6_pktinfo) ); cmsg = CMSG_FIRSTHDR( &msg_hdr ); cmsg->cmsg_level = IPPROTO_IPV6; cmsg->cmsg_type = IPV6_PKTINFO; cmsg->cmsg_len = CMSG_LEN( sizeof(struct in6_pktinfo) ); pktinfo = (struct in6_pktinfo*) CMSG_DATA( cmsg ); pktinfo->ipi6_ifindex = 0; pktinfo->ipi6_addr = *src_Addr; return sendmsg( socket, &msg_hdr, flags ); } // **************************************************************************** static int sm_send_msg(SmServiceDomainInterfaceT* interface, SmMsgT* msg ) { struct sockaddr_in dst_addr4; int result = -1; SmIpv4AddressT* ipv4_dst; memset( &dst_addr4, 0, sizeof(dst_addr4) ); dst_addr4.sin_family = AF_INET; dst_addr4.sin_port = htons(interface->network_port); if ( SM_INTERFACE_OAM != interface->interface_type ) { ipv4_dst = &(interface->network_multicast.u.ipv4); } else { ipv4_dst = &(interface->network_peer_address.u.ipv4); } if( 0 == ipv4_dst->sin.s_addr ) { //don't send to 0.0.0.0 return _MSG_NOT_SENT_TO_TARGET; } dst_addr4.sin_addr.s_addr = ipv4_dst->sin.s_addr; result = sendto( interface->unicast_socket, msg, sizeof(SmMsgT), 0, (struct sockaddr *) &dst_addr4, sizeof(dst_addr4) ); return result; } static int sm_send_ipv6_msg(SmServiceDomainInterfaceT* interface, SmMsgT* msg ) { struct sockaddr_in6 dst_addr6; int result = -1; SmIpv6AddressT* ipv6_dst; memset( &dst_addr6, 0, sizeof(dst_addr6) ); dst_addr6.sin6_family = AF_INET6; dst_addr6.sin6_port = htons(interface->network_port); if ( SM_INTERFACE_OAM != interface->interface_type ) { ipv6_dst = &(interface->network_multicast.u.ipv6); }else { ipv6_dst = &(interface->network_peer_address.u.ipv6); } dst_addr6.sin6_addr = ipv6_dst->sin6; if (memcmp(&in6addr_any, &dst_addr6.sin6_addr, sizeof(dst_addr6.sin6_addr)) == 0 ) { // don't send to :: return _MSG_NOT_SENT_TO_TARGET; } result = sm_msg_sendmsg_src_ipv6( interface->unicast_socket, msg, sizeof(SmMsgT), 0, &dst_addr6, &interface->network_address.u.ipv6.sin6 ); return result; } // **************************************************************************** // Messaging - Send Node Hello // =========================== SmErrorT sm_msg_send_node_hello( char node_name[], SmNodeAdminStateT admin_state, SmNodeOperationalStateT oper_state, SmNodeAvailStatusT avail_status, SmNodeReadyStateT ready_state, SmUuidT state_uuid, long uptime, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgNodeHelloT* hello_msg = &(msg->u.node_hello); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_NODE_HELLO); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( hello_msg->node_name, sizeof(hello_msg->node_name), "%s", node_name ); snprintf( hello_msg->admin_state, sizeof(hello_msg->admin_state), "%s", sm_node_admin_state_str(admin_state) ); snprintf( hello_msg->oper_state, sizeof(hello_msg->oper_state), "%s", sm_node_oper_state_str(oper_state) ); snprintf( hello_msg->avail_status, sizeof(hello_msg->avail_status), "%s", sm_node_avail_status_str(avail_status) ); snprintf( hello_msg->ready_state, sizeof(hello_msg->ready_state), "%s", sm_node_ready_state_str(ready_state) ); snprintf( hello_msg->state_uuid, sizeof(hello_msg->state_uuid), "%s", state_uuid ); hello_msg->uptime = htonl(uptime); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_node_hello_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Node Update // ============================ SmErrorT sm_msg_send_node_update( char node_name[], SmNodeAdminStateT admin_state, SmNodeOperationalStateT oper_state, SmNodeAvailStatusT avail_status, SmNodeReadyStateT ready_state, SmUuidT old_state_uuid, SmUuidT state_uuid, long uptime, bool force, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgNodeUpdateT* update_msg = &(msg->u.node_update); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_NODE_UPDATE); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( update_msg->node_name, sizeof(update_msg->node_name), "%s", node_name ); snprintf( update_msg->admin_state, sizeof(update_msg->admin_state), "%s", sm_node_admin_state_str(admin_state) ); snprintf( update_msg->oper_state, sizeof(update_msg->oper_state), "%s", sm_node_oper_state_str(oper_state) ); snprintf( update_msg->avail_status, sizeof(update_msg->avail_status), "%s", sm_node_avail_status_str(avail_status) ); snprintf( update_msg->ready_state, sizeof(update_msg->ready_state), "%s", sm_node_ready_state_str(ready_state) ); snprintf( update_msg->old_state_uuid, sizeof(update_msg->old_state_uuid), "%s", old_state_uuid ); snprintf( update_msg->state_uuid, sizeof(update_msg->state_uuid), "%s", state_uuid ); update_msg->uptime = htonl(uptime); update_msg->force = htonl(force); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_node_update_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Node Swact // =========================== SmErrorT sm_msg_send_node_swact( char node_name[], bool force, SmUuidT request_uuid, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgNodeSwactT* swact_msg = &(msg->u.node_swact); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_NODE_SWACT); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( swact_msg->node_name, sizeof(swact_msg->node_name), "%s", node_name ); snprintf( swact_msg->request_uuid, sizeof(swact_msg->request_uuid), "%s", request_uuid ); swact_msg->force = htonl(force); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_node_swact_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Node Swact Ack // =============================== SmErrorT sm_msg_send_node_swact_ack( char node_name[], bool force, SmUuidT request_uuid, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgNodeSwactAckT* swact_ack_msg = NULL; int result = -1; swact_ack_msg = &(msg->u.node_swact_ack); memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_NODE_SWACT_ACK); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( swact_ack_msg->node_name, sizeof(swact_ack_msg->node_name), "%s", node_name ); snprintf( swact_ack_msg->request_uuid, sizeof(swact_ack_msg->request_uuid), "%s", request_uuid ); swact_ack_msg->force = htonl(force); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_node_swact_ack_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Service Domain Hello // ===================================== SmErrorT sm_msg_send_service_domain_hello( char node_name[], SmOrchestrationTypeT orchestration, SmDesignationTypeT designation, int generation, int priority, int hello_interval, int dead_interval, int wait_interval, int exchange_interval, char leader[], SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgServiceDomainHelloT* hello_msg = &(msg->u.hello); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_SERVICE_DOMAIN_HELLO); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( hello_msg->service_domain, sizeof(hello_msg->service_domain), "%s", interface->service_domain ); snprintf( hello_msg->node_name, sizeof(hello_msg->node_name), "%s", node_name ); snprintf( hello_msg->orchestration, sizeof(hello_msg->orchestration), "%s", sm_orchestration_type_str(orchestration) ); snprintf( hello_msg->designation, sizeof(hello_msg->designation), "%s", sm_designation_type_str(designation) ); hello_msg->generation = htonl(generation); hello_msg->priority = htonl(priority); hello_msg->hello_interval = htonl(hello_interval); hello_msg->dead_interval = htonl(dead_interval); hello_msg->wait_interval = htonl(wait_interval); hello_msg->exchange_interval = htonl(exchange_interval); snprintf( hello_msg->leader, sizeof(hello_msg->leader), "%s", leader ); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_service_domain_hello_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Service Domain Pause // ===================================== SmErrorT sm_msg_send_service_domain_pause( char node_name[], int pause_interval, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgServiceDomainPauseT* pause_msg = &(msg->u.pause); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_SERVICE_DOMAIN_PAUSE); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( pause_msg->service_domain, sizeof(pause_msg->service_domain), "%s", interface->service_domain ); snprintf( pause_msg->node_name, sizeof(pause_msg->node_name), "%s", node_name ); pause_msg->pause_interval = htonl(pause_interval); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_service_domain_pause_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Service Domain Exchange Start // ============================================== SmErrorT sm_msg_send_service_domain_exchange_start( char node_name[], char exchange_node_name[], int exchange_seq, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgServiceDomainExchangeStartT* exchange_start_msg; int result = -1; exchange_start_msg = &(msg->u.exchange_start); memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_SERVICE_DOMAIN_EXCHANGE_START); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( exchange_start_msg->service_domain, sizeof(exchange_start_msg->service_domain), "%s", interface->service_domain ); snprintf( exchange_start_msg->node_name, sizeof(exchange_start_msg->node_name), "%s", node_name ); snprintf( exchange_start_msg->exchange_node_name, sizeof(exchange_start_msg->exchange_node_name), "%s", exchange_node_name ); exchange_start_msg->exchange_seq = htonl(exchange_seq); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_service_domain_exchange_start_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Service Domain Exchange // ======================================== SmErrorT sm_msg_send_service_domain_exchange( char node_name[], char exchange_node_name[], int exchange_seq, int64_t member_id, char member_name[], SmServiceGroupStateT member_desired_state, SmServiceGroupStateT member_state, SmServiceGroupStatusT member_status, SmServiceGroupConditionT member_condition, int64_t member_health, char reason_text[], bool more_members, int64_t last_received_member_id, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgServiceDomainExchangeT* exchange_msg = &(msg->u.exchange); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_SERVICE_DOMAIN_EXCHANGE); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( exchange_msg->service_domain, sizeof(exchange_msg->service_domain), "%s", interface->service_domain ); snprintf( exchange_msg->node_name, sizeof(exchange_msg->node_name), "%s", node_name ); snprintf( exchange_msg->exchange_node_name, sizeof(exchange_msg->exchange_node_name), "%s", exchange_node_name ); exchange_msg->exchange_seq = htonl(exchange_seq); exchange_msg->member_id = htonll(member_id); snprintf( exchange_msg->member_name, sizeof(exchange_msg->member_name), "%s", member_name ); snprintf( exchange_msg->member_desired_state, sizeof(exchange_msg->member_desired_state), "%s", sm_service_group_state_str(member_desired_state) ); snprintf( exchange_msg->member_state, sizeof(exchange_msg->member_state), "%s", sm_service_group_state_str(member_state) ); snprintf( exchange_msg->member_status, sizeof(exchange_msg->member_status), "%s", sm_service_group_status_str(member_status) ); snprintf( exchange_msg->member_condition, sizeof( exchange_msg->member_condition), "%s", sm_service_group_condition_str(member_condition) ); exchange_msg->member_health = htonll(member_health); snprintf( exchange_msg->reason_text, sizeof(exchange_msg->reason_text), "%s", reason_text ); exchange_msg->more_members = htonl(more_members ? 1 : 0); exchange_msg->last_received_member_id = htonll(last_received_member_id); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_service_domain_exchange_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Service Domain Member Request // ============================================== SmErrorT sm_msg_send_service_domain_member_request( char node_name[], char member_node_name[], int64_t member_id, char member_name[], SmServiceGroupActionT member_action, SmServiceGroupActionFlagsT member_action_flags, SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgServiceDomainMemberRequestT* request_msg = &(msg->u.request); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_SERVICE_DOMAIN_MEMBER_REQUEST); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( request_msg->service_domain, sizeof(request_msg->service_domain), "%s", interface->service_domain ); snprintf( request_msg->node_name, sizeof(request_msg->node_name), "%s", node_name ); snprintf( request_msg->member_node_name, sizeof(request_msg->member_node_name), "%s", member_node_name ); request_msg->member_id = htonll(member_id); snprintf( request_msg->member_name, sizeof(request_msg->member_name), "%s", member_name ); snprintf( request_msg->member_action, sizeof(request_msg->member_action), "%s", sm_service_group_action_str(member_action) ); request_msg->member_action_flags = htonll(member_action_flags); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_service_domain_member_request_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Send Service Domain Member Update // ============================================= SmErrorT sm_msg_send_service_domain_member_update( char node_name[], char member_node_name[], int64_t member_id, char member_name[], SmServiceGroupStateT member_desired_state, SmServiceGroupStateT member_state, SmServiceGroupStatusT member_status, SmServiceGroupConditionT member_condition, int64_t member_health, const char reason_text[], SmServiceDomainInterfaceT* interface ) { SmMsgT* msg = (SmMsgT*) _tx_buffer; SmMsgServiceDomainMemberUpdateT* update_msg = &(msg->u.update); int result = -1; memset( _tx_buffer, 0, sizeof(_tx_buffer) ); msg->header.version = htons(SM_VERSION); msg->header.revision = htons(SM_REVISION); msg->header.max_supported_version = htons(SM_VERSION); msg->header.max_supported_revision = htons(SM_REVISION); msg->header.msg_len = htons(sizeof(SmMsgT)); msg->header.msg_type = htons(SM_MSG_TYPE_SERVICE_DOMAIN_MEMBER_UPDATE); msg->header.msg_flags = htonll(0); snprintf( msg->header.msg_instance, sizeof(msg->header.msg_instance), "%s", _msg_instance ); msg->header.msg_seq_num = htonll(_msg_seq_num); snprintf( msg->header.node_name, sizeof(msg->header.node_name), "%s", _hostname ); snprintf( update_msg->service_domain, sizeof(update_msg->service_domain), "%s", interface->service_domain ); snprintf( update_msg->node_name, sizeof(update_msg->node_name), "%s", node_name ); snprintf( update_msg->member_node_name, sizeof(update_msg->member_node_name), "%s", member_node_name ); update_msg->member_id = htonll(member_id); snprintf( update_msg->member_name, sizeof(update_msg->member_name), "%s", member_name ); snprintf( update_msg->member_desired_state, sizeof(update_msg->member_desired_state), "%s", sm_service_group_state_str(member_desired_state) ); snprintf( update_msg->member_state, sizeof(update_msg->member_state), "%s", sm_service_group_state_str(member_state) ); snprintf( update_msg->member_status, sizeof(update_msg->member_status), "%s", sm_service_group_status_str(member_status) ); snprintf( update_msg->member_condition, sizeof(update_msg->member_condition), "%s", sm_service_group_condition_str(member_condition) ); update_msg->member_health = htonll(member_health); snprintf( update_msg->reason_text, sizeof(update_msg->reason_text), "%s", reason_text ); if( SM_AUTH_TYPE_HMAC_SHA512 == interface->auth_type ) { SmSha512HashT hash; msg->header.auth_type = htonl(interface->auth_type); sm_sha512_hmac( msg, sizeof(SmMsgT), interface->auth_key, strlen(interface->auth_key), &hash ); memcpy( &(msg->header.auth_vector[0]), &(hash.bytes[0]), SM_SHA512_HASH_SIZE ); } else { msg->header.auth_type = htonl(SM_AUTH_TYPE_NONE); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { result = sm_send_msg(interface, msg); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { result = sm_send_ipv6_msg(interface, msg); } if( 0 > result ) { if ( _MSG_NOT_SENT_TO_TARGET != result ) { DPRINTFE( "Failed to send message on socket for interface (%s), " "error=%s.", interface->interface_name, strerror( errno ) ); return( SM_FAILED ); } return( SM_OKAY ); } ++_send_service_domain_member_update_cnt; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Get Ancillary Data // ============================== static void* sm_msg_get_ancillary_data( struct msghdr* msg_hdr, int cmsg_level, int cmsg_type ) { struct cmsghdr* cmsg; for( cmsg = CMSG_FIRSTHDR(msg_hdr); NULL != cmsg; cmsg = CMSG_NXTHDR( msg_hdr, cmsg) ) { if(( cmsg_level == cmsg->cmsg_level )&& ( cmsg_type == cmsg->cmsg_type )) { return( CMSG_DATA(cmsg) ); } } return( NULL ); } // **************************************************************************** // **************************************************************************** // Messaging - Dispatch Message // ============================ static void sm_msg_dispatch_msg( bool is_multicast_msg, SmMsgT* msg, SmNetworkAddressT* network_address, int network_port, SmMsgPeerInterfaceInfoT* peer_interface ) { SmListT* entry = NULL; SmListEntryDataPtrT entry_data; SmMsgCallbacksT* callbacks; SmMsgNodeHelloT* node_hello_msg = &(msg->u.node_hello); SmMsgNodeUpdateT* node_update_msg = &(msg->u.node_update); SmMsgNodeSwactT* node_swact_msg; SmMsgNodeSwactAckT* node_swact_ack_msg; SmNodeAdminStateT node_admin_state; SmNodeOperationalStateT node_oper_state; SmNodeAvailStatusT node_avail_status; SmNodeReadyStateT node_ready_state; SmMsgServiceDomainHelloT* hello_msg = &(msg->u.hello); SmMsgServiceDomainPauseT* pause_msg = &(msg->u.pause); SmMsgServiceDomainExchangeStartT* exchange_start_msg; SmMsgServiceDomainExchangeT* exchange_msg = &(msg->u.exchange); SmMsgServiceDomainMemberRequestT* request_msg = &(msg->u.request); SmMsgServiceDomainMemberUpdateT* update_msg = &(msg->u.update); SmServiceGroupStateT member_desired_state; SmServiceGroupStateT member_state; SmServiceGroupStatusT member_status; SmServiceGroupConditionT member_condition; SmServiceGroupActionT member_action; node_swact_msg = &(msg->u.node_swact); node_swact_ack_msg = &(msg->u.node_swact_ack); exchange_start_msg = &(msg->u.exchange_start); if( SM_VERSION != ntohs(msg->header.version) ) { ++_rcvd_bad_msg_version; DPRINTFD( "Received unsupported version (%i).", ntohs(msg->header.version) ); return; } if( 0 == strcmp( _hostname, msg->header.node_name ) ) { DPRINTFD( "Received own message (%i),", ntohs(msg->header.msg_type) ); return; } if( !(sm_msg_in_sequence( msg->header.node_name, msg->header.msg_instance, ntohll(msg->header.msg_seq_num) )) ) { DPRINTFD( "Duplicate message received from node (%s), " "msg_seq=%" PRIi64 ".", msg->header.node_name, ntohll(msg->header.msg_seq_num) ); return; } else { DPRINTFD( "Message received from node (%s), " "msg_seq=%" PRIi64 ".", msg->header.node_name, ntohll(msg->header.msg_seq_num) ); } if( SM_AUTH_TYPE_HMAC_SHA512 == ntohl(msg->header.auth_type) ) { uint8_t auth_vector[SM_AUTHENTICATION_VECTOR_MAX_CHAR]; SmSha512HashT hash; memcpy( auth_vector, &(msg->header.auth_vector[0]), SM_AUTHENTICATION_VECTOR_MAX_CHAR ); memset( &(msg->header.auth_vector[0]), 0, SM_AUTHENTICATION_VECTOR_MAX_CHAR ); sm_sha512_hmac( msg, sizeof(SmMsgT), peer_interface->auth_key, strlen(peer_interface->auth_key), &hash ); if( 0 != memcmp( &(hash.bytes[0]), auth_vector, SM_SHA512_HASH_SIZE ) ) { ++_rcvd_bad_msg_auth; DPRINTFD( "Authentication check failed on message (%i) from " "node (%s).", ntohs(msg->header.msg_type), msg->header.node_name ); return; } else { DPRINTFD( "Authentication check passed on message (%i) from " "node (%s).", ntohs(msg->header.msg_type), msg->header.node_name ); } } uint16_t msg_type = ntohs(msg->header.msg_type) ; switch( msg_type ) { case SM_MSG_TYPE_NODE_HELLO: ++_rcvd_node_hello_cnt; node_admin_state = sm_node_admin_state_value(node_hello_msg->admin_state); node_oper_state = sm_node_oper_state_value(node_hello_msg->oper_state); node_avail_status = sm_node_avail_status_value(node_hello_msg->avail_status); node_ready_state = sm_node_ready_state_value(node_hello_msg->ready_state); SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->node_hello ) continue; callbacks->node_hello( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), node_hello_msg->node_name, node_admin_state, node_oper_state, node_avail_status, node_ready_state, node_hello_msg->state_uuid, ntohl(node_hello_msg->uptime) ); } break; case SM_MSG_TYPE_NODE_UPDATE: ++_rcvd_node_update_cnt; node_admin_state = sm_node_admin_state_value(node_update_msg->admin_state); node_oper_state = sm_node_oper_state_value(node_update_msg->oper_state); node_avail_status = sm_node_avail_status_value(node_update_msg->avail_status); node_ready_state = sm_node_ready_state_value(node_update_msg->ready_state); SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->node_update ) continue; callbacks->node_update( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), node_update_msg->node_name, node_admin_state, node_oper_state, node_avail_status, node_ready_state, node_update_msg->old_state_uuid, node_update_msg->state_uuid, ntohl(node_update_msg->uptime), ntohl(node_update_msg->force) ); } break; case SM_MSG_TYPE_NODE_SWACT: ++_rcvd_node_swact_cnt; SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->node_swact ) continue; callbacks->node_swact( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), node_swact_msg->node_name, ntohl(node_swact_msg->force), node_swact_msg->request_uuid ); } break; case SM_MSG_TYPE_NODE_SWACT_ACK: ++_rcvd_node_swact_ack_cnt; SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->node_swact_ack ) continue; callbacks->node_swact_ack( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), node_swact_ack_msg->node_name, ntohl(node_swact_ack_msg->force), node_swact_ack_msg->request_uuid ); } break; case SM_MSG_TYPE_SERVICE_DOMAIN_HELLO: ++_rcvd_service_domain_hello_cnt; SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->hello ) continue; callbacks->hello( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), hello_msg->service_domain, hello_msg->node_name, hello_msg->orchestration, hello_msg->designation, ntohl(hello_msg->generation), ntohl(hello_msg->priority), ntohl(hello_msg->hello_interval), ntohl(hello_msg->dead_interval), ntohl(hello_msg->wait_interval), ntohl(hello_msg->exchange_interval), hello_msg->leader ); } break; case SM_MSG_TYPE_SERVICE_DOMAIN_PAUSE: ++_send_service_domain_pause_cnt; SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->pause ) continue; callbacks->pause( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), pause_msg->service_domain, pause_msg->node_name, ntohl(pause_msg->pause_interval) ); } break; case SM_MSG_TYPE_SERVICE_DOMAIN_EXCHANGE_START: if( 0 != strcmp( exchange_start_msg->exchange_node_name, _hostname ) ) { DPRINTFD( "Exchange start message not for us." ); return; } ++_rcvd_service_domain_exchange_start_cnt; SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->exchange_start ) continue; callbacks->exchange_start( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), exchange_start_msg->service_domain, exchange_start_msg->node_name, ntohl(exchange_start_msg->exchange_seq) ); } break; case SM_MSG_TYPE_SERVICE_DOMAIN_EXCHANGE: if( 0 != strcmp( exchange_msg->exchange_node_name, _hostname ) ) { DPRINTFD( "Exchange message not for us." ); return; } ++_rcvd_service_domain_exchange_cnt; member_desired_state = sm_service_group_state_value( exchange_msg->member_desired_state ); member_state = sm_service_group_state_value( exchange_msg->member_state ); member_status = sm_service_group_status_value( exchange_msg->member_status ); member_condition = sm_service_group_condition_value( exchange_msg->member_condition ); SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->exchange ) continue; callbacks->exchange( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), exchange_msg->service_domain, exchange_msg->node_name, ntohl(exchange_msg->exchange_seq), ntohll(exchange_msg->member_id), exchange_msg->member_name, member_desired_state, member_state, member_status, member_condition, ntohll(exchange_msg->member_health), exchange_msg->reason_text, ntohl(exchange_msg->more_members) ? true : false, ntohll(exchange_msg->last_received_member_id) ); } break; case SM_MSG_TYPE_SERVICE_DOMAIN_MEMBER_REQUEST: if( 0 != strcmp( request_msg->member_node_name, _hostname ) ) { DPRINTFD( "Member request message not for us." ); return; } ++_rcvd_service_domain_member_request_cnt; member_action = sm_service_group_action_value( request_msg->member_action ); SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->member_request ) continue; callbacks->member_request( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), request_msg->service_domain, request_msg->node_name, request_msg->member_node_name, ntohll(request_msg->member_id), request_msg->member_name, member_action, ntohll(request_msg->member_action_flags) ); } break; case SM_MSG_TYPE_SERVICE_DOMAIN_MEMBER_UPDATE: ++_rcvd_service_domain_member_update_cnt; member_desired_state = sm_service_group_state_value( update_msg->member_desired_state ); member_state = sm_service_group_state_value( update_msg->member_state ); member_status = sm_service_group_status_value( update_msg->member_status ); member_condition = sm_service_group_condition_value( update_msg->member_condition ); SM_LIST_FOREACH( _callbacks, entry, entry_data ) { callbacks = (SmMsgCallbacksT*) entry_data; if( NULL == callbacks->member_update ) continue; callbacks->member_update( network_address, network_port, ntohs(msg->header.version), ntohs(msg->header.revision), update_msg->service_domain, update_msg->node_name, update_msg->member_node_name, ntohll(update_msg->member_id), update_msg->member_name, member_desired_state, member_state, member_status, member_condition, ntohll(update_msg->member_health), update_msg->reason_text ); } break; default: DPRINTFI( "Unsupported message type (%i) received.", ntohs(msg->header.msg_type) ); break; } } // **************************************************************************** // **************************************************************************** // Messaging - Dispatch Ipv4 Udp // ============================= static void sm_msg_dispatch_ipv4_udp( int selobj, int64_t msg_method ) { SmMsgT* msg = (SmMsgT*) _rx_buffer; SmNetworkAddressT network_address; SmMsgPeerInterfaceInfoT* peer_interface = NULL; SmErrorT error; int network_port; struct sockaddr_in src_addr; struct iovec iovec = {(void*)_rx_buffer, sizeof(_rx_buffer)}; struct msghdr msg_hdr; int bytes_read; memset( &network_address, 0, sizeof(network_address) ); memset( _rx_control_buffer, 0, sizeof(_rx_control_buffer) ); memset( _rx_buffer, 0, sizeof(_rx_buffer) ); memset( &msg_hdr, 0, sizeof(msg_hdr) ); msg_hdr.msg_name = &src_addr; msg_hdr.msg_namelen= sizeof(src_addr); msg_hdr.msg_iov = &iovec; msg_hdr.msg_iovlen = 1; msg_hdr.msg_control = _rx_control_buffer; msg_hdr.msg_controllen = sizeof(_rx_control_buffer); int retry_i; for( retry_i = 5; retry_i != 0; --retry_i ) { bytes_read = recvmsg( selobj, &msg_hdr, MSG_NOSIGNAL | MSG_DONTWAIT ); if( 0 < bytes_read ) { break; } else if( 0 == bytes_read ) { // For connection oriented sockets, this indicates that the peer // has performed an orderly shutdown. return; } else if(( 0 > bytes_read )&&( EINTR != errno )) { DPRINTFE( "Failed to receive message, errno=%s.", strerror( errno ) ); return; } DPRINTFD( "Interrupted while receiving message, retry=%d, errno=%s.", retry_i, strerror( errno ) ); } ++_rcvd_total_msgs; if( !_messaging_enabled ) { ++_rcvd_msgs_while_disabled; DPRINTFD( "Messaging is disabled." ); return; } if( AF_INET == src_addr.sin_family ) { char if_name[SM_INTERFACE_NAME_MAX_CHAR] = {0}; struct in_pktinfo* pkt_info; char network_address_str[SM_NETWORK_ADDRESS_MAX_CHAR]; pkt_info = (struct in_pktinfo*) sm_msg_get_ancillary_data( &msg_hdr, SOL_IP, IP_PKTINFO ); if( NULL == pkt_info ) { DPRINTFD( "No packet information available." ); return; } error = sm_hw_get_if_name( pkt_info->ipi_ifindex, if_name ); if( SM_OKAY != error ) { if( SM_NOT_FOUND == error ) { DPRINTFD( "Failed to get interface name for interface index " "(%i), error=%s.", pkt_info->ipi_ifindex, sm_error_str(error) ); } else { DPRINTFE( "Failed to get interface name for interface index " "(%i), error=%s.", pkt_info->ipi_ifindex, sm_error_str(error) ); } return; } network_address.type = SM_NETWORK_TYPE_IPV4_UDP; network_address.u.ipv4.sin.s_addr = src_addr.sin_addr.s_addr; network_port = ntohs(src_addr.sin_port); sm_network_address_str( &network_address, network_address_str ); DPRINTFD( "Received message from ip (%s), port (%i) on " "interface (%s).", network_address_str, network_port, if_name ); peer_interface = sm_msg_get_peer_interface( if_name, &network_address, network_port ); if( NULL == peer_interface ) { DPRINTFD( "Message received not for us, if=%s, ip=%s, port=%i.", if_name, network_address_str, network_port ); return; } } else { DPRINTFE( "Received unsupported network address type (%i).", src_addr.sin_family ); return; } // Once the message is received, pass it to protocol-independent handler sm_msg_dispatch_msg( msg_method, msg, &network_address, network_port, peer_interface ); } // **************************************************************************** // **************************************************************************** // Messaging - Dispatch Ipv6 Udp // ============================= static void sm_msg_dispatch_ipv6_udp( int selobj, int64_t msg_method ) { SmMsgT* msg = (SmMsgT*) _rx_buffer; SmNetworkAddressT network_address; SmMsgPeerInterfaceInfoT* peer_interface = NULL; SmErrorT error; int network_port; struct sockaddr_in6 src_addr; struct iovec iovec = {(void*)_rx_buffer, sizeof(_rx_buffer)}; struct msghdr msg_hdr; int bytes_read; memset( &network_address, 0, sizeof(network_address) ); memset( _rx_control_buffer, 0, sizeof(_rx_control_buffer) ); memset( _rx_buffer, 0, sizeof(_rx_buffer) ); memset( &msg_hdr, 0, sizeof(msg_hdr) ); msg_hdr.msg_name = &src_addr; msg_hdr.msg_namelen= sizeof(src_addr); msg_hdr.msg_iov = &iovec; msg_hdr.msg_iovlen = 1; msg_hdr.msg_control = _rx_control_buffer; msg_hdr.msg_controllen = sizeof(_rx_control_buffer); int retry_i; for( retry_i = 5; retry_i != 0; --retry_i ) { bytes_read = recvmsg( selobj, &msg_hdr, MSG_NOSIGNAL | MSG_DONTWAIT ); if( 0 < bytes_read ) { break; } else if( 0 == bytes_read ) { // For connection oriented sockets, this indicates that the peer // has performed an orderly shutdown. return; } else if(( 0 > bytes_read )&&( EINTR != errno )) { DPRINTFE( "Failed to receive message, errno=%s.", strerror( errno ) ); return; } DPRINTFD( "Interrupted while receiving message, retry=%d, errno=%s.", retry_i, strerror( errno ) ); } ++_rcvd_total_msgs; if( !_messaging_enabled ) { ++_rcvd_msgs_while_disabled; DPRINTFD( "Messaging is disabled." ); return; } if( AF_INET6 == src_addr.sin6_family ) { char if_name[SM_INTERFACE_NAME_MAX_CHAR] = {0}; struct in6_pktinfo* pkt_info; char network_address_str[SM_NETWORK_ADDRESS_MAX_CHAR]; pkt_info = (struct in6_pktinfo*) sm_msg_get_ancillary_data( &msg_hdr, SOL_IPV6, IPV6_PKTINFO ); if( NULL == pkt_info ) { DPRINTFD( "No packet information available." ); return; } error = sm_hw_get_if_name( pkt_info->ipi6_ifindex, if_name ); if( SM_OKAY != error ) { if( SM_NOT_FOUND == error ) { DPRINTFD( "Failed to get interface name for interface index " "(%i), error=%s.", pkt_info->ipi6_ifindex, sm_error_str(error) ); } else { DPRINTFE( "Failed to get interface name for interface index " "(%i), error=%s.", pkt_info->ipi6_ifindex, sm_error_str(error) ); } return; } network_address.type = SM_NETWORK_TYPE_IPV6_UDP; network_address.u.ipv6.sin6 = src_addr.sin6_addr; network_port = ntohs(src_addr.sin6_port); sm_network_address_str( &network_address, network_address_str ); DPRINTFD( "Received message from ip (%s), port (%i) on " "interface (%s).", network_address_str, network_port, if_name ); peer_interface = sm_msg_get_peer_interface( if_name, &network_address, network_port ); if( NULL == peer_interface ) { DPRINTFD( "Message received not for us, if=%s, ip=%s, port=%i.", if_name, network_address_str, network_port ); return; } } else { DPRINTFE( "Received unsupported network address type (%i).", src_addr.sin6_family ); return; } // Once the message is received, pass it to protocol-independent handler sm_msg_dispatch_msg( msg_method, msg, &network_address, network_port, peer_interface ); } // **************************************************************************** // **************************************************************************** // Messaging - Register Ipv4 Multicast Address // =========================================== static SmErrorT sm_msg_register_ipv4_multicast( SmServiceDomainInterfaceT* interface ) { int if_index; struct ip_mreqn mreq; int result = 0; SmIpv4AddressT* ipv4_multicast = &(interface->network_multicast.u.ipv4); SmErrorT error; error = sm_hw_get_if_index( interface->interface_name, &if_index ); if( SM_OKAY != error ) { DPRINTFE( "Failed to convert interface name (%s) to interface index, " "error=%s.", interface->interface_name, sm_error_str( error ) ); return( error ); } memset( &mreq, 0, sizeof(mreq) ); mreq.imr_multiaddr.s_addr = ipv4_multicast->sin.s_addr; mreq.imr_ifindex = if_index; result = setsockopt( interface->multicast_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq) ); if( 0 > result ) { DPRINTFE( "Failed to add multicast membership to interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Register Ipv6 Multicast Address // =========================================== static SmErrorT sm_msg_register_ipv6_multicast( SmServiceDomainInterfaceT* interface ) { int if_index; struct ipv6_mreq mreq; int result = 0; SmIpv6AddressT* ipv6_multicast = &(interface->network_multicast.u.ipv6); SmErrorT error; error = sm_hw_get_if_index( interface->interface_name, &if_index ); if( SM_OKAY != error ) { DPRINTFE( "Failed to convert interface name (%s) to interface index, " "error=%s.", interface->interface_name, sm_error_str( error ) ); return( error ); } memset( &mreq, 0, sizeof(mreq) ); mreq.ipv6mr_multiaddr = ipv6_multicast->sin6; mreq.ipv6mr_interface = if_index; result = setsockopt( interface->multicast_socket, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq) ); if( 0 > result ) { DPRINTFE( "Failed to add multicast membership to interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Deregister Ipv4 Multicast Address // ============================================= static SmErrorT sm_msg_deregister_ipv4_multicast( SmServiceDomainInterfaceT* interface ) { int if_index; struct ip_mreqn mreq; int result = 0; SmIpv4AddressT* ipv4_multicast = &(interface->network_multicast.u.ipv4); SmErrorT error; error = sm_hw_get_if_index( interface->interface_name, &if_index ); if( SM_OKAY != error ) { DPRINTFE( "Failed to convert interface name (%s) to interface index, " "error=%s.", interface->interface_name, sm_error_str( error ) ); return( error ); } memset( &mreq, 0, sizeof(mreq) ); mreq.imr_multiaddr.s_addr = ipv4_multicast->sin.s_addr; mreq.imr_ifindex = if_index; result = setsockopt( interface->multicast_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq) ); if( 0 > result ) { DPRINTFE( "Failed to drop multicast membership from interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Deregister Ipv6 Multicast Address // ============================================= static SmErrorT sm_msg_deregister_ipv6_multicast( SmServiceDomainInterfaceT* interface ) { int if_index; struct ipv6_mreq mreq; int result = 0; SmIpv6AddressT* ipv6_multicast = &(interface->network_multicast.u.ipv6); SmErrorT error; error = sm_hw_get_if_index( interface->interface_name, &if_index ); if( SM_OKAY != error ) { DPRINTFE( "Failed to convert interface name (%s) to interface index, " "error=%s.", interface->interface_name, sm_error_str( error ) ); return( error ); } memset( &mreq, 0, sizeof(mreq) ); mreq.ipv6mr_multiaddr = ipv6_multicast->sin6; mreq.ipv6mr_interface = if_index; result = setsockopt( interface->multicast_socket, IPPROTO_IPV6, IPV6_LEAVE_GROUP, &mreq, sizeof(mreq) ); if( 0 > result ) { DPRINTFE( "Failed to drop multicast membership from interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Open Ipv4 UDP Multicast Socket // ========================================== static SmErrorT sm_msg_open_ipv4_udp_multicast_socket( SmServiceDomainInterfaceT* interface, int* socket_fd ) { int flags; int sock; int result; struct ifreq ifr; struct sockaddr_in addr; SmIpv4AddressT* ipv4_address = &(interface->network_address.u.ipv4); SmIpv4AddressT* ipv4_multicast = &(interface->network_multicast.u.ipv4); *socket_fd = -1; // Create socket. sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); if( 0 > sock ) { DPRINTFE( "Failed to open socket for interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } // Set socket to non-blocking. flags = fcntl( sock, F_GETFL, 0 ); if( 0 > flags ) { DPRINTFE( "Failed to get flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } if( 0 > fcntl( sock, F_SETFL, flags | O_NONBLOCK ) ) { DPRINTFE( "Failed to set flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Close on exec. flags = fcntl( sock, F_GETFD, 0 ); if( 0 > flags ) { DPRINTFE( "Failed to get flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } if( 0 > fcntl( sock, F_SETFD, flags | FD_CLOEXEC ) ) { DPRINTFE( "Failed to set flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Allow address reuse on socket. flags = 1; result = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (void*) &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set reuseaddr socket option on interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Bind address to socket. memset( &addr, 0, sizeof(addr) ); addr.sin_family = AF_INET; addr.sin_port = htons(interface->network_port); addr.sin_addr.s_addr = ipv4_multicast->sin.s_addr; result = bind( sock, (struct sockaddr *) &addr, sizeof(addr) ); if( 0 > result ) { DPRINTFE( "Failed to bind multicast address to socket for " "interface (%s), error=%s.", interface->interface_name, strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Set multicast interface on socket. result = setsockopt( sock, IPPROTO_IP, IP_MULTICAST_IF, (struct in_addr*) &(ipv4_address->sin.s_addr), sizeof(struct in_addr) ); if( 0 > result ) { DPRINTFE( "Failed to set unicast address on socket for " "interface (%s), error=%s.", interface->interface_name, strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Bind socket to interface. memset(&ifr, 0, sizeof(ifr)); snprintf( ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface->interface_name ); result = setsockopt( sock, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr) ); if( 0 > result ) { DPRINTFE( "Failed to bind socket to interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set multicast TTL. flags = 1; result = setsockopt( sock, IPPROTO_IP, IP_MULTICAST_TTL, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set multicast ttl for interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Disable looping of sent multicast packets on socket. flags = 0; result = setsockopt( sock, IPPROTO_IP, IP_MULTICAST_LOOP, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to stop looping of multicast messages for " "interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket send priority on interface. flags = IPTOS_CLASS_CS6; result = setsockopt( sock, IPPROTO_IP, IP_TOS, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "multicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } flags = 6; result = setsockopt( sock, SOL_SOCKET, SO_PRIORITY, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "multicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket receive packet information. flags = 1; result = setsockopt( sock, SOL_IP, IP_PKTINFO, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket receive packet information for " "interface (%s) multicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } *socket_fd = sock; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Open IPv6 UDP Multicast Socket // ========================================== static SmErrorT sm_msg_open_ipv6_udp_multicast_socket( SmServiceDomainInterfaceT* interface, int* socket_fd ) { int flags; int sock; int result; struct ifreq ifr; struct sockaddr_in6 addr; SmIpv6AddressT* ipv6_multicast = &(interface->network_multicast.u.ipv6); *socket_fd = -1; // Create socket. sock = socket( AF_INET6, SOCK_DGRAM, IPPROTO_UDP ); if( 0 > sock ) { DPRINTFE( "Failed to open socket for interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } // Set socket to non-blocking. flags = fcntl( sock, F_GETFL, 0 ); if( 0 > flags ) { DPRINTFE( "Failed to get flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } if( 0 > fcntl( sock, F_SETFL, flags | O_NONBLOCK ) ) { DPRINTFE( "Failed to set flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Close on exec. flags = fcntl( sock, F_GETFD, 0 ); if( 0 > flags ) { DPRINTFE( "Failed to get flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } if( 0 > fcntl( sock, F_SETFD, flags | FD_CLOEXEC ) ) { DPRINTFE( "Failed to set flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Allow address reuse on socket. flags = 1; result = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (void*) &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set reuseaddr socket option on interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Bind address to socket. memset( &addr, 0, sizeof(addr) ); addr.sin6_family = AF_INET6; addr.sin6_port = htons(interface->network_port); addr.sin6_addr = ipv6_multicast->sin6; result = bind( sock, (struct sockaddr *) &addr, sizeof(addr) ); if( 0 > result ) { DPRINTFE( "Failed to bind multicast address to socket for " "interface (%s), error=%s.", interface->interface_name, strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Bind socket to interface. memset( &ifr, 0, sizeof(ifr) ); snprintf( ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface->interface_name ); result = setsockopt( sock, SOL_SOCKET, SO_BINDTODEVICE, (void* )&ifr, sizeof(ifr) ); if( 0 > result ) { DPRINTFE( "Failed to bind socket to interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set multicast TTL. flags = 1; result = setsockopt( sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set multicast ttl for interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Disable looping of sent multicast packets on socket. flags = 0; result = setsockopt( sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to stop looping of multicast messages for " "interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket send priority on interface. flags = IPTOS_CLASS_CS6; result = setsockopt( sock, IPPROTO_IPV6, IPV6_TCLASS, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "multicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } flags = 6; result = setsockopt( sock, SOL_SOCKET, SO_PRIORITY, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "multicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket receive packet information. flags = 1; result = setsockopt( sock, SOL_IPV6, IPV6_RECVPKTINFO, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket receive packet information for " "interface (%s) multicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } *socket_fd = sock; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Open Ipv4 UDP Unicast Socket // ======================================== static SmErrorT sm_msg_open_ipv4_udp_unicast_socket( SmServiceDomainInterfaceT* interface, int* socket_fd ) { int flags; int sock; int result; struct sockaddr_in src_addr; SmIpv4AddressT* ipv4_address = &(interface->network_address.u.ipv4); *socket_fd = -1; // Create socket. sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); if( 0 > sock ) { DPRINTFE( "Failed to open socket for interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } // Set socket to non-blocking. flags = fcntl( sock, F_GETFL, 0 ); if( 0 > flags ) { DPRINTFE( "Failed to get flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } if( 0 > fcntl( sock, F_SETFL, flags | O_NONBLOCK ) ) { DPRINTFE( "Failed to set flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Close on exec. if( 0 > fcntl( sock, F_SETFD, FD_CLOEXEC ) ) { DPRINTFE( "Failed to set fd, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Allow address reuse on socket. flags = 1; result = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (void*) &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set reuseaddr socket option on interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Bind address to socket. memset( &src_addr, 0, sizeof(src_addr) ); src_addr.sin_family = AF_INET; src_addr.sin_port = htons(interface->network_port); src_addr.sin_addr.s_addr = ipv4_address->sin.s_addr; result = bind( sock, (struct sockaddr *) &src_addr, sizeof(src_addr) ); if( 0 > result ) { DPRINTFE( "Failed to bind unicast address to socket for " "interface (%s), error=%s.", interface->interface_name, strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Bind socket to interface. result = setsockopt( sock, SOL_SOCKET, SO_BINDTODEVICE, interface->interface_name, strlen(interface->interface_name)+1 ); if( 0 > result ) { DPRINTFE( "Failed to bind socket to interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Disable looping of sent multicast packets on socket. flags = 0; result = setsockopt( sock, IPPROTO_IP, IP_MULTICAST_LOOP, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to stop looping of unicast messages for " "interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket send priority on interface. flags = IPTOS_CLASS_CS6; result = setsockopt( sock, IPPROTO_IP, IP_TOS, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "unicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } flags = 6; result = setsockopt( sock, SOL_SOCKET, SO_PRIORITY, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "unicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket receive packet information. flags = 1; result = setsockopt( sock, SOL_IP, IP_PKTINFO, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket receive packet information for " "interface (%s) unicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } *socket_fd = sock; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Open IPv6 UDP Unicast Socket // ======================================== static SmErrorT sm_msg_open_ipv6_udp_unicast_socket( SmServiceDomainInterfaceT* interface, int* socket_fd ) { int flags; int sock; int result; struct sockaddr_in6 src_addr; SmIpv6AddressT* ipv6_address = &(interface->network_address.u.ipv6); *socket_fd = -1; // Create socket. sock = socket( AF_INET6, SOCK_DGRAM, IPPROTO_UDP ); if( 0 > sock ) { DPRINTFE( "Failed to open socket for interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); return( SM_FAILED ); } // Set socket to non-blocking. flags = fcntl( sock, F_GETFL, 0 ); if( 0 > flags ) { DPRINTFE( "Failed to get flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } if( 0 > fcntl( sock, F_SETFL, flags | O_NONBLOCK ) ) { DPRINTFE( "Failed to set flags, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Close on exec. if( 0 > fcntl( sock, F_SETFD, FD_CLOEXEC ) ) { DPRINTFE( "Failed to set fd, error=%s.", strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Allow address reuse on socket. flags = 1; result = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (void*) &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set reuseaddr socket option on interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Bind address to socket. memset( &src_addr, 0, sizeof(src_addr) ); src_addr.sin6_family = AF_INET6; src_addr.sin6_port = htons(interface->network_port); src_addr.sin6_addr = ipv6_address->sin6; result = bind( sock, (struct sockaddr *) &src_addr, sizeof(src_addr) ); if( 0 > result ) { DPRINTFE( "Failed to bind unicast address to socket for " "interface (%s), error=%s.", interface->interface_name, strerror( errno ) ); close( sock ); return( SM_FAILED ); } // Bind socket to interface. result = setsockopt( sock, SOL_SOCKET, SO_BINDTODEVICE, interface->interface_name, strlen(interface->interface_name)+1 ); if( 0 > result ) { DPRINTFE( "Failed to bind socket to interface (%s), " "errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Disable looping of sent multicast packets on socket. flags = 0; result = setsockopt( sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to stop looping of unicast messages for " "interface (%s), errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket send priority on interface. flags = IPTOS_CLASS_CS6; result = setsockopt( sock, IPPROTO_IPV6, IPV6_TCLASS, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "unicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } flags = 6; result = setsockopt( sock, SOL_SOCKET, SO_PRIORITY, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket send priority for interface (%s) " "unicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } // Set socket receive packet information. flags = 1; result = setsockopt( sock, SOL_IPV6, IPV6_RECVPKTINFO, &flags, sizeof(flags) ); if( 0 > result ) { DPRINTFE( "Failed to set socket receive packet information for " "interface (%s) unicast messages, errno=%s.", interface->interface_name, strerror(errno) ); close( sock ); return( SM_FAILED ); } *socket_fd = sock; return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Open Sockets // ======================== SmErrorT sm_msg_open_sockets( SmServiceDomainInterfaceT* interface ) { SmErrorT error; if( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type ) { int unicast_socket, multicast_socket; error = sm_msg_open_ipv4_udp_unicast_socket( interface, &unicast_socket ); if( SM_OKAY != error ) { DPRINTFE( "Failed to open unicast socket for interface (%s), " "error=%s.", interface->interface_name, sm_error_str(error) ); return( error ); } error = sm_selobj_register( unicast_socket, sm_msg_dispatch_ipv4_udp, (int64_t) false ); if( SM_OKAY != error ) { DPRINTFE( "Failed to register selection object for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); return( SM_FAILED ); } if( interface->network_multicast.type != SM_NETWORK_TYPE_NIL ) { error = sm_msg_open_ipv4_udp_multicast_socket( interface, &multicast_socket ); if( SM_OKAY != error ) { DPRINTFE( "Failed to open multicast socket for interface (%s), " "error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); return( error ); } error = sm_selobj_register( multicast_socket, sm_msg_dispatch_ipv4_udp, (int64_t) false ); if( SM_OKAY != error ) { DPRINTFE( "Failed to register selection object for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); close( multicast_socket ); return( SM_FAILED ); } interface->unicast_socket = unicast_socket; interface->multicast_socket = multicast_socket; error = sm_msg_register_ipv4_multicast( interface ); if( SM_OKAY != error ) { DPRINTFE( "Failed to register multicast address for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); interface->unicast_socket = -1; close( multicast_socket ); interface->multicast_socket = -1; return( SM_FAILED ); } } else { DPRINTFD( "Multicast not configured in the interface %s", interface->interface_name ); interface->unicast_socket = unicast_socket; interface->multicast_socket = -1; } return( SM_OKAY ); } else if( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type ) { int unicast_socket, multicast_socket; error = sm_msg_open_ipv6_udp_unicast_socket( interface, &unicast_socket ); if( SM_OKAY != error ) { DPRINTFE( "Failed to open unicast socket for interface (%s), " "error=%s.", interface->interface_name, sm_error_str(error) ); return( error ); } error = sm_selobj_register( unicast_socket, sm_msg_dispatch_ipv6_udp, (int64_t) false); if( SM_OKAY != error ) { DPRINTFE( "Failed to register selection object for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); return( SM_FAILED ); } if( interface->network_multicast.type != SM_NETWORK_TYPE_NIL ) { error = sm_msg_open_ipv6_udp_multicast_socket( interface, &multicast_socket ); if( SM_OKAY != error ) { DPRINTFE( "Failed to open multicast socket for interface (%s), " "error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); return( error ); } error = sm_selobj_register( multicast_socket, sm_msg_dispatch_ipv6_udp, (int64_t) false ); if( SM_OKAY != error ) { DPRINTFE( "Failed to register selection object for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); close( multicast_socket ); return( SM_FAILED ); } interface->unicast_socket = unicast_socket; interface->multicast_socket = multicast_socket; error = sm_msg_register_ipv6_multicast( interface ); if( SM_OKAY != error ) { DPRINTFE( "Failed to register multicast address for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); close( unicast_socket ); interface->unicast_socket = -1; close( multicast_socket ); interface->multicast_socket = -1; return( SM_FAILED ); } } else { interface->unicast_socket = unicast_socket; interface->multicast_socket = -1; } return( SM_OKAY ); } else { DPRINTFE( "Unsupported network type (%s).", sm_network_type_str( interface->network_type ) ); return( SM_FAILED ); } } // **************************************************************************** // **************************************************************************** // Messaging - Close Sockets // ========================= SmErrorT sm_msg_close_sockets( SmServiceDomainInterfaceT* interface ) { SmErrorT error; if( -1 < interface->unicast_socket ) { error = sm_selobj_deregister( interface->unicast_socket ); if( SM_OKAY != error ) { DPRINTFE( "Failed to deregister selection object for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); } close( interface->unicast_socket ); interface->unicast_socket = -1; } if( -1 < interface->multicast_socket ) { error = sm_selobj_deregister( interface->multicast_socket ); if( SM_OKAY != error ) { DPRINTFE( "Failed to deregister selection object for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); } if(( SM_NETWORK_TYPE_IPV4_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV4 == interface->network_type )) { error = sm_msg_deregister_ipv4_multicast( interface ); } else if(( SM_NETWORK_TYPE_IPV6_UDP == interface->network_type )|| ( SM_NETWORK_TYPE_IPV6 == interface->network_type )) { error = sm_msg_deregister_ipv6_multicast( interface ); } if( SM_OKAY != error ) { DPRINTFE( "Failed to deregister multicast address for " "interface (%s), error=%s.", interface->interface_name, sm_error_str(error) ); } close( interface->multicast_socket ); interface->multicast_socket = -1; } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Dump Data // ===================== void sm_msg_dump_data( FILE* log ) { fprintf( log, "--------------------------------------------------------------------\n" ); fprintf( log, "MESSAGING DATA\n" ); fprintf( log, " rcvd_total_msgs..............................%" PRIu64 "\n", _rcvd_total_msgs ); fprintf( log, " rcvd_msgs_while_disabled.....................%" PRIu64 "\n", _rcvd_msgs_while_disabled ); fprintf( log, " rcvd_bad_msg_auth............................%" PRIu64 "\n", _rcvd_bad_msg_auth ); fprintf( log, " rcvd_bad_msg_version.........................%" PRIu64 "\n", _rcvd_bad_msg_version ); fprintf( log, " send_node_hello_count........................%" PRIu64 "\n", _send_node_hello_cnt ); fprintf( log, " rcvd_node_hello_count........................%" PRIu64 "\n", _rcvd_node_hello_cnt ); fprintf( log, " send_node_update_count.......................%" PRIu64 "\n", _send_node_update_cnt ); fprintf( log, " rcvd_node_update_count.......................%" PRIu64 "\n", _rcvd_node_update_cnt ); fprintf( log, " send_node_swact_count........................%" PRIu64 "\n", _send_node_swact_cnt ); fprintf( log, " rcvd_node_swact_count........................%" PRIu64 "\n", _rcvd_node_swact_cnt ); fprintf( log, " send_node_swact_ack_count....................%" PRIu64 "\n", _send_node_swact_ack_cnt ); fprintf( log, " rcvd_node_swact_ack_count....................%" PRIu64 "\n", _rcvd_node_swact_ack_cnt ); fprintf( log, " send_service_domain_hello_count..............%" PRIu64 "\n", _send_service_domain_hello_cnt ); fprintf( log, " rcvd_service_domain_hello_count..............%" PRIu64 "\n", _rcvd_service_domain_hello_cnt ); fprintf( log, " send_service_domain_pause_count..............%" PRIu64 "\n", _send_service_domain_pause_cnt ); fprintf( log, " rcvd_service_domain_pause_count..............%" PRIu64 "\n", _rcvd_service_domain_pause_cnt ); fprintf( log, " send_service_domain_exchange_start_count.....%" PRIu64 "\n", _send_service_domain_exchange_start_cnt ); fprintf( log, " rcvd_service_domain_exchange_start_count.....%" PRIu64 "\n", _rcvd_service_domain_exchange_start_cnt ); fprintf( log, " send_service_domain_exchange_count...........%" PRIu64 "\n", _send_service_domain_exchange_cnt ); fprintf( log, " rcvd_service_domain_exchange_count...........%" PRIu64 "\n", _rcvd_service_domain_exchange_cnt ); fprintf( log, " send_service_domain_member_request_count.....%" PRIu64 "\n", _send_service_domain_member_request_cnt ); fprintf( log, " rcvd_service_domain_member_request_count.....%" PRIu64 "\n", _rcvd_service_domain_member_request_cnt ); fprintf( log, " send_service_domain_member_update_count......%" PRIu64 "\n", _send_service_domain_member_update_cnt ); fprintf( log, " rcvd_service_domain_member_update_count......%" PRIu64 "\n", _rcvd_service_domain_member_update_cnt ); fprintf( log, "--------------------------------------------------------------------\n" ); } // **************************************************************************** // **************************************************************************** // Messaging - Initialize // ====================== SmErrorT sm_msg_initialize( void ) { SmErrorT error; _hostname[0] = '\0'; error = sm_node_utils_get_hostname( _hostname ); if( SM_OKAY != error ) { DPRINTFE( "Failed to get local hostname." ); return( SM_FAILED ); } _messaging_enabled = false; sm_uuid_create( _msg_instance ); DPRINTFI( "Message instance (%s) created.", _msg_instance ); DPRINTFV( "Hello message size is %i.", sizeof(SmMsgNodeHelloT) ); DPRINTFV( "Node update message size is %i.", sizeof(SmMsgNodeUpdateT) ); DPRINTFV( "Swact message size is %i.", sizeof(SmMsgNodeSwactT) ); DPRINTFV( "Swact ack message size is %i.", sizeof(SmMsgNodeSwactAckT) ); DPRINTFV( "Service Domain Hello message size is %i.", sizeof(SmMsgServiceDomainHelloT) ); DPRINTFV( "Service Domain Pause message size is %i.", sizeof(SmMsgServiceDomainPauseT) ); DPRINTFV( "Service Domain Exchange Start message size is %i.", sizeof(SmMsgServiceDomainExchangeStartT) ); DPRINTFV( "Service Domain Exchange message size is %i.", sizeof(SmMsgServiceDomainExchangeT) ); DPRINTFV( "Service Domain Member Request message size is %i.", sizeof(SmMsgServiceDomainMemberRequestT) ); DPRINTFV( "Service Domain Member Update message size is %i.", sizeof(SmMsgServiceDomainMemberUpdateT) ); return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Messaging - Finalize // ==================== SmErrorT sm_msg_finalize( void ) { _hostname[0] = '\0'; _messaging_enabled = false; memset( _msg_instance, 0, sizeof(_msg_instance) ); return( SM_OKAY ); } // ****************************************************************************
SidneyAn/ha
service-mgmt/sm/src/sm_service_table.c
<reponame>SidneyAn/ha // // Copyright (c) 2014-2018 Wind River Systems, Inc. // // SPDX-License-Identifier: Apache-2.0 // #include "sm_service_table.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sm_limits.h" #include "sm_types.h" #include "sm_debug.h" #include "sm_list.h" #include "sm_db.h" #include "sm_db_foreach.h" #include "sm_db_services.h" #include "sm_db_service_instances.h" #include "sm_service_enable.h" #include "sm_service_disable.h" #include "sm_service_go_active.h" #include "sm_service_go_standby.h" #include "sm_service_audit.h" #include "sm_service_group_table.h" #include "sm_service_group_member_table.h" static SmListT* _services = NULL; static SmDbHandleT* _sm_db_handle = NULL; static SmErrorT sm_service_table_add( void* user_data[], void* record ); // **************************************************************************** // Service Table - clear failure state // returns true if service is in a failure state // ==================== bool sm_service_clear_failure_state(SmServiceT* service) { SmErrorT error; bool prev_failure_condition; prev_failure_condition = service->recover || service->fail_count > 0 || service->action_fail_count > 0 || service->transition_fail_count > 0 || service->status == SM_SERVICE_STATUS_FAILED || service->condition == SM_SERVICE_CONDITION_RECOVERY_FAILURE || service->condition == SM_SERVICE_CONDITION_ACTION_FAILURE || service->condition == SM_SERVICE_CONDITION_FATAL_FAILURE; if( prev_failure_condition ) { service->recover = false; service->fail_count = 0; service->action_fail_count = 0; service->transition_fail_count = 0; service->status = SM_SERVICE_STATUS_NONE; service->condition = SM_SERVICE_CONDITION_NONE; error = sm_service_table_persist( service ); if( SM_OKAY != error ) { DPRINTFE( "Failed to persist service (%s) data, error=%s.", service->name, sm_error_str(error) ); } DPRINTFI( "Cleared previous failure condition for service (%s) " "in % state.", service->name, sm_service_state_str(service->state) ); } return prev_failure_condition; } // **************************************************************************** // Service Table - Read // ==================== SmServiceT* sm_service_table_read( char service_name[] ) { SmListT* entry = NULL; SmListEntryDataPtrT entry_data; SmServiceT* service; SM_LIST_FOREACH( _services, entry, entry_data ) { service = (SmServiceT*) entry_data; if( 0 == strcmp( service_name, service->name ) ) { return( service ); } } return( NULL ); } // **************************************************************************** // **************************************************************************** // Service Table - Read By Identifier // ================================== SmServiceT* sm_service_table_read_by_id( int64_t service_id ) { SmListT* entry = NULL; SmListEntryDataPtrT entry_data; SmServiceT* service; SM_LIST_FOREACH( _services, entry, entry_data ) { service = (SmServiceT*) entry_data; if( service_id == service->id ) { return( service ); } } return( NULL ); } // **************************************************************************** // **************************************************************************** // Service Table - Read By Pid // =========================== SmServiceT* sm_service_table_read_by_pid( int pid ) { SmListT* entry = NULL; SmListEntryDataPtrT entry_data; SmServiceT* service; SM_LIST_FOREACH( _services, entry, entry_data ) { service = (SmServiceT*) entry_data; if( pid == service->pid ) { return( service ); } } return( NULL ); } // **************************************************************************** // **************************************************************************** // Service Table - Read By Action Pid // ================================== SmServiceT* sm_service_table_read_by_action_pid( int pid ) { SmListT* entry = NULL; SmListEntryDataPtrT entry_data; SmServiceT* service; SM_LIST_FOREACH( _services, entry, entry_data ) { service = (SmServiceT*) entry_data; if( pid == service->action_pid ) { return( service ); } } return( NULL ); } // **************************************************************************** // **************************************************************************** // Service Table - For Each // ======================== void sm_service_table_foreach( void* user_data[], SmServiceTableForEachCallbackT callback ) { SmListT* entry = NULL; SmListEntryDataPtrT entry_data; SM_LIST_FOREACH( _services, entry, entry_data ) { callback( user_data, (SmServiceT*) entry_data ); } } // **************************************************************************** // **************************************************************************** // Service Table - Add // =================== static SmErrorT sm_service_table_add( void* user_data[], void* record ) { SmServiceT* service; SmDbServiceT* db_service = (SmDbServiceT*) record; SmDbServiceInstanceT db_service_instance; SmErrorT error; int *count = NULL; if(user_data) { count = (int*)user_data[0]; (*count) ++; } error = sm_db_service_instances_read( _sm_db_handle, db_service->name, &db_service_instance ); if( SM_OKAY != error ) { DPRINTFE( "Failed to read instance for service (%s), error=%s.", db_service->name, sm_error_str( error ) ); return( error ); } service = sm_service_table_read( db_service->name ); if( NULL == service ) { service = (SmServiceT*) malloc( sizeof(SmServiceT) ); if( NULL == service ) { DPRINTFE( "Failed to allocate service table entry." ); return( SM_FAILED ); } memset( service, 0, sizeof(SmServiceT) ); service->id = db_service->id; snprintf( service->name, sizeof(service->name), "%s", db_service->name ); snprintf( service->instance_name, sizeof(service->instance_name), "%s", db_service_instance.instance_name ); snprintf( service->instance_params, sizeof(service->instance_params), "%s", db_service_instance.instance_params ); service->desired_state = db_service->desired_state; service->state = db_service->state; service->status = db_service->status; service->condition = db_service->condition; service->recover = false; service->clear_fatal_condition = false; service->max_failures = db_service->max_failures; service->fail_count = 0; service->fail_countdown = db_service->fail_countdown; service->fail_countdown_interval_in_ms = db_service->fail_countdown_interval_in_ms; service->fail_countdown_timer_id = SM_TIMER_ID_INVALID; service->audit_timer_id = SM_TIMER_ID_INVALID; service->action_running = SM_SERVICE_ACTION_NONE; service->action_pid = -1; service->action_timer_id = SM_TIMER_ID_INVALID; service->action_attempts = 0; service->action_state_timer_id = SM_TIMER_ID_INVALID; service->pid = -1; snprintf( service->pid_file, sizeof(service->pid_file), "%s", db_service->pid_file ); service->pid_file_audit_timer_id = SM_TIMER_ID_INVALID; service->action_fail_count = 0; service->max_action_failures = db_service->max_action_failures; service->transition_fail_count = 0; service->max_transition_failures = db_service->max_transition_failures; error = sm_service_go_active_exists( service, &service->go_active_action_exists ); if( SM_OKAY != error ) { DPRINTFE( "Failed to determine if go-active action for " "service (%s) exists, error=%s.", service->name, sm_error_str( error ) ); free( service ); return( error ); } error = sm_service_go_standby_exists( service, &service->go_standby_action_exists ); if( SM_OKAY != error ) { DPRINTFE( "Failed to determine if go-standby action for service " "(%s) exists, error=%s.", service->name, sm_error_str( error ) ); free( service ); return( error ); } error = sm_service_enable_exists( service, &service->enable_action_exists ); if( SM_OKAY != error ) { DPRINTFE( "Failed to determine if enable action for service " "(%s) exists, error=%s.", service->name, sm_error_str( error ) ); free( service ); return( error ); } error = sm_service_disable_exists( service, &service->disable_action_exists ); if( SM_OKAY != error ) { DPRINTFE( "Failed to determine if disable action for service " "(%s) exists, error=%s.", service->name, sm_error_str( error ) ); free( service ); return( error ); } error = sm_service_audit_enabled_exists( service, &service->audit_enabled_exists ); if( SM_OKAY != error ) { DPRINTFE( "Failed to determine if audit enabled action for " "service (%s) exists, error=%s.", service->name, sm_error_str( error ) ); free( service ); return( error ); } error = sm_service_audit_disabled_exists( service, &service->audit_disabled_exists ); if( SM_OKAY != error ) { DPRINTFE( "Failed to determine if audit disabled action for " "service (%s) exists, error=%s.", service->name, sm_error_str( error ) ); free( service ); return( error ); } service->disable_check_dependency = true; service->disable_skip_dependent = false; SM_LIST_PREPEND( _services, (SmListEntryDataPtrT) service ); } else { service->id = db_service->id; snprintf( service->instance_name, sizeof(service->instance_name), "%s", db_service_instance.instance_name ); snprintf( service->instance_params, sizeof(service->instance_params), "%s", db_service_instance.instance_params ); service->max_failures = db_service->max_failures; service->fail_countdown = db_service->fail_countdown; service->fail_countdown_interval_in_ms = db_service->fail_countdown_interval_in_ms; service->max_action_failures = db_service->max_action_failures; service->max_transition_failures = db_service->max_transition_failures; snprintf( service->pid_file, sizeof(service->pid_file), "%s", db_service->pid_file ); } service->provisioned = db_service->provisioned; return( SM_OKAY ); } // **************************************************************************** SmErrorT sm_service_provision(char service_name[]) { SmServiceT* service = sm_service_table_read(service_name); if(NULL != service) { return SM_OKAY; } SmErrorT error; SmDbServiceT db_service; error = sm_db_services_read( _sm_db_handle, service_name, &db_service ); if(SM_OKAY != error) { return error; } error = sm_service_table_add(NULL, &db_service); if(SM_OKAY != error) { DPRINTFE("Failed to provision service %s, error %s", service_name, sm_error_str(error)); return SM_FAILED; } service = sm_service_table_read(service_name); if(NULL == service) { DPRINTFE("Service %s not found.", service_name); return SM_FAILED; } return SM_OKAY; } SmErrorT sm_service_deprovision(char service_name[]) { SmServiceT* service = sm_service_table_read(service_name); if(NULL == service) { DPRINTFI("Service %s not found in provisioned list. Already deprovisioned?", service_name); return SM_OKAY; } SM_LIST_REMOVE( _services, (SmListEntryDataPtrT) service ); free(service); return SM_OKAY; } // **************************************************************************** // Service Table - Load // ==================== SmErrorT sm_service_table_load( void ) { char db_query[SM_DB_QUERY_STATEMENT_MAX_CHAR]; SmDbServiceT service; SmErrorT error; int count = 0; void* user_data[] = {&count}; if( NULL != _services ) { SM_LIST_CLEANUP_ALL( _services ); _services = NULL; } snprintf( db_query, sizeof(db_query), "%s = 'yes'", SM_SERVICES_TABLE_COLUMN_PROVISIONED ); error = sm_db_foreach( SM_DATABASE_NAME, SM_SERVICES_TABLE_NAME, db_query, &service, sm_db_services_convert, sm_service_table_add, user_data ); if( SM_OKAY != error ) { DPRINTFE( "Failed to loop over services in database, error=%s.", sm_error_str( error ) ); return( error ); } DPRINTFI("load %d services", count); return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Service Table - Persist // ======================= SmErrorT sm_service_table_persist( SmServiceT* service ) { SmDbServiceT db_service; SmErrorT error; memset( &db_service, 0, sizeof(db_service) ); db_service.id = service->id; db_service.provisioned = service->provisioned; snprintf( db_service.name, sizeof(db_service.name), "%s", service->name ); db_service.desired_state = service->desired_state; db_service.state = service->state; db_service.status = service->status; db_service.condition = service->condition; db_service.max_failures = service->max_failures; db_service.fail_countdown = service->fail_countdown; db_service.fail_countdown_interval_in_ms = service->fail_countdown_interval_in_ms; db_service.max_action_failures = service->max_action_failures; db_service.max_transition_failures = service->max_transition_failures; snprintf( db_service.pid_file, sizeof(db_service.pid_file), "%s", service->pid_file ); error = sm_db_services_update( _sm_db_handle, &db_service ); if( SM_OKAY != error ) { DPRINTFE( "Failed to update database, error=%s.", sm_error_str( error ) ); return( error ); } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Service - Loop service members // =============================== static void _sm_loop_service_group_members( void* user_data[], SmServiceGroupMemberT* service_group_member ) { SmServiceT* service; service = sm_service_table_read( service_group_member->service_name ); if( NULL == service ) { DPRINTFE( "Could not find service (%s) of " "service group (%s).", service_group_member->service_name, service_group_member->name); return; } snprintf(service->group_name, sizeof(service->group_name), "%s", service_group_member->name); } // **************************************************************************** // **************************************************************************** // Service Table - Loop service groups // ================================================= static void _sm_loop_service_groups( void* user_data[], SmServiceGroupT* service_group ) { sm_service_group_member_table_foreach_member( service_group->name, NULL, _sm_loop_service_group_members ); } // **************************************************************************** // **************************************************************************** // Service Table - Initialize // ========================== SmErrorT sm_service_table_initialize( void ) { SmErrorT error; _services = NULL; error = sm_db_connect( SM_DATABASE_NAME, &_sm_db_handle ); if( SM_OKAY != error ) { DPRINTFE( "Failed to connect to database (%s), error=%s.", SM_DATABASE_NAME, sm_error_str( error ) ); return( error ); } error = sm_service_table_load(); if( SM_OKAY != error ) { DPRINTFE( "Failed to load services from database, error=%s.", sm_error_str( error ) ); return( error ); } sm_service_group_table_foreach( NULL, _sm_loop_service_groups ); return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Service Table - Finalize // ======================== SmErrorT sm_service_table_finalize( void ) { SmErrorT error; SM_LIST_CLEANUP_ALL( _services ); if( NULL != _sm_db_handle ) { error = sm_db_disconnect( _sm_db_handle ); if( SM_OKAY != error ) { DPRINTFE( "Failed to disconnect from database (%s), error=%s.", SM_DATABASE_NAME, sm_error_str( error ) ); } _sm_db_handle = NULL; } return( SM_OKAY ); } // ****************************************************************************
danylorudenko/bgfx
3rdparty/spirv-tools/source/opt/passes.h
<gh_stars>1-10 // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SOURCE_OPT_PASSES_H_ #define SOURCE_OPT_PASSES_H_ // A single header to include all passes. #include "source/opt/aggressive_dead_code_elim_pass.h" #include "source/opt/amd_ext_to_khr.h" #include "source/opt/block_merge_pass.h" #include "source/opt/ccp_pass.h" #include "source/opt/cfg_cleanup_pass.h" #include "source/opt/code_sink.h" #include "source/opt/combine_access_chains.h" #include "source/opt/compact_ids_pass.h" #include "source/opt/convert_to_half_pass.h" #include "source/opt/copy_prop_arrays.h" #include "source/opt/dead_branch_elim_pass.h" #include "source/opt/dead_insert_elim_pass.h" #include "source/opt/dead_variable_elimination.h" #include "source/opt/decompose_initialized_variables_pass.h" #include "source/opt/desc_sroa.h" #include "source/opt/eliminate_dead_constant_pass.h" #include "source/opt/eliminate_dead_functions_pass.h" #include "source/opt/eliminate_dead_members_pass.h" #include "source/opt/fix_storage_class.h" #include "source/opt/flatten_decoration_pass.h" #include "source/opt/fold_spec_constant_op_and_composite_pass.h" #include "source/opt/freeze_spec_constant_value_pass.h" #include "source/opt/generate_webgpu_initializers_pass.h" #include "source/opt/graphics_robust_access_pass.h" #include "source/opt/if_conversion.h" #include "source/opt/inline_exhaustive_pass.h" #include "source/opt/inline_opaque_pass.h" #include "source/opt/inst_bindless_check_pass.h" #include "source/opt/inst_buff_addr_check_pass.h" #include "source/opt/legalize_vector_shuffle_pass.h" #include "source/opt/licm_pass.h" #include "source/opt/local_access_chain_convert_pass.h" #include "source/opt/local_redundancy_elimination.h" #include "source/opt/local_single_block_elim_pass.h" #include "source/opt/local_single_store_elim_pass.h" #include "source/opt/local_ssa_elim_pass.h" #include "source/opt/loop_fission.h" #include "source/opt/loop_fusion_pass.h" #include "source/opt/loop_peeling.h" #include "source/opt/loop_unroller.h" #include "source/opt/loop_unswitch_pass.h" #include "source/opt/merge_return_pass.h" #include "source/opt/null_pass.h" #include "source/opt/private_to_local_pass.h" #include "source/opt/process_lines_pass.h" #include "source/opt/reduce_load_size.h" #include "source/opt/redundancy_elimination.h" #include "source/opt/relax_float_ops_pass.h" #include "source/opt/remove_duplicates_pass.h" #include "source/opt/replace_invalid_opc.h" #include "source/opt/scalar_replacement_pass.h" #include "source/opt/set_spec_constant_default_value_pass.h" #include "source/opt/simplification_pass.h" #include "source/opt/split_invalid_unreachable_pass.h" #include "source/opt/ssa_rewrite_pass.h" #include "source/opt/strength_reduction_pass.h" #include "source/opt/strip_atomic_counter_memory_pass.h" #include "source/opt/strip_debug_info_pass.h" #include "source/opt/strip_reflect_info_pass.h" #include "source/opt/unify_const_pass.h" #include "source/opt/upgrade_memory_model.h" #include "source/opt/vector_dce.h" #include "source/opt/workaround1209.h" #include "source/opt/wrap_opkill.h" #endif // SOURCE_OPT_PASSES_H_
danylorudenko/bgfx
assimpimporter/assimp-importer.h
#pragma once int myfunc();
thefranke/dirtchamber
src/dune/light_propagation_volume.h
<reponame>thefranke/dirtchamber /* * Dune D3D library - <NAME> 2012 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DUNE_LIGHT_PROPAGATION_VOLUME #define DUNE_LIGHT_PROPAGATION_VOLUME #include <D3D11.h> #include "render_target.h" #include "shader_resource.h" #include "cbuffer.h" #include "d3d_tools.h" namespace dune { class gbuffer; struct d3d_mesh; } namespace dune { /*! * \brief A Light Propagation Volume. * * This class manages all resources and rendering steps necessary to create a * Light Propagation Volume (LPV). This includes a variety of shaders and * several volume textures, as well as constant buffers to transform from * world to volume space etc. */ class light_propagation_volume : public shader_resource { public: float time_inject_; float time_propagate_; float time_normalize_; struct param { float vpl_scale; float lpv_flux_amplifier; UINT num_vpls; BOOL debug_gi; }; protected: ID3D11BlendState* bs_inject_; ID3D11BlendState* bs_propagate_; sampler_state ss_vplfilter_; ID3D11VertexShader* vs_inject_; ID3D11GeometryShader* gs_inject_; ID3D11PixelShader* ps_inject_; ID3D11VertexShader* vs_propagate_; ID3D11GeometryShader* gs_propagate_; ID3D11PixelShader* ps_propagate_; ID3D11PixelShader* ps_normalize_; INT propagate_start_slot_; INT inject_rsm_start_slot_; ID3D11Buffer* lpv_volume_; ID3D11InputLayout* input_layout_; UINT volume_size_; render_target lpv_r_[2]; render_target lpv_g_[2]; render_target lpv_b_[2]; render_target lpv_accum_r_; render_target lpv_accum_g_; render_target lpv_accum_b_; render_target lpv_inject_counter_; size_t iterations_rendered_; unsigned int curr_; unsigned int next_; DirectX::XMFLOAT4X4 world_to_lpv_; struct cbs_debug { DirectX::XMFLOAT3 lpv_pos; float pad; }; cbuffer<cbs_debug> cb_debug_; struct cbs_parameters { DirectX::XMFLOAT4X4 world_to_lpv; UINT lpv_size; DirectX::XMFLOAT3 pad; }; cbuffer<cbs_parameters> cb_parameters_; struct cbs_propagation { UINT iteration; DirectX::XMFLOAT3 pad; }; cbuffer<cbs_propagation> cb_propagation_; typedef cbuffer<param> cb_gi_parameters; cb_gi_parameters cb_gi_parameters_; dune::profile_query profiler_; protected: void swap_buffers(); void normalize(ID3D11DeviceContext* context); void propagate(ID3D11DeviceContext* context); void propagate(ID3D11DeviceContext* context, size_t num_iterations); public: light_propagation_volume(); virtual ~light_propagation_volume() {} virtual void create(ID3D11Device* device, UINT volume_size); virtual void destroy(); //!@{ /*! \brief Return local cbuffer parameters. */ cb_gi_parameters& parameters() { return cb_gi_parameters_; } const cb_gi_parameters& parameters() const { return cb_gi_parameters_; } //!@} /*! * \brief Set the complete injection shader. * * Set the injection shader for the LPV, which includes vertex, geometry and pixel shader, as well * as a normalization pixel shader. The injection reads VPLs from a gbuffer bound to texture slots * starting at inject_rsm_start_slot, and after the injection normalizes it (i.e. divides each voxel * by the number of injects it received). * * \param vs The injection vertex shader. * \param gs The injection geometry shader. * \param ps The injection pixel shader. * \param ps_normalize The normalization pixel shader. * \param inject_rsm_start_slot The slot at which all gbuffer textures will be bound consecutively. */ void set_inject_shader(ID3D11VertexShader* vs, ID3D11GeometryShader* gs, ID3D11PixelShader* ps, ID3D11PixelShader* ps_normalize, UINT inject_rsm_start_slot); /*! * \brief Set the complete propagation shader. * * Set the propagation shader for the LPV, which includes vertex, geometry and pixel shader, a binary input layout * and a starting slot for the volumes which are currently read from. * * The propagation works by switching between a front and backbuffer volume for the LPV. In each step, the previously rendered volume * is bound as input and read from to propagate energy and write it to a new volume. The three volumes for red, green and blue spherical * harmonic components are bound to inject_rsm_start_slot consecutively. Since the geometry shader is in charge of scattering radiance to * neighbor voxels, it also needs an input layout for some basic vertices. * * \param device The Direct3d device. * \param vs The propagation vertex shader. * \param gs The propagation geometry shader. * \param ps The propagation pixel shader. * \param input_binary A blob of the shaders input layout. * \param propagate_start_slot The slot at which the propagation shader expects three volumes for red, green and blue spherical harmonic components. */ void set_propagate_shader(ID3D11Device* device, ID3D11VertexShader* vs, ID3D11GeometryShader* gs, ID3D11PixelShader* ps, ID3DBlob* input_binary, UINT propagate_start_slot); /*! * \brief Inject VPLs from an RSM into the LPV. * * Injects VPLs generated from the parameter rsm into the LPV. The exact method to generate VPLs is implementation-dependent, * but the behavior can be overwritten. * * \param context A Direc3D context. * \param rsm A reflective shadow map with colors, normals and lineardepth. * \param clear If true, the volume will be cleared before injection. */ virtual void inject(ID3D11DeviceContext* context, gbuffer& rsm, bool clear); /*! \brief Run the normalization and propagation of the LPV. */ void render(ID3D11DeviceContext* context); //!@{ /*! \brief Get/set the number of propagation steps for the LPV. */ size_t num_propagations() const { return iterations_rendered_; } void set_num_propagations(size_t n) { iterations_rendered_ = n; } //!@} /*! \brief A rendering function to visualize the LPV with colored cubes for each voxel. */ void visualize(ID3D11DeviceContext* context, d3d_mesh* node, UINT debug_info_slot); //!@{ /*! \brief Set/get the world -> LPV matrix, which transforms world coordinates to LPV volume coordinates. */ void set_model_matrix(ID3D11DeviceContext* context, const DirectX::XMFLOAT4X4& model, const DirectX::XMFLOAT3& lpv_min, const DirectX::XMFLOAT3& lpv_max, UINT lpv_parameters_slot); const DirectX::XMFLOAT4X4& world_to_lpv() const { return world_to_lpv_; } //!@} virtual void to_ps(ID3D11DeviceContext* context, UINT slot); }; /*! * \brief A Delta Light Propagation Volume (DLPV). * * This class is an implementation of [[Franke 2013]](http://www.tobias-franke.eu/publications/franke13dlpv). * A DLPV is an LPV that extracts the difference in illumination caused by the introduction * of an additional object into a scene. It can be used to correct for this difference, for instance * in augmented reality applications. * * The mechanic works like this: instead of injecting one RSM, two a rendered. One * is rendered with a scene, the other with the same scene and an additional object. * By injecting the latter first, and then injecting the former negatively, the * delta is extracted and propagated in the volume. * * A DLPV also injects direct light to form out rough shadow blobs. Propagation * of direct and indirect injects is independent from one another. */ class delta_light_propagation_volume : public light_propagation_volume { protected: ID3D11BlendState* bs_negative_inject_; ID3D11VertexShader* vs_direct_inject_; bool negative_; struct cbs_delta_injection { FLOAT scale; BOOL is_direct; FLOAT pad1; FLOAT pad2; }; cbuffer<cbs_delta_injection> cb_delta_injection_; public: delta_light_propagation_volume(); virtual ~delta_light_propagation_volume() {} virtual void create(ID3D11Device* device, UINT volume_size); virtual void destroy(); /*! \brief Additionally to the regular indirect injection shader, this will set the direct injection pixel shader. */ void set_direct_inject_shader(ID3D11VertexShader* ps); /*! * \brief Overwrites the default injection to include direct injects. * * After each clear, RSMs are injected in a toggled order: positive, negative, positive, negative ... * * \param context A Direct3D context. * \param rsm The GBuffer of the RSM. * \param clear Set to true if the injected volume should be cleared. If you inject multiple RSMs set this only at the first call to true. * \param is_direct Specify if this is a direct or indirect injection. * \param scale A multiplier for injected VPL intensity */ void inject(ID3D11DeviceContext* context, gbuffer& rsm, bool clear, bool is_direct, float scale); /*! \brief Render/propagate indirect injects. */ void render_indirect(ID3D11DeviceContext* context); //!@{ /*! \brief Render/propagate direct injects. */ void propagate_direct(ID3D11DeviceContext* context, size_t num_iterations); void render_direct(ID3D11DeviceContext* context, size_t num_iterations, UINT lpv_out_start_slot); //!@} }; } #endif
thefranke/dirtchamber
src/common_renderer.h
<filename>src/common_renderer.h<gh_stars>100-1000 /* * The Dirtchamber - <NAME> 2014 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef COMMON_RENDERER_H #define COMMON_RENDERER_H #undef NOMINMAX #include <DXUT.h> #include <dune/dune.h> #include "../shader/common.h" #include "pppipe.h" #include "skydome.h" extern std::vector<dune::tstring> files_scene; extern float z_near; extern float z_far; /*! \brief Dirtchamber shared code. */ namespace dc { /*! * \brief A common, simple deferred renderer. * * Implements a basic deferred renderer with a camera, a skydome, a scene composed * from one or more models (gilga_mesh) and a postprocessor with SSAO, Bloom, HDR Rendering, * TV grain, Depth of Field, FXAA, Godrays etc. * * The common_renderer renders the camera view into a GBuffer with the following layout: * - **color** : DXGI_FORMAT_R16G16B16A16_FLOAT * - **specular** : DXGI_FORMAT_R16G16B16A16_FLOAT * - **normals** : DXGI_FORMAT_R10G10B10A2_UNORM * - **linear depth and variance** : DXGI_FORMAT_R32G32_FLOAT * * The postprocessor target is a DXGI_FORMAT_R16G16B16A16_FLOAT render_target. */ class common_renderer : public dune::deferred_renderer { protected: struct per_frame { float time; float time_delta; DirectX::XMFLOAT2 pad0; }; struct onetime { DirectX::XMFLOAT4 scene_dim_max; DirectX::XMFLOAT4 scene_dim_min; }; protected: dune::camera camera_; dune::cbuffer<per_frame> cb_per_frame_; dune::cbuffer<onetime> cb_onetime_; dune::gilga_mesh debug_box_; dune::composite_mesh scene_; dune::gbuffer def_; skydome sky_; DirectX::XMFLOAT3 bb_min_; DirectX::XMFLOAT3 bb_max_; pppipe postprocessor_; ID3D11ShaderResourceView* noise_srv_; protected: /*! \brief Derived classes can overload this method to call render() on more dune objects. Buffers etc. are all set up already. */ virtual void do_render_scene(ID3D11DeviceContext* context); /*! \brief Resets all render target views to nullptr. */ void reset_omrtv(ID3D11DeviceContext* context); protected: /*! \brief Upload the bounding box of a mesh to the pixel shader */ void update_bbox(ID3D11DeviceContext* context, dune::d3d_mesh& mesh); /*! \brief Upload camera parameters to the respective shaders. */ void update_camera_parameters(ID3D11DeviceContext* context); /*! \brief Update the scene with a new model matrix to move/scale/... stuff. */ void update_scene(ID3D11DeviceContext* context, const DirectX::XMMATRIX& world /* = DirectX::XMMatrixIdentity() */); /*! \brief Upload one-time parameters (really just once) such as noise textures. */ void update_onetime_parameters(ID3D11DeviceContext* context, dune::d3d_mesh& mesh); /*! \brief Clear the GBufer and render the scene. */ void render_scene(ID3D11DeviceContext* context, float* clear_color, ID3D11DepthStencilView* dsv); public: virtual void create(ID3D11Device* device); virtual void destroy(); virtual void resize(UINT width, UINT height); virtual void render(ID3D11DeviceContext* context, ID3D11RenderTargetView* backbuffer, ID3D11DepthStencilView* dsv); /*! \brief Upload postprocessing parameters from the postprocessing pipeline. */ virtual void update_postprocessing_parameters(ID3D11DeviceContext* context); /*! \brief Update function for everything called once a frame. */ virtual void update_frame(ID3D11DeviceContext* context, double time, float elapsed_time); /*! \brief Update function called for the camera. */ virtual void update_camera(ID3D11DeviceContext* context, HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); /*! \brief A function called if the shaders should be reloaded. */ virtual void reload_shader(ID3D11Device* device, ID3D11DeviceContext* context) {} /*! * \brief Set deferred rendering shaders. * * Sets the complete shaders for a deferred renderer, which includes an input_binary for a fullscreen triangle, * a vertex and pixel shader for deferred rendering, an overlay shader which displays GBuffer textures for * debugging, a start slot for the deferred GBuffer, a slot for the current GBuffer texture to render on an overlay * and a postprocessing start slot where the postprocessor expects the frontbuffer (i.e. the result of the deferred pass) * is located at. * * \param device The Direct3D device. * \param input_binary The input layout for the fullscreen triangle. * \param vs_deferred The vertex shader of the deferred renderer * \param ps_deferred The pixel shader of the deferred renderer * \param ps_overlay A shader which displays an overlay of a selected GBuffer texture for debugging purposes * \param start_slot The slot at which the GBuffer starts * \param overlay_slot A slot at which the currently selected GBuffer texture is located. Call overlay() to render the texture. * \param postprocessing_slot The slot at which the final deferred buffer is located at. */ void set_shader(ID3D11Device* device, ID3DBlob* input_binary, ID3D11VertexShader* vs_deferred, ID3D11PixelShader* ps_deferred, ID3D11PixelShader* ps_overlay, UINT start_slot, UINT overlay_slot, UINT postprocessing_slot); inline pppipe& postprocessor() { return postprocessor_; } inline dune::camera& camera() { return camera_; } inline dune::composite_mesh& scene() { return scene_; } /*! \brief Saves dune objects used in the common_renderer. Overload to add more. */ virtual void save(dune::serializer& s); /*! \brief Load dune objects used in the common_renderer. Overload to add more. */ virtual void load(ID3D11DeviceContext* context, const dune::serializer& s); }; /*! * \brief A common_renderer also rendering an RSM. * * The rsm_renderer derives from a common_renderer and adds one light source of type L. * For this light source, an RSM is generated. Depending on the type of the light source, there * may be two or more RSMs. */ template<typename L = dune::directional_light> class rsm_renderer : public dc::common_renderer { protected: L main_light_; dune::render_target rsm_depth_; dune::render_target dummy_spec_; bool update_rsm_; protected: /*! \brief Update and upload RSM camera parameters (i.e. light view projection matrix etc.). */ void update_rsm_camera_parameters(ID3D11DeviceContext* context, dune::directional_light& l) { auto cb = &camera_.parameters().data(); { XMStoreFloat4x4(&cb->vp, DirectX::XMLoadFloat4x4(&l.parameters().data().vp)); XMStoreFloat4x4(&cb->vp_inv, XMLoadFloat4x4(&l.parameters().data().vp_inv)); cb->camera_pos = DirectX::XMFLOAT3 ( l.parameters().data().position.x, l.parameters().data().position.y, l.parameters().data().position.z ); cb->z_far = z_far; } camera_.parameters().to_vs(context, SLOT_CAMERA_VS); } /*! \brief Render a scene from a directional_light position into an RSM. */ void render_rsm(ID3D11DeviceContext* context, float* clear_color, dune::gbuffer& rsm) { // render rsm ID3D11RenderTargetView* rsm_views[] = { rsm[L"colors"]->rtv(), rsm[L"normals"]->rtv(), rsm[L"lineardepth"]->rtv(), dummy_spec_.rtv() }; ID3D11DepthStencilView* dsv = rsm_depth_.dsv(); context->ClearDepthStencilView(dsv, D3D11_CLEAR_DEPTH, 1.0, 0); dune::clear_rtvs(context, rsm_views, 2, clear_color); float cc[4] = { z_far, z_far, z_far, z_far }; dune::clear_rtvs(context, rsm_views + 2, 1, cc); DirectX::XMFLOAT2 size = rsm[L"colors"]->size(); dune::set_viewport(context, static_cast<size_t>(size.x), static_cast<size_t>(size.y)); context->OMSetRenderTargets(4, rsm_views, dsv); do_render_rsm(context); reset_omrtv(context); } /*! \brief Virtual function to render more stuff for the RSM. */ virtual void do_render_rsm(ID3D11DeviceContext* context) { scene_.set_shader_slots(SLOT_TEX_DIFFUSE, SLOT_TEX_NORMAL); for (size_t x = 0; x < scene_.size(); ++x) { dune::gilga_mesh* m = dynamic_cast<dune::gilga_mesh*>(scene_[x].get()); if (m) m->set_alpha_slot(SLOT_TEX_ALPHA); } scene_.render(context); } public: virtual void create(ID3D11Device* device) { common_renderer::create(device); auto ld_color = def_[L"colors"]->desc(); auto ld_normal = def_[L"normals"]->desc(); auto ld_ldepth = def_[L"lineardepth"]->desc(); auto ld_spec = def_[L"specular"]->desc(); // setup reflective shadow map ld_color.Width = ld_normal.Width = ld_ldepth.Width = ld_spec.Width = ld_color.Height = ld_normal.Height = ld_ldepth.Height = ld_spec.Height = 1024; dummy_spec_.create(device, ld_spec); main_light_.create(device, L"rsm", ld_color, ld_normal, ld_ldepth); DXGI_SURFACE_DESC ld_rsmdepth; ld_rsmdepth.Format = DXGI_FORMAT_R32_TYPELESS; ld_rsmdepth.Width = 1024; ld_rsmdepth.Height = 1024; ld_rsmdepth.SampleDesc.Count = 1; ld_rsmdepth.SampleDesc.Quality = 0; rsm_depth_.create(device, ld_rsmdepth); // add buffers to deferred renderer add_buffer(*main_light_.rsm()[L"lineardepth"], SLOT_TEX_SVO_RSM_RHO_START); } /*! \brief Update and upload parameters (view projection matrix, flux etc.) of a directional light. */ void update_light_parameters(ID3D11DeviceContext* context, dune::directional_light& l) { DirectX::XMMATRIX world = DirectX::XMLoadFloat4x4(&scene_.world()); // TODO: make better DirectX::XMVECTOR up = { -1.f, 0.f, 0.f, 0.f }; DirectX::XMVECTOR upt; upt = DirectX::XMVector4Transform(up, world); upt = DirectX::XMVector4Normalize(upt); DirectX::XMFLOAT4 upt_vec; DirectX::XMStoreFloat4(&upt_vec, upt); // projection matrix auto light_proj = dune::make_projection(z_near, z_far); l.update(upt_vec, light_proj); l.parameters().to_ps(context, SLOT_LIGHT_PS); update_rsm_ = true; } virtual void destroy() { common_renderer::destroy(); main_light_.destroy(); rsm_depth_.destroy(); dummy_spec_.destroy(); } inline dune::directional_light& main_light() { return main_light_; } virtual void save(dune::serializer& s) { common_renderer::save(s); s << main_light_; } virtual void load(ID3D11DeviceContext* context, const dune::serializer& s) { common_renderer::load(context, s); s >> main_light_; } }; } #endif
thefranke/dirtchamber
src/dune/record_tools.h
/* * Dune D3D library - <NAME> 2017 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DUNE_RECORD_TOOLS #define DUNE_RECORD_TOOLS #include "unicode.h" #include <D3D11.h> namespace dune { class gbuffer; } namespace dune { class video_recorder { protected: UINT width_, height_, fps_; ID3D11Texture2D* ffmpeg_texture_; FILE* ffmpeg_; tstring path_; public: video_recorder(); virtual ~video_recorder(); void create(ID3D11Device* device, UINT width, UINT height, UINT fps, const tstring& path = L"../../data"); void destroy(); void start_recording(); void stop_recording(); void add_frame(ID3D11DeviceContext* context, ID3D11RenderTargetView* rtv); void add_frame(ID3D11DeviceContext* context, ID3D11Resource* resource); }; void dump_rtv(ID3D11Device* device, ID3D11DeviceContext* context, UINT width, UINT height, DXGI_FORMAT format, ID3D11RenderTargetView* rtv, const tstring& name); void dump_gbuffer(ID3D11Device* device, ID3D11DeviceContext* context, gbuffer& g, const tstring& name); } #endif
thefranke/dirtchamber
src/dune/serializer.h
<gh_stars>100-1000 /* * Dune D3D library - <NAME> 2014 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DUNE_SERIALIZER #define DUNE_SERIALIZER #include "exception.h" #include <boost/any.hpp> #include <map> #include "unicode.h" namespace dune { typedef int BOOL; /*! * \brief Serializer to read/write Dune objects from/into JSON/XML. * * This class manages a map of key-value pairs of tstring objects and can * read or write them to XML files. Keys can be structured into sub-keys by * dividing them with dots. For instance, the hierarchy * * > foo { bar { baz }, bar1 { baz } } * * can be expressed with the following keys * * > foo.bar.baz * * > foo.bar1.baz * * The serializer is used to save information about Dune objects into * files. This enables loading program configurations. */ class serializer { protected: std::map<tstring, tstring> properties_; public: /*! \brief Save the current key-value's into a file specified by filename. */ void save(const tstring& filename); /*! \brief Load key-value pairs from a file specified by filename. */ void load(const tstring& filename); /*! * \brief Get a value from a specified key. * * Fetch a value from the storage and return it as type T. * * \tparam T The type of the parameter. * \param key The key specifying the value. * \return The requested value. * \throws exception The key does not exist. */ template<typename T> T get(const tstring& key) const { auto i = properties_.find(key); if (i == properties_.end()) throw dune::exception(L"Unknown key: " + key); T value; tstringstream ss(i->second); ss >> std::boolalpha >> value; return value; } /*! * \brief Add a new key-value pair or overwrite an existing key with a new value. * * Add a value of type T to the storage. If the key already exists, the value * is simply replaced. * * \tparam T The type of the parameter. * \param key The key specifying the value. * \param value The value. */ template<typename T> void put(const tstring& key, const T& value) { tstringstream ss; ss << value; properties_[key] = ss.str(); } // Special case for type BOOL template<> void put(const tstring& key, const BOOL& value) { tstringstream ss; // BOOL is actually int, meh if (value == 0) ss << std::boolalpha << false; else if (value == 1) ss << std::boolalpha << true; else ss << value; properties_[key] = ss.str(); } }; } #endif
thefranke/dirtchamber
src/gi_renderer.h
<filename>src/gi_renderer.h /* * The Dirtchamber - <NAME> 2014 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef GI_RENDERER_H #define GI_RENDERER_H #include <dune/dune.h> #undef NOMINMAX #include "common_renderer.h" #include "common_dxut.h" #include "common_gui.h" /*! * \brief A full global illumination renderer. * * This class implements an rsm_renderer and enhances it to provide a full scale GI solution. * This is done via Light Propagation Volumes or Voxel Cone Tracing. Because both are volumetric * solutions and share almost all code, you can switch between both with a define \#LPV. If \#LPV * is set, a Light Propagation Volume is used, otherwise a Sparse Voxel Octree will be instantiated. */ class gi_renderer : public dc::rsm_renderer<dune::directional_light> { public: float time_deferred_; float time_rsm_; protected: dune::profile_query profiler_; #ifdef LPV dune::light_propagation_volume volume_; #define VOLUME_SIZE LPV_SIZE #define VOLUME_PARAMETERS_SLOT SLOT_LPV_PARAMETERS_VS_PS #else dune::sparse_voxel_octree volume_; #define VOLUME_SIZE SVO_SIZE #define VOLUME_PARAMETERS_SLOT SLOT_SVO_PARAMETERS_VS_GS_PS #endif public: virtual void create(ID3D11Device* device) { rsm_renderer::create(device); // create sparse voxel octree volume_.create(device, VOLUME_SIZE); profiler_.create(device); load_shader(device); } virtual void destroy() { rsm_renderer::destroy(); volume_.destroy(); profiler_.destroy(); } virtual void render(ID3D11DeviceContext* context, ID3D11RenderTargetView* backbuffer, ID3D11DepthStencilView* dsv) { static float clear_color[4] = { 0.0f, 0.f, 0.0f, 1.0f }; render_gi(context, clear_color); render_scene(context, clear_color, dsv); context->GenerateMips(main_light_.rsm()[L"lineardepth"]->srv()); context->GenerateMips(def_[L"lineardepth"]->srv()); dune::set_viewport(context, DXUTGetWindowWidth(), DXUTGetWindowHeight()); profiler_.begin(context); deferred_renderer::render(context, backbuffer, dsv); time_deferred_ = profiler_.result(); } protected: void load_shader(ID3D11Device* device) { // setup mesh effect DWORD shader_flags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) | defined(_DEBUG) shader_flags |= D3DCOMPILE_DEBUG; #endif ID3DBlob* vs_blob = nullptr; ID3D11VertexShader* vs = nullptr; ID3D11GeometryShader* gs = nullptr; ID3D11PixelShader* ps = nullptr; ID3D11PixelShader* ps1 = nullptr; auto cleanup = [&]() { dune::safe_release(vs_blob); dune::safe_release(vs); dune::safe_release(ps); dune::safe_release(ps1); dune::safe_release(gs); }; // mesh shader dune::compile_shader(device, L"../../shader/d3d_mesh.hlsl", "vs_5_0", "vs_mesh", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(device, L"../../shader/d3d_mesh.hlsl", "ps_5_0", "ps_mesh", shader_flags, nullptr, &ps); scene_.set_shader(device, vs_blob, vs, ps); cleanup(); // deferred shader dune::compile_shader(device, L"../../shader/fs_triangle.hlsl", "vs_5_0", "vs_fs_triangle", shader_flags, nullptr, &vs, &vs_blob); #ifdef LPV dune::compile_shader(device, L"../../shader/deferred_lpv.hlsl", "ps_5_0", "ps_lpv", shader_flags, nullptr, &ps); #else dune::compile_shader(device, L"../../shader/deferred_vct.hlsl", "ps_5_0", "ps_vct", shader_flags, nullptr, &ps); #endif dune::compile_shader(device, L"../../shader/overlay.hlsl", "ps_5_0", "ps_overlay", shader_flags, nullptr, &ps1); set_shader(device, vs_blob, vs, ps, ps1, SLOT_TEX_DEFERRED_START, SLOT_TEX_OVERLAY, SLOT_TEX_POSTPROCESSING_START); cleanup(); // skydome shader dune::compile_shader(device, L"../../shader/d3d_mesh_skydome.hlsl", "vs_5_0", "vs_skydome", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(device, L"../../shader/d3d_mesh_skydome.hlsl", "ps_5_0", "ps_skydome", shader_flags, nullptr, &ps); sky_.set_shader(device, vs_blob, vs, ps); cleanup(); #ifdef LPV // lpv inject shader dune::compile_shader(device, L"../../shader/lpv_inject.hlsl", "vs_5_0", "vs_lpv_inject", shader_flags, nullptr, &vs); dune::compile_shader(device, L"../../shader/lpv_inject.hlsl", "gs_5_0", "gs_lpv_inject", shader_flags, nullptr, &gs); dune::compile_shader(device, L"../../shader/lpv_inject.hlsl", "ps_5_0", "ps_lpv_inject", shader_flags, nullptr, &ps); dune::compile_shader(device, L"../../shader/lpv_normalize.hlsl", "ps_5_0", "ps_lpv_normalize", shader_flags, nullptr, &ps1); volume_.set_inject_shader(vs, gs, ps, ps1, SLOT_TEX_LPV_INJECT_RSM_START); cleanup(); // lpv propagate shader dune::compile_shader(device, L"../../shader/lpv_propagate.hlsl", "vs_5_0", "vs_lpv_propagate", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(device, L"../../shader/lpv_propagate.hlsl", "gs_5_0", "gs_lpv_propagate", shader_flags, nullptr, &gs); dune::compile_shader(device, L"../../shader/lpv_propagate.hlsl", "ps_5_0", "ps_lpv_propagate", shader_flags, nullptr, &ps); volume_.set_propagate_shader(device, vs, gs, ps, vs_blob, SLOT_TEX_LPV_PROPAGATE_START); cleanup(); // lpv volume visualization dune::compile_shader(device, L"../../shader/lpv_rendervol.hlsl", "vs_5_0", "vs_rendervol", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(device, L"../../shader/lpv_rendervol.hlsl", "ps_5_0", "ps_rendervol", shader_flags, nullptr, &ps); debug_box_.set_shader(device, vs_blob, vs, ps); cleanup(); #else // svo voxelize shader dune::compile_shader(device, L"../../shader/svo_voxelize.hlsl", "vs_5_0", "vs_svo_voxelize", shader_flags, nullptr, &vs); dune::compile_shader(device, L"../../shader/svo_voxelize.hlsl", "gs_5_0", "gs_svo_voxelize", shader_flags, nullptr, &gs); dune::compile_shader(device, L"../../shader/svo_voxelize.hlsl", "ps_5_0", "ps_svo_voxelize", shader_flags, nullptr, &ps); volume_.set_shader_voxelize(vs, gs, ps); cleanup(); // svo inject shader dune::compile_shader(device, L"../../shader/svo_inject.hlsl", "vs_5_0", "vs_svo_inject", shader_flags, nullptr, &vs); dune::compile_shader(device, L"../../shader/svo_inject.hlsl", "ps_5_0", "ps_svo_inject", shader_flags, nullptr, &ps); volume_.set_shader_inject(vs, ps, SLOT_TEX_SVO_RSM_RHO_START); cleanup(); #endif } /*! \brief Render/compute the GI volume, whether it be LPV or SVO. */ void render_volume(ID3D11DeviceContext* context, float* clear_color) { #ifdef LPV ID3D11ShaderResourceView* null_srv[] = { nullptr, nullptr, nullptr }; context->PSSetShaderResources(SLOT_TEX_LPV_DEFERRED_START, 3, null_srv); // TODO: inject main_light, not main_light.rsm() volume_.inject(context, main_light_.rsm(), true); volume_.render(context); volume_.to_ps(context, SLOT_TEX_LPV_DEFERRED_START); #else // voxelize scene for (size_t x = 0; x < scene_.size(); ++x) { dune::gilga_mesh* m = dynamic_cast<dune::gilga_mesh*>(scene_[x].get()); m->set_shader_slots(SLOT_TEX_DIFFUSE); if (m) volume_.voxelize(context, *m, x == 0); } volume_.inject(context, main_light_); // prefilter volume volume_.filter(context); // upload to gpu volume_.to_ps(context, SLOT_TEX_SVO_V_START); #endif } /*! * \brief Compute global illumination for the scene. * * This method first makes sure that the RSM/GI solution needs to be updated. * If so, a new RSM is rendered for one directional light, which will then be injected * into a volume and further processed. */ void render_gi(ID3D11DeviceContext* context, float* clear_color) { if (update_rsm_) { // setup rsm view update_rsm_camera_parameters(context, main_light_); // inject first bounce profiler_.begin(context); render_rsm(context, clear_color, main_light_.rsm()); time_rsm_ = profiler_.result(); // render gi volume render_volume(context, clear_color); update_rsm_ = false; } } public: void update_gi_parameters(ID3D11DeviceContext* context) { volume_.set_model_matrix(the_context, scene_.world(), bb_min_, bb_max_, SLOT_LPV_PARAMETERS_VS_PS); volume_.parameters().to_ps(context, SLOT_GI_PARAMETERS_PS); update_rsm_ = true; } void update_everything(ID3D11DeviceContext* context) { update_scene(context, DirectX::XMMatrixIdentity()); update_camera_parameters(context); update_light_parameters(context, main_light_); update_onetime_parameters(context, scene_); update_postprocessing_parameters(context); update_gi_parameters(context); } void reload_shader(ID3D11Device* device, ID3D11DeviceContext* context) { load_shader(device); update_everything(context); } virtual void save(dune::serializer& s) { rsm_renderer::save(s); s << volume_; } virtual void load(ID3D11DeviceContext* context, const dune::serializer& s) { rsm_renderer::load(context, s); s >> volume_; update_everything(context); } inline auto volume() -> decltype((volume_)) { return volume_; } }; #endif
thefranke/dirtchamber
src/dune/render_target.h
/* * Dune D3D library - <NAME> 2011 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DUNE_RENDER_TARGET #define DUNE_RENDER_TARGET #include <D3D11.h> #include <DirectXMath.h> #include <string> #include "texture.h" namespace dune { /*! * \brief A render target wrapper. * * A render target is a texture that can be "written" to from the outside, whether it be from * the GPU or the CPU. A render_target object can be created in several different manners * (from manual specification to supplying common descriptors) and provides functions * to query views later used to read from or render to it. Furthermore, depending on the * parameters supplied to create(), render_target objects can also be CPU mapped to read * or write from/to them. */ class render_target : public texture { protected: ID3D11Device* device_; ID3D11RenderTargetView* rtview_; ID3D11DepthStencilView* dsview_; bool cached_; std::vector<BYTE> cached_copy_; protected: virtual void do_create(ID3D11Device* device, D3D11_TEXTURE2D_DESC desc, D3D11_SUBRESOURCE_DATA* subresource); public: render_target(); virtual ~render_target() {} /* \brief Returns the render target view (RTV). */ ID3D11RenderTargetView* const rtv() const { return rtview_; } /* \brief Returns the depth stencil view (DSV). */ ID3D11DepthStencilView* const dsv() const { return dsview_; } /* * \brief Resize the render_target. * * Resizes the render_target. Because new views are generated, old views still bound to the GPU are invalid. After a resize, * all views need to be re-bound! * * \param width The new width of the render_target. * \param height The new height of the render_target. */ void resize(UINT width, UINT height); virtual void destroy(); /*! \brief If this texture is cached, this method will copy the CPU side cache to the render_target texture. */ void update(ID3D11DeviceContext* context); /*! \brief Copy a data array of num_bytes size into the internal CPU cache. */ void copy(const BYTE* data, size_t num_bytes); /*! \brief Returns a pointer to the internal CPU texture cache. */ template<typename T> T data() { return reinterpret_cast<T>(&cached_copy_[0]); } //!@{ /*! \brief Enable caching. If this is true, creating this object will copy the initial sub-resource to a cache. */ void enable_cached(bool c) { cached_ = c; } bool cached() { return cached_; } //!@} }; void load_static_target(ID3D11Device* device, const tstring& filename, render_target& t); } #endif // RENDER_TARGET
thefranke/dirtchamber
src/drf_renderer.h
<gh_stars>100-1000 /* * The Dirtchamber - <NAME> 2013 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DRF_RENDERER_H #define DRF_RENDERER_H #include <dune/dune.h> #include "common_renderer.h" #include "common_dxut.h" #include "common_gui.h" /*! * \brief A Delta Radiance Field renderer for augmented reality. * * This class is an implementation of an augmented reality relighting renderer using * Delta Radiance Fields (see README.md for more information on publications). Depending * on the define \#DLPV, this class will use different volumetric GI methods to * relight the surrounding scene: if \#DLPV is set, Delta Light Propagation Volumes * will be used for GI. If \#DLPV isn't set, Delta Voxel Cone Tracing will do the job. * * A Kinect camera is required to run this sample as a *true* AR renderer. A marker * to print out is available in /data/marker.png. * * If you do not have a Kinect or haven't compiled Dune with support for the Microsoft * Kinect SDK (i.e \#MICROSOFT_KINECT_SDK isn't defined), you can still use the sample * with a static background (see /data/real_static_scene.png), which is a * snapshot frame of a Kinect color image. */ class drf_renderer : public dc::rsm_renderer <dune::differential_directional_light> { public: float time_rsm_mu_; float time_rsm_rho_; float time_deferred_; protected: #ifdef DLPV dune::delta_light_propagation_volume delta_radiance_field_; dune::light_propagation_volume lpv_rho_; #define VOLUME_SIZE LPV_SIZE #define VOLUME_PARAMETERS_SLOT SLOT_LPV_PARAMETERS_VS_PS #else dune::delta_sparse_voxel_octree delta_radiance_field_; #define VOLUME_SIZE SVO_SIZE #define VOLUME_PARAMETERS_SLOT SLOT_SVO_PARAMETERS_VS_GS_PS #endif #ifdef MICROSOFT_KINECT_SDK dune::kinect_gbuffer kinect_; #else dune::render_target real_static_background_; #endif dune::tracker tracker_; dune::profile_query profiler_; dune::gilga_mesh synthetic_object_; #define reconstructed_real_scene_ scene_ ID3D11RasterizerState* no_culling_; bool render_mu_; float rotation_angle_; protected: void load_shader(ID3D11Device* device) { // setup mesh effect DWORD shader_flags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) | defined(_DEBUG) shader_flags |= D3DCOMPILE_DEBUG; #endif ID3DBlob* vs_blob = nullptr; ID3D11VertexShader* vs = nullptr; ID3D11VertexShader* vs1 = nullptr; ID3D11VertexShader* vs2 = nullptr; ID3D11GeometryShader* gs = nullptr; ID3D11PixelShader* ps = nullptr; ID3D11PixelShader* ps1 = nullptr; ID3D11PixelShader* ps2 = nullptr; auto cleanup = [&]() { dune::safe_release(vs_blob); dune::safe_release(vs); dune::safe_release(vs1); dune::safe_release(vs2); dune::safe_release(ps); dune::safe_release(ps1); dune::safe_release(ps2); dune::safe_release(gs); }; // mesh shader dune::compile_shader(device, L"../../shader/d3d_mesh.hlsl", "vs_5_0", "vs_mesh", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(device, L"../../shader/d3d_mesh.hlsl", "ps_5_0", "ps_mesh", shader_flags, nullptr, &ps); reconstructed_real_scene_.set_shader(device, vs_blob, vs, ps); synthetic_object_.set_shader(device, vs_blob, vs, ps); cleanup(); // deferred shader + postprocessor dune::compile_shader(device, L"../../shader/fs_triangle.hlsl", "vs_5_0", "vs_fs_triangle", shader_flags, nullptr, &vs, &vs_blob); #ifdef DLPV dune::compile_shader(device, L"../../shader/deferred_dlpv_kinect.hlsl", "ps_5_0", "ps_ar_dlpv", shader_flags, nullptr, &ps); #else dune::compile_shader(device, L"../../shader/deferred_dvct_kinect.hlsl", "ps_5_0", "ps_ar_dvct", shader_flags, nullptr, &ps); #endif dune::compile_shader(device, L"../../shader/overlay.hlsl", "ps_5_0", "ps_overlay", shader_flags, nullptr, &ps1); set_shader(device, vs_blob, vs, ps, ps1, SLOT_TEX_DEFERRED_START, SLOT_TEX_OVERLAY, SLOT_TEX_POSTPROCESSING_START); cleanup(); // skydome shader dune::compile_shader(device, L"../../shader/d3d_mesh_skydome.hlsl", "vs_5_0", "vs_skydome", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(device, L"../../shader/d3d_mesh_skydome.hlsl", "ps_5_0", "ps_skydome", shader_flags, nullptr, &ps); sky_.set_shader(device, vs_blob, vs, ps); cleanup(); #ifdef DLPV // lpv inject shader dune::compile_shader(the_device, L"../../shader/lpv_inject.hlsl", "vs_5_0", "vs_delta_lpv_inject", shader_flags, nullptr, &vs); dune::compile_shader(the_device, L"../../shader/lpv_inject.hlsl", "vs_5_0", "vs_lpv_inject", shader_flags, nullptr, &vs1); dune::compile_shader(the_device, L"../../shader/lpv_inject.hlsl", "gs_5_0", "gs_lpv_inject", shader_flags, nullptr, &gs); dune::compile_shader(the_device, L"../../shader/lpv_inject.hlsl", "ps_5_0", "ps_delta_lpv_inject", shader_flags, nullptr, &ps); dune::compile_shader(the_device, L"../../shader/lpv_inject.hlsl", "ps_5_0", "ps_lpv_inject", shader_flags, nullptr, &ps2); dune::compile_shader(the_device, L"../../shader/lpv_normalize.hlsl", "ps_5_0", "ps_lpv_normalize", shader_flags, nullptr, &ps1); dune::compile_shader(the_device, L"../../shader/lpv_inject.hlsl", "vs_5_0", "vs_delta_lpv_direct_inject", shader_flags, nullptr, &vs2); delta_radiance_field_.set_inject_shader(vs, gs, ps, ps1, SLOT_TEX_LPV_INJECT_RSM_START); delta_radiance_field_.set_direct_inject_shader(vs2); lpv_rho_.set_inject_shader(vs1, gs, ps2, ps1, SLOT_TEX_LPV_INJECT_RSM_START); cleanup(); // lpv propagate shader dune::compile_shader(the_device, L"../../shader/lpv_propagate.hlsl", "vs_5_0", "vs_lpv_propagate", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(the_device, L"../../shader/lpv_propagate.hlsl", "gs_5_0", "gs_lpv_propagate", shader_flags, nullptr, &gs); dune::compile_shader(the_device, L"../../shader/lpv_propagate.hlsl", "ps_5_0", "ps_delta_lpv_propagate", shader_flags, nullptr, &ps); dune::compile_shader(the_device, L"../../shader/lpv_propagate.hlsl", "ps_5_0", "ps_lpv_propagate", shader_flags, nullptr, &ps1); delta_radiance_field_.set_propagate_shader(the_device, vs, gs, ps, vs_blob, SLOT_TEX_LPV_PROPAGATE_START); lpv_rho_.set_propagate_shader(the_device, vs, gs, ps1, vs_blob, SLOT_TEX_LPV_PROPAGATE_START); cleanup(); // lpv volume visualization dune::compile_shader(the_device, L"../../shader/lpv_rendervol.hlsl", "vs_5_0", "vs_rendervol", shader_flags, nullptr, &vs, &vs_blob); dune::compile_shader(the_device, L"../../shader/lpv_rendervol.hlsl", "ps_5_0", "ps_rendervol", shader_flags, nullptr, &ps); debug_box_.set_shader(the_device, vs_blob, vs, ps); cleanup(); #else // svo voxelize shader dune::compile_shader(device, L"../../shader/svo_voxelize.hlsl", "vs_5_0", "vs_svo_voxelize", shader_flags, nullptr, &vs); dune::compile_shader(device, L"../../shader/svo_voxelize.hlsl", "gs_5_0", "gs_svo_voxelize", shader_flags, nullptr, &gs); dune::compile_shader(device, L"../../shader/svo_voxelize.hlsl", "ps_5_0", "ps_svo_voxelize", shader_flags, nullptr, &ps); delta_radiance_field_.set_shader_voxelize(vs, gs, ps); cleanup(); // svo inject shader dune::compile_shader(device, L"../../shader/svo_inject.hlsl", "vs_5_0", "vs_svo_inject", shader_flags, nullptr, &vs); dune::compile_shader(device, L"../../shader/svo_inject.hlsl", "ps_5_0", "ps_svo_delta_inject", shader_flags, nullptr, &ps); delta_radiance_field_.set_shader_inject(vs, ps, SLOT_TEX_SVO_RSM_MU_START, SLOT_TEX_SVO_RSM_RHO_START); cleanup(); #endif } /*! \brief Renders a Delta Radiance Field. */ void render_drf(ID3D11DeviceContext* context, float* clear_color) { #ifdef DLPV ID3D11ShaderResourceView* null_srv[] = { nullptr, nullptr, nullptr }; context->PSSetShaderResources(SLOT_TEX_LPV_DEFERRED_START, 3, null_srv); lpv_rho_.inject(context, main_light_.rho(), true); lpv_rho_.render(context); float vpl_scale = delta_radiance_field_.parameters().data().vpl_scale; // TODO: fixme float flux_scale = main_light_.parameters().data().flux.x; // inject indirect delta_radiance_field_.inject(context, main_light_.rho(), true, false, vpl_scale); delta_radiance_field_.inject(context, main_light_.mu(), false, false, vpl_scale); delta_radiance_field_.render_indirect(context); // inject direct delta_radiance_field_.inject(context, main_light_.rho(), true, true, flux_scale); delta_radiance_field_.inject(context, main_light_.mu(), false, true, flux_scale); delta_radiance_field_.render_direct(context, 5, SLOT_TEX_LPV_DEFERRED_START); #else // TODO: voxelize only on geo change // voxelize reconstructed real scene for (size_t x = 0; x < reconstructed_real_scene_.size(); ++x) { dune::gilga_mesh* m = dynamic_cast<dune::gilga_mesh*>(reconstructed_real_scene_[x].get()); if (m) delta_radiance_field_.voxelize(context, *m); } // voxelize synthetic object delta_radiance_field_.voxelize(context, synthetic_object_); // inject differential light, i.e. RSM rho and mu delta_radiance_field_.inject(context, main_light_); // prefilter volume delta_radiance_field_.filter(context); // upload to gpu delta_radiance_field_.to_ps(context, SLOT_TEX_SVO_V_START); #endif } /*! * \brief Compute global illumination for the scene. * * This method first makes sure that the RSM/GI solution needs to be updated. * If so, a new RSM is rendered for one directional light, which will then be injected * into a volume and further processed. */ void render_gi(ID3D11DeviceContext* context, float* clear_color) { if (update_rsm_) { // setup rsm view update_rsm_camera_parameters(context, main_light_); // inject first bounce render_mu_ = false; profiler_.begin(context); render_rsm(context, clear_color, main_light_.rho()); time_rsm_rho_ = profiler_.result(); render_mu_ = true; profiler_.begin(context); render_rsm(context, clear_color, main_light_.mu()); time_rsm_mu_ = profiler_.result(); // render delta radiance field render_drf(context, clear_color); update_rsm_ = false; } } virtual void do_render_scene(ID3D11DeviceContext* context) { // play safe just in case real scene is just a quad context->RSSetState(no_culling_); reconstructed_real_scene_.set_shader_slots(SLOT_TEX_DIFFUSE, SLOT_TEX_NORMAL, SLOT_TEX_SPECULAR); synthetic_object_.set_shader_slots(SLOT_TEX_DIFFUSE, SLOT_TEX_NORMAL, SLOT_TEX_SPECULAR); reconstructed_real_scene_.render(context); synthetic_object_.render(context); } virtual void do_render_rsm(ID3D11DeviceContext* context) { // play safe just in case real scene is just a quad context->RSSetState(no_culling_); reconstructed_real_scene_.set_shader_slots(SLOT_TEX_DIFFUSE, SLOT_TEX_NORMAL); synthetic_object_.set_shader_slots(SLOT_TEX_DIFFUSE, SLOT_TEX_NORMAL); reconstructed_real_scene_.render(context); if (!render_mu_) synthetic_object_.render(context); } public: virtual void create(ID3D11Device* device) { // remove last entry from files_scene and use as synthetic object dune::tstring so_file = *files_scene.rbegin(); files_scene.pop_back(); rsm_renderer::create(device); profiler_.create(device); tracker_.create(L"../../data/camera_parameters.xml"); tracker_.load_pattern(L"../../data/marker.png"); synthetic_object_.create(device, so_file); delta_radiance_field_.create(device, VOLUME_SIZE); #ifdef DLPV lpv_rho_.create(device, VOLUME_SIZE); #endif CD3D11_RASTERIZER_DESC raster_desc = CD3D11_RASTERIZER_DESC(CD3D11_DEFAULT()); raster_desc.FrontCounterClockwise = true; raster_desc.CullMode = D3D11_CULL_NONE; dune::assert_hr(device->CreateRasterizerState(&raster_desc, &no_culling_)); load_shader(device); #ifdef MICROSOFT_KINECT_SDK kinect_.create(device, L"kinect"); add_buffer(kinect_, SLOT_TEX_DEFERRED_KINECT_START); kinect_.start(); #else dune::load_static_target(device, L"../../data/real_static_scene.png", real_static_background_); real_static_background_.name = L"static_rgb"; add_buffer(real_static_background_, SLOT_TEX_DEFERRED_KINECT_START); #endif } virtual void destroy() { #ifdef MICROSOFT_KINECT_SDK kinect_.destroy(); #else real_static_background_.destroy(); #endif rsm_renderer::destroy(); delta_radiance_field_.destroy(); synthetic_object_.destroy(); dune::safe_release(no_culling_); profiler_.destroy(); #ifdef DLPV lpv_rho_.destroy(); #endif } virtual void render(ID3D11DeviceContext* context, ID3D11RenderTargetView* backbuffer, ID3D11DepthStencilView* dsv) { static float clear_color[4] = { 0.0f, 0.f, 0.0f, 1.0f }; #ifdef MICROSOFT_KINECT_SDK kinect_.update(context); tracker_.track_frame(*kinect_.color()); #else tracker_.track_frame(real_static_background_); #endif update_tracked_scene(context); render_gi(context, clear_color); render_scene(context, clear_color, dsv); context->GenerateMips(main_light_.rho()[L"lineardepth"]->srv()); context->GenerateMips(main_light_.mu()[L"lineardepth"]->srv()); context->GenerateMips(def_[L"lineardepth"]->srv()); dune::set_viewport(context, DXUTGetWindowWidth(), DXUTGetWindowHeight()); profiler_.begin(context); deferred_renderer::render(context, backbuffer, dsv); time_deferred_ = profiler_.result(); } void update_gi_parameters(ID3D11DeviceContext* context) { delta_radiance_field_.set_model_matrix(context, synthetic_object_.world(), bb_min_, bb_max_, VOLUME_PARAMETERS_SLOT); delta_radiance_field_.parameters().to_ps(context, SLOT_GI_PARAMETERS_PS); #ifdef DLPV lpv_rho_.set_model_matrix(context, synthetic_object_.world(), bb_min_, bb_max_, VOLUME_PARAMETERS_SLOT); lpv_rho_.parameters().to_ps(context, SLOT_GI_PARAMETERS_PS); #endif update_rsm_ = true; } /*! \brief Update all objects (synthetic and real reconstructed scene) with a matrix from the tracker. */ void update_tracked_scene(ID3D11DeviceContext* context) { using namespace DirectX; XMMATRIX empty = XMMatrixIdentity(); XMFLOAT4X4 tempty; XMStoreFloat4x4(&tempty, empty); XMFLOAT3 etrans = { 0, 0, -2.5 }; // update virtual object now update_bbox(context, synthetic_object_); XMVECTOR trans = { dc::gui::slider_value(IDC_TRACK_TRANSX, true) * 2.0f - 1.0f, dc::gui::slider_value(IDC_TRACK_TRANSY, true) * 2.0f - 1.0f, dc::gui::slider_value(IDC_TRACK_TRANSZ, true) * 2.0f - 1.0f, 0.f }; trans = XMVectorScale(trans, 100); float scale = dc::gui::slider_value(IDC_TRACK_SCALE, true) * 100; XMFLOAT3 ttrans; XMStoreFloat3(&ttrans, trans); XMFLOAT4X4 tmodel = tracker_.model_view_matrix(scale, ttrans, tempty, 0); // set virtual object model view matrix synthetic_object_.set_world(tmodel); // update synthetic objects XMMATRIX rot = XMMatrixIdentity(); if (dc::gui::checkbox_value(IDC_TRACK_ANIMATE)) rot *= XMMatrixRotationY(rotation_angle_); update_scene(context, rot * DirectX::XMLoadFloat4x4(&tmodel)); // calculate new bounds 2x the size of the maximum edge of the virtual objects bounding box XMFLOAT3 bb_min = synthetic_object_.bb_min(); XMFLOAT3 bb_max = synthetic_object_.bb_max(); XMVECTOR v_bb_min = XMLoadFloat3(&bb_min); XMVECTOR v_bb_max = XMLoadFloat3(&bb_max); XMVECTOR v_bb_diag = XMVectorSubtract(v_bb_max, v_bb_min); float l = std::max(std::max(XMVectorGetX(v_bb_diag), XMVectorGetY(v_bb_diag)), XMVectorGetZ(v_bb_diag)); l *= 2; XMVECTORF32 l_edge = { l, l, l, 0 }; XMVECTOR v_bb_center = XMVectorScale(XMVectorAdd(v_bb_max, v_bb_min), 0.5f); v_bb_max = v_bb_center + l_edge; v_bb_min = v_bb_center - l_edge; XMStoreFloat3(&bb_min_, v_bb_min); XMStoreFloat3(&bb_max_, v_bb_max); dc::gui::get_parameters(main_light_, synthetic_object_, z_near, z_far); update_light_parameters(context, main_light_); update_gi_parameters(context); } void update_frame(ID3D11DeviceContext* context, double time, float elapsed_time) { rsm_renderer::update_frame(context, time, elapsed_time); rotation_angle_ += 0.5f * elapsed_time; } void update_everything(ID3D11DeviceContext* context) { update_tracked_scene(context); update_onetime_parameters(context, synthetic_object_); update_camera_parameters(context); update_light_parameters(context, main_light_); update_postprocessing_parameters(context); update_gi_parameters(context); } void reload_shader(ID3D11Device* device, ID3D11DeviceContext* context) { load_shader(device); update_everything(context); } virtual void save(dune::serializer& s) { rsm_renderer::save(s); s << delta_radiance_field_; } virtual void load(ID3D11DeviceContext* context, const dune::serializer& s) { rsm_renderer::load(context, s); s >> delta_radiance_field_; update_everything(context); } inline auto drf() -> decltype((delta_radiance_field_)) { return delta_radiance_field_; } #ifdef DLPV inline dune::light_propagation_volume& lpv_rho() { return lpv_rho_; } #endif inline dune::gilga_mesh& synthetic_object() { return synthetic_object_; } inline dune::tracker& tracker() { return tracker_; } }; #endif
thefranke/dirtchamber
src/dune/simple_mesh.h
/* * Dune D3D library - <NAME> 2011 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DUNE_SIMPLE_MESH #define DUNE_SIMPLE_MESH #include <D3D11.h> #include <vector> #include "d3d_tools.h" #include "mesh.h" namespace dune { /*! * \brief A very simple mesh class with position-only vertex attributes. * * This class represents a very simple implementation of a d3d_mesh. A simple_mesh only contains vertices with a position attribute. * Use this class if you want to specify simple geometry for which fixed attributes will be declared in a shader. An example usage * of this class is the fullscreen triangle used for a deferred renderer. * * \note Yes I know you can use SV_VertexID as well to generate a fullscreen triangle, but PIX didn't like it and since then I didn't care... * */ class simple_mesh : public d3d_mesh { protected: struct vertex { DirectX::XMFLOAT3 v; }; std::vector<vertex> vertices_; ID3D11Buffer* mesh_data_; protected: virtual const D3D11_INPUT_ELEMENT_DESC* vertex_desc() { static D3D11_INPUT_ELEMENT_DESC l[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, 0 }; return l; } public: simple_mesh() : vertices_(), mesh_data_() { } virtual ~simple_mesh() {} /*! \brief Add a new vertex p to the mesh. */ void push_back(DirectX::XMFLOAT3& p) { vertex v = { p }; vertices_.push_back(v); } /*! * \brief Create a new simple_mesh. * * This function creates a new, empty simple_mesh. * * \param device The Direct3D device. * \param name Instead of a filename, a name is used to write the creating of a simple_mesh into a log. This parameter serves no other purpose. */ virtual void create(ID3D11Device* device, const tstring& name) { tclog << L"Creating: simple geometry " << name << L" with " << num_faces() << " faces" << std::endl; D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(vertex)* 3; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA InitData; ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = &vertices_[0]; assert_hr(device->CreateBuffer(&bd, &InitData, &mesh_data_)); } virtual void render(ID3D11DeviceContext* context, DirectX::XMFLOAT4X4* to_clip = nullptr) { context->VSSetShader(vs_, nullptr, 0); context->IASetInputLayout(vertex_layout_); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); static const UINT stride = sizeof(vertex); static const UINT offset = 0; context->IASetVertexBuffers(0, 1, &mesh_data_, &stride, &offset); context->Draw(static_cast<UINT>(num_vertices()), 0); } virtual size_t num_vertices() { return vertices_.size(); } virtual size_t num_faces() { return num_vertices() / 3; } virtual void destroy() { safe_release(mesh_data_); vertices_.clear(); d3d_mesh::destroy(); } }; } #endif
thefranke/dirtchamber
src/pppipe.h
/* * The Dirtchamber - <NAME> 2013 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef PPPIPE #define PPPIPE #include <dune/cbuffer.h> #include <dune/postprocess.h> #include <dune/serializer.h> /*! * \brief A default implementation of the postprocessor. * * This is a default implementation of the postprocessor class. The output of a deferred renderer * is rendered to the frontbuffer render_target of the postprocessor. Each postprocess effect is rendered * by swapping input and output of the previous shader, until the last shader writes its output to the * backbuffer provided to the postprocessor. * * This postprocessor implements SSAO, Godrays, Depth-of-Field, Bloom, FXAA, exposure adaptation, a CRT monitor * effect, TV grain and HDR rendering. */ class pppipe : public dune::postprocessor { public: struct parameters { BOOL ssao_enabled; float ssao_scale; BOOL godrays_enabled; float godrays_tau; BOOL dof_enabled; float dof_focal_plane; float dof_coc_scale; BOOL bloom_enabled; float bloom_sigma; float bloom_treshold; BOOL fxaa_enabled; BOOL exposure_adapt; float exposure_key; float exposure_speed; BOOL crt_enabled; BOOL film_grain_enabled; }; protected: typedef dune::cbuffer<parameters> cb_pp_parameters; cb_pp_parameters cb_pp_parameters_; ID3D11PixelShader* ssao_; ID3D11PixelShader* bloom_; ID3D11PixelShader* godrays_; ID3D11PixelShader* godrays_merge_; ID3D11PixelShader* dof_; ID3D11PixelShader* adapt_exposure_; ID3D11PixelShader* fxaa_; ID3D11PixelShader* bloom_treshold_; ID3D11PixelShader* crt_; ID3D11PixelShader* film_grain_; ID3D11PixelShader* gauss_godrays_h_; ID3D11PixelShader* gauss_godrays_v_; ID3D11PixelShader* gauss_bloom_h_; ID3D11PixelShader* gauss_bloom_v_; ID3D11PixelShader* gauss_dof_h_; ID3D11PixelShader* gauss_dof_v_; ID3D11PixelShader* copy_; virtual void do_create(ID3D11Device* device); virtual void do_destroy(); virtual void do_set_shader(ID3D11Device* device); virtual void do_resize(UINT width, UINT height); dune::render_target blurred_[6]; dune::render_target bloom_full_; dune::render_target frontbuffer_blurred_; dune::render_target temporary_; dune::render_target rt_adapted_luminance_[2]; //!@{ /*! \brief Render depth of field and blur it. */ void dof(ID3D11DeviceContext* context, dune::render_target& in, dune::render_target& out); void dofblur(ID3D11DeviceContext* context, dune::render_target& in, dune::render_target& out); //!@} //!@{ /*! \brief Render bloom and blur it. */ void bloom(ID3D11DeviceContext* context, dune::render_target& frontbuffer); void bloomblur(ID3D11DeviceContext* context, dune::render_target& in, dune::render_target& out); //!@} /*! \brief Compute godrays on half size buffer. */ void godrays(ID3D11DeviceContext* context, dune::render_target& in, dune::render_target& out); /*! \brief Render the entire pipeline by switching back and forth between a two temporary buffers. */ void render(ID3D11DeviceContext* context, ID3D11PixelShader* ps, dune::render_target& in, ID3D11RenderTargetView* out); public: virtual void render(ID3D11DeviceContext* context, ID3D11RenderTargetView* backbuffer); //!@{ /*! \brief Return local cbuffer parameters. */ cb_pp_parameters& parameters() { return cb_pp_parameters_; } const cb_pp_parameters& parameters() const { return cb_pp_parameters_; } //!@} }; //!@{ /*! \brief Read/write postprocessor from/to a serializer. */ dune::serializer& operator<<(dune::serializer& s, const pppipe& p); const dune::serializer& operator>>(const dune::serializer& s, pppipe& p); //!@} #endif
thefranke/dirtchamber
src/dune/dune.h
/* * * The Dune D3D library - <NAME> 2011 * For copyright and license see LICENSE * http://www.tobias-franke.eu * * "God created Arrakis to train the faithful." * */ /*! \file */ /// Direct3D helper library namespace dune {} #include "assimp_mesh.h" #include "exception.h" #include "camera.h" #include "cbuffer.h" #include "common_tools.h" #include "composite_mesh.h" #include "deferred_renderer.h" #include "d3d_tools.h" #include "gbuffer.h" #include "light.h" #include "light_propagation_volume.h" #include "logger.h" #include "math_tools.h" #include "mesh.h" #include "postprocess.h" #include "record_tools.h" #include "render_target.h" #include "sdk_mesh.h" #include "shader_resource.h" #include "shader_tools.h" #include "sparse_voxel_octree.h" #include "serializer.h" #include "serializer_tools.h" #include "texture.h" #include "texture_cache.h" #include "unicode.h" #include "kinect_gbuffer.h" #include "tracker.h"
thefranke/dirtchamber
src/dune/sparse_voxel_octree.h
<gh_stars>100-1000 /* * Dune D3D library - <NAME> 2013 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DUNE_SPARSE_VOXEL_OCTREE #define DUNE_SPARSE_VOXEL_OCTREE #include <D3D11.h> #include "cbuffer.h" #include "shader_resource.h" namespace dune { struct d3d_mesh; class gilga_mesh; class directional_light; class differential_directional_light; } namespace dune { /*! * \brief A sparse voxel octree (SVO). * * This class implements a sparse voxel octree (currently just a volume) filtered and uploaded to the GPU, where it can * be used for Voxel Cone Tracing. The SVO contains to volume textures: v_normal_, which contains a four component 3D texture * where each texel is an RGB encoded normal plus a occlusion marker, and v_rho_ which contains the injected first bounce * from an RSM. * * A typical SVO is handled in three steps when rendering: * - One or more calls to voxelize meshes * - One or more calls to inject RSMs * - A final call to filter (i.e. mip-map) both volume textures * * After uploading both volumes to the GPU, voxel cone tracing can be performed. */ class sparse_voxel_octree : public shader_resource { public: struct param { float gi_scale; float glossiness; UINT num_vpls; BOOL debug_gi; }; protected: ID3D11BlendState* bs_voxelize_; ID3D11SamplerState* ss_visualize_; ID3D11VertexShader* vs_voxelize_; ID3D11GeometryShader* gs_voxelize_; ID3D11PixelShader* ps_voxelize_; ID3D11VertexShader* vs_inject_; ID3D11PixelShader* ps_inject_; INT inject_rsm_rho_start_slot_; ID3D11Texture3D* v_normal_; ID3D11Texture3D* v_rho_; ID3D11ShaderResourceView* srv_v_normal_; ID3D11ShaderResourceView* srv_v_rho_; ID3D11UnorderedAccessView* uav_v_normal_; ID3D11UnorderedAccessView* uav_v_rho_; ID3D11RasterizerState* no_culling_; UINT volume_size_; DirectX::XMFLOAT4X4 world_to_svo_; DirectX::XMFLOAT3 svo_min_, svo_max_; struct cbs_parameters { DirectX::XMFLOAT4X4 world_to_svo; DirectX::XMFLOAT4 bb_min; DirectX::XMFLOAT4 bb_max; }; cbuffer<cbs_parameters> cb_parameters_; dune::profile_query profiler_; typedef cbuffer<param> cb_gi_parameters; cb_gi_parameters cb_gi_parameters_; UINT last_bound_; protected: virtual void clear_ps(ID3D11DeviceContext* context); public: float time_voxelize_; float time_inject_; float time_mip_; public: sparse_voxel_octree(); virtual ~sparse_voxel_octree() {} //!@{ /*! \brief Return local cbuffer parameters. */ cb_gi_parameters& parameters() { return cb_gi_parameters_; } const cb_gi_parameters& parameters() const { return cb_gi_parameters_; } //!@} virtual void create(ID3D11Device* device, UINT volume_size); virtual void destroy(); /*! * \brief Set the complete voxelization shader. * * This method sets the voxelization shader, which includes a vertex, geometry and pixel shader. * The shader is an implementation of [[Schwarz and Seidel 2010]](http://research.michael-schwarz.com/publ/2010/vox/). * * \param vs The voxelization vertex shader. * \param gs The voxelization geometry shader. * \param ps The voxelization pixel shader. */ void set_shader_voxelize(ID3D11VertexShader* vs, ID3D11GeometryShader* gs, ID3D11PixelShader* ps); /*! * \brief Set the complete injection shader. * * This method sets the injection shader, which includes a vertex and pixel shader, and a slot * at which register the shader can expect to read a gbuffer of the RSM with colors, normals and * lineardepth. * * \param vs The injection vertex shader. * \param ps The injection pixel shader. * \param rsm_start_slot The slot at which the gbuffer of an RSM starts. */ void set_shader_inject(ID3D11VertexShader* vs, ID3D11PixelShader* ps, UINT rsm_start_slot); /*! \brief Voxelize a mesh into a volume with normals and an occupied marker. If clear is true, the volume is cleared before voxelization. */ void voxelize(ID3D11DeviceContext* context, gilga_mesh& mesh, bool clear = true); /*! \brief Inject a bounce from directional_light into the SVO. */ virtual void inject(ID3D11DeviceContext* context, directional_light& light); /*! \brief Pre-filter (i.e. mip-map) the SVO. */ void filter(ID3D11DeviceContext* context); //!@{ /*! \brief Set/get the world -> SVO matrix, which transforms world coordinates to SVO volume coordinates. */ void set_model_matrix(ID3D11DeviceContext* context, const DirectX::XMFLOAT4X4& model, const DirectX::XMFLOAT3& svo_min, const DirectX::XMFLOAT3& svo_max, UINT svo_parameters_slot); const DirectX::XMFLOAT4X4& world_to_svo() const { return world_to_svo_; } //!@} virtual void to_ps(ID3D11DeviceContext* context, UINT volume_start_slot); }; /*! * \brief A Delta Radiance Field of an SVO necessary for Delta Voxel Cone Tracing (DVCT) * * This class is an implementation of [[Franke 2014]](http://www.tobias-franke.eu/publications/franke14dvct). * A DLPV is an LPV that extracts the difference in illumination caused by the introduction * of an additional object into a scene. It can be used to correct for this difference, for instance * in augmented reality applications. * * The mechanic works like this: instead of injecting one RSM, two a rendered. One * is rendered with a scene, the other with the same scene and an additional object. * By injecting the latter first, and then injecting the former negatively, the * delta is extracted and propagated in the volume. * * A DLPV also injects direct light to form out rough shadow blobs. Propagation * of direct and indirect injects is independent from one another. */ class delta_sparse_voxel_octree : public sparse_voxel_octree { protected: ID3D11Texture3D* v_delta_; ID3D11ShaderResourceView* srv_v_delta_; ID3D11UnorderedAccessView* uav_v_delta_; INT inject_rsm_mu_start_slot_; protected: virtual void clear_ps(ID3D11DeviceContext* context); public: delta_sparse_voxel_octree(); virtual ~delta_sparse_voxel_octree() {} virtual void create(ID3D11Device* device, UINT volume_size); virtual void destroy(); void set_shader_inject(ID3D11VertexShader* vs, ID3D11PixelShader* ps, UINT mu_start_slot, UINT rho_start_slot); virtual void inject(ID3D11DeviceContext* context, differential_directional_light& light); virtual void to_ps(ID3D11DeviceContext* context, UINT volume_start_slot); }; } #endif
thefranke/dirtchamber
src/dune/math_tools.h
/* * Dune D3D library - <NAME> 2011 * For copyright and license see LICENSE * http://www.tobias-franke.eu */ /*! \file */ #ifndef DUNE_MATH_TOOLS #define DUNE_MATH_TOOLS #include <DirectXMath.h> namespace dune { const float PI = 3.1415926f; const float DEG_TO_RAD = PI/180.f; /*! \brief Get a number of the Halton sequence. */ float halton(int index, int base); /*! \brief Get a number-pair of the Hammersley sequence. */ DirectX::XMFLOAT2 hammersley2d(unsigned int i, unsigned int N); DirectX::XMMATRIX make_projection(float z_near, float z_far); /*! \brief Approximate functions namespace. */ namespace approx { inline double sin(double x); inline double exp(double x); } /*! \brief Helper functions to convert PBRT matrix operations. */ namespace pbrt { DirectX::XMMATRIX translate(float x, float y, float z); DirectX::XMMATRIX rotate(float angle, float x, float y, float z); } } #endif
stvnrhodes/CNCAirbrush
mbed/CNCAirbrush/ImgBuffer.h
<filename>mbed/CNCAirbrush/ImgBuffer.h #ifndef IMGBUFFER_H #define IMGBUFFER_H #define MAX_IMG_BUF 1024 class ImgBuffer { public: ImgBuffer() { write = 0; read = 0; size = MAX_IMG_BUF + 1; }; bool isFull() { return ((write + 1) % size == read); }; bool isEmpty() { return (read == write); }; void queue(uint8_t k) { if (isFull()) { read++; read %= size; } buf[write++] = k; write %= size; } uint16_t available() { return (write >= read) ? write - read : size - read + write; }; bool dequeue(uint8_t * c) { if (!isEmpty()) { *c = buf[read++]; read %= size; } return(!isEmpty()); }; void clear() { read = write; }; private: volatile uint16_t write; volatile uint16_t read; uint16_t size; uint8_t buf[MAX_IMG_BUF + 1]; }; #endif
stvnrhodes/CNCAirbrush
mbed/mbed/rtc_time.h
<reponame>stvnrhodes/CNCAirbrush /* Title: time * Implementation of the C time.h functions * * Provides mechanisms to set and read the current time, based * on the microcontroller Real-Time Clock (RTC), plus some * standard C manipulation and formating functions. * * Example: * > #include "mbed.h" * > * > int main() { * > set_time(1256729737); // Set RTC time to Wed, 28 Oct 2009 11:35:37 * > * > while(1) { * > time_t seconds = time(NULL); * > * > printf("Time as seconds since January 1, 1970 = %d\n", seconds); * > * > printf("Time as a basic string = %s", ctime(&seconds)); * > * > char buffer[32]; * > strftime(buffer, 32, "%I:%M %p\n", localtime(&seconds)); * > printf("Time as a custom formatted string = %s", buffer); * > * > wait(1); * > } * > } */ /* mbed Microcontroller Library - rtc_time * Copyright (c) 2009 ARM Limited. All rights reserved. */ #include <time.h> #ifdef __cplusplus extern "C" { #endif #if 0 // for documentation only /* Function: time * Get the current time * * Returns the current timestamp as the number of seconds since January 1, 1970 * (the UNIX timestamp). The value is based on the current value of the * microcontroller Real-Time Clock (RTC), which can be set using <set_time>. * * Example: * > #include "mbed.h" * > * > int main() { * > time_t seconds = time(NULL); * > printf("It is %d seconds since January 1, 1970\n", seconds); * > } * * Variables: * t - Pointer to a time_t to be set, or NULL if not used * returns - Number of seconds since January 1, 1970 (the UNIX timestamp) */ time_t time(time_t *t); #endif /* Function: set_time * Set the current time * * Initialises and sets the time of the microcontroller Real-Time Clock (RTC) * to the time represented by the number of seconds since January 1, 1970 * (the UNIX timestamp). * * Example: * > #include "mbed.h" * > * > int main() { * > set_time(1256729737); // Set time to Wed, 28 Oct 2009 11:35:37 * > } * * Variables: * t - Number of seconds since January 1, 1970 (the UNIX timestamp) */ void set_time(time_t t); #if 0 // for documentation only /* Function: mktime * Converts a tm structure in to a timestamp * * Converts the tm structure in to a timestamp in seconds since January 1, 1970 * (the UNIX timestamp). The values of tm_wday and tm_yday of the tm structure * are also updated to their appropriate values. * * Example: * > #include "mbed.h" * > * > int main() { * > // setup time structure for Wed, 28 Oct 2009 11:35:37 * > struct tm t; * > t.tm_sec = 37; // 0-59 * > t.tm_min = 35; // 0-59 * > t.tm_hour = 11; // 0-23 * > t.tm_mday = 28; // 1-31 * > t.tm_mon = 9; // 0-11 * > t.tm_year = 109; // year since 1900 * > * > // convert to timestamp and display (1256729737) * > time_t seconds = mktime(&t); * > printf("Time as seconds since January 1, 1970 = %d\n", seconds); * > } * * Variables: * t - The tm structure to convert * returns - The converted timestamp */ time_t mktime(struct tm *t); #endif #if 0 // for documentation only /* Function: localtime * Converts a timestamp in to a tm structure * * Converts the timestamp pointed to by t to a (statically allocated) * tm structure. * * Example: * > #include "mbed.h" * > * > int main() { * > time_t seconds = 1256729737; * > struct tm *t = localtime(&seconds); * > } * * Variables: * t - Pointer to the timestamp * returns - Pointer to the (statically allocated) tm structure */ struct tm *localtime(const time_t *t); #endif #if 0 // for documentation only /* Function: ctime * Converts a timestamp to a human-readable string * * Converts a time_t timestamp in seconds since January 1, 1970 (the UNIX * timestamp) to a human readable string format. The result is of the * format: "Wed Oct 28 11:35:37 2009\n" * * Example: * > #include "mbed.h" * > * > int main() { * > time_t seconds = time(NULL); * > printf("Time as a string = %s", ctime(&seconds)); * > } * * Variables: * t - The timestamp to convert * returns - Pointer to a (statically allocated) string containing the * human readable representation, including a '\n' character */ char *ctime(const time_t *t); #endif #if 0 // for documentation only /* Function: strftime * Converts a tm structure to a custom format human-readable string * * Creates a formated string from a tm structure, based on a string format * specifier provided. * * Format Specifiers: * %S - Second (00-59) * %M - Minute (00-59) * %H - Hour (00-23) * %d - Day (01-31) * %m - Month (01-12) * %Y/%y - Year (2009/09) * * %A/%a - Weekday Name (Monday/Mon) * %B/%b - Month Name (January/Jan) * %I - 12 Hour Format (01-12) * %p - "AM" or "PM" * %X - Time (14:55:02) * %x - Date (08/23/01) * * Example: * > #include "mbed.h" * > * > int main() { * > time_t seconds = time(NULL); * > * > char buffer[32]; * > strftime(buffer, 32, "%I:%M %p\n", localtime(&seconds)); * > printf("Time as a formatted string = %s", buffer); * > } * * Variables: * buffer - String buffer to store the result * max - Maximum number of characters to store in the buffer * format - Format specifier string * t - Pointer to the tm structure to convert * returns - Number of characters copied */ size_t strftime(char *buffer, size_t max, const char *format, const struct tm *t); #endif #ifdef __cplusplus } #endif
stvnrhodes/CNCAirbrush
mbed/CNCAirbrush/CmdBuffer.h
#ifndef CMDBUFFER_H #define CMDBUFFER_H #define MAX_CMD_BUF 16 #define MAX_CMD_NUM 0xb #define MAX_INTERRUPTS 3 // Command Struct typedef struct { char cmd; union { float f[6]; long l[6]; }; } Command; class CmdBuffer { public: CmdBuffer() { write = 0; read = 0; size = MAX_CMD_BUF + 1; temp_ptr = 0; temp_size = 2 + 6*9; cmd_sizes[0x0] = 3; cmd_sizes[0x1] = 5; cmd_sizes[0x2] = 6; cmd_sizes[0x3] = 6; cmd_sizes[0x4] = 1; cmd_sizes[0x5] = 1; cmd_sizes[0x6] = 4; cmd_sizes[0x7] = 1; cmd_sizes[0x8] = 0; cmd_sizes[0x9] = 0; cmd_sizes[0xa] = 0; interrupt_cmds[0] = 0xff; interrupt_cmds[1] = 0xff; interrupt_cmds[2] = 0xff; }; bool isFull() { return ((write + 1) % size == read); }; bool isEmpty() { return (read == write); }; // Return true if we've queued a command bool queue(char k) { tempbuf[temp_ptr++] = k; if (temp_ptr == 2) { int cmd_num = (0x0f&char_to_num(tempbuf[1]))|(0xf0&char_to_num(tempbuf[0])<<4); if (cmd_num > MAX_CMD_NUM) { //Invalid temp_ptr = 0; temp_size = 4 + 6*9; return true; } else { temp_size = 2 + 9 * cmd_sizes[cmd_num]; } } if (temp_ptr >= temp_size) { Command c; c.cmd = (0x0f&char_to_num(tempbuf[1]))|(0xf0&char_to_num(tempbuf[0])<<4); for (int i = 0; i < cmd_sizes[c.cmd]; i++) { c.l[i] = str_to_long(tempbuf + 3 + i*9); #ifdef DEBUG printf("arg%d: %x\n\r",i,c.l[i]); #endif } for (int i = 0; i < MAX_INTERRUPTS; i++) { if (c.cmd == interrupt_cmds[i]){ interrupt_funcs[i](&c); } } queue_cmd(c); temp_ptr = 0; temp_size = 4 + 6*9; return true; } return false; } uint16_t available() { return (write >= read) ? write - read : size - read + write; }; Command * dequeue() { Command * c = NULL; if (!isEmpty()) { c = &buf[read++]; read %= size; } return c; }; bool attach_interrupt(char cmd, void (*func)(Command *), int num) { if (num < MAX_INTERRUPTS) { interrupt_funcs[num] = func; interrupt_cmds[num] = cmd; return true; } return false; } private: void queue_cmd(Command k) { if (isFull()) { read++; read %= size; } buf[write++] = k; write %= size; } // Return 0xf if char is invalid char char_to_num(char c) { if(c >= '0' && c <= '9') { return c - '0'; } else if(c >= 'a' && c <= 'f') { return c - 'a' + 0xa; } else if(c >= 'A' && c <= 'F') { return c - 'A' + 0xa; } else { #ifdef DEBUG printf("CmdBuffer::char_to_num: invalid number\r\n"); #endif return 0xf; } } long str_to_long(char * str) { long ans = 0; for (int i = 7; (i > 0 && i < 8); i -= 2) { ans = ans << 8; ans |= (0xf0 & char_to_num(str[i - 1])<<4); ans |= (0x0f & char_to_num(str[i])); } return ans; } volatile uint16_t write; volatile uint16_t read; uint16_t size; void (*interrupt_funcs[MAX_INTERRUPTS])(Command *); char interrupt_cmds[MAX_INTERRUPTS]; Command buf[MAX_CMD_BUF + 1]; volatile uint16_t temp_ptr; volatile uint16_t temp_size; char tempbuf[2 + 6*9 + 1]; uint16_t cmd_sizes[MAX_CMD_NUM]; }; #endif
stvnrhodes/CNCAirbrush
mbed/mbed/FunctionPointer.h
<gh_stars>1-10 /* mbed Microcontroller Library - FunctionPointer * Copyright (c) 2007-2009 ARM Limited. All rights reserved. */ #ifndef MBED_FUNCTIONPOINTER_H #define MBED_FUNCTIONPOINTER_H #include <string.h> namespace mbed { /* Class FunctionPointer * A class for storing and calling a pointer to a static or member void function */ class FunctionPointer { public: /* Constructor FunctionPointer * Create a FunctionPointer, attaching a static function * * Variables * function - The void static function to attach (default is none) */ FunctionPointer(void (*function)(void) = 0); /* Constructor FunctionPointer * Create a FunctionPointer, attaching a member function * * Variables * object - The object pointer to invoke the member function on (i.e. the this pointer) * function - The address of the void member function to attach */ template<typename T> FunctionPointer(T *object, void (T::*member)(void)) { attach(object, member); } /* Function attach * Attach a static function * * Variables * function - The void static function to attach (default is none) */ void attach(void (*function)(void) = 0); /* Function attach * Attach a member function * * Variables * object - The object pointer to invoke the member function on (i.e. the this pointer) * function - The address of the void member function to attach */ template<typename T> void attach(T *object, void (T::*member)(void)) { _object = static_cast<void*>(object); memcpy(_member, (char*)&member, sizeof(member)); _membercaller = &FunctionPointer::membercaller<T>; _function = 0; } /* Function call * Call the attached static or member function */ void call(); private: template<typename T> static void membercaller(void *object, char *member) { T* o = static_cast<T*>(object); void (T::*m)(void); memcpy((char*)&m, member, sizeof(m)); (o->*m)(); } void (*_function)(void); // static function pointer - 0 if none attached void *_object; // object this pointer - 0 if none attached char _member[16]; // raw member function pointer storage - converted back by registered _membercaller void (*_membercaller)(void*, char*); // registered membercaller function to convert back and call _member on _object }; } // namespace mbed #endif
stvnrhodes/CNCAirbrush
mbed/mbed/PortInOut.h
<filename>mbed/mbed/PortInOut.h /* mbed Microcontroller Library - PortInOut * Copyright (c) 2006-2011 ARM Limited. All rights reserved. */ #ifndef MBED_PORTINOUT_H #define MBED_PORTINOUT_H #include "device.h" #if DEVICE_PORTINOUT #include "PortNames.h" #include "PinNames.h" namespace mbed { /* Class: PortInOut * A multiple pin digital in/out used to set/read multiple bi-directional pins */ class PortInOut { public: /* Constructor: PortInOut * Create an PortInOut, connected to the specified port * * Variables: * port - Port to connect to (Port0-Port5) * mask - A bitmask to identify which bits in the port should be included (0 - ignore) */ PortInOut(PortName port, int mask = 0xFFFFFFFF); /* Function: write * Write the value to the output port * * Variables: * value - An integer specifying a bit to write for every corresponding port pin */ void write(int value); /* Function: read * Read the value currently output on the port * * Variables: * returns - An integer with each bit corresponding to associated port pin setting */ int read(); /* Function: output * Set as an output */ void output(); /* Function: input * Set as an input */ void input(); /* Function: mode * Set the input pin mode * * Variables: * mode - PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode mode); /* Function: operator= * A shorthand for <write> */ PortInOut& operator= (int value) { write(value); return *this; } PortInOut& operator= (PortInOut& rhs) { write(rhs.read()); return *this; } /* Function: operator int() * A shorthand for <read> */ operator int() { return read(); } private: #if defined(TARGET_LPC1768) || defined(TARGET_LPC2368) LPC_GPIO_TypeDef *_gpio; #endif PortName _port; uint32_t _mask; }; } // namespace mbed #endif #endif
stvnrhodes/CNCAirbrush
mbed/CNCAirbrush/CBuffer.h
<gh_stars>1-10 #ifndef CBUFFER_H #define CBUFFER_H #define MAX_BUF 128 class CBuffer { public: CBuffer() { write = 0; read = 0; size = MAX_BUF + 1; }; bool isFull() { return ((write + 1) % size == read); }; bool isEmpty() { return (read == write); }; void queue(uint8_t k) { if (isFull()) { read++; read %= size; } buf[write++] = k; write %= size; } uint16_t available() { return (write >= read) ? write - read : size - read + write; }; bool dequeue(uint8_t * c) { if (!isEmpty()) { *c = buf[read++]; read %= size; } return(!isEmpty()); }; private: volatile uint16_t write; volatile uint16_t read; uint16_t size; uint8_t buf[MAX_BUF + 1]; }; #endif
stvnrhodes/CNCAirbrush
mbed/mbed/CAN.h
/* mbed Microcontroller Library - can * Copyright (c) 2009-2011 ARM Limited. All rights reserved. */ #ifndef MBED_CAN_H #define MBED_CAN_H #include "device.h" #if DEVICE_CAN #include "Base.h" #include "platform.h" #include "PinNames.h" #include "PeripheralNames.h" #include "can_helper.h" #include "FunctionPointer.h" #include <string.h> namespace mbed { /* Class: CANMessage * */ class CANMessage : public CAN_Message { public: /* Constructor: CANMessage * Creates empty CAN message. */ CANMessage() { len = 8; type = CANData; format = CANStandard; id = 0; memset(data, 0, 8); } /* Constructor: CANMessage * Creates CAN message with specific content. */ CANMessage(int _id, const char *_data, char _len = 8, CANType _type = CANData, CANFormat _format = CANStandard) { len = _len & 0xF; type = _type; format = _format; id = _id; memcpy(data, _data, _len); } /* Constructor: CANMessage * Creates CAN remote message. */ CANMessage(int _id, CANFormat _format = CANStandard) { len = 0; type = CANRemote; format = _format; id = _id; memset(data, 0, 8); } #if 0 // Inhereted from CAN_Message, for documentation only /* Variable: id * The message id. * * If format is CANStandard it must be an 11 bit long id * If format is CANExtended it must be an 29 bit long id */ unsigned int id; /* Variable: data * Space for 8 byte payload. * * If type is CANData data can store up to 8 byte data. */ unsigned char data[8]; /* Variable: len * Length of data in bytes. * * If type is CANData data can store up to 8 byte data. */ unsigned char len; /* Variable: format * Defines if the message has standard or extended format. * * Defines the type of message id: * Default is CANStandard which implies 11 bit id. * CANExtended means 29 bit message id. */ CANFormat format; /* Variable: type * Defines the type of a message. * * The message type can rather be CANData for a message with data (default). * Or CANRemote for a request of a specific CAN message. */ CANType type; // 0 - DATA FRAME, 1 - REMOTE FRAME #endif }; /* Class: CAN * A can bus client, used for communicating with can devices */ class CAN : public Base { public: /* Constructor: CAN * Creates an CAN interface connected to specific pins. * * Example: * > #include "mbed.h" * > * > Ticker ticker; * > DigitalOut led1(LED1); * > DigitalOut led2(LED2); * > CAN can1(p9, p10); * > CAN can2(p30, p29); * > * > char counter = 0; * > * > void send() { * > if(can1.write(CANMessage(1337, &counter, 1))) { * > printf("Message sent: %d\n", counter); * > counter++; * > } * > led1 = !led1; * > } * > * > int main() { * > ticker.attach(&send, 1); * > CANMessage msg; * > while(1) { * > if(can2.read(msg)) { * > printf("Message received: %d\n\n", msg.data[0]); * > led2 = !led2; * > } * > wait(0.2); * > } * > } * * Variables: * rd - read from transmitter * td - transmit to transmitter */ CAN(PinName rd, PinName td); virtual ~CAN(); /* Function: frequency * Set the frequency of the CAN interface * * Variables: * hz - The bus frequency in hertz * returns - 1 if successful, 0 otherwise */ int frequency(int hz); /* Function: write * Write a CANMessage to the bus. * * Variables: * msg - The CANMessage to write. * * Returns: * 0 - If write failed. * 1 - If write was successful. */ int write(CANMessage msg); /* Function: read * Read a CANMessage from the bus. * * Variables: * msg - A CANMessage to read to. * * Returns: * 0 - If no message arrived. * 1 - If message arrived. */ int read(CANMessage &msg); /* Function: reset * Reset CAN interface. * * To use after error overflow. */ void reset(); /* Function: monitor * Puts or removes the CAN interface into silent monitoring mode * * Variables: * silent - boolean indicating whether to go into silent mode or not */ void monitor(bool silent); /* Function: rderror * Returns number of read errors to detect read overflow errors. */ unsigned char rderror(); /* Function: tderror * Returns number of write errors to detect write overflow errors. */ unsigned char tderror(); /* Function: attach * Attach a function to call whenever a CAN frame received interrupt is * generated. * * Variables: * fptr - A pointer to a void function, or 0 to set as none */ void attach(void (*fptr)(void)); /* Function attach * Attach a member function to call whenever a CAN frame received interrupt * is generated. * * Variables: * tptr - pointer to the object to call the member function on * mptr - pointer to the member function to be called */ template<typename T> void attach(T* tptr, void (T::*mptr)(void)) { if((mptr != NULL) && (tptr != NULL)) { _rxirq.attach(tptr, mptr); setup_interrupt(); } else { remove_interrupt(); } } private: CANName _id; FunctionPointer _rxirq; void setup_interrupt(void); void remove_interrupt(void); }; } // namespace mbed #endif // MBED_CAN_H #endif
stvnrhodes/CNCAirbrush
mbed/mbed/FileSystemLike.h
/* mbed Microcontroller Library - FileSystemLike * Copyright (c) 2008-2009 ARM Limited. All rights reserved. */ #ifndef MBED_FILESYSTEMLIKE_H #define MBED_FILESYSTEMLIKE_H #ifdef __ARMCC_VERSION # define O_RDONLY 0 # define O_WRONLY 1 # define O_RDWR 2 # define O_CREAT 0x0200 # define O_TRUNC 0x0400 # define O_APPEND 0x0008 typedef int mode_t; #else # include <sys/fcntl.h> #endif #include "Base.h" #include "FileHandle.h" #include "DirHandle.h" namespace mbed { /* Class FileSystemLike * A filesystem-like object is one that can be used to open files * though it by fopen("/name/filename", mode) * * Implementations must define at least open (the default definitions * of the rest of the functions just return error values). */ class FileSystemLike : public Base { public: /* Constructor FileSystemLike * * Variables * name - The name to use for the filesystem. */ FileSystemLike(const char *name) : Base(name) {} /* Function open * * Variables * filename - The name of the file to open. * flags - One of O_RDONLY, O_WRONLY, or O_RDWR, OR'd with * zero or more of O_CREAT, O_TRUNC, or O_APPEND. * returns - A pointer to a FileHandle object representing the * file on success, or NULL on failure. */ virtual FileHandle *open(const char *filename, int flags) = 0; /* Function remove * Remove a file from the filesystem. * * Variables * filename - the name of the file to remove. * returns - 0 on success, -1 on failure. */ virtual int remove(const char *filename) { return -1; }; /* Function rename * Rename a file in the filesystem. * * Variables * oldname - the name of the file to rename. * newname - the name to rename it to. * returns - 0 on success, -1 on failure. */ virtual int rename(const char *oldname, const char *newname) { return -1; }; /* Function opendir * Opens a directory in the filesystem and returns a DirHandle * representing the directory stream. * * Variables * name - The name of the directory to open. * returns - A DirHandle representing the directory stream, or * NULL on failure. */ virtual DirHandle *opendir(const char *name) { return NULL; }; /* Function mkdir * Creates a directory in the filesystem. * * Variables * name - The name of the directory to create. * mode - The permissions to create the directory with. * returns - 0 on success, -1 on failure. */ virtual int mkdir(const char *name, mode_t mode) { return -1; } // TODO other filesystem functions (mkdir, rm, rn, ls etc) }; } // namespace mbed #endif
stvnrhodes/CNCAirbrush
mbed/mbed/I2C.h
<gh_stars>1-10 /* mbed Microcontroller Library - I2C * Copyright (c) 2007-2011 ARM Limited. All rights reserved. */ #ifndef MBED_I2C_H #define MBED_I2C_H #include "device.h" #if DEVICE_I2C #include "platform.h" #include "PinNames.h" #include "PeripheralNames.h" #include "Base.h" namespace mbed { /* Class: I2C * An I2C Master, used for communicating with I2C slave devices * * Example: * > // Read from I2C slave at address 0x62 * > * > #include "mbed.h" * > * > I2C i2c(p28, p27); * > * > int main() { * > int address = 0x62; * > char data[2]; * > i2c.read(address, data, 2); * > } */ class I2C : public Base { public: enum RxStatus { NoData , MasterGeneralCall , MasterWrite , MasterRead }; enum Acknowledge { NoACK = 0 , ACK = 1 }; /* Constructor: I2C * Create an I2C Master interface, connected to the specified pins * * Variables: * sda - I2C data line pin * scl - I2C clock line pin */ I2C(PinName sda, PinName scl, const char *name = NULL); /* Function: frequency * Set the frequency of the I2C interface * * Variables: * hz - The bus frequency in hertz */ void frequency(int hz); /* Function: read * Read from an I2C slave * * Performs a complete read transaction. The bottom bit of * the address is forced to 1 to indicate a read. * * Variables: * address - 8-bit I2C slave address [ addr | 1 ] * data - Pointer to the byte-array to read data in to * length - Number of bytes to read * repeated - Repeated start, true - don't send stop at end * returns - 0 on success (ack), or non-0 on failure (nack) */ int read(int address, char *data, int length, bool repeated = false); /* Function: read * Read a single byte from the I2C bus * * Variables: * ack - indicates if the byte is to be acknowledged (1 = acknowledge) * returns - the byte read */ int read(int ack); /* Function: write * Write to an I2C slave * * Performs a complete write transaction. The bottom bit of * the address is forced to 0 to indicate a write. * * Variables: * address - 8-bit I2C slave address [ addr | 0 ] * data - Pointer to the byte-array data to send * length - Number of bytes to send * repeated - Repeated start, true - do not send stop at end * returns - 0 on success (ack), or non-0 on failure (nack) */ int write(int address, const char *data, int length, bool repeated = false); /* Function: write * Write single byte out on the I2C bus * * Variables: * data - data to write out on bus * returns - a '1' if an ACK was received, a '0' otherwise */ int write(int data); /* Function: start * Creates a start condition on the I2C bus */ void start(void); /* Function: stop * Creates a stop condition on the I2C bus */ void stop(void); protected: void aquire(); I2CName _i2c; static I2C *_owner; int _hz; }; } // namespace mbed #endif #endif
stvnrhodes/CNCAirbrush
mbed/mbed/DigitalIn.h
/* mbed Microcontroller Library - DigitalIn * Copyright (c) 2006-2011 ARM Limited. All rights reserved. */ #ifndef MBED_DIGITALIN_H #define MBED_DIGITALIN_H #include "platform.h" #include "PinNames.h" #include "PeripheralNames.h" #include "Base.h" namespace mbed { /* Class: DigitalIn * A digital input, used for reading the state of a pin * * Example: * > // Flash an LED while a DigitalIn is true * > * > #include "mbed.h" * > * > DigitalIn enable(p5); * > DigitalOut led(LED1); * > * > int main() { * > while(1) { * > if(enable) { * > led = !led; * > } * > wait(0.25); * > } * > } */ class DigitalIn : public Base { public: /* Constructor: DigitalIn * Create a DigitalIn connected to the specified pin * * Variables: * pin - DigitalIn pin to connect to * name - (optional) A string to identify the object */ DigitalIn(PinName pin, const char *name = NULL); /* Function: read * Read the input, represented as 0 or 1 (int) * * Variables: * returns - An integer representing the state of the input pin, * 0 for logical 0 and 1 for logical 1 */ int read() { #if defined(TARGET_LPC1768) || defined(TARGET_LPC2368) return ((_gpio->FIOPIN & _mask) ? 1 : 0); #elif defined(TARGET_LPC11U24) return ((LPC_GPIO->PIN[_index] & _mask) ? 1 : 0); #endif } /* Function: mode * Set the input pin mode * * Variables: * mode - PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode pull); #ifdef MBED_OPERATORS /* Function: operator int() * An operator shorthand for <read()> */ operator int() { return read(); } #endif #ifdef MBED_RPC virtual const struct rpc_method *get_rpc_methods(); static struct rpc_class *get_rpc_class(); #endif protected: PinName _pin; #if defined(TARGET_LPC1768) || defined(TARGET_LPC2368) LPC_GPIO_TypeDef *_gpio; #elif defined(TARGET_LPC11U24) int _index; #endif uint32_t _mask; }; } // namespace mbed #endif
stvnrhodes/CNCAirbrush
mbed/mbed/Timer.h
/* mbed Microcontroller Library - Timer * Copyright (c) 2007-2009 ARM Limited. All rights reserved. */ #ifndef MBED_TIMER_H #define MBED_TIMER_H #include "platform.h" #include "PinNames.h" #include "PeripheralNames.h" #include "Base.h" namespace mbed { /* Class: Timer * A general purpose timer * * Example: * > // Count the time to toggle a LED * > * > #include "mbed.h" * > * > Timer timer; * > DigitalOut led(LED1); * > int begin, end; * > * > int main() { * > timer.start(); * > begin = timer.read_us(); * > led = !led; * > end = timer.read_us(); * > printf("Toggle the led takes %d us", end - begin); * > } */ class Timer : public Base { public: Timer(const char *name = NULL); /* Function: start * Start the timer */ void start(); /* Function: stop * Stop the timer */ void stop(); /* Function: reset * Reset the timer to 0. * * If it was already counting, it will continue */ void reset(); /* Function: read * Get the time passed in seconds */ float read(); /* Function: read_ms * Get the time passed in mili-seconds */ int read_ms(); /* Function: read_us * Get the time passed in micro-seconds */ int read_us(); #ifdef MBED_OPERATORS operator float(); #endif #ifdef MBED_RPC virtual const struct rpc_method *get_rpc_methods(); static struct rpc_class *get_rpc_class(); #endif protected: int slicetime(); int _running; // whether the timer is running unsigned int _start; // the start time of the latest slice int _time; // any accumulated time from previous slices }; } // namespace mbed #endif
stvnrhodes/CNCAirbrush
mbed/mbed/Serial.h
<reponame>stvnrhodes/CNCAirbrush /* mbed Microcontroller Library - Serial * Copyright (c) 2007-2011 ARM Limited. All rights reserved. */ #ifndef MBED_SERIAL_H #define MBED_SERIAL_H #include "device.h" #if DEVICE_SERIAL #include "platform.h" #include "PinNames.h" #include "PeripheralNames.h" #include "Stream.h" #include "FunctionPointer.h" namespace mbed { /* Class: Serial * A serial port (UART) for communication with other serial devices * * Can be used for Full Duplex communication, or Simplex by specifying * one pin as NC (Not Connected) * * Example: * > // Print "Hello World" to the PC * > * > #include "mbed.h" * > * > Serial pc(USBTX, USBRX); * > * > int main() { * > pc.printf("Hello World\n"); * > } */ class Serial : public Stream { public: /* Constructor: Serial * Create a Serial port, connected to the specified transmit and receive pins * * Variables: * tx - Transmit pin * rx - Receive pin * * Note: Either tx or rx may be specified as NC if unused */ Serial(PinName tx, PinName rx, const char *name = NULL); /* Function: baud * Set the baud rate of the serial port * * Variables: * baudrate - The baudrate of the serial port (default = 9600). */ void baud(int baudrate); enum Parity { None = 0 , Odd , Even , Forced1 , Forced0 }; enum IrqType { RxIrq = 0 , TxIrq }; /* Function: format * Set the transmission format used by the Serial port * * Variables: * bits - The number of bits in a word (5-8; default = 8) * parity - The parity used (Serial::None, Serial::Odd, Serial::Even, Serial::Forced1, Serial::Forced0; default = Serial::None) * stop - The number of stop bits (1 or 2; default = 1) */ void format(int bits = 8, Parity parity = Serial::None, int stop_bits = 1); #if 0 // Inhereted from Stream, for documentation only /* Function: putc * Write a character * * Variables: * c - The character to write to the serial port */ int putc(int c); /* Function: getc * Read a character * * Reads a character from the serial port. This will block until * a character is available. To see if a character is available, * see <readable> * * Variables: * returns - The character read from the serial port */ int getc(); /* Function: printf * Write a formated string * * Variables: * format - A printf-style format string, followed by the * variables to use in formating the string. */ int printf(const char* format, ...); /* Function: scanf * Read a formated string * * Variables: * format - A scanf-style format string, * followed by the pointers to variables to store the results. */ int scanf(const char* format, ...); #endif /* Function: readable * Determine if there is a character available to read * * Variables: * returns - 1 if there is a character available to read, else 0 */ int readable(); /* Function: writeable * Determine if there is space available to write a character * * Variables: * returns - 1 if there is space to write a character, else 0 */ int writeable(); /* Function: attach * Attach a function to call whenever a serial interrupt is generated * * Variables: * fptr - A pointer to a void function, or 0 to set as none * type - Which serial interrupt to attach the member function to (Seriall::RxIrq for receive, TxIrq for transmit buffer empty) */ void attach(void (*fptr)(void), IrqType type = RxIrq); /* Function: attach * Attach a member function to call whenever a serial interrupt is generated * * Variables: * tptr - pointer to the object to call the member function on * mptr - pointer to the member function to be called * type - Which serial interrupt to attach the member function to (Seriall::RxIrq for receive, TxIrq for transmit buffer empty) */ template<typename T> void attach(T* tptr, void (T::*mptr)(void), IrqType type = RxIrq) { if((mptr != NULL) && (tptr != NULL)) { _irq[type].attach(tptr, mptr); setup_interrupt(type); } } #ifdef MBED_RPC virtual const struct rpc_method *get_rpc_methods(); static struct rpc_class *get_rpc_class(); #endif protected: void setup_interrupt(IrqType type); void remove_interrupt(IrqType type); virtual int _getc(); virtual int _putc(int c); UARTName _uart; FunctionPointer _irq[2]; int _uidx; }; } // namespace mbed #endif #endif
stvnrhodes/CNCAirbrush
mbed/StepperMotors/Stepper.h
/* mbed Stepper Library * Copyright (c) 2012 <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. */ #ifndef STEPPER_H #define STEPPER_H #include "mbed.h" class Stepper { public: /** Create a stepper object connected to the specified clk pin and dir pin * * @param pin step pin to trigger for steps * @param pin dir pin to choose direction * @param pin en pin to enable the motor */ Stepper(PinName step, PinName dir, PinName en); /** Turn on the stepper motor * @param direction 1 for away from motor or 0 for towards motor */ void stepOn(bool direction); /** Turn off the stepper motor **/ void stepOff(void); /** Enable the motor * @param en Whether to enable the motor */ void enable(bool en); /** Set the position of the motor to a new offset * @param long position The position we set it to */ void setPosition(long position); /** Get the position of the motor @return current position of the stepper motor */ long getPosition(void); private: DigitalOut _step; DigitalOut _dir; DigitalOut _en; long _position; }; #endif
stvnrhodes/CNCAirbrush
mbed/mbed/TimerEvent.h
<gh_stars>1-10 /* mbed Microcontroller Library - TimerEvent * Copyright (c) 2007-2009 ARM Limited. All rights reserved. */ #ifndef MBED_TIMEREVENT_H #define MBED_TIMEREVENT_H namespace mbed { // Base abstraction for timer interrupts class TimerEvent { public: TimerEvent(); // The handler registered with the underlying timer interrupt static void irq(); // Destruction removes it... virtual ~TimerEvent(); protected: // The handler called to service the timer event of the derived class virtual void handler() = 0; // insert in to linked list void insert(unsigned int timestamp); // remove from linked list, if in it void remove(); // Get the current usec timestamp static unsigned int timestamp(); static TimerEvent *_head; // The head of the list of the events, NULL if none TimerEvent *_next; // Pointer to the next in the list, NULL if last unsigned int _timestamp; // The timestamp at which the even should be triggered }; } // namespace mbed #endif
stvnrhodes/CNCAirbrush
mbed/mbed/BusOut.h
/* mbed Microcontroller Library - BusOut * Copyright (c) 2007-2009 ARM Limited. All rights reserved. */ #ifndef MBED_BUSOUT_H #define MBED_BUSOUT_H #include "platform.h" #include "PinNames.h" #include "PeripheralNames.h" #include "Base.h" #include "DigitalOut.h" namespace mbed { /* Class: BusOut * A digital output bus, used for setting the state of a collection of pins */ class BusOut : public Base { public: /* Group: Configuration Methods */ /* Constructor: BusOut * Create an BusOut, connected to the specified pins * * Variables: * p<n> - DigitalOut pin to connect to bus bit <n> (p5-p30, NC) * * Note: * It is only required to specify as many pin variables as is required * for the bus; the rest will default to NC (not connected) */ BusOut(PinName p0, PinName p1 = NC, PinName p2 = NC, PinName p3 = NC, PinName p4 = NC, PinName p5 = NC, PinName p6 = NC, PinName p7 = NC, PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC, const char *name = NULL); BusOut(PinName pins[16], const char *name = NULL); virtual ~BusOut(); /* Group: Access Methods */ /* Function: write * Write the value to the output bus * * Variables: * value - An integer specifying a bit to write for every corresponding DigitalOut pin */ void write(int value); /* Function: read * Read the value currently output on the bus * * Variables: * returns - An integer with each bit corresponding to associated DigitalOut pin setting */ int read(); #ifdef MBED_OPERATORS /* Group: Access Method Shorthand */ /* Function: operator= * A shorthand for <write> */ BusOut& operator= (int v); BusOut& operator= (BusOut& rhs); /* Function: operator int() * A shorthand for <read> */ operator int(); #endif #ifdef MBED_RPC virtual const struct rpc_method *get_rpc_methods(); static struct rpc_class *get_rpc_class(); #endif protected: DigitalOut* _pin[16]; #ifdef MBED_RPC static void construct(const char *arguments, char *res); #endif }; } // namespace mbed #endif
stvnrhodes/CNCAirbrush
mbed/mbed/platform.h
/* mbed Microcontroller Library - platform * Copyright (c) 2009 ARM Limited. All rights reserved. */ #ifndef MBED_PLATFORM_H #define MBED_PLATFORM_H #define MBED_RPC #define MBED_OPERATORS #endif
stvnrhodes/CNCAirbrush
mbed/mbed/wait_api.h
<reponame>stvnrhodes/CNCAirbrush /* Title: wait * Generic wait functions. * * These provide simple NOP type wait capabilities. * * Example: * > #include "mbed.h" * > * > DigitalOut heartbeat(LED1); * > * > int main() { * > while (1) { * > heartbeat = 1; * > wait(0.5); * > heartbeat = 0; * > wait(0.5); * > } * > } */ /* mbed Microcontroller Library - wait_api * Copyright (c) 2009 ARM Limited. All rights reserved. */ #ifndef MBED_WAIT_API_H #define MBED_WAIT_API_H #ifdef __cplusplus extern "C" { #endif /* Function: wait * Waits for a number of seconds, with microsecond resolution (within * the accuracy of single precision floating point). * * Variables: * s - number of seconds to wait */ void wait(float s); /* Function: wait_ms * Waits a number of milliseconds. * * Variables: * ms - the whole number of milliseconds to wait */ void wait_ms(int ms); /* Function: wait_us * Waits a number of microseconds. * * Variables: * us - the whole number of microseconds to wait */ void wait_us(int us); #ifdef TARGET_LPC11U24 /* Function: sleep * Send the microcontroller to sleep * * The processor is setup ready for sleep, and sent to sleep using __WFI(). In this mode, the * system clock to the core is stopped until a reset or an interrupt occurs. This eliminates * dynamic power used by the processor, memory systems and buses. The processor, peripheral and * memory state are maintained, and the peripherals continue to work and can generate interrupts. * * The processor can be woken up by any internal peripheral interrupt or external pin interrupt. * * Note: The mbed interface semihosting is disconnected as part of going to sleep, and can not be restored. * Flash re-programming and the USB serial port will remain active, but the mbed program will no longer be * able to access the LocalFileSystem */ void sleep(void); /* Function: deepsleep * Send the microcontroller to deep sleep * * This processor is setup ready for deep sleep, and sent to sleep using __WFI(). This mode * has the same sleep features as sleep plus it powers down peripherals and clocks. All state * is still maintained. * * The processor can only be woken up by an external interrupt on a pin or a watchdog timer. * * Note: The mbed interface semihosting is disconnected as part of going to sleep, and can not be restored. * Flash re-programming and the USB serial port will remain active, but the mbed program will no longer be * able to access the LocalFileSystem */ void deepsleep(void); #endif #ifdef __cplusplus } #endif #endif
stvnrhodes/CNCAirbrush
mbed/CNCAirbrush/Wifly.h
<filename>mbed/CNCAirbrush/Wifly.h<gh_stars>1-10 /** * @author <NAME> * * @section LICENSE * * Copyright (c) 2012 <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. * * @section DESCRIPTION * * CNCAirbrush Berkeley ME102B Project * */ #ifndef WIFLY_H #define WIFLY_H #include "mbed.h" #include "CBuffer.h" #include "CmdBuffer.h" #include "ImgBuffer.h" /** Wifly Class * * Example: * @code * #include "mbed.h" * #include "Wifly.h" * * Wifly wifly(p9, p10, p8); * Serial pc(USBTX, USBRX); * * int main() * { * while(1){ * if(wifly.hasCmd()){ * Command * c; * wifly.getCmd(c) * pc.printf("Msg: %d\r\n", c->cmd); } * } * @endcode */ class Wifly { public: /** * Constructor to create an adhoc network * * @param tx mbed pin to use for tx line of Serial interface * @param rx mbed pin to use for rx line of Serial interface * @param ssid ssid of the adhoc network which will be created * @param ip ip of the wifi module (default: "169.254.1.1") * @param netmask netmask (default: "255.255.0.0") * @param channel channel (default: "1") * @param baudrate speed of the communication (default: 460800) */ Wifly( PinName tx, PinName rx, PinName reset, char * ssid = "CNCAirbrush", char * ip = "169.254.1.1", char * netmask = "255.255.0.0", int channel = 1, int baudrate = 115200); /** * Send a string to the wifi module by serial port. This function desactivates the user interrupt handler when a character is received to analyze the response from the wifi module. * Useful to send a command to the module and wait a response. * * * @param str string to be sent * @param ACK string which must be acknowledge by the wifi module. If "ACK" == "NO", no string has to be acknoledged. (default: "NO") * @param res this field will contain the response from the wifi module, result of a command sent. This field is available only if ACK = "NO" AND res != NULL (default: NULL) * * @return true if ACK has been found in the response from the wifi module. False otherwise or if there is no response in 5s. */ bool send(char * str, char * ACK = "NO", char * res = NULL); /** * Attach an interrupt for the given command * * @param cmd command number to trigger the interrupt for * @param func function to run on interrupt (must return void) * @param num interrupt number (I currently allow up to 3) * * @return true if interrupt has been attached */ bool attach_interrupt(char cmd, void (*func)(Command *), int num); /** * Report that there's a command waiting to be read. * * @return true if there's a command waiting to be read. */ bool hasCmd(); /** * Fetch the most recent command * * @return the command on top of the stack */ Command * getCmd(); /** * Connect the wifi module to the ssid contained in the constructor. * * @return true if successfully sent */ bool sendCmd(Command * c); /** * Create an adhoc network with the ssid contained in the constructor * * @return true if the network is well created, false otherwise */ bool createAdhocNetwork(); /** * Read a string if available * *@param str pointer where will be stored the string read */ bool read(char * str); /** * Reset the wifi module */ void reset(); /** * Check if characters are available * * @return number of available characters */ int readable(); /** * Read a character * * @return the character read */ char getc(); /** * Flush the buffer */ void flush(); /** * Write a character * * @param the character which will be written */ void putc(char c); /** * To enter in command mode (we can configure the module) * * @return true if successful, false otherwise */ bool cmdMode(); /** * To exit the command mode * * @return true if successful, false otherwise */ bool exit(); /** * Attach a member function to call when a character is received. * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called */ template<typename T> void attach(T* tptr, void (T::*mptr)(void)) { if ((mptr != NULL) && (tptr != NULL)) { rx.attach(tptr, mptr); } } /** * Attach a callback for when a character is received * * @param fptr function pointer */ void attach(void (*fn)(void)) { if (fn != NULL) { rx.attach(fn); } } private: Serial wifi; DigitalOut reset_pin; bool wpa; bool adhoc; bool dhcp; char phrase[30]; char ssid[30]; char ip[20]; char netmask[20]; char imgpos; char last_char; int channel; FILE *fp; CBuffer buf_wifly; CmdBuffer cmd_buffer; ImgBuffer img_buffer; char char_to_num(char c); char num_to_char(char n); long str_to_long(char * str); float str_to_float(char * str); void long_to_str(char * str, long n); void float_to_str(char * str, float f); void attach_rx(bool null); void attach_img(bool null); void attach_cmd(bool null); void handler_rx(void); void handler_img(void); void handler_cmd(void); void write_img(void); FunctionPointer rx; bool gettingImg; bool gotImg; }; #endif
stvnrhodes/CNCAirbrush
mbed/StepperMotors/Bitmap.h
/** * @author <NAME> * * @section LICENSE * * Copyright (c) 2012 <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. */ #ifndef BITMAP_H #define BITMAP_H #include "mbed.h" class Bitmap { public: /** * Constructor to deal with bitmap */ Bitmap (); /** * Load an image into the bitmap. * * @return true if the image is successfully loaded */ bool openImg(char* filename); /** * Change the row we're looking at. * * @return true if successful. */ bool setRow(int row); /** * Get whether we should draw a pixel at the given spot * * @param pixel The pixel to check * @param reversed Whether to reverse the pixel * @return true if there's a pixel. */ bool isPixel(int pixel, bool reversed); bool isPixel(int pixel); /** * Get whether it's a blank row * * @return true if there are no pixels in the row */ bool isBlankRow(void); /** * Return the height of the bitmap * * @return height */ int getHeight(); /** * Return the width of the bitmap * * @return width */ int getWidth(); /** * Close the image when we're done with it * * @return true if properly closed */ bool closeImg(void); private: FILE * fp; bool loaded; long offset, width, height, row_size, row_num; char * row_data; /** * Get the pixel at a position * @param pixel column * * @return true if the pixel is black */ bool pixel(int column); }; #endif
stvnrhodes/CNCAirbrush
mbed/mbed/Base.h
<filename>mbed/mbed/Base.h /* mbed Microcontroller Library - Base * Copyright (c) 2006-2008 ARM Limited. All rights reserved. */ #ifndef MBED_BASE_H #define MBED_BASE_H #include "platform.h" #include "PinNames.h" #include "PeripheralNames.h" #include <cstdlib> #include "DirHandle.h" namespace mbed { #ifdef MBED_RPC struct rpc_function { const char *name; void (*caller)(const char*, char*); }; struct rpc_class { const char *name; const rpc_function *static_functions; struct rpc_class *next; }; #endif /* Class Base * The base class for most things */ class Base { public: Base(const char *name = NULL); virtual ~Base(); /* Function register_object * Registers this object with the given name, so that it can be * looked up with lookup. If this object has already been * registered, then this just changes the name. * * Variables * name - The name to give the object. If NULL we do nothing. */ void register_object(const char *name); /* Function name * Returns the name of the object, or NULL if it has no name. */ const char *name(); #ifdef MBED_RPC /* Function rpc * Call the given method with the given arguments, and write the * result into the string pointed to by result. The default * implementation calls rpc_methods to determine the supported * methods. * * Variables * method - The name of the method to call. * arguments - A list of arguments separated by spaces. * result - A pointer to a string to write the result into. May * be NULL, in which case nothing is written. * * Returns * true if method corresponds to a valid rpc method, or * false otherwise. */ virtual bool rpc(const char *method, const char *arguments, char *result); /* Function get_rpc_methods * Returns a pointer to an array describing the rpc methods * supported by this object, terminated by either * RPC_METHOD_END or RPC_METHOD_SUPER(Superclass). * * Example * > class Example : public Base { * > int foo(int a, int b) { return a + b; } * > virtual const struct rpc_method *get_rpc_methods() { * > static const rpc_method rpc_methods[] = { * > { "foo", generic_caller<int, Example, int, int, &Example::foo> }, * > RPC_METHOD_SUPER(Base) * > }; * > return rpc_methods; * > } * > }; */ virtual const struct rpc_method *get_rpc_methods(); /* Function rpc * Use the lookup function to lookup an object and, if * successful, call its rpc method * * Variables * returns - false if name does not correspond to an object, * otherwise the return value of the call to the object's rpc * method. */ static bool rpc(const char *name, const char *method, const char *arguments, char *result); #endif /* Function lookup * Lookup and return the object that has the given name. * * Variables * name - the name to lookup. * len - the length of name. */ static Base *lookup(const char *name, unsigned int len); static DirHandle *opendir(); friend class BaseDirHandle; protected: static Base *_head; Base *_next; const char *_name; bool _from_construct; private: #ifdef MBED_RPC static rpc_class *_classes; static const rpc_function _base_funcs[]; static rpc_class _base_class; #endif void delete_self(); static void list_objs(const char *arguments, char *result); static void clear(const char*,char*); static char *new_name(Base *p); public: #ifdef MBED_RPC /* Function add_rpc_class * Add the class to the list of classes which can have static * methods called via rpc (the static methods which can be called * are defined by that class' get_rpc_class() static method). */ template<class C> static void add_rpc_class() { rpc_class *c = C::get_rpc_class(); c->next = _classes; _classes = c; } template<class C> static const char *construct() { Base *p = new C(); p->_from_construct = true; if(p->_name==NULL) { p->register_object(new_name(p)); } return p->_name; } template<class C, typename A1> static const char *construct(A1 arg1) { Base *p = new C(arg1); p->_from_construct = true; if(p->_name==NULL) { p->register_object(new_name(p)); } return p->_name; } template<class C, typename A1, typename A2> static const char *construct(A1 arg1, A2 arg2) { Base *p = new C(arg1,arg2); p->_from_construct = true; if(p->_name==NULL) { p->register_object(new_name(p)); } return p->_name; } template<class C, typename A1, typename A2, typename A3> static const char *construct(A1 arg1, A2 arg2, A3 arg3) { Base *p = new C(arg1,arg2,arg3); p->_from_construct = true; if(p->_name==NULL) { p->register_object(new_name(p)); } return p->_name; } template<class C, typename A1, typename A2, typename A3, typename A4> static const char *construct(A1 arg1, A2 arg2, A3 arg3, A4 arg4) { Base *p = new C(arg1,arg2,arg3,arg4); p->_from_construct = true; if(p->_name==NULL) { p->register_object(new_name(p)); } return p->_name; } #endif }; /* Macro MBED_OBJECT_NAME_MAX * The maximum size of object name (including terminating null byte) * that will be recognised when using fopen to open a FileLike * object, or when using the rpc function. */ #define MBED_OBJECT_NAME_MAX 32 /* Macro MBED_METHOD_NAME_MAX * The maximum size of rpc method name (including terminating null * byte) that will be recognised by the rpc function (in rpc.h). */ #define MBED_METHOD_NAME_MAX 32 } // namespace mbed #endif
stvnrhodes/CNCAirbrush
mbed/mbed/Ethernet.h
/* mbed Microcontroller Library - Ethernet * Copyright (c) 2009-2011 ARM Limited. All rights reserved. */ #ifndef MBED_ETHERNET_H #define MBED_ETHERNET_H #include "device.h" #if DEVICE_ETHERNET #include "Base.h" namespace mbed { /* Class: Ethernet * An ethernet interface, to use with the ethernet pins. * * Example: * > // Read destination and source from every ethernet packet * > * > #include "mbed.h" * > * > Ethernet eth; * > * > int main() { * > char buf[0x600]; * > * > while(1) { * > int size = eth.receive(); * > if(size > 0) { * > eth.read(buf, size); * > printf("Destination: %02X:%02X:%02X:%02X:%02X:%02X\n", * > buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]); * > printf("Source: %02X:%02X:%02X:%02X:%02X:%02X\n", * > buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]); * > } * > * > wait(1); * > } * > } * */ class Ethernet : public Base { public: /* Constructor: Ethernet * Initialise the ethernet interface. */ Ethernet(); /* Destructor: Ethernet * Powers the hardware down. */ virtual ~Ethernet(); enum Mode { AutoNegotiate , HalfDuplex10 , FullDuplex10 , HalfDuplex100 , FullDuplex100 }; /* Function: write * Writes into an outgoing ethernet packet. * * It will append size bytes of data to the previously written bytes. * * Variables: * data - An array to write. * size - The size of data. * * Returns: * The number of written bytes. */ int write(const char *data, int size); /* Function: send * Send an outgoing ethernet packet. * * After filling in the data in an ethernet packet it must be send. * Send will provide a new packet to write to. * * Returns: * 0 - If the sending was failed. * 1 - If the package is successfully sent. */ int send(); /* Function: receive * Recevies an arrived ethernet packet. * * Receiving an ethernet packet will drop the last received ethernet packet * and make a new ethernet packet ready to read. * If no ethernet packet is arrived it will return 0. * * Returns: * 0 - If no ethernet packet is arrived. * The size of the arrived packet. */ int receive(); /* Function: read * Read from an recevied ethernet packet. * * After receive returnd a number bigger than 0it is * possible to read bytes from this packet. * Read will write up to size bytes into data. * * It is possible to use read multible times. * Each time read will start reading after the last read byte before. * * Returns: * The number of byte read. */ int read(char *data, int size); /* Function: address * Gives the ethernet address of the mbed. * * Variables: * mac - Must be a pointer to a 6 byte char array to copy the ethernet address in. */ void address(char *mac); /* Function: link * Returns if an ethernet link is pressent or not. It takes a wile after Ethernet initializion to show up. * * Returns: * 0 - If no ethernet link is pressent. * 1 - If an ethernet link is pressent. * * Example: * > // Using the Ethernet link function * > #include "mbed.h" * > * > Ethernet eth; * > * > int main() { * > wait(1); // Needed after startup. * > if(eth.link()) { * > printf("online\n"); * > } else { * > printf("offline\n"); * > } * > } * */ int link(); /* Function: set_link * Sets the speed and duplex parameters of an ethernet link * * Variables: * mode - the speed and duplex mode to set the link to: * * > AutoNegotiate Auto negotiate speed and duplex * > HalfDuplex10 10 Mbit, half duplex * > FullDuplex10 10 Mbit, full duplex * > HalfDuplex100 100 Mbit, half duplex * > FullDuplex100 100 Mbit, full duplex */ void set_link(Mode mode); }; } // namespace mbed #endif #endif
stvnrhodes/CNCAirbrush
mbed/mbed/PortOut.h
<reponame>stvnrhodes/CNCAirbrush /* mbed Microcontroller Library - PortOut * Copyright (c) 2006-2011 ARM Limited. All rights reserved. */ #ifndef MBED_PORTOUT_H #define MBED_PORTOUT_H #include "device.h" #if DEVICE_PORTOUT #include "platform.h" #include "PinNames.h" #include "Base.h" #include "PortNames.h" namespace mbed { /* Class: PortOut * A multiple pin digital out * * Example: * > // Toggle all four LEDs * > * > #include "mbed.h" * > * > // LED1 = P1.18 LED2 = P1.20 LED3 = P1.21 LED4 = P1.23 * > #define LED_MASK 0x00B40000 * > * > PortOut ledport(Port1, LED_MASK); * > * > int main() { * > while(1) { * > ledport = LED_MASK; * > wait(1); * > ledport = 0; * > wait(1); * > } * > } */ class PortOut { public: /* Constructor: PortOut * Create an PortOut, connected to the specified port * * Variables: * port - Port to connect to (Port0-Port5) * mask - A bitmask to identify which bits in the port should be included (0 - ignore) */ PortOut(PortName port, int mask = 0xFFFFFFFF); /* Function: write * Write the value to the output port * * Variables: * value - An integer specifying a bit to write for every corresponding PortOut pin */ void write(int value); /* Function: read * Read the value currently output on the port * * Variables: * returns - An integer with each bit corresponding to associated PortOut pin setting */ int read(); /* Function: operator= * A shorthand for <write> */ PortOut& operator= (int value) { write(value); return *this; } PortOut& operator= (PortOut& rhs) { write(rhs.read()); return *this; } /* Function: operator int() * A shorthand for <read> */ operator int() { return read(); } private: #if defined(TARGET_LPC1768) || defined(TARGET_LPC2368) LPC_GPIO_TypeDef *_gpio; #endif PortName _port; uint32_t _mask; }; } // namespace mbed #endif #endif