diff options
Diffstat (limited to 'include')
-rw-r--r-- | include/aspeed/JTABLES.H | 72 | ||||
-rw-r--r-- | include/ast_jpeg_decoder.hpp | 1051 | ||||
-rw-r--r-- | include/ast_video_puller.hpp | 141 | ||||
-rw-r--r-- | include/ast_video_types.hpp | 8 | ||||
-rw-r--r-- | include/dbus_monitor.hpp | 43 | ||||
-rw-r--r-- | include/dbus_singleton.hpp | 4 | ||||
-rw-r--r-- | include/gzip_helper.hpp | 4 | ||||
-rw-r--r-- | include/http_utility.hpp | 4 | ||||
-rw-r--r-- | include/image_upload.hpp | 34 | ||||
-rw-r--r-- | include/openbmc_dbus_rest.hpp | 367 | ||||
-rw-r--r-- | include/pam_authenticate.hpp | 47 | ||||
-rw-r--r-- | include/persistent_data_middleware.hpp | 80 | ||||
-rw-r--r-- | include/redfish_v1.hpp | 58 | ||||
-rw-r--r-- | include/security_headers_middleware.hpp | 49 | ||||
-rw-r--r-- | include/sessions.hpp | 160 | ||||
-rw-r--r-- | include/ssl_key_handler.hpp | 102 | ||||
-rw-r--r-- | include/token_authorization_middleware.hpp | 259 | ||||
-rw-r--r-- | include/web_kvm.hpp | 241 | ||||
-rw-r--r-- | include/webassets.hpp | 60 | ||||
-rw-r--r-- | include/webserver_common.hpp | 4 |
20 files changed, 1388 insertions, 1400 deletions
diff --git a/include/aspeed/JTABLES.H b/include/aspeed/JTABLES.H index 8f2d9f3c6f..641fcfb76a 100644 --- a/include/aspeed/JTABLES.H +++ b/include/aspeed/JTABLES.H @@ -13,24 +13,24 @@ static const unsigned char dezigzag[64 + 15] = { // let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
-static const unsigned char *std_luminance_qt;
-static const unsigned char *std_chrominance_qt;
+static const unsigned char *stdLuminanceQt;
+static const unsigned char *stdChrominanceQt;
// Standard Huffman tables (cf. JPEG standard section K.3) */
-static const unsigned char std_dc_luminance_nrcodes[17] = {
+static const unsigned char stdDcLuminanceNrcodes[17] = {
0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0};
-static const unsigned char std_dc_luminance_values[12] = {0, 1, 2, 3, 4, 5,
+static const unsigned char stdDcLuminanceValues[12] = {0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
-static const unsigned char std_dc_chrominance_nrcodes[17] = {
+static const unsigned char stdDcChrominanceNrcodes[17] = {
0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0};
-static const unsigned char std_dc_chrominance_values[12] = {0, 1, 2, 3, 4, 5,
+static const unsigned char stdDcChrominanceValues[12] = {0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
-static const unsigned char std_ac_luminance_nrcodes[17] = {
+static const unsigned char stdAcLuminanceNrcodes[17] = {
0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d};
-static const unsigned char std_ac_luminance_values[162] = {
+static const unsigned char stdAcLuminanceValues[162] = {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72,
@@ -46,9 +46,9 @@ static const unsigned char std_ac_luminance_values[162] = { 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4,
0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa};
-static const unsigned char std_ac_chrominance_nrcodes[17] = {
+static const unsigned char stdAcChrominanceNrcodes[17] = {
0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77};
-static const unsigned char std_ac_chrominance_values[162] = {
+static const unsigned char stdAcChrominanceValues[162] = {
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41,
0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1,
@@ -64,7 +64,7 @@ static const unsigned char std_ac_chrominance_values[162] = { 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4,
0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa};
-static const unsigned short int DC_LUMINANCE_HUFFMANCODE[13 * 2] = {
+static const unsigned short int dcLuminanceHuffmancode[13 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x6000, 3,
@@ -80,7 +80,7 @@ static const unsigned short int DC_LUMINANCE_HUFFMANCODE[13 * 2] = { /* 12 */ 0xFFFF, 9,
};
-static const unsigned short int DC_CHROMINANCE_HUFFMANCODE[13 * 2] = {
+static const unsigned short int dcChrominanceHuffmancode[13 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x8000, 2,
@@ -96,7 +96,7 @@ static const unsigned short int DC_CHROMINANCE_HUFFMANCODE[13 * 2] = { /* 12 */ 0xFFFF, 11,
};
-static const unsigned short int AC_LUMINANCE_HUFFMANCODE[39 * 2] = {
+static const unsigned short int acLuminanceHuffmancode[39 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x8000, 2,
@@ -138,7 +138,7 @@ static const unsigned short int AC_LUMINANCE_HUFFMANCODE[39 * 2] = { /* 38 */ 0xFFFF, 16,
};
-static const unsigned short int AC_CHROMINANCE_HUFFMANCODE[45 * 2] = {
+static const unsigned short int acChrominanceHuffmancode[45 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x8000, 2,
@@ -187,59 +187,59 @@ static const unsigned short int AC_CHROMINANCE_HUFFMANCODE[45 * 2] = { };
//[100]=========================
-static const unsigned char Tbl_100Y[64] = {
+static const unsigned char tbl100Y[64] = {
2, 1, 1, 2, 3, 5, 6, 7, 1, 1, 1, 2, 3, 7, 7, 6,
1, 1, 2, 3, 5, 7, 8, 7, 1, 2, 2, 3, 6, 10, 10, 7,
2, 2, 4, 7, 8, 13, 12, 9, 3, 4, 6, 8, 10, 13, 14, 11,
6, 8, 9, 10, 12, 15, 15, 12, 9, 11, 11, 12, 14, 12, 12, 12};
-static const unsigned char Tbl_100UV[64] = {
+static const unsigned char tbl100Uv[64] = {
3, 3, 4, 8, 18, 18, 18, 18, 3, 3, 4, 12, 18, 18, 18, 18,
4, 4, 10, 18, 18, 18, 18, 18, 8, 12, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18};
//[086]=========================
-static const unsigned char Tbl_086Y[64] = {
+static const unsigned char tbl086Y[64] = {
3, 2, 1, 3, 4, 7, 9, 11, 2, 2, 2, 3, 4, 10, 11, 10,
2, 2, 3, 4, 7, 10, 12, 10, 2, 3, 4, 5, 9, 16, 15, 11,
3, 4, 6, 10, 12, 20, 19, 14, 4, 6, 10, 12, 15, 19, 21, 17,
9, 12, 14, 16, 19, 22, 22, 18, 13, 17, 17, 18, 21, 18, 19, 18};
-static const unsigned char Tbl_086UV[64] = {
+static const unsigned char tbl086Uv[64] = {
4, 5, 6, 13, 27, 27, 27, 27, 5, 5, 7, 18, 27, 27, 27, 27,
6, 7, 15, 27, 27, 27, 27, 27, 13, 18, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27};
//[071]=========================
-static const unsigned char Tbl_071Y[64] = {
+static const unsigned char tbl071Y[64] = {
6, 4, 3, 6, 9, 15, 19, 22, 4, 4, 5, 7, 9, 21, 22, 20,
5, 4, 6, 9, 15, 21, 25, 21, 5, 6, 8, 10, 19, 32, 30, 23,
6, 8, 13, 21, 25, 40, 38, 28, 9, 13, 20, 24, 30, 39, 42, 34,
18, 24, 29, 32, 38, 45, 45, 37, 27, 34, 35, 36, 42, 37, 38, 37};
-static const unsigned char Tbl_071UV[64] = {
+static const unsigned char tbl071Uv[64] = {
9, 10, 13, 26, 55, 55, 55, 55, 10, 11, 14, 37, 55, 55, 55, 55,
13, 14, 31, 55, 55, 55, 55, 55, 26, 37, 55, 55, 55, 55, 55, 55,
55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55,
55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55};
//[057]=========================
-static const unsigned char Tbl_057Y[64] = {
+static const unsigned char tbl057Y[64] = {
9, 6, 5, 9, 13, 22, 28, 34, 6, 6, 7, 10, 14, 32, 33, 30,
7, 7, 9, 13, 22, 32, 38, 31, 7, 9, 12, 16, 28, 48, 45, 34,
10, 12, 20, 31, 38, 61, 57, 43, 13, 19, 30, 36, 45, 58, 63, 51,
27, 36, 43, 48, 57, 68, 67, 56, 40, 51, 53, 55, 63, 56, 57, 55};
-static const unsigned char Tbl_057UV[64] = {
+static const unsigned char tbl057Uv[64] = {
13, 14, 19, 38, 80, 80, 80, 80, 14, 17, 21, 53, 80, 80, 80, 80,
19, 21, 45, 80, 80, 80, 80, 80, 38, 53, 80, 80, 80, 80, 80, 80,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80};
//[043]=========================
-static const unsigned char Tbl_043Y[64] = {
+static const unsigned char tbl043Y[64] = {
11, 7, 7, 11, 17, 28, 36, 43, 8, 8, 10, 13, 18, 41, 43, 39,
10, 9, 11, 17, 28, 40, 49, 40, 10, 12, 15, 20, 36, 62, 57, 44,
12, 15, 26, 40, 48, 78, 74, 55, 17, 25, 39, 46, 58, 74, 81, 66,
35, 46, 56, 62, 74, 86, 86, 72, 51, 66, 68, 70, 80, 71, 74, 71};
-static const unsigned char Tbl_043UV[64] = {
+static const unsigned char tbl043Uv[64] = {
18, 19, 26, 51, 108, 108, 108, 108, 19, 22, 28, 72, 108,
108, 108, 108, 26, 28, 61, 108, 108, 108, 108, 108, 51, 72,
108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
@@ -247,12 +247,12 @@ static const unsigned char Tbl_043UV[64] = { 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108};
//[029]=========================
-static const unsigned char Tbl_029Y[64] = {
+static const unsigned char tbl029Y[64] = {
14, 9, 9, 14, 21, 36, 46, 55, 10, 10, 12, 17, 23, 52, 54, 49,
12, 11, 14, 21, 36, 51, 62, 50, 12, 15, 19, 26, 46, 78, 72, 56,
16, 19, 33, 50, 61, 98, 93, 69, 21, 31, 49, 58, 73, 94, 102, 83,
44, 58, 70, 78, 93, 109, 108, 91, 65, 83, 86, 88, 101, 90, 93, 89};
-static const unsigned char Tbl_029UV[64] = {
+static const unsigned char tbl029Uv[64] = {
22, 24, 32, 63, 133, 133, 133, 133, 24, 28, 34, 88, 133,
133, 133, 133, 32, 34, 75, 133, 133, 133, 133, 133, 63, 88,
133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133,
@@ -260,40 +260,40 @@ static const unsigned char Tbl_029UV[64] = { 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133};
//[014]=========================
-static const unsigned char Tbl_014Y[64] = {
+static const unsigned char tbl014Y[64] = {
17, 12, 10, 17, 26, 43, 55, 66, 13, 13, 15, 20, 28, 63, 65, 60,
15, 14, 17, 26, 43, 62, 75, 61, 15, 18, 24, 31, 55, 95, 87, 67,
19, 24, 40, 61, 74, 119, 112, 84, 26, 38, 60, 70, 88, 113, 123, 100,
53, 70, 85, 95, 112, 132, 131, 110, 78, 100, 103, 107, 122, 109, 112, 108};
-static const unsigned char Tbl_014UV[64] = {
+static const unsigned char tbl014Uv[64] = {
27, 29, 39, 76, 160, 160, 160, 160, 29, 34, 42, 107, 160,
160, 160, 160, 39, 42, 91, 160, 160, 160, 160, 160, 76, 107,
160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160};
//[000]=========================
-static const unsigned char Tbl_000Y[64] = {
+static const unsigned char tbl000Y[64] = {
20, 13, 12, 20, 30, 50, 63, 76, 15, 15, 17, 23, 32, 72, 75, 68,
17, 16, 20, 30, 50, 71, 86, 70, 17, 21, 27, 36, 63, 108, 100, 77,
22, 27, 46, 70, 85, 136, 128, 96, 30, 43, 68, 80, 101, 130, 141, 115,
61, 80, 97, 108, 128, 151, 150, 126, 90, 115, 118, 122, 140, 125, 128, 123};
-static const unsigned char Tbl_000UV[64] = {
+static const unsigned char tbl000Uv[64] = {
31, 33, 45, 88, 185, 185, 185, 185, 33, 39, 48, 123, 185,
185, 185, 185, 45, 48, 105, 185, 185, 185, 185, 185, 88, 123,
185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185,
185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185,
185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185};
-struct Huffman_table {
- unsigned char Length[17]; // k =1-16 ; L[k] indicates the number of Huffman
+struct HuffmanTable {
+ unsigned char length[17]; // k =1-16 ; L[k] indicates the number of Huffman
// codes of length k
- unsigned short int minor_code[17]; // indicates the value of the smallest
+ unsigned short int minorCode[17]; // indicates the value of the smallest
// Huffman code of length k
- unsigned short int major_code[17]; // similar, but the highest code
- unsigned char V[65536]; // V[k][j] = Value associated to the j-th Huffman
+ unsigned short int majorCode[17]; // similar, but the highest code
+ unsigned char v[65536]; // V[k][j] = Value associated to the j-th Huffman
// code of length k
// High nibble = nr of previous 0 coefficients
// Low nibble = size (in bits) of the coefficient which will be taken from the
// data stream
- unsigned char Len[65536];
+ unsigned char len[65536];
};
diff --git a/include/ast_jpeg_decoder.hpp b/include/ast_jpeg_decoder.hpp index d2a482ab74..99e60054c5 100644 --- a/include/ast_jpeg_decoder.hpp +++ b/include/ast_jpeg_decoder.hpp @@ -1,30 +1,30 @@ #pragma once +#include <aspeed/JTABLES.H> #include <ast_video_types.hpp> #include <array> -#include <aspeed/JTABLES.H> #include <cassert> #include <cstdint> #include <cstring> #include <iostream> #include <vector> -namespace AstVideo { +namespace ast_video { -struct COLOR_CACHE { - COLOR_CACHE() - : Color{0x008080, 0xFF8080, 0x808080, 0xC08080}, Index{0, 1, 2, 3} {} +struct ColorCache { + ColorCache() + : color{0x008080, 0xFF8080, 0x808080, 0xC08080}, index{0, 1, 2, 3} {} - unsigned long Color[4]; - unsigned char Index[4]; - unsigned char BitMapBits{}; + unsigned long color[4]; + unsigned char index[4]; + unsigned char bitMapBits{}; }; struct RGB { - unsigned char B; - unsigned char G; - unsigned char R; - unsigned char Reserved; + unsigned char b; + unsigned char g; + unsigned char r; + unsigned char reserved; }; enum class JpgBlock { @@ -54,61 +54,60 @@ class AstJpegDecoder { public: AstJpegDecoder() { // TODO(ed) figure out how to init this in the constructor - YUVBuffer.resize(1920 * 1200); - OutBuffer.resize(1920 * 1200); - for (auto &r : OutBuffer) { - r.R = 0x00; - r.G = 0x00; - r.B = 0x00; - r.Reserved = 0xAA; + yuvBuffer.resize(1920 * 1200); + outBuffer.resize(1920 * 1200); + for (auto &r : outBuffer) { + r.r = 0x00; + r.g = 0x00; + r.b = 0x00; + r.reserved = 0xAA; } int qfactor = 16; - SCALEFACTOR = qfactor; - SCALEFACTORUV = qfactor; - ADVANCESCALEFACTOR = 16; - ADVANCESCALEFACTORUV = 16; - init_jpg_table(); + scalefactor = qfactor; + scalefactoruv = qfactor; + advancescalefactor = 16; + advancescalefactoruv = 16; + initJpgTable(); } - void load_quant_table(std::array<long, 64> &quant_table) { - float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f, - 1.0f, 0.785694958f, 0.541196100f, 0.275899379f}; + void loadQuantTable(std::array<long, 64> &quant_table) { + float scalefactor_f[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f, + 1.0f, 0.785694958f, 0.541196100f, 0.275899379f}; uint8_t j, row, col; std::array<uint8_t, 64> tempQT{}; // Load quantization coefficients from JPG file, scale them for DCT and // reorder // from zig-zag order - switch (Y_selector) { + switch (ySelector) { case 0: - std_luminance_qt = Tbl_000Y; + stdLuminanceQt = tbl000Y; break; case 1: - std_luminance_qt = Tbl_014Y; + stdLuminanceQt = tbl014Y; break; case 2: - std_luminance_qt = Tbl_029Y; + stdLuminanceQt = tbl029Y; break; case 3: - std_luminance_qt = Tbl_043Y; + stdLuminanceQt = tbl043Y; break; case 4: - std_luminance_qt = Tbl_057Y; + stdLuminanceQt = tbl057Y; break; case 5: - std_luminance_qt = Tbl_071Y; + stdLuminanceQt = tbl071Y; break; case 6: - std_luminance_qt = Tbl_086Y; + stdLuminanceQt = tbl086Y; break; case 7: - std_luminance_qt = Tbl_100Y; + stdLuminanceQt = tbl100Y; break; } - set_quant_table(std_luminance_qt, static_cast<uint8_t>(SCALEFACTOR), - tempQT); + setQuantTable(stdLuminanceQt, static_cast<uint8_t>(scalefactor), tempQT); for (j = 0; j <= 63; j++) { quant_table[j] = tempQT[zigzag[j]]; @@ -117,14 +116,14 @@ class AstJpegDecoder { for (row = 0; row <= 7; row++) { for (col = 0; col <= 7; col++) { quant_table[j] = static_cast<long>( - (quant_table[j] * scalefactor[row] * scalefactor[col]) * 65536); + (quant_table[j] * scalefactor_f[row] * scalefactor_f[col]) * 65536); j++; } } - byte_pos += 64; + bytePos += 64; } - void load_quant_tableCb(std::array<long, 64> &quant_table) { + void loadQuantTableCb(std::array<long, 64> &quant_table) { float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f, 1.0f, 0.785694958f, 0.541196100f, 0.275899379f}; uint8_t j, row, col; @@ -132,63 +131,63 @@ class AstJpegDecoder { // Load quantization coefficients from JPG file, scale them for DCT and // reorder from zig-zag order - if (Mapping == 0) { - switch (UV_selector) { + if (mapping == 0) { + switch (uvSelector) { case 0: - std_chrominance_qt = Tbl_000Y; + stdChrominanceQt = tbl000Y; break; case 1: - std_chrominance_qt = Tbl_014Y; + stdChrominanceQt = tbl014Y; break; case 2: - std_chrominance_qt = Tbl_029Y; + stdChrominanceQt = tbl029Y; break; case 3: - std_chrominance_qt = Tbl_043Y; + stdChrominanceQt = tbl043Y; break; case 4: - std_chrominance_qt = Tbl_057Y; + stdChrominanceQt = tbl057Y; break; case 5: - std_chrominance_qt = Tbl_071Y; + stdChrominanceQt = tbl071Y; break; case 6: - std_chrominance_qt = Tbl_086Y; + stdChrominanceQt = tbl086Y; break; case 7: - std_chrominance_qt = Tbl_100Y; + stdChrominanceQt = tbl100Y; break; } } else { - switch (UV_selector) { + switch (uvSelector) { case 0: - std_chrominance_qt = Tbl_000UV; + stdChrominanceQt = tbl000Uv; break; case 1: - std_chrominance_qt = Tbl_014UV; + stdChrominanceQt = tbl014Uv; break; case 2: - std_chrominance_qt = Tbl_029UV; + stdChrominanceQt = tbl029Uv; break; case 3: - std_chrominance_qt = Tbl_043UV; + stdChrominanceQt = tbl043Uv; break; case 4: - std_chrominance_qt = Tbl_057UV; + stdChrominanceQt = tbl057Uv; break; case 5: - std_chrominance_qt = Tbl_071UV; + stdChrominanceQt = tbl071Uv; break; case 6: - std_chrominance_qt = Tbl_086UV; + stdChrominanceQt = tbl086Uv; break; case 7: - std_chrominance_qt = Tbl_100UV; + stdChrominanceQt = tbl100Uv; break; } } - set_quant_table(std_chrominance_qt, static_cast<uint8_t>(SCALEFACTORUV), - tempQT); + setQuantTable(stdChrominanceQt, static_cast<uint8_t>(scalefactoruv), + tempQT); for (j = 0; j <= 63; j++) { quant_table[j] = tempQT[zigzag[j]]; @@ -201,10 +200,10 @@ class AstJpegDecoder { j++; } } - byte_pos += 64; + bytePos += 64; } // Note: Added for Dual_JPEG - void load_advance_quant_table(std::array<long, 64> &quant_table) { + void loadAdvanceQuantTable(std::array<long, 64> &quant_table) { float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f, 1.0f, 0.785694958f, 0.541196100f, 0.275899379f}; uint8_t j, row, col; @@ -213,35 +212,35 @@ class AstJpegDecoder { // Load quantization coefficients from JPG file, scale them for DCT and // reorder // from zig-zag order - switch (advance_selector) { + switch (advanceSelector) { case 0: - std_luminance_qt = Tbl_000Y; + stdLuminanceQt = tbl000Y; break; case 1: - std_luminance_qt = Tbl_014Y; + stdLuminanceQt = tbl014Y; break; case 2: - std_luminance_qt = Tbl_029Y; + stdLuminanceQt = tbl029Y; break; case 3: - std_luminance_qt = Tbl_043Y; + stdLuminanceQt = tbl043Y; break; case 4: - std_luminance_qt = Tbl_057Y; + stdLuminanceQt = tbl057Y; break; case 5: - std_luminance_qt = Tbl_071Y; + stdLuminanceQt = tbl071Y; break; case 6: - std_luminance_qt = Tbl_086Y; + stdLuminanceQt = tbl086Y; break; case 7: - std_luminance_qt = Tbl_100Y; + stdLuminanceQt = tbl100Y; break; } // Note: pass ADVANCE SCALE FACTOR to sub-function in Dual-JPEG - set_quant_table(std_luminance_qt, static_cast<uint8_t>(ADVANCESCALEFACTOR), - tempQT); + setQuantTable(stdLuminanceQt, static_cast<uint8_t>(advancescalefactor), + tempQT); for (j = 0; j <= 63; j++) { quant_table[j] = tempQT[zigzag[j]]; @@ -254,11 +253,11 @@ class AstJpegDecoder { j++; } } - byte_pos += 64; + bytePos += 64; } // Note: Added for Dual-JPEG - void load_advance_quant_tableCb(std::array<long, 64> &quant_table) { + void loadAdvanceQuantTableCb(std::array<long, 64> &quant_table) { float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f, 1.0f, 0.785694958f, 0.541196100f, 0.275899379f}; uint8_t j, row, col; @@ -267,64 +266,64 @@ class AstJpegDecoder { // Load quantization coefficients from JPG file, scale them for DCT and // reorder // from zig-zag order - if (Mapping == 1) { - switch (advance_selector) { + if (mapping == 1) { + switch (advanceSelector) { case 0: - std_chrominance_qt = Tbl_000Y; + stdChrominanceQt = tbl000Y; break; case 1: - std_chrominance_qt = Tbl_014Y; + stdChrominanceQt = tbl014Y; break; case 2: - std_chrominance_qt = Tbl_029Y; + stdChrominanceQt = tbl029Y; break; case 3: - std_chrominance_qt = Tbl_043Y; + stdChrominanceQt = tbl043Y; break; case 4: - std_chrominance_qt = Tbl_057Y; + stdChrominanceQt = tbl057Y; break; case 5: - std_chrominance_qt = Tbl_071Y; + stdChrominanceQt = tbl071Y; break; case 6: - std_chrominance_qt = Tbl_086Y; + stdChrominanceQt = tbl086Y; break; case 7: - std_chrominance_qt = Tbl_100Y; + stdChrominanceQt = tbl100Y; break; } } else { - switch (advance_selector) { + switch (advanceSelector) { case 0: - std_chrominance_qt = Tbl_000UV; + stdChrominanceQt = tbl000Uv; break; case 1: - std_chrominance_qt = Tbl_014UV; + stdChrominanceQt = tbl014Uv; break; case 2: - std_chrominance_qt = Tbl_029UV; + stdChrominanceQt = tbl029Uv; break; case 3: - std_chrominance_qt = Tbl_043UV; + stdChrominanceQt = tbl043Uv; break; case 4: - std_chrominance_qt = Tbl_057UV; + stdChrominanceQt = tbl057Uv; break; case 5: - std_chrominance_qt = Tbl_071UV; + stdChrominanceQt = tbl071Uv; break; case 6: - std_chrominance_qt = Tbl_086UV; + stdChrominanceQt = tbl086Uv; break; case 7: - std_chrominance_qt = Tbl_100UV; + stdChrominanceQt = tbl100Uv; break; } } // Note: pass ADVANCE SCALE FACTOR to sub-function in Dual-JPEG - set_quant_table(std_chrominance_qt, - static_cast<uint8_t>(ADVANCESCALEFACTORUV), tempQT); + setQuantTable(stdChrominanceQt, static_cast<uint8_t>(advancescalefactoruv), + tempQT); for (j = 0; j <= 63; j++) { quant_table[j] = tempQT[zigzag[j]]; @@ -337,10 +336,10 @@ class AstJpegDecoder { j++; } } - byte_pos += 64; + bytePos += 64; } - void IDCT_transform(short *coef, uint8_t *data, uint8_t nBlock) { + void idctTransform(short *coef, uint8_t *data, uint8_t nBlock) { #define FIX_1_082392200 ((int)277) /* FIX(1.082392200) */ #define FIX_1_414213562 ((int)362) /* FIX(1.414213562) */ #define FIX_1_847759065 ((int)473) /* FIX(1.847759065) */ @@ -357,38 +356,38 @@ class AstJpegDecoder { long *quantptr; int *wsptr = workspace; unsigned char *outptr; - unsigned char *r_limit = rlimit_table + 128; - int ctr, dcval, DCTSIZE = 8; + unsigned char *rLimit = rlimitTable + 128; + int ctr, dcval, dctsize = 8; - quantptr = &QT[nBlock][0]; + quantptr = &qt[nBlock][0]; // Pass 1: process columns from input (inptr), store into work array(wsptr) for (ctr = 8; ctr > 0; ctr--) { /* Due to quantization, we will usually find that many of the input - * coefficients are zero, especially the AC terms. We can exploit this - * by short-circuiting the IDCT calculation for any column in which all - * the AC terms are zero. In that case each output is equal to the - * DC coefficient (with scale factor as needed). - * With typical images and quantization tables, half or more of the - * column DCT calculations can be simplified this way. - */ - - if ((inptr[DCTSIZE * 1] | inptr[DCTSIZE * 2] | inptr[DCTSIZE * 3] | - inptr[DCTSIZE * 4] | inptr[DCTSIZE * 5] | inptr[DCTSIZE * 6] | - inptr[DCTSIZE * 7]) == 0) { + * coefficients are zero, especially the AC terms. We can exploit this + * by short-circuiting the IDCT calculation for any column in which all + * the AC terms are zero. In that case each output is equal to the + * DC coefficient (with scale factor as needed). + * With typical images and quantization tables, half or more of the + * column DCT calculations can be simplified this way. + */ + + if ((inptr[dctsize * 1] | inptr[dctsize * 2] | inptr[dctsize * 3] | + inptr[dctsize * 4] | inptr[dctsize * 5] | inptr[dctsize * 6] | + inptr[dctsize * 7]) == 0) { /* AC terms all zero */ - dcval = static_cast<int>((inptr[DCTSIZE * 0] * quantptr[DCTSIZE * 0]) >> + dcval = static_cast<int>((inptr[dctsize * 0] * quantptr[dctsize * 0]) >> 16); - wsptr[DCTSIZE * 0] = dcval; - wsptr[DCTSIZE * 1] = dcval; - wsptr[DCTSIZE * 2] = dcval; - wsptr[DCTSIZE * 3] = dcval; - wsptr[DCTSIZE * 4] = dcval; - wsptr[DCTSIZE * 5] = dcval; - wsptr[DCTSIZE * 6] = dcval; - wsptr[DCTSIZE * 7] = dcval; + wsptr[dctsize * 0] = dcval; + wsptr[dctsize * 1] = dcval; + wsptr[dctsize * 2] = dcval; + wsptr[dctsize * 3] = dcval; + wsptr[dctsize * 4] = dcval; + wsptr[dctsize * 5] = dcval; + wsptr[dctsize * 6] = dcval; + wsptr[dctsize * 7] = dcval; inptr++; /* advance pointers to next column */ quantptr++; @@ -398,10 +397,10 @@ class AstJpegDecoder { /* Even part */ - tmp0 = (inptr[DCTSIZE * 0] * quantptr[DCTSIZE * 0]) >> 16; - tmp1 = (inptr[DCTSIZE * 2] * quantptr[DCTSIZE * 2]) >> 16; - tmp2 = (inptr[DCTSIZE * 4] * quantptr[DCTSIZE * 4]) >> 16; - tmp3 = (inptr[DCTSIZE * 6] * quantptr[DCTSIZE * 6]) >> 16; + tmp0 = (inptr[dctsize * 0] * quantptr[dctsize * 0]) >> 16; + tmp1 = (inptr[dctsize * 2] * quantptr[dctsize * 2]) >> 16; + tmp2 = (inptr[dctsize * 4] * quantptr[dctsize * 4]) >> 16; + tmp3 = (inptr[dctsize * 6] * quantptr[dctsize * 6]) >> 16; tmp10 = tmp0 + tmp2; /* phase 3 */ tmp11 = tmp0 - tmp2; @@ -416,10 +415,10 @@ class AstJpegDecoder { /* Odd part */ - tmp4 = (inptr[DCTSIZE * 1] * quantptr[DCTSIZE * 1]) >> 16; - tmp5 = (inptr[DCTSIZE * 3] * quantptr[DCTSIZE * 3]) >> 16; - tmp6 = (inptr[DCTSIZE * 5] * quantptr[DCTSIZE * 5]) >> 16; - tmp7 = (inptr[DCTSIZE * 7] * quantptr[DCTSIZE * 7]) >> 16; + tmp4 = (inptr[dctsize * 1] * quantptr[dctsize * 1]) >> 16; + tmp5 = (inptr[dctsize * 3] * quantptr[dctsize * 3]) >> 16; + tmp6 = (inptr[dctsize * 5] * quantptr[dctsize * 5]) >> 16; + tmp7 = (inptr[dctsize * 7] * quantptr[dctsize * 7]) >> 16; z13 = tmp6 + tmp5; /* phase 6 */ z10 = tmp6 - tmp5; @@ -437,14 +436,14 @@ class AstJpegDecoder { tmp5 = tmp11 - tmp6; tmp4 = tmp10 + tmp5; - wsptr[DCTSIZE * 0] = (tmp0 + tmp7); - wsptr[DCTSIZE * 7] = (tmp0 - tmp7); - wsptr[DCTSIZE * 1] = (tmp1 + tmp6); - wsptr[DCTSIZE * 6] = (tmp1 - tmp6); - wsptr[DCTSIZE * 2] = (tmp2 + tmp5); - wsptr[DCTSIZE * 5] = (tmp2 - tmp5); - wsptr[DCTSIZE * 4] = (tmp3 + tmp4); - wsptr[DCTSIZE * 3] = (tmp3 - tmp4); + wsptr[dctsize * 0] = (tmp0 + tmp7); + wsptr[dctsize * 7] = (tmp0 - tmp7); + wsptr[dctsize * 1] = (tmp1 + tmp6); + wsptr[dctsize * 6] = (tmp1 - tmp6); + wsptr[dctsize * 2] = (tmp2 + tmp5); + wsptr[dctsize * 5] = (tmp2 - tmp5); + wsptr[dctsize * 4] = (tmp3 + tmp4); + wsptr[dctsize * 3] = (tmp3 - tmp4); inptr++; /* advance pointers to next column */ quantptr++; @@ -460,16 +459,16 @@ class AstJpegDecoder { #define IDESCALE(x, n) ((int)((x) >> (n))) wsptr = workspace; - for (ctr = 0; ctr < DCTSIZE; ctr++) { + for (ctr = 0; ctr < dctsize; ctr++) { outptr = data + ctr * 8; /* Rows of zeroes can be exploited in the same way as we did with columns. - * However, the column calculation has created many nonzero AC terms, so - * the simplification applies less often (typically 5% to 10% of the time). - * On machines with very fast multiplication, it's possible that the - * test takes more time than it's worth. In that case this section - * may be commented out. - */ + * However, the column calculation has created many nonzero AC terms, so + * the simplification applies less often (typically 5% to 10% of the + * time). On machines with very fast multiplication, it's possible that + * the test takes more time than it's worth. In that case this section + * may be commented out. + */ /* Even part */ tmp10 = (wsptr[0] + wsptr[4]); @@ -503,32 +502,32 @@ class AstJpegDecoder { /* Final output stage: scale down by a factor of 8 and range-limit */ - outptr[0] = r_limit[IDESCALE((tmp0 + tmp7), (PASS1_BITS + 3)) & 1023L]; - outptr[7] = r_limit[IDESCALE((tmp0 - tmp7), (PASS1_BITS + 3)) & 1023L]; - outptr[1] = r_limit[IDESCALE((tmp1 + tmp6), (PASS1_BITS + 3)) & 1023L]; - outptr[6] = r_limit[IDESCALE((tmp1 - tmp6), (PASS1_BITS + 3)) & 1023L]; - outptr[2] = r_limit[IDESCALE((tmp2 + tmp5), (PASS1_BITS + 3)) & 1023L]; - outptr[5] = r_limit[IDESCALE((tmp2 - tmp5), (PASS1_BITS + 3)) & 1023L]; - outptr[4] = r_limit[IDESCALE((tmp3 + tmp4), (PASS1_BITS + 3)) & 1023L]; - outptr[3] = r_limit[IDESCALE((tmp3 - tmp4), (PASS1_BITS + 3)) & 1023L]; + outptr[0] = rLimit[IDESCALE((tmp0 + tmp7), (PASS1_BITS + 3)) & 1023L]; + outptr[7] = rLimit[IDESCALE((tmp0 - tmp7), (PASS1_BITS + 3)) & 1023L]; + outptr[1] = rLimit[IDESCALE((tmp1 + tmp6), (PASS1_BITS + 3)) & 1023L]; + outptr[6] = rLimit[IDESCALE((tmp1 - tmp6), (PASS1_BITS + 3)) & 1023L]; + outptr[2] = rLimit[IDESCALE((tmp2 + tmp5), (PASS1_BITS + 3)) & 1023L]; + outptr[5] = rLimit[IDESCALE((tmp2 - tmp5), (PASS1_BITS + 3)) & 1023L]; + outptr[4] = rLimit[IDESCALE((tmp3 + tmp4), (PASS1_BITS + 3)) & 1023L]; + outptr[3] = rLimit[IDESCALE((tmp3 - tmp4), (PASS1_BITS + 3)) & 1023L]; - wsptr += DCTSIZE; /* advance pointer to next row */ + wsptr += dctsize; /* advance pointer to next row */ } } - void YUVToRGB( + void yuvToRgb( int txb, int tyb, unsigned char *pYCbCr, // in, Y: 256 or 64 bytes; Cb: 64 bytes; Cr: 64 bytes struct RGB *pYUV, // in, Y: 256 or 64 bytes; Cb: 64 bytes; Cr: 64 bytes unsigned char *pBgr // out, BGR format, 16*16*3 = 768 bytes; or 8*8*3=192 bytes - ) { + ) { int i, j, pos, m, n; unsigned char cb, cr, *py, *pcb, *pcr, *py420[4]; int y; struct RGB *pByte; int nBlocksInMcu = 6; - unsigned int pixel_x, pixel_y; + unsigned int pixelX, pixelY; pByte = reinterpret_cast<struct RGB *>(pBgr); if (yuvmode == YuvMode::YUV444) { @@ -536,9 +535,9 @@ class AstJpegDecoder { pcb = pYCbCr + 64; pcr = pcb + 64; - pixel_x = txb * 8; - pixel_y = tyb * 8; - pos = (pixel_y * WIDTH) + pixel_x; + pixelX = txb * 8; + pixelY = tyb * 8; + pos = (pixelY * width) + pixelX; for (j = 0; j < 8; j++) { for (i = 0; i < 8; i++) { @@ -548,14 +547,14 @@ class AstJpegDecoder { cr = pcr[m]; n = pos + i; // For 2Pass. Save the YUV value - pYUV[n].B = cb; - pYUV[n].G = y; - pYUV[n].R = cr; - pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]]; - pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]]; - pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]]; + pYUV[n].b = cb; + pYUV[n].g = y; + pYUV[n].r = cr; + pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]]; + pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]]; + pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]]; } - pos += WIDTH; + pos += width; } } else { for (i = 0; i < nBlocksInMcu - 2; i++) { @@ -564,9 +563,9 @@ class AstJpegDecoder { pcb = pYCbCr + (nBlocksInMcu - 2) * 64; pcr = pcb + 64; - pixel_x = txb * 16; - pixel_y = tyb * 16; - pos = (pixel_y * WIDTH) + pixel_x; + pixelX = txb * 16; + pixelY = tyb * 16; + pos = (pixelY * width) + pixelX; for (j = 0; j < 16; j++) { for (i = 0; i < 16; i++) { @@ -576,15 +575,15 @@ class AstJpegDecoder { cb = pcb[m]; cr = pcr[m]; n = pos + i; - pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]]; - pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]]; - pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]]; + pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]]; + pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]]; + pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]]; } - pos += WIDTH; + pos += width; } } } - void YUVToBuffer( + void yuvToBuffer( int txb, int tyb, unsigned char *pYCbCr, // in, Y: 256 or 64 bytes; Cb: 64 bytes; Cr: 64 bytes @@ -592,13 +591,13 @@ class AstJpegDecoder { *pYUV, // out, BGR format, 16*16*3 = 768 bytes; or 8*8*3=192 bytes unsigned char *pBgr // out, BGR format, 16*16*3 = 768 bytes; or 8*8*3=192 bytes - ) { + ) { int i, j, pos, m, n; unsigned char cb, cr, *py, *pcb, *pcr, *py420[4]; int y; struct RGB *pByte; int nBlocksInMcu = 6; - unsigned int pixel_x, pixel_y; + unsigned int pixelX, pixelY; pByte = reinterpret_cast<struct RGB *>(pBgr); if (yuvmode == YuvMode::YUV444) { @@ -606,25 +605,25 @@ class AstJpegDecoder { pcb = pYCbCr + 64; pcr = pcb + 64; - pixel_x = txb * 8; - pixel_y = tyb * 8; - pos = (pixel_y * WIDTH) + pixel_x; + pixelX = txb * 8; + pixelY = tyb * 8; + pos = (pixelY * width) + pixelX; for (j = 0; j < 8; j++) { for (i = 0; i < 8; i++) { m = ((j << 3) + i); n = pos + i; - y = pYUV[n].G + (py[m] - 128); - cb = pYUV[n].B + (pcb[m] - 128); - cr = pYUV[n].R + (pcr[m] - 128); - pYUV[n].B = cb; - pYUV[n].G = y; - pYUV[n].R = cr; - pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]]; - pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]]; - pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]]; + y = pYUV[n].g + (py[m] - 128); + cb = pYUV[n].b + (pcb[m] - 128); + cr = pYUV[n].r + (pcr[m] - 128); + pYUV[n].b = cb; + pYUV[n].g = y; + pYUV[n].r = cr; + pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]]; + pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]]; + pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]]; } - pos += WIDTH; + pos += width; } } else { for (i = 0; i < nBlocksInMcu - 2; i++) { @@ -633,9 +632,9 @@ class AstJpegDecoder { pcb = pYCbCr + (nBlocksInMcu - 2) * 64; pcr = pcb + 64; - pixel_x = txb * 16; - pixel_y = tyb * 16; - pos = (pixel_y * WIDTH) + pixel_x; + pixelX = txb * 16; + pixelY = tyb * 16; + pos = (pixelY * width) + pixelX; for (j = 0; j < 16; j++) { for (i = 0; i < 16; i++) { @@ -645,125 +644,125 @@ class AstJpegDecoder { cb = pcb[m]; cr = pcr[m]; n = pos + i; - pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]]; - pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]]; - pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]]; + pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]]; + pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]]; + pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]]; } - pos += WIDTH; + pos += width; } } } - void Decompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection) { + void decompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection) { unsigned char *ptr; unsigned char byTileYuv[768] = {}; - memset(DCT_coeff, 0, 384 * 2); + memset(dctCoeff, 0, 384 * 2); ptr = byTileYuv; - process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 0); - IDCT_transform(DCT_coeff, ptr, QT_TableSelection); + processHuffmanDataUnit(ydcNr, yacNr, &dcy, 0); + idctTransform(dctCoeff, ptr, QT_TableSelection); ptr += 64; if (yuvmode == YuvMode::YUV420) { - process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 64); - IDCT_transform(DCT_coeff + 64, ptr, QT_TableSelection); + processHuffmanDataUnit(ydcNr, yacNr, &dcy, 64); + idctTransform(dctCoeff + 64, ptr, QT_TableSelection); ptr += 64; - process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 128); - IDCT_transform(DCT_coeff + 128, ptr, QT_TableSelection); + processHuffmanDataUnit(ydcNr, yacNr, &dcy, 128); + idctTransform(dctCoeff + 128, ptr, QT_TableSelection); ptr += 64; - process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 192); - IDCT_transform(DCT_coeff + 192, ptr, QT_TableSelection); + processHuffmanDataUnit(ydcNr, yacNr, &dcy, 192); + idctTransform(dctCoeff + 192, ptr, QT_TableSelection); ptr += 64; - process_Huffman_data_unit(CbDC_nr, CbAC_nr, &DCCb, 256); - IDCT_transform(DCT_coeff + 256, ptr, QT_TableSelection + 1); + processHuffmanDataUnit(cbDcNr, cbAcNr, &dcCb, 256); + idctTransform(dctCoeff + 256, ptr, QT_TableSelection + 1); ptr += 64; - process_Huffman_data_unit(CrDC_nr, CrAC_nr, &DCCr, 320); - IDCT_transform(DCT_coeff + 320, ptr, QT_TableSelection + 1); + processHuffmanDataUnit(crDcNr, crAcNr, &dcCr, 320); + idctTransform(dctCoeff + 320, ptr, QT_TableSelection + 1); } else { - process_Huffman_data_unit(CbDC_nr, CbAC_nr, &DCCb, 64); - IDCT_transform(DCT_coeff + 64, ptr, QT_TableSelection + 1); + processHuffmanDataUnit(cbDcNr, cbAcNr, &dcCb, 64); + idctTransform(dctCoeff + 64, ptr, QT_TableSelection + 1); ptr += 64; - process_Huffman_data_unit(CrDC_nr, CrAC_nr, &DCCr, 128); - IDCT_transform(DCT_coeff + 128, ptr, QT_TableSelection + 1); + processHuffmanDataUnit(crDcNr, crAcNr, &dcCr, 128); + idctTransform(dctCoeff + 128, ptr, QT_TableSelection + 1); } - // YUVToRGB (txb, tyb, byTileYuv, (unsigned char *)outBuf); - // YUVBuffer for YUV record - YUVToRGB(txb, tyb, byTileYuv, YUVBuffer.data(), + // yuvToRgb (txb, tyb, byTileYuv, (unsigned char *)outBuf); + // yuvBuffer for YUV record + yuvToRgb(txb, tyb, byTileYuv, yuvBuffer.data(), reinterpret_cast<unsigned char *>(outBuf)); } - void Decompress_2PASS(int txb, int tyb, char *outBuf, - uint8_t QT_TableSelection) { + void decompress2Pass(int txb, int tyb, char *outBuf, + uint8_t QT_TableSelection) { unsigned char *ptr; unsigned char byTileYuv[768]; - memset(DCT_coeff, 0, 384 * 2); + memset(dctCoeff, 0, 384 * 2); ptr = byTileYuv; - process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 0); - IDCT_transform(DCT_coeff, ptr, QT_TableSelection); + processHuffmanDataUnit(ydcNr, yacNr, &dcy, 0); + idctTransform(dctCoeff, ptr, QT_TableSelection); ptr += 64; - process_Huffman_data_unit(CbDC_nr, CbAC_nr, &DCCb, 64); - IDCT_transform(DCT_coeff + 64, ptr, QT_TableSelection + 1); + processHuffmanDataUnit(cbDcNr, cbAcNr, &dcCb, 64); + idctTransform(dctCoeff + 64, ptr, QT_TableSelection + 1); ptr += 64; - process_Huffman_data_unit(CrDC_nr, CrAC_nr, &DCCr, 128); - IDCT_transform(DCT_coeff + 128, ptr, QT_TableSelection + 1); + processHuffmanDataUnit(crDcNr, crAcNr, &dcCr, 128); + idctTransform(dctCoeff + 128, ptr, QT_TableSelection + 1); - YUVToBuffer(txb, tyb, byTileYuv, YUVBuffer.data(), + yuvToBuffer(txb, tyb, byTileYuv, yuvBuffer.data(), reinterpret_cast<unsigned char *>(outBuf)); - // YUVToRGB (txb, tyb, byTileYuv, (unsigned char *)outBuf); + // yuvToRgb (txb, tyb, byTileYuv, (unsigned char *)outBuf); } - void VQ_Decompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection, - struct COLOR_CACHE *VQ) { + void vqDecompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection, + struct ColorCache *VQ) { unsigned char *ptr, i; unsigned char byTileYuv[192]; - int Data; + int data; ptr = byTileYuv; - if (VQ->BitMapBits == 0) { + if (VQ->bitMapBits == 0) { for (i = 0; i < 64; i++) { - ptr[0] = (VQ->Color[VQ->Index[0]] & 0xFF0000) >> 16; - ptr[64] = (VQ->Color[VQ->Index[0]] & 0x00FF00) >> 8; - ptr[128] = VQ->Color[VQ->Index[0]] & 0x0000FF; + ptr[0] = (VQ->color[VQ->index[0]] & 0xFF0000) >> 16; + ptr[64] = (VQ->color[VQ->index[0]] & 0x00FF00) >> 8; + ptr[128] = VQ->color[VQ->index[0]] & 0x0000FF; ptr += 1; } } else { for (i = 0; i < 64; i++) { - Data = static_cast<int>(lookKbits(VQ->BitMapBits)); - ptr[0] = (VQ->Color[VQ->Index[Data]] & 0xFF0000) >> 16; - ptr[64] = (VQ->Color[VQ->Index[Data]] & 0x00FF00) >> 8; - ptr[128] = VQ->Color[VQ->Index[Data]] & 0x0000FF; + data = static_cast<int>(lookKbits(VQ->bitMapBits)); + ptr[0] = (VQ->color[VQ->index[data]] & 0xFF0000) >> 16; + ptr[64] = (VQ->color[VQ->index[data]] & 0x00FF00) >> 8; + ptr[128] = VQ->color[VQ->index[data]] & 0x0000FF; ptr += 1; - skipKbits(VQ->BitMapBits); + skipKbits(VQ->bitMapBits); } } - // YUVToRGB (txb, tyb, byTileYuv, (unsigned char *)outBuf); - YUVToRGB(txb, tyb, byTileYuv, YUVBuffer.data(), + // yuvToRgb (txb, tyb, byTileYuv, (unsigned char *)outBuf); + yuvToRgb(txb, tyb, byTileYuv, yuvBuffer.data(), reinterpret_cast<unsigned char *>(outBuf)); } - void MoveBlockIndex() { + void moveBlockIndex() { if (yuvmode == YuvMode::YUV444) { txb++; - if (txb >= static_cast<int>(WIDTH / 8)) { + if (txb >= static_cast<int>(width / 8)) { tyb++; - if (tyb >= static_cast<int>(HEIGHT / 8)) { + if (tyb >= static_cast<int>(height / 8)) { tyb = 0; } txb = 0; } } else { txb++; - if (txb >= static_cast<int>(WIDTH / 16)) { + if (txb >= static_cast<int>(width / 16)) { tyb++; - if (tyb >= static_cast<int>(HEIGHT / 16)) { + if (tyb >= static_cast<int>(height / 16)) { tyb = 0; } txb = 0; @@ -771,7 +770,7 @@ class AstJpegDecoder { } } - void Init_Color_Table() { + void initColorTable() { int i, x; int nScale = 1L << 16; // equal to power(2,16) int nHalf = nScale >> 1; @@ -780,180 +779,180 @@ class AstJpegDecoder { /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ - /* Cr=>R value is nearest int to 1.597656 * x */ - /* Cb=>B value is nearest int to 2.015625 * x */ - /* Cr=>G value is scaled-up -0.8125 * x */ - /* Cb=>G value is scaled-up -0.390625 * x */ + /* Cr=>r value is nearest int to 1.597656 * x */ + /* Cb=>b value is nearest int to 2.015625 * x */ + /* Cr=>g value is scaled-up -0.8125 * x */ + /* Cb=>g value is scaled-up -0.390625 * x */ for (i = 0, x = -128; i < 256; i++, x++) { - m_CrToR[i] = (FIX(1.597656) * x + nHalf) >> 16; - m_CbToB[i] = (FIX(2.015625) * x + nHalf) >> 16; - m_CrToG[i] = (-FIX(0.8125) * x + nHalf) >> 16; - m_CbToG[i] = (-FIX(0.390625) * x + nHalf) >> 16; + mCrToR[i] = (FIX(1.597656) * x + nHalf) >> 16; + mCbToB[i] = (FIX(2.015625) * x + nHalf) >> 16; + mCrToG[i] = (-FIX(0.8125) * x + nHalf) >> 16; + mCbToG[i] = (-FIX(0.390625) * x + nHalf) >> 16; } for (i = 0, x = -16; i < 256; i++, x++) { - m_Y[i] = (FIX(1.164) * x + nHalf) >> 16; + mY[i] = (FIX(1.164) * x + nHalf) >> 16; } - // For Color Text Enchance Y Re-map. Recommend to disable in default + // For color Text Enchance Y Re-map. Recommend to disable in default /* for (i = 0; i < (VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate); i++) { temp = (double)i / VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate; temp1 = 1.0 / VideoEngineInfo->INFData.Gamma1Parameter; - m_Y[i] = + mY[i] = (BYTE)(VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate * pow (temp, temp1)); - if (m_Y[i] > 255) m_Y[i] = 255; + if (mY[i] > 255) mY[i] = 255; } for (i = (VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate); i < 256; i++) { - m_Y[i] = + mY[i] = (BYTE)((VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate) + (256 - VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate) * ( pow((double)((i - VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate) / (256 - (VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate))), (1.0 / VideoEngineInfo->INFData.Gamma2Parameter)) )); - if (m_Y[i] > 255) m_Y[i] = 255; + if (mY[i] > 255) mY[i] = 255; } */ } - void load_Huffman_table(Huffman_table *HT, const unsigned char *nrcode, - const unsigned char *value, - const unsigned short int *Huff_code) { + void loadHuffmanTable(HuffmanTable *HT, const unsigned char *nrcode, + const unsigned char *value, + const unsigned short int *Huff_code) { unsigned char k, j, i; - unsigned int code, code_index; + unsigned int code, codeIndex; for (j = 1; j <= 16; j++) { - HT->Length[j] = nrcode[j]; + HT->length[j] = nrcode[j]; } for (i = 0, k = 1; k <= 16; k++) { - for (j = 0; j < HT->Length[k]; j++) { - HT->V[WORD_hi_lo(k, j)] = value[i]; + for (j = 0; j < HT->length[k]; j++) { + HT->v[wordHiLo(k, j)] = value[i]; i++; } } code = 0; for (k = 1; k <= 16; k++) { - HT->minor_code[k] = static_cast<unsigned short int>(code); - for (j = 1; j <= HT->Length[k]; j++) { + HT->minorCode[k] = static_cast<unsigned short int>(code); + for (j = 1; j <= HT->length[k]; j++) { code++; } - HT->major_code[k] = static_cast<unsigned short int>(code - 1); + HT->majorCode[k] = static_cast<unsigned short int>(code - 1); code *= 2; - if (HT->Length[k] == 0) { - HT->minor_code[k] = 0xFFFF; - HT->major_code[k] = 0; + if (HT->length[k] == 0) { + HT->minorCode[k] = 0xFFFF; + HT->majorCode[k] = 0; } } - HT->Len[0] = 2; + HT->len[0] = 2; i = 2; - for (code_index = 1; code_index < 65535; code_index++) { - if (code_index < Huff_code[i]) { - HT->Len[code_index] = static_cast<unsigned char>(Huff_code[i + 1]); + for (codeIndex = 1; codeIndex < 65535; codeIndex++) { + if (codeIndex < Huff_code[i]) { + HT->len[codeIndex] = static_cast<unsigned char>(Huff_code[i + 1]); } else { i = i + 2; - HT->Len[code_index] = static_cast<unsigned char>(Huff_code[i + 1]); + HT->len[codeIndex] = static_cast<unsigned char>(Huff_code[i + 1]); } } } - void init_jpg_table() { - Init_Color_Table(); - prepare_range_limit_table(); - load_Huffman_table(&HTDC[0], std_dc_luminance_nrcodes, - std_dc_luminance_values, DC_LUMINANCE_HUFFMANCODE); - load_Huffman_table(&HTAC[0], std_ac_luminance_nrcodes, - std_ac_luminance_values, AC_LUMINANCE_HUFFMANCODE); - load_Huffman_table(&HTDC[1], std_dc_chrominance_nrcodes, - std_dc_chrominance_values, DC_CHROMINANCE_HUFFMANCODE); - load_Huffman_table(&HTAC[1], std_ac_chrominance_nrcodes, - std_ac_chrominance_values, AC_CHROMINANCE_HUFFMANCODE); + void initJpgTable() { + initColorTable(); + prepareRangeLimitTable(); + loadHuffmanTable(&htdc[0], stdDcLuminanceNrcodes, stdDcLuminanceValues, + dcLuminanceHuffmancode); + loadHuffmanTable(&htac[0], stdAcLuminanceNrcodes, stdAcLuminanceValues, + acLuminanceHuffmancode); + loadHuffmanTable(&htdc[1], stdDcChrominanceNrcodes, stdDcChrominanceValues, + dcChrominanceHuffmancode); + loadHuffmanTable(&htac[1], stdAcChrominanceNrcodes, stdAcChrominanceValues, + acChrominanceHuffmancode); } - void prepare_range_limit_table() + void prepareRangeLimitTable() /* Allocate and fill in the sample_range_limit table */ { int j; - rlimit_table = reinterpret_cast<unsigned char *>(malloc(5 * 256L + 128)); + rlimitTable = reinterpret_cast<unsigned char *>(malloc(5 * 256L + 128)); /* First segment of "simple" table: limit[x] = 0 for x < 0 */ - memset((void *)rlimit_table, 0, 256); - rlimit_table += 256; /* allow negative subscripts of simple table */ + memset((void *)rlimitTable, 0, 256); + rlimitTable += 256; /* allow negative subscripts of simple table */ /* Main part of "simple" table: limit[x] = x */ for (j = 0; j < 256; j++) { - rlimit_table[j] = j; + rlimitTable[j] = j; } /* End of simple table, rest of first half of post-IDCT table */ for (j = 256; j < 640; j++) { - rlimit_table[j] = 255; + rlimitTable[j] = 255; } /* Second half of post-IDCT table */ - memset((void *)(rlimit_table + 640), 0, 384); + memset((void *)(rlimitTable + 640), 0, 384); for (j = 0; j < 128; j++) { - rlimit_table[j + 1024] = j; + rlimitTable[j + 1024] = j; } } - inline unsigned short int WORD_hi_lo(uint8_t byte_high, uint8_t byte_low) { + inline unsigned short int wordHiLo(uint8_t byte_high, uint8_t byte_low) { return (byte_high << 8) + byte_low; } // river - void process_Huffman_data_unit(uint8_t DC_nr, uint8_t AC_nr, - signed short int *previous_DC, - unsigned short int position) { + void processHuffmanDataUnit(uint8_t DC_nr, uint8_t AC_nr, + signed short int *previous_DC, + unsigned short int position) { uint8_t nr = 0; uint8_t k; - unsigned short int tmp_Hcode; - uint8_t size_val, count_0; - unsigned short int *min_code; - uint8_t *huff_values; - uint8_t byte_temp; + unsigned short int tmpHcode; + uint8_t sizeVal, count0; + unsigned short int *minCode; + uint8_t *huffValues; + uint8_t byteTemp; - min_code = HTDC[DC_nr].minor_code; - // maj_code=HTDC[DC_nr].major_code; - huff_values = HTDC[DC_nr].V; + minCode = htdc[DC_nr].minorCode; + // maj_code=htdc[DC_nr].majorCode; + huffValues = htdc[DC_nr].v; // DC - k = HTDC[DC_nr].Len[static_cast<unsigned short int>(codebuf >> 16)]; + k = htdc[DC_nr].len[static_cast<unsigned short int>(codebuf >> 16)]; // river // tmp_Hcode=lookKbits(k); - tmp_Hcode = static_cast<unsigned short int>(codebuf >> (32 - k)); + tmpHcode = static_cast<unsigned short int>(codebuf >> (32 - k)); skipKbits(k); - size_val = huff_values[WORD_hi_lo( - k, static_cast<uint8_t>(tmp_Hcode - min_code[k]))]; - if (size_val == 0) { - DCT_coeff[position + 0] = *previous_DC; + sizeVal = + huffValues[wordHiLo(k, static_cast<uint8_t>(tmpHcode - minCode[k]))]; + if (sizeVal == 0) { + dctCoeff[position + 0] = *previous_DC; } else { - DCT_coeff[position + 0] = *previous_DC + getKbits(size_val); - *previous_DC = DCT_coeff[position + 0]; + dctCoeff[position + 0] = *previous_DC + getKbits(sizeVal); + *previous_DC = dctCoeff[position + 0]; } // Second, AC coefficient decoding - min_code = HTAC[AC_nr].minor_code; - // maj_code=HTAC[AC_nr].major_code; - huff_values = HTAC[AC_nr].V; + minCode = htac[AC_nr].minorCode; + // maj_code=htac[AC_nr].majorCode; + huffValues = htac[AC_nr].v; nr = 1; // AC coefficient do { - k = HTAC[AC_nr].Len[static_cast<unsigned short int>(codebuf >> 16)]; - tmp_Hcode = static_cast<unsigned short int>(codebuf >> (32 - k)); + k = htac[AC_nr].len[static_cast<unsigned short int>(codebuf >> 16)]; + tmpHcode = static_cast<unsigned short int>(codebuf >> (32 - k)); skipKbits(k); - byte_temp = huff_values[WORD_hi_lo( - k, static_cast<uint8_t>(tmp_Hcode - min_code[k]))]; - size_val = byte_temp & 0xF; - count_0 = byte_temp >> 4; - if (size_val == 0) { - if (count_0 != 0xF) { + byteTemp = + huffValues[wordHiLo(k, static_cast<uint8_t>(tmpHcode - minCode[k]))]; + sizeVal = byteTemp & 0xF; + count0 = byteTemp >> 4; + if (sizeVal == 0) { + if (count0 != 0xF) { break; } nr += 16; } else { - nr += count_0; // skip count_0 zeroes - DCT_coeff[position + dezigzag[nr++]] = getKbits(size_val); + nr += count0; // skip count_0 zeroes + dctCoeff[position + dezigzag[nr++]] = getKbits(sizeVal); } } while (nr < 64); } @@ -970,8 +969,8 @@ class AstJpegDecoder { unsigned long readbuf; if ((newbits - k) <= 0) { - readbuf = Buffer[buffer_index]; - buffer_index++; + readbuf = buffer[bufferIndex]; + bufferIndex++; codebuf = (codebuf << k) | ((newbuf | (readbuf >> (newbits))) >> (32 - k)); newbuf = readbuf << (k - newbits); @@ -984,38 +983,38 @@ class AstJpegDecoder { } signed short int getKbits(uint8_t k) { - signed short int signed_wordvalue; + signed short int signedWordvalue; // river // signed_wordvalue=lookKbits(k); - signed_wordvalue = static_cast<unsigned short int>(codebuf >> (32 - k)); - if (((1L << (k - 1)) & signed_wordvalue) == 0) { + signedWordvalue = static_cast<unsigned short int>(codebuf >> (32 - k)); + if (((1L << (k - 1)) & signedWordvalue) == 0) { // neg_pow2 was previously defined as the below. It seemed silly to keep // a table of values around for something // THat's relatively easy to compute, so it was replaced with the // appropriate math // signed_wordvalue = signed_wordvalue - (0xFFFF >> (16 - k)); - std::array<signed short int, 17> neg_pow2 = { + std::array<signed short int, 17> negPow2 = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767}; - signed_wordvalue = signed_wordvalue + neg_pow2[k]; + signedWordvalue = signedWordvalue + negPow2[k]; } skipKbits(k); - return signed_wordvalue; + return signedWordvalue; } - int init_JPG_decoding() { - byte_pos = 0; - load_quant_table(QT[0]); - load_quant_tableCb(QT[1]); + int initJpgDecoding() { + bytePos = 0; + loadQuantTable(qt[0]); + loadQuantTableCb(qt[1]); // Note: Added for Dual-JPEG - load_advance_quant_table(QT[2]); - load_advance_quant_tableCb(QT[3]); + loadAdvanceQuantTable(qt[2]); + loadAdvanceQuantTableCb(qt[3]); return 1; } - void set_quant_table(const uint8_t *basic_table, uint8_t scale_factor, - std::array<uint8_t, 64>& newtable) + void setQuantTable(const uint8_t *basic_table, uint8_t scale_factor, + std::array<uint8_t, 64> &newtable) // Set quantization table and zigzag reorder it { uint8_t i; @@ -1034,12 +1033,12 @@ class AstJpegDecoder { } void updatereadbuf(uint32_t *codebuf, uint32_t *newbuf, int walks, - int *newbits, std::vector<uint32_t> &Buffer) { + int *newbits, std::vector<uint32_t> &buffer) { unsigned long readbuf; if ((*newbits - walks) <= 0) { - readbuf = Buffer[buffer_index]; - buffer_index++; + readbuf = buffer[bufferIndex]; + bufferIndex++; *codebuf = (*codebuf << walks) | ((*newbuf | (readbuf >> (*newbits))) >> (32 - walks)); *newbuf = readbuf << (walks - *newbits); @@ -1051,71 +1050,71 @@ class AstJpegDecoder { } } - uint32_t decode(std::vector<uint32_t> &buffer, unsigned long width, - unsigned long height, YuvMode yuvmode_in, int y_selector, - int uv_selector) { - COLOR_CACHE Decode_Color; - if (width != USER_WIDTH || height != USER_HEIGHT || yuvmode_in != yuvmode || - y_selector != Y_selector || uv_selector != UV_selector) { + uint32_t decode(std::vector<uint32_t> &bufferVector, unsigned long width, + unsigned long height, YuvMode yuvmode_in, int ySelector, + int uvSelector) { + ColorCache decodeColor; + if (width != userWidth || height != userHeight || yuvmode_in != yuvmode || + ySelector != ySelector || uvSelector != uvSelector) { yuvmode = yuvmode_in; - Y_selector = y_selector; // 0-7 - UV_selector = uv_selector; // 0-7 - USER_HEIGHT = height; - USER_WIDTH = width; - WIDTH = width; - HEIGHT = height; + ySelector = ySelector; // 0-7 + uvSelector = uvSelector; // 0-7 + userHeight = height; + userWidth = width; + width = width; + height = height; // TODO(ed) Magic number section. Document appropriately - advance_selector = 0; // 0-7 - Mapping = 0; // 0 or 1 + advanceSelector = 0; // 0-7 + mapping = 0; // 0 or 1 if (yuvmode == YuvMode::YUV420) { - if ((WIDTH % 16) != 0u) { - WIDTH = WIDTH + 16 - (WIDTH % 16); + if ((width % 16) != 0u) { + width = width + 16 - (width % 16); } - if ((HEIGHT % 16) != 0u) { - HEIGHT = HEIGHT + 16 - (HEIGHT % 16); + if ((height % 16) != 0u) { + height = height + 16 - (height % 16); } } else { - if ((WIDTH % 8) != 0u) { - WIDTH = WIDTH + 8 - (WIDTH % 8); + if ((width % 8) != 0u) { + width = width + 8 - (width % 8); } - if ((HEIGHT % 8) != 0u) { - HEIGHT = HEIGHT + 8 - (HEIGHT % 8); + if ((height % 8) != 0u) { + height = height + 8 - (height % 8); } } - init_JPG_decoding(); + initJpgDecoding(); } // TODO(ed) cleanup cruft - Buffer = buffer.data(); + buffer = bufferVector.data(); - codebuf = buffer[0]; - newbuf = buffer[1]; - buffer_index = 2; + codebuf = bufferVector[0]; + newbuf = bufferVector[1]; + bufferIndex = 2; txb = tyb = 0; newbits = 32; - DCY = DCCb = DCCr = 0; + dcy = dcCb = dcCr = 0; - static const uint32_t VQ_HEADER_MASK = 0x01; - static const uint32_t VQ_NO_UPDATE_HEADER = 0x00; - static const uint32_t VQ_UPDATE_HEADER = 0x01; - static const int VQ_NO_UPDATE_LENGTH = 0x03; - static const int VQ_UPDATE_LENGTH = 0x1B; - static const uint32_t VQ_INDEX_MASK = 0x03; - static const uint32_t VQ_COLOR_MASK = 0xFFFFFF; + static const uint32_t vqHeaderMask = 0x01; + static const uint32_t vqNoUpdateHeader = 0x00; + static const uint32_t vqUpdateHeader = 0x01; + static const int vqNoUpdateLength = 0x03; + static const int vqUpdateLength = 0x1B; + static const uint32_t vqIndexMask = 0x03; + static const uint32_t vqColorMask = 0xFFFFFF; - static const int BLOCK_AST2100_START_LENGTH = 0x04; - static const int BLOCK_AST2100_SKIP_LENGTH = 20; // S:1 H:3 X:8 Y:8 + static const int blockAsT2100StartLength = 0x04; + static const int blockAsT2100SkipLength = 20; // S:1 H:3 X:8 Y:8 do { - auto block_header = static_cast<JpgBlock>((codebuf >> 28) & 0xFF); - switch (block_header) { + auto blockHeader = static_cast<JpgBlock>((codebuf >> 28) & 0xFF); + switch (blockHeader) { case JpgBlock::JPEG_NO_SKIP_CODE: - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits, - buffer); - Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0); + updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits, + bufferVector); + decompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0); break; case JpgBlock::FRAME_END_CODE: return 0; @@ -1125,116 +1124,116 @@ class AstJpegDecoder { txb = (codebuf & 0x0FF00000) >> 20; tyb = (codebuf & 0x0FF000) >> 12; - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits, - buffer); - Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0); + updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits, + bufferVector); + decompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0); break; case JpgBlock::VQ_NO_SKIP_1_COLOR_CODE: - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits, - buffer); - Decode_Color.BitMapBits = 0; + updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits, + bufferVector); + decodeColor.bitMapBits = 0; for (int i = 0; i < 1; i++) { - Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK); - if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) { - updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask); + if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) { + updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits, + bufferVector); } else { - Decode_Color.Color[Decode_Color.Index[i]] = - ((codebuf >> 5) & VQ_COLOR_MASK); - updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.color[decodeColor.index[i]] = + ((codebuf >> 5) & vqColorMask); + updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits, + bufferVector); } } - VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0, - &Decode_Color); + vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0, + &decodeColor); break; case JpgBlock::VQ_SKIP_1_COLOR_CODE: txb = (codebuf & 0x0FF00000) >> 20; tyb = (codebuf & 0x0FF000) >> 12; - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits, - buffer); - Decode_Color.BitMapBits = 0; + updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits, + bufferVector); + decodeColor.bitMapBits = 0; for (int i = 0; i < 1; i++) { - Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK); - if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) { - updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask); + if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) { + updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits, + bufferVector); } else { - Decode_Color.Color[Decode_Color.Index[i]] = - ((codebuf >> 5) & VQ_COLOR_MASK); - updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.color[decodeColor.index[i]] = + ((codebuf >> 5) & vqColorMask); + updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits, + bufferVector); } } - VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0, - &Decode_Color); + vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0, + &decodeColor); break; case JpgBlock::VQ_NO_SKIP_2_COLOR_CODE: - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits, - buffer); - Decode_Color.BitMapBits = 1; + updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits, + bufferVector); + decodeColor.bitMapBits = 1; for (int i = 0; i < 2; i++) { - Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK); - if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) { - updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask); + if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) { + updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits, + bufferVector); } else { - Decode_Color.Color[Decode_Color.Index[i]] = - ((codebuf >> 5) & VQ_COLOR_MASK); - updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.color[decodeColor.index[i]] = + ((codebuf >> 5) & vqColorMask); + updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits, + bufferVector); } } - VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0, - &Decode_Color); + vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0, + &decodeColor); break; case JpgBlock::VQ_SKIP_2_COLOR_CODE: txb = (codebuf & 0x0FF00000) >> 20; tyb = (codebuf & 0x0FF000) >> 12; - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits, - buffer); - Decode_Color.BitMapBits = 1; + updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits, + bufferVector); + decodeColor.bitMapBits = 1; for (int i = 0; i < 2; i++) { - Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK); - if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) { - updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask); + if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) { + updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits, + bufferVector); } else { - Decode_Color.Color[Decode_Color.Index[i]] = - ((codebuf >> 5) & VQ_COLOR_MASK); - updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.color[decodeColor.index[i]] = + ((codebuf >> 5) & vqColorMask); + updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits, + bufferVector); } } - VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0, - &Decode_Color); + vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0, + &decodeColor); break; case JpgBlock::VQ_NO_SKIP_4_COLOR_CODE: - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits, - buffer); - Decode_Color.BitMapBits = 2; - - for (unsigned char &i : Decode_Color.Index) { - i = ((codebuf >> 29) & VQ_INDEX_MASK); - if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) { - updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits, - buffer); + updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits, + bufferVector); + decodeColor.bitMapBits = 2; + + for (unsigned char &i : decodeColor.index) { + i = ((codebuf >> 29) & vqIndexMask); + if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) { + updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits, + bufferVector); } else { - Decode_Color.Color[i] = ((codebuf >> 5) & VQ_COLOR_MASK); - updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.color[i] = ((codebuf >> 5) & vqColorMask); + updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits, + bufferVector); } } - VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0, - &Decode_Color); + vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0, + &decodeColor); break; @@ -1242,33 +1241,33 @@ class AstJpegDecoder { txb = (codebuf & 0x0FF00000) >> 20; tyb = (codebuf & 0x0FF000) >> 12; - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits, - buffer); - Decode_Color.BitMapBits = 2; + updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits, + bufferVector); + decodeColor.bitMapBits = 2; - for (unsigned char &i : Decode_Color.Index) { - i = ((codebuf >> 29) & VQ_INDEX_MASK); - if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) { - updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits, - buffer); + for (unsigned char &i : decodeColor.index) { + i = ((codebuf >> 29) & vqIndexMask); + if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) { + updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits, + bufferVector); } else { - Decode_Color.Color[i] = ((codebuf >> 5) & VQ_COLOR_MASK); - updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits, - buffer); + decodeColor.color[i] = ((codebuf >> 5) & vqColorMask); + updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits, + bufferVector); } } - VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0, - &Decode_Color); + vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0, + &decodeColor); break; case JpgBlock::JPEG_SKIP_PASS2_CODE: txb = (codebuf & 0x0FF00000) >> 20; tyb = (codebuf & 0x0FF000) >> 12; - updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits, - buffer); - Decompress_2PASS(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), - 2); + updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits, + bufferVector); + decompress2Pass(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), + 2); break; default: @@ -1276,22 +1275,22 @@ class AstJpegDecoder { return -1; break; } - MoveBlockIndex(); + moveBlockIndex(); - } while (buffer_index <= buffer.size()); + } while (bufferIndex <= bufferVector.size()); return -1; } #ifdef cimg_version void dump_to_bitmap_file() { - cimg_library::CImg<unsigned char> image(WIDTH, HEIGHT, 1, 3); - for (int y = 0; y < WIDTH; y++) { - for (int x = 0; x < HEIGHT; x++) { - auto pixel = OutBuffer[x + (y * WIDTH)]; - image(x, y, 0) = pixel.R; - image(x, y, 1) = pixel.G; - image(x, y, 2) = pixel.B; + cimg_library::CImg<unsigned char> image(width, height, 1, 3); + for (int y = 0; y < width; y++) { + for (int x = 0; x < height; x++) { + auto pixel = outBuffer[x + (y * width)]; + image(x, y, 0) = pixel.r; + image(x, y, 1) = pixel.g; + image(x, y, 2) = pixel.b; } } image.save("/tmp/file2.bmp"); @@ -1300,56 +1299,56 @@ class AstJpegDecoder { private: YuvMode yuvmode{}; - // WIDTH and HEIGHT are the modes your display used - unsigned long WIDTH{}; - unsigned long HEIGHT{}; - unsigned long USER_WIDTH{}; - unsigned long USER_HEIGHT{}; - unsigned char Y_selector{}; - int SCALEFACTOR; - int SCALEFACTORUV; - int ADVANCESCALEFACTOR; - int ADVANCESCALEFACTORUV; - int Mapping{}; - unsigned char UV_selector{}; - unsigned char advance_selector{}; - int byte_pos{}; // current byte position + // width and height are the modes your display used + unsigned long width{}; + unsigned long height{}; + unsigned long userWidth{}; + unsigned long userHeight{}; + unsigned char ySelector{}; + int scalefactor; + int scalefactoruv; + int advancescalefactor; + int advancescalefactoruv; + int mapping{}; + unsigned char uvSelector{}; + unsigned char advanceSelector{}; + int bytePos{}; // current byte position // quantization tables, no more than 4 quantization tables - std::array<std::array<long, 64>, 4> QT{}; + std::array<std::array<long, 64>, 4> qt{}; // DC huffman tables , no more than 4 (0..3) - std::array<Huffman_table, 4> HTDC{}; + std::array<HuffmanTable, 4> htdc{}; // AC huffman tables (0..3) - std::array<Huffman_table, 4> HTAC{}; - std::array<int, 256> m_CrToR{}; - std::array<int, 256> m_CbToB{}; - std::array<int, 256> m_CrToG{}; - std::array<int, 256> m_CbToG{}; - std::array<int, 256> m_Y{}; - unsigned long buffer_index{}; + std::array<HuffmanTable, 4> htac{}; + std::array<int, 256> mCrToR{}; + std::array<int, 256> mCbToB{}; + std::array<int, 256> mCrToG{}; + std::array<int, 256> mCbToG{}; + std::array<int, 256> mY{}; + unsigned long bufferIndex{}; uint32_t codebuf{}, newbuf{}, readbuf{}; - const unsigned char *std_luminance_qt{}; - const uint8_t *std_chrominance_qt{}; + const unsigned char *stdLuminanceQt{}; + const uint8_t *stdChrominanceQt{}; - signed short int DCY{}, DCCb{}, DCCr{}; // Coeficientii DC pentru Y,Cb,Cr - signed short int DCT_coeff[384]{}; - // std::vector<signed short int> DCT_coeff; // Current DCT_coefficients + signed short int dcy{}, dcCb{}, dcCr{}; // Coeficientii DC pentru Y,Cb,Cr + signed short int dctCoeff[384]{}; + // std::vector<signed short int> dctCoeff; // Current DCT_coefficients // quantization table number for Y, Cb, Cr - uint8_t YQ_nr = 0, CbQ_nr = 1, CrQ_nr = 1; + uint8_t yqNr = 0, cbQNr = 1, crQNr = 1; // DC Huffman table number for Y,Cb, Cr - uint8_t YDC_nr = 0, CbDC_nr = 1, CrDC_nr = 1; + uint8_t ydcNr = 0, cbDcNr = 1, crDcNr = 1; // AC Huffman table number for Y,Cb, Cr - uint8_t YAC_nr = 0, CbAC_nr = 1, CrAC_nr = 1; + uint8_t yacNr = 0, cbAcNr = 1, crAcNr = 1; int txb = 0; int tyb = 0; int newbits{}; - uint8_t *rlimit_table{}; - std::vector<RGB> YUVBuffer; + uint8_t *rlimitTable{}; + std::vector<RGB> yuvBuffer; // TODO(ed) this shouldn't exist. It is cruft that needs cleaning up - uint32_t *Buffer{}; + uint32_t *buffer{}; public: - std::vector<RGB> OutBuffer; + std::vector<RGB> outBuffer; }; -} // namespace AstVideo
\ No newline at end of file +} // namespace ast_video
\ No newline at end of file diff --git a/include/ast_video_puller.hpp b/include/ast_video_puller.hpp index 6cd7f37c35..c2ccea27c3 100644 --- a/include/ast_video_puller.hpp +++ b/include/ast_video_puller.hpp @@ -1,31 +1,31 @@ #pragma once -#include <cassert> #include <ast_video_types.hpp> +#include <cassert> #include <iostream> #include <mutex> #include <vector> #include <boost/asio.hpp> -namespace AstVideo { +namespace ast_video { // // Cursor struct is used in User Mode // -struct AST_CUR_ATTRIBUTION_TAG { +struct AstCurAttributionTag { unsigned int posX; unsigned int posY; - unsigned int cur_width; - unsigned int cur_height; - unsigned int cur_type; // 0:mono 1:color 2:disappear cursor - unsigned int cur_change_flag; + unsigned int curWidth; + unsigned int curHeight; + unsigned int curType; // 0:mono 1:color 2:disappear cursor + unsigned int curChangeFlag; }; // // For storing Cursor Information // -struct AST_CURSOR_TAG { - AST_CUR_ATTRIBUTION_TAG attr; +struct AstCursorTag { + AstCurAttributionTag attr; // unsigned char icon[MAX_CUR_OFFSETX*MAX_CUR_OFFSETY*2]; unsigned char *icon; //[64*64*2]; }; @@ -34,11 +34,11 @@ struct AST_CURSOR_TAG { // For select image format, i.e. 422 JPG420, 444 JPG444, lumin/chrom table, 0 // ~ 11, low to high // -struct FEATURES_TAG { - short jpg_fmt; // 422:JPG420, 444:JPG444 - short lumin_tbl; - short chrom_tbl; - short tolerance_noise; +struct FeaturesTag { + short jpgFmt; // 422:JPG420, 444:JPG444 + short luminTbl; + short chromTbl; + short toleranceNoise; int w; int h; unsigned char *buf; @@ -47,48 +47,48 @@ struct FEATURES_TAG { // // For configure video engine control registers // -struct IMAGE_INFO { - short do_image_refresh; // Action 0:motion 1:fullframe 2:quick cursor - char qc_valid; // quick cursor enable/disable +struct ImageInfo { + short doImageRefresh; // Action 0:motion 1:fullframe 2:quick cursor + char qcValid; // quick cursor enable/disable unsigned int len; int crypttype; char cryptkey[16]; union { - FEATURES_TAG features; - AST_CURSOR_TAG cursor_info; + FeaturesTag features; + AstCursorTag cursorInfo; } parameter; }; class SimpleVideoPuller { public: - SimpleVideoPuller() : image_info(){}; + SimpleVideoPuller() : imageInfo(){}; void initialize() { std::cout << "Opening /dev/video\n"; - video_fd = open("/dev/video", O_RDWR); - if (video_fd == 0) { + videoFd = open("/dev/video", O_RDWR); + if (videoFd == 0) { std::cout << "Failed to open /dev/video\n"; throw std::runtime_error("Failed to open /dev/video"); } std::cout << "Opened successfully\n"; } - RawVideoBuffer read_video() { - assert(video_fd != 0); + RawVideoBuffer readVideo() { + assert(videoFd != 0); RawVideoBuffer raw; - image_info.do_image_refresh = 1; // full frame refresh - image_info.qc_valid = 0; // quick cursor disabled - image_info.parameter.features.buf = + imageInfo.doImageRefresh = 1; // full frame refresh + imageInfo.qcValid = 0; // quick cursor disabled + imageInfo.parameter.features.buf = reinterpret_cast<unsigned char *>(raw.buffer.data()); - image_info.crypttype = -1; + imageInfo.crypttype = -1; std::cout << "Writing\n"; int status; /* - status = write(video_fd, reinterpret_cast<char*>(&image_info), - sizeof(image_info)); - if (status != sizeof(image_info)) { + status = write(videoFd, reinterpret_cast<char*>(&imageInfo), + sizeof(imageInfo)); + if (status != sizeof(imageInfo)) { std::cout << "Write failed. Return: " << status << "\n"; perror("perror output:"); } @@ -96,19 +96,19 @@ class SimpleVideoPuller { std::cout << "Write done\n"; */ std::cout << "Reading\n"; - status = read(video_fd, reinterpret_cast<char *>(&image_info), - sizeof(image_info)); + status = + read(videoFd, reinterpret_cast<char *>(&imageInfo), sizeof(imageInfo)); std::cout << "Done reading\n"; if (status != 0) { std::cerr << "Read failed with status " << status << "\n"; } - raw.buffer.resize(image_info.len); + raw.buffer.resize(imageInfo.len); - raw.height = image_info.parameter.features.h; - raw.width = image_info.parameter.features.w; - if (image_info.parameter.features.jpg_fmt == 422) { + raw.height = imageInfo.parameter.features.h; + raw.width = imageInfo.parameter.features.w; + if (imageInfo.parameter.features.jpgFmt == 422) { raw.mode = YuvMode::YUV420; } else { raw.mode = YuvMode::YUV444; @@ -117,57 +117,58 @@ class SimpleVideoPuller { } private: - int video_fd{}; - IMAGE_INFO image_info; + int videoFd{}; + ImageInfo imageInfo; }; #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) class AsyncVideoPuller { public: - using video_callback = std::function<void (RawVideoBuffer &)>; + using video_callback = std::function<void(RawVideoBuffer &)>; - explicit AsyncVideoPuller(boost::asio::io_service &io_service) - : image_info(), dev_video(io_service, open("/dev/video", O_RDWR)) { + explicit AsyncVideoPuller(boost::asio::io_service &ioService) + : imageInfo(), devVideo(ioService, open("/dev/video", O_RDWR)) { videobuf = std::make_shared<RawVideoBuffer>(); - image_info.do_image_refresh = 1; // full frame refresh - image_info.qc_valid = 0; // quick cursor disabled - image_info.parameter.features.buf = + imageInfo.doImageRefresh = 1; // full frame refresh + imageInfo.qcValid = 0; // quick cursor disabled + imageInfo.parameter.features.buf = reinterpret_cast<unsigned char *>(videobuf->buffer.data()); - image_info.crypttype = -1; + imageInfo.crypttype = -1; }; - void register_callback(video_callback &callback) { - std::lock_guard<std::mutex> lock(callback_mutex); + void registerCallback(video_callback &callback) { + std::lock_guard<std::mutex> lock(callbackMutex); callbacks.push_back(callback); - start_read(); + startRead(); } - void start_read() { - auto mutable_buffer = boost::asio::buffer(&image_info, sizeof(image_info)); - boost::asio::async_read( - dev_video, mutable_buffer, [this](const boost::system::error_code &ec, - std::size_t bytes_transferred) { - if (ec) { - std::cerr << "Read failed with status " << ec << "\n"; - } else { - this->read_done(); - } - }); + void startRead() { + auto mutableBuffer = boost::asio::buffer(&imageInfo, sizeof(imageInfo)); + boost::asio::async_read(devVideo, mutableBuffer, + [this](const boost::system::error_code &ec, + std::size_t bytes_transferred) { + if (ec) { + std::cerr << "Read failed with status " << ec + << "\n"; + } else { + this->readDone(); + } + }); } - void read_done() { + void readDone() { std::cout << "Done reading\n"; - videobuf->buffer.resize(image_info.len); + videobuf->buffer.resize(imageInfo.len); - videobuf->height = image_info.parameter.features.h; - videobuf->width = image_info.parameter.features.w; - if (image_info.parameter.features.jpg_fmt == 422) { + videobuf->height = imageInfo.parameter.features.h; + videobuf->width = imageInfo.parameter.features.w; + if (imageInfo.parameter.features.jpgFmt == 422) { videobuf->mode = YuvMode::YUV420; } else { videobuf->mode = YuvMode::YUV444; } - std::lock_guard<std::mutex> lock(callback_mutex); + std::lock_guard<std::mutex> lock(callbackMutex); for (auto &callback : callbacks) { // TODO(ed) call callbacks async and double buffer frames callback(*videobuf); @@ -176,10 +177,10 @@ class AsyncVideoPuller { private: std::shared_ptr<RawVideoBuffer> videobuf; - boost::asio::posix::stream_descriptor dev_video; - IMAGE_INFO image_info; - std::mutex callback_mutex; + boost::asio::posix::stream_descriptor devVideo; + ImageInfo imageInfo; + std::mutex callbackMutex; std::vector<video_callback> callbacks; }; #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) -} // namespace AstVideo +} // namespace ast_video diff --git a/include/ast_video_types.hpp b/include/ast_video_types.hpp index f5cfffd1e5..f9801460e6 100644 --- a/include/ast_video_types.hpp +++ b/include/ast_video_types.hpp @@ -2,7 +2,7 @@ #include <cstdint> #include <vector> -namespace AstVideo { +namespace ast_video { enum class YuvMode { YUV444 = 0, YUV420 = 1 }; class RawVideoBuffer { @@ -10,10 +10,10 @@ class RawVideoBuffer { RawVideoBuffer() : buffer(1024 * 1024 * 10, 0){}; unsigned long height{}; unsigned long width{}; - int y_selector{}; - int uv_selector{}; + int ySelector{}; + int uvSelector{}; YuvMode mode; // TODO(ed) determine a more appropriate buffer size std::vector<uint32_t> buffer; }; -} // namespace AstVideo
\ No newline at end of file +} // namespace ast_video
\ No newline at end of file diff --git a/include/dbus_monitor.hpp b/include/dbus_monitor.hpp index ab7ebef928..43385e6571 100644 --- a/include/dbus_monitor.hpp +++ b/include/dbus_monitor.hpp @@ -11,65 +11,64 @@ struct DbusWebsocketSession { std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches; }; -static boost::container::flat_map<crow::websocket::connection*, +static boost::container::flat_map<crow::websocket::Connection*, DbusWebsocketSession> sessions; -int on_property_update(sd_bus_message* m, void* userdata, - sd_bus_error* ret_error) { +int onPropertyUpdate(sd_bus_message* m, void* userdata, + sd_bus_error* ret_error) { if (ret_error == nullptr || sd_bus_error_is_set(ret_error)) { - CROW_LOG_ERROR << "Sdbus error in on_property_update"; + BMCWEB_LOG_ERROR << "Sdbus error in on_property_update"; return 0; } sdbusplus::message::message message(m); - std::string object_name; + std::string objectName; std::vector< std::pair<std::string, sdbusplus::message::variant< std::string, bool, int64_t, uint64_t, double>>> values; - message.read(object_name, values); + message.read(objectName, values); nlohmann::json j; const std::string& path = message.get_path(); for (auto& value : values) { mapbox::util::apply_visitor([&](auto&& val) { j[path] = val; }, value.second); } - std::string data_to_send = j.dump(); + std::string dataToSend = j.dump(); - for (const std::pair<crow::websocket::connection*, DbusWebsocketSession>& + for (const std::pair<crow::websocket::Connection*, DbusWebsocketSession>& session : sessions) { - session.first->send_text(data_to_send); + session.first->sendText(dataToSend); } }; template <typename... Middlewares> -void request_routes(Crow<Middlewares...>& app) { - CROW_ROUTE(app, "/dbus_monitor") +void requestRoutes(Crow<Middlewares...>& app) { + BMCWEB_ROUTE(app, "/dbus_monitor") .websocket() - .onopen([&](crow::websocket::connection& conn) { - std::string path_namespace(conn.req.url_params.get("path_namespace")); - if (path_namespace.empty()) { - conn.send_text( + .onopen([&](crow::websocket::Connection& conn) { + std::string pathNamespace(conn.req.urlParams.get("path_namespace")); + if (pathNamespace.empty()) { + conn.sendText( nlohmann::json({"error", "Did not specify path_namespace"})); conn.close("error"); } sessions[&conn] = DbusWebsocketSession(); - std::string match_string( + std::string matchString( "type='signal'," "interface='org.freedesktop.DBus.Properties'," "path_namespace='" + - path_namespace + "'"); + pathNamespace + "'"); sessions[&conn].matches.emplace_back( std::make_unique<sdbusplus::bus::match::match>( - *crow::connections::system_bus, match_string, - on_property_update)); + *crow::connections::systemBus, matchString, onPropertyUpdate)); }) - .onclose([&](crow::websocket::connection& conn, + .onclose([&](crow::websocket::Connection& conn, const std::string& reason) { sessions.erase(&conn); }) - .onmessage([&](crow::websocket::connection& conn, const std::string& data, + .onmessage([&](crow::websocket::Connection& conn, const std::string& data, bool is_binary) { - CROW_LOG_ERROR << "Got unexpected message from client on sensorws"; + BMCWEB_LOG_ERROR << "Got unexpected message from client on sensorws"; }); } } // namespace dbus_monitor diff --git a/include/dbus_singleton.hpp b/include/dbus_singleton.hpp index e6be81b373..a4a16bb2d1 100644 --- a/include/dbus_singleton.hpp +++ b/include/dbus_singleton.hpp @@ -4,7 +4,7 @@ namespace mapbox { template <typename T, typename... Types> -const T* get_ptr(const mapbox::util::variant<Types...>& v) { +const T* getPtr(const mapbox::util::variant<Types...>& v) { if (v.template is<std::remove_const_t<T>>()) { return &v.template get_unchecked<std::remove_const_t<T>>(); } else { @@ -15,7 +15,7 @@ const T* get_ptr(const mapbox::util::variant<Types...>& v) { namespace crow { namespace connections { -static std::shared_ptr<sdbusplus::asio::connection> system_bus; +static std::shared_ptr<sdbusplus::asio::connection> systemBus; } // namespace connections } // namespace crow diff --git a/include/gzip_helper.hpp b/include/gzip_helper.hpp index 9b7d253a25..e577c1ffd1 100644 --- a/include/gzip_helper.hpp +++ b/include/gzip_helper.hpp @@ -4,8 +4,8 @@ #include <cstring> #include <string> -inline bool gzip_inflate(const std::string& compressedBytes, - std::string& uncompressedBytes) { +inline bool gzipInflate(const std::string& compressedBytes, + std::string& uncompressedBytes) { if (compressedBytes.empty()) { uncompressedBytes = compressedBytes; return true; diff --git a/include/http_utility.hpp b/include/http_utility.hpp index 7b04b0f036..f2d317206a 100644 --- a/include/http_utility.hpp +++ b/include/http_utility.hpp @@ -2,8 +2,8 @@ #include <boost/algorithm/string.hpp> namespace http_helpers { -inline bool request_prefers_html(const crow::request& req) { - boost::string_view header = req.get_header_value("accept"); +inline bool requestPrefersHtml(const crow::Request& req) { + boost::string_view header = req.getHeaderValue("accept"); std::vector<std::string> encodings; // chrome currently sends 6 accepts headers, firefox sends 4. encodings.reserve(6); diff --git a/include/image_upload.hpp b/include/image_upload.hpp index 2a959677df..df5c1ae491 100644 --- a/include/image_upload.hpp +++ b/include/image_upload.hpp @@ -14,17 +14,17 @@ namespace image_upload { std::unique_ptr<sdbusplus::bus::match::match> fwUpdateMatcher; -inline void uploadImageHandler(const crow::request& req, crow::response& res, +inline void uploadImageHandler(const crow::Request& req, crow::Response& res, const std::string& filename) { // Only allow one FW update at a time if (fwUpdateMatcher != nullptr) { - res.add_header("Retry-After", "30"); + res.addHeader("Retry-After", "30"); res.result(boost::beast::http::status::service_unavailable); res.end(); return; } // Make this const static so it survives outside this method - static boost::asio::deadline_timer timeout(*req.io_service, + static boost::asio::deadline_timer timeout(*req.ioService, boost::posix_time::seconds(5)); timeout.expires_from_now(boost::posix_time::seconds(5)); @@ -35,10 +35,10 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res, // expected, we were canceled before the timer completed. return; } - CROW_LOG_ERROR << "Timed out waiting for log event"; + BMCWEB_LOG_ERROR << "Timed out waiting for log event"; if (ec) { - CROW_LOG_ERROR << "Async_wait failed " << ec; + BMCWEB_LOG_ERROR << "Async_wait failed " << ec; return; } @@ -48,11 +48,11 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res, std::function<void(sdbusplus::message::message&)> callback = [&res](sdbusplus::message::message& m) { - CROW_LOG_DEBUG << "Match fired"; + BMCWEB_LOG_DEBUG << "Match fired"; boost::system::error_code ec; timeout.cancel(ec); if (ec) { - CROW_LOG_ERROR << "error canceling timer " << ec; + BMCWEB_LOG_ERROR << "error canceling timer " << ec; } std::string versionInfo; m.read(versionInfo); // Read in the object path that was just created @@ -61,15 +61,15 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res, if (index != std::string::npos) { versionInfo.erase(0, index); } - res.json_value = {{"data", std::move(versionInfo)}, - {"message", "200 OK"}, - {"status", "ok"}}; - CROW_LOG_DEBUG << "ending response"; + res.jsonValue = {{"data", std::move(versionInfo)}, + {"message", "200 OK"}, + {"status", "ok"}}; + BMCWEB_LOG_DEBUG << "ending response"; res.end(); fwUpdateMatcher = nullptr; }; fwUpdateMatcher = std::make_unique<sdbusplus::bus::match::match>( - *crow::connections::system_bus, + *crow::connections::systemBus, "interface='org.freedesktop.DBus.ObjectManager',type='signal'," "member='InterfacesAdded',path='/xyz/openbmc_project/logging'", callback); @@ -77,7 +77,7 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res, std::string filepath( "/tmp/images/" + boost::uuids::to_string(boost::uuids::random_generator()())); - CROW_LOG_DEBUG << "Writing file to " << filepath; + BMCWEB_LOG_DEBUG << "Writing file to " << filepath; std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc); out << req.body; @@ -86,16 +86,16 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res, template <typename... Middlewares> void requestRoutes(Crow<Middlewares...>& app) { - CROW_ROUTE(app, "/upload/image/<str>") + BMCWEB_ROUTE(app, "/upload/image/<str>") .methods("POST"_method, - "PUT"_method)([](const crow::request& req, crow::response& res, + "PUT"_method)([](const crow::Request& req, crow::Response& res, const std::string& filename) { uploadImageHandler(req, res, filename); }); - CROW_ROUTE(app, "/upload/image") + BMCWEB_ROUTE(app, "/upload/image") .methods("POST"_method, - "PUT"_method)([](const crow::request& req, crow::response& res) { + "PUT"_method)([](const crow::Request& req, crow::Response& res) { uploadImageHandler(req, res, ""); }); } diff --git a/include/openbmc_dbus_rest.hpp b/include/openbmc_dbus_rest.hpp index c10148e783..1f3b9e29bd 100644 --- a/include/openbmc_dbus_rest.hpp +++ b/include/openbmc_dbus_rest.hpp @@ -10,41 +10,41 @@ namespace crow { namespace openbmc_mapper { -void introspect_objects(crow::response &res, std::string process_name, - std::string path, - std::shared_ptr<nlohmann::json> transaction) { - crow::connections::system_bus->async_method_call( +void introspectObjects(crow::Response &res, std::string process_name, + std::string path, + std::shared_ptr<nlohmann::json> transaction) { + crow::connections::systemBus->async_method_call( [ - &res, transaction, process_name{std::move(process_name)}, - object_path{std::move(path)} + &res, transaction, processName{std::move(process_name)}, + objectPath{std::move(path)} ](const boost::system::error_code ec, const std::string &introspect_xml) { if (ec) { - CROW_LOG_ERROR << "Introspect call failed with error: " - << ec.message() << " on process: " << process_name - << " path: " << object_path << "\n"; + BMCWEB_LOG_ERROR << "Introspect call failed with error: " + << ec.message() << " on process: " << processName + << " path: " << objectPath << "\n"; } else { - transaction->push_back({{"path", object_path}}); + transaction->push_back({{"path", objectPath}}); tinyxml2::XMLDocument doc; doc.Parse(introspect_xml.c_str()); tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node"); if (pRoot == nullptr) { - CROW_LOG_ERROR << "XML document failed to parse " << process_name - << " " << object_path << "\n"; + BMCWEB_LOG_ERROR << "XML document failed to parse " << processName + << " " << objectPath << "\n"; } else { tinyxml2::XMLElement *node = pRoot->FirstChildElement("node"); while (node != nullptr) { - std::string child_path = node->Attribute("name"); + std::string childPath = node->Attribute("name"); std::string newpath; - if (object_path != "/") { - newpath += object_path; + if (objectPath != "/") { + newpath += objectPath; } - newpath += "/" + child_path; + newpath += "/" + childPath; // introspect the subobjects as well - introspect_objects(res, process_name, newpath, transaction); + introspectObjects(res, processName, newpath, transaction); node = node->NextSiblingElement("node"); } @@ -52,8 +52,8 @@ void introspect_objects(crow::response &res, std::string process_name, } // if we're the last outstanding caller, finish the request if (transaction.use_count() == 1) { - res.json_value = {{"status", "ok"}, - {"bus_name", process_name}, + res.jsonValue = {{"status", "ok"}, + {"bus_name", processName}, {"objects", std::move(*transaction)}}; res.end(); } @@ -74,39 +74,38 @@ using ManagedObjectType = std::vector<std::pair< std::string, boost::container::flat_map<std::string, DbusRestVariantType>>>>; -void get_managed_objects_for_enumerate( +void getManagedObjectsForEnumerate( const std::string &object_name, const std::string &connection_name, - crow::response &res, std::shared_ptr<nlohmann::json> transaction) { - crow::connections::system_bus->async_method_call( + crow::Response &res, std::shared_ptr<nlohmann::json> transaction) { + crow::connections::systemBus->async_method_call( [&res, transaction](const boost::system::error_code ec, const ManagedObjectType &objects) { if (ec) { - CROW_LOG_ERROR << ec; + BMCWEB_LOG_ERROR << ec; } else { - nlohmann::json &data_json = *transaction; - - for (auto &object_path : objects) { - CROW_LOG_DEBUG << "Reading object " - << static_cast<const std::string &>( - object_path.first); - nlohmann::json &object_json = - data_json[static_cast<const std::string &>(object_path.first)]; - if (object_json.is_null()) { - object_json = nlohmann::json::object(); + nlohmann::json &dataJson = *transaction; + + for (auto &objectPath : objects) { + BMCWEB_LOG_DEBUG + << "Reading object " + << static_cast<const std::string &>(objectPath.first); + nlohmann::json &objectJson = + dataJson[static_cast<const std::string &>(objectPath.first)]; + if (objectJson.is_null()) { + objectJson = nlohmann::json::object(); } - for (const auto &interface : object_path.second) { + for (const auto &interface : objectPath.second) { for (const auto &property : interface.second) { - nlohmann::json &property_json = object_json[property.first]; + nlohmann::json &propertyJson = objectJson[property.first]; mapbox::util::apply_visitor( - [&property_json](auto &&val) { property_json = val; }, + [&propertyJson](auto &&val) { propertyJson = val; }, property.second); // dbus-rest represents booleans as 1 or 0, implement to match // TODO(ed) see if dbus-rest should be changed - const bool *property_bool = - property_json.get_ptr<const bool *>(); - if (property_bool != nullptr) { - property_json = *property_bool ? 1 : 0; + const bool *propertyBool = propertyJson.get_ptr<const bool *>(); + if (propertyBool != nullptr) { + propertyJson = *propertyBool ? 1 : 0; } } } @@ -114,9 +113,9 @@ void get_managed_objects_for_enumerate( } if (transaction.use_count() == 1) { - res.json_value = {{"message", "200 OK"}, - {"status", "ok"}, - {"data", std::move(*transaction)}}; + res.jsonValue = {{"message", "200 OK"}, + {"status", "ok"}, + {"data", std::move(*transaction)}}; res.end(); } }, @@ -130,13 +129,13 @@ using GetSubTreeType = std::vector< // Structure for storing data on an in progress action struct InProgressActionData { - InProgressActionData(crow::response &res) : res(res){}; + InProgressActionData(crow::Response &res) : res(res){}; ~InProgressActionData() { if (res.result() == boost::beast::http::status::internal_server_error) { // Reset the json object to clear out any data that made it in before the // error happened // todo(ed) handle error condition with proper code - res.json_value = nlohmann::json::object(); + res.jsonValue = nlohmann::json::object(); } res.end(); } @@ -144,7 +143,7 @@ struct InProgressActionData { void setErrorStatus() { res.result(boost::beast::http::status::internal_server_error); } - crow::response &res; + crow::Response &res; std::string path; std::string method_name; nlohmann::json arguments; @@ -198,7 +197,7 @@ std::vector<std::string> dbus_arg_split(const std::string &string) { int convert_json_to_dbus(sd_bus_message *m, const std::string &arg_type, const nlohmann::json &input_json) { int r = 0; - CROW_LOG_DEBUG << "Converting " << input_json.dump() + BMCWEB_LOG_DEBUG << "Converting " << input_json.dump() << " to type: " << arg_type; const std::vector<std::string> arg_types = dbus_arg_split(arg_type); @@ -335,7 +334,7 @@ int convert_json_to_dbus(sd_bus_message *m, const std::string &arg_type, sd_bus_message_close_container(m); } else if (boost::starts_with(arg_code, "v")) { std::string contained_type = arg_code.substr(1); - CROW_LOG_DEBUG << "variant type: " << arg_code + BMCWEB_LOG_DEBUG << "variant type: " << arg_code << " appending variant of type: " << contained_type; r = sd_bus_message_open_container(m, SD_BUS_TYPE_VARIANT, contained_type.c_str()); @@ -408,15 +407,15 @@ int convert_json_to_dbus(sd_bus_message *m, const std::string &arg_type, void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction, const std::string &connectionName) { - CROW_LOG_DEBUG << "find_action_on_interface for connection " + BMCWEB_LOG_DEBUG << "find_action_on_interface for connection " << connectionName; - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( [ transaction, connectionName{std::string(connectionName)} ](const boost::system::error_code ec, const std::string &introspect_xml) { - CROW_LOG_DEBUG << "got xml:\n " << introspect_xml; + BMCWEB_LOG_DEBUG << "got xml:\n " << introspect_xml; if (ec) { - CROW_LOG_ERROR << "Introspect call failed with error: " + BMCWEB_LOG_ERROR << "Introspect call failed with error: " << ec.message() << " on process: " << connectionName << "\n"; } else { @@ -425,7 +424,7 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction, doc.Parse(introspect_xml.c_str()); tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node"); if (pRoot == nullptr) { - CROW_LOG_ERROR << "XML document failed to parse " << connectionName + BMCWEB_LOG_ERROR << "XML document failed to parse " << connectionName << "\n"; } else { @@ -438,10 +437,10 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction, interface_node->FirstChildElement("method"); while (method_node != nullptr) { std::string this_method_name = method_node->Attribute("name"); - CROW_LOG_DEBUG << "Found method: " << this_method_name; + BMCWEB_LOG_DEBUG << "Found method: " << this_method_name; if (this_method_name == transaction->method_name) { sdbusplus::message::message m = - crow::connections::system_bus->new_method_call( + crow::connections::systemBus->new_method_call( connectionName.c_str(), transaction->path.c_str(), this_interface_name.c_str(), transaction->method_name.c_str()); @@ -471,14 +470,14 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction, } argument_node = method_node->NextSiblingElement("arg"); } - crow::connections::system_bus->async_send( + crow::connections::systemBus->async_send( m, [transaction](boost::system::error_code ec, sdbusplus::message::message &m) { if (ec) { transaction->setErrorStatus(); return; } - transaction->res.json_value = {{"status", "ok"}, + transaction->res.jsonValue = {{"status", "ok"}, {"message", "200 OK"}, {"data", nullptr}}; }); @@ -495,7 +494,7 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction, "Introspect"); } -void handle_action(const crow::request &req, crow::response &res, +void handle_action(const crow::Request &req, crow::Response &res, const std::string &object_path, const std::string &method_name) { nlohmann::json request_dbus_data = @@ -516,7 +515,7 @@ void handle_action(const crow::request &req, crow::response &res, transaction->path = object_path; transaction->method_name = method_name; transaction->arguments = std::move(request_dbus_data); - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( [transaction]( const boost::system::error_code ec, const std::vector<std::pair<std::string, std::vector<std::string>>> @@ -526,7 +525,7 @@ void handle_action(const crow::request &req, crow::response &res, return; } - CROW_LOG_DEBUG << "GetObject returned objects " + BMCWEB_LOG_DEBUG << "GetObject returned objects " << interface_names.size(); for (const std::pair<std::string, std::vector<std::string>> &object : @@ -539,31 +538,31 @@ void handle_action(const crow::request &req, crow::response &res, std::array<std::string, 0>()); } -void handle_list(crow::response &res, const std::string &object_path) { - crow::connections::system_bus->async_method_call( +void handle_list(crow::Response &res, const std::string &objectPath) { + crow::connections::systemBus->async_method_call( [&res](const boost::system::error_code ec, - std::vector<std::string> &object_paths) { + std::vector<std::string> &objectPaths) { if (ec) { res.result(boost::beast::http::status::internal_server_error); } else { - res.json_value = {{"status", "ok"}, + res.jsonValue = {{"status", "ok"}, {"message", "200 OK"}, - {"data", std::move(object_paths)}}; + {"data", std::move(objectPaths)}}; } res.end(); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", - "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", object_path, + "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", objectPath, static_cast<int32_t>(99), std::array<std::string, 0>()); } -void handle_enumerate(crow::response &res, const std::string &object_path) { - crow::connections::system_bus->async_method_call( - [&res, object_path{std::string(object_path)} ]( +void handle_enumerate(crow::Response &res, const std::string &objectPath) { + crow::connections::systemBus->async_method_call( + [&res, objectPath{std::string(objectPath)} ]( const boost::system::error_code ec, const GetSubTreeType &object_names) { if (ec) { - res.json_value = {{"message", "200 OK"}, + res.jsonValue = {{"message", "200 OK"}, {"status", "ok"}, {"data", nlohmann::json::object()}}; @@ -574,8 +573,8 @@ void handle_enumerate(crow::response &res, const std::string &object_path) { boost::container::flat_set<std::string> connections; for (const auto &object : object_names) { - for (const auto &connection : object.second) { - connections.insert(connection.first); + for (const auto &Connection : object.second) { + connections.insert(Connection.first); } } @@ -586,25 +585,26 @@ void handle_enumerate(crow::response &res, const std::string &object_path) { } auto transaction = std::make_shared<nlohmann::json>(nlohmann::json::object()); - for (const std::string &connection : connections) { - get_managed_objects_for_enumerate(object_path, connection, res, - transaction); + for (const std::string &Connection : connections) { + getManagedObjectsForEnumerate(objectPath, Connection, res, + transaction); } }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", - "xyz.openbmc_project.ObjectMapper", "GetSubTree", object_path, (int32_t)0, + "xyz.openbmc_project.ObjectMapper", "GetSubTree", objectPath, (int32_t)0, std::array<std::string, 0>()); } -void handle_get(crow::response &res, const std::string &object_path, - const std::string &dest_property) { +void handle_get(crow::Response &res, std::string &object_path, + std::string &dest_property) { + BMCWEB_LOG_DEBUG << "handle_get: " << object_path << " prop:" << dest_property; std::shared_ptr<std::string> property_name = std::make_shared<std::string>(dest_property); using GetObjectType = std::vector<std::pair<std::string, std::vector<std::string>>>; - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( [&res, object_path, property_name](const boost::system::error_code ec, - const GetObjectType &object_names) { + const GetObjectType &object_names) { if (ec || object_names.size() <= 0) { res.result(boost::beast::http::status::not_found); res.end(); @@ -625,13 +625,13 @@ void handle_get(crow::response &res, const std::string &object_path, } for (const std::string &interface : interfaceNames) { - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( [&res, response, property_name]( const boost::system::error_code ec, const std::vector<std::pair< std::string, DbusRestVariantType>> &properties) { if (ec) { - CROW_LOG_ERROR << "Bad dbus request error: " << ec; + BMCWEB_LOG_ERROR << "Bad dbus request error: " << ec; } else { for (const std::pair<std::string, DbusRestVariantType> &property : properties) { @@ -652,7 +652,7 @@ void handle_get(crow::response &res, const std::string &object_path, } } if (response.use_count() == 1) { - res.json_value = {{"status", "ok"}, + res.jsonValue = {{"status", "ok"}, {"message", "200 OK"}, {"data", *response}}; @@ -670,8 +670,8 @@ void handle_get(crow::response &res, const std::string &object_path, } struct AsyncPutRequest { - AsyncPutRequest(crow::response &res) : res(res) { - res.json_value = { + AsyncPutRequest(crow::Response &res) : res(res) { + res.jsonValue = { {"status", "ok"}, {"message", "200 OK"}, {"data", nullptr}}; } ~AsyncPutRequest() { @@ -679,12 +679,12 @@ struct AsyncPutRequest { // Reset the json object to clear out any data that made it in before the // error happened // todo(ed) handle error condition with proper code - res.json_value = nlohmann::json::object(); + res.jsonValue = nlohmann::json::object(); } - if (res.json_value.empty()) { + if (res.jsonValue.empty()) { res.result(boost::beast::http::status::forbidden); - res.json_value = { + res.jsonValue = { {"status", "error"}, {"message", "403 Forbidden"}, {"data", @@ -699,13 +699,13 @@ struct AsyncPutRequest { res.result(boost::beast::http::status::internal_server_error); } - crow::response &res; + crow::Response &res; std::string objectPath; std::string propertyName; nlohmann::json propertyValue; }; -void handle_put(const crow::request &req, crow::response &res, +void handle_put(const crow::Request &req, crow::Response &res, const std::string &objectPath, const std::string &destProperty) { nlohmann::json request_dbus_data = @@ -732,7 +732,7 @@ void handle_put(const crow::request &req, crow::response &res, using GetObjectType = std::vector<std::pair<std::string, std::vector<std::string>>>; - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( [transaction](const boost::system::error_code ec, const GetObjectType &object_names) { if (!ec && object_names.size() <= 0) { @@ -744,12 +744,12 @@ void handle_put(const crow::request &req, crow::response &res, object_names) { const std::string &connectionName = connection.first; - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( [ connectionName{std::string(connectionName)}, transaction ]( const boost::system::error_code ec, const std::string &introspectXml) { if (ec) { - CROW_LOG_ERROR + BMCWEB_LOG_ERROR << "Introspect call failed with error: " << ec.message() << " on process: " << connectionName; transaction->setErrorStatus(); @@ -760,7 +760,7 @@ void handle_put(const crow::request &req, crow::response &res, doc.Parse(introspectXml.c_str()); tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node"); if (pRoot == nullptr) { - CROW_LOG_ERROR << "XML document failed to parse: " + BMCWEB_LOG_ERROR << "XML document failed to parse: " << introspectXml; transaction->setErrorStatus(); return; @@ -769,17 +769,17 @@ void handle_put(const crow::request &req, crow::response &res, pRoot->FirstChildElement("interface"); while (ifaceNode != nullptr) { const char *interfaceName = ifaceNode->Attribute("name"); - CROW_LOG_DEBUG << "found interface " << interfaceName; + BMCWEB_LOG_DEBUG << "found interface " << interfaceName; tinyxml2::XMLElement *propNode = ifaceNode->FirstChildElement("property"); while (propNode != nullptr) { const char *propertyName = propNode->Attribute("name"); - CROW_LOG_DEBUG << "Found property " << propertyName; + BMCWEB_LOG_DEBUG << "Found property " << propertyName; if (propertyName == transaction->propertyName) { const char *argType = propNode->Attribute("type"); if (argType != nullptr) { sdbusplus::message::message m = - crow::connections::system_bus->new_method_call( + crow::connections::systemBus->new_method_call( connectionName.c_str(), transaction->objectPath.c_str(), "org.freedesktop.DBus.Properties", "Set"); @@ -802,13 +802,13 @@ void handle_put(const crow::request &req, crow::response &res, return; } - crow::connections::system_bus->async_send( + crow::connections::systemBus->async_send( m, [transaction](boost::system::error_code ec, sdbusplus::message::message &m) { - CROW_LOG_DEBUG << "sent"; + BMCWEB_LOG_DEBUG << "sent"; if (ec) { - transaction->res.json_value["status"] = "error"; - transaction->res.json_value["message"] = + transaction->res.jsonValue["status"] = "error"; + transaction->res.jsonValue["message"] = ec.message(); } }); @@ -829,43 +829,44 @@ void handle_put(const crow::request &req, crow::response &res, } template <typename... Middlewares> -void request_routes(Crow<Middlewares...> &app) { - CROW_ROUTE(app, "/bus/") - .methods("GET"_method)([](const crow::request &req, crow::response &res) { - res.json_value = {{"busses", {{{"name", "system"}}}}, {"status", "ok"}}; +void requestRoutes(Crow<Middlewares...> &app) { + BMCWEB_ROUTE(app, "/bus/") + .methods("GET"_method)([](const crow::Request &req, crow::Response &res) { + res.jsonValue = {{"busses", {{{"name", "system"}}}}, {"status", "ok"}}; }); - CROW_ROUTE(app, "/bus/system/") - .methods("GET"_method)([](const crow::request &req, crow::response &res) { + BMCWEB_ROUTE(app, "/bus/system/") + .methods("GET"_method)([](const crow::Request &req, crow::Response &res) { + auto myCallback = [&res](const boost::system::error_code ec, std::vector<std::string> &names) { if (ec) { - CROW_LOG_ERROR << "Dbus call failed with code " << ec; + BMCWEB_LOG_ERROR << "Dbus call failed with code " << ec; res.result(boost::beast::http::status::internal_server_error); } else { std::sort(names.begin(), names.end()); nlohmann::json j{{"status", "ok"}}; - auto &objects_sub = j["objects"]; + auto &objectsSub = j["objects"]; for (auto &name : names) { - objects_sub.push_back({{"name", name}}); + objectsSub.push_back({{"name", name}}); } - res.json_value = std::move(j); + res.jsonValue = std::move(j); } res.end(); }; - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( std::move(myCallback), "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames"); }); - CROW_ROUTE(app, "/list/") - .methods("GET"_method)([](const crow::request &req, crow::response &res) { + BMCWEB_ROUTE(app, "/list/") + .methods("GET"_method)([](const crow::Request &req, crow::Response &res) { handle_list(res, "/"); }); - CROW_ROUTE(app, "/xyz/<path>") + BMCWEB_ROUTE(app, "/xyz/<path>") .methods("GET"_method, "PUT"_method, - "POST"_method)([](const crow::request &req, crow::response &res, + "POST"_method)([](const crow::Request &req, crow::Response &res, const std::string &path) { std::string object_path = "/xyz/" + path; @@ -915,15 +916,15 @@ void request_routes(Crow<Middlewares...> &app) { res.end(); }); - CROW_ROUTE(app, "/bus/system/<str>/") - .methods("GET"_method)([](const crow::request &req, crow::response &res, - const std::string &connection) { + BMCWEB_ROUTE(app, "/bus/system/<str>/") + .methods("GET"_method)([](const crow::Request &req, crow::Response &res, + const std::string &Connection) { std::shared_ptr<nlohmann::json> transaction; - introspect_objects(res, connection, "/", transaction); + introspectObjects(res, Connection, "/", transaction); }); - CROW_ROUTE(app, "/download/dump/<str>/") - .methods("GET"_method)([](const crow::request &req, crow::response &res, + BMCWEB_ROUTE(app, "/download/dump/<str>/") + .methods("GET"_method)([](const crow::Request &req, crow::Response &res, const std::string &dumpId) { std::regex validFilename("^[\\w\\- ]+(\\.?[\\w\\- ]+)$"); if (!std::regex_match(dumpId, validFilename)) { @@ -948,7 +949,7 @@ void request_routes(Crow<Middlewares...> &app) { if (readFile.good()) { continue; } - res.add_header("Content-Type", "application/octet-stream"); + res.addHeader("Content-Type", "application/octet-stream"); res.body() = {std::istreambuf_iterator<char>(readFile), std::istreambuf_iterator<char>()}; res.end(); @@ -958,18 +959,18 @@ void request_routes(Crow<Middlewares...> &app) { return; }); - CROW_ROUTE(app, "/bus/system/<str>/<path>") - .methods("GET"_method)([](const crow::request &req, crow::response &res, - const std::string &process_name, - const std::string &requested_path) { + BMCWEB_ROUTE(app, "/bus/system/<str>/<path>") + .methods("GET"_method)([](const crow::Request &req, crow::Response &res, + const std::string &processName, + const std::string &requestedPath) { std::vector<std::string> strs; - boost::split(strs, requested_path, boost::is_any_of("/")); - std::string object_path; - std::string interface_name; - std::string method_name; + boost::split(strs, requestedPath, boost::is_any_of("/")); + std::string objectPath; + std::string interfaceName; + std::string methodName; auto it = strs.begin(); if (it == strs.end()) { - object_path = "/"; + objectPath = "/"; } while (it != strs.end()) { // Check if segment contains ".". If it does, it must be an @@ -980,17 +981,17 @@ void request_routes(Crow<Middlewares...> &app) { // part of our <path> specifier above, which causes the normal // trailing backslash redirector to fail. } else if (!it->empty()) { - object_path += "/" + *it; + objectPath += "/" + *it; } it++; } if (it != strs.end()) { - interface_name = *it; + interfaceName = *it; it++; // after interface, we might have a method name if (it != strs.end()) { - method_name = *it; + methodName = *it; it++; } } @@ -1001,16 +1002,16 @@ void request_routes(Crow<Middlewares...> &app) { res.end(); return; } - if (interface_name.empty()) { - crow::connections::system_bus->async_method_call( - [&, process_name, object_path]( + if (interfaceName.empty()) { + crow::connections::systemBus->async_method_call( + [&, processName, objectPath]( const boost::system::error_code ec, const std::string &introspect_xml) { if (ec) { - CROW_LOG_ERROR + BMCWEB_LOG_ERROR << "Introspect call failed with error: " << ec.message() - << " on process: " << process_name - << " path: " << object_path << "\n"; + << " on process: " << processName + << " path: " << objectPath << "\n"; } else { tinyxml2::XMLDocument doc; @@ -1018,45 +1019,45 @@ void request_routes(Crow<Middlewares...> &app) { doc.Parse(introspect_xml.c_str()); tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node"); if (pRoot == nullptr) { - CROW_LOG_ERROR << "XML document failed to parse " - << process_name << " " << object_path - << "\n"; - res.json_value = {{"status", "XML parse error"}}; + BMCWEB_LOG_ERROR << "XML document failed to parse " + << processName << " " << objectPath + << "\n"; + res.jsonValue = {{"status", "XML parse error"}}; res.result( boost::beast::http::status::internal_server_error); } else { - nlohmann::json interfaces_array = nlohmann::json::array(); + nlohmann::json interfacesArray = nlohmann::json::array(); tinyxml2::XMLElement *interface = pRoot->FirstChildElement("interface"); while (interface != nullptr) { - std::string iface_name = interface->Attribute("name"); - interfaces_array.push_back({{"name", iface_name}}); + std::string ifaceName = interface->Attribute("name"); + interfacesArray.push_back({{"name", ifaceName}}); interface = interface->NextSiblingElement("interface"); } - res.json_value = {{"status", "ok"}, - {"bus_name", process_name}, - {"interfaces", interfaces_array}, - {"object_path", object_path}}; + res.jsonValue = {{"status", "ok"}, + {"bus_name", processName}, + {"interfaces", interfacesArray}, + {"object_path", objectPath}}; } } res.end(); }, - process_name, object_path, "org.freedesktop.DBus.Introspectable", + processName, objectPath, "org.freedesktop.DBus.Introspectable", "Introspect"); } else { - crow::connections::system_bus->async_method_call( + crow::connections::systemBus->async_method_call( [ - &, process_name, object_path, - interface_name{std::move(interface_name)} + &, processName, objectPath, + interface_name{std::move(interfaceName)} ](const boost::system::error_code ec, const std::string &introspect_xml) { if (ec) { - CROW_LOG_ERROR + BMCWEB_LOG_ERROR << "Introspect call failed with error: " << ec.message() - << " on process: " << process_name - << " path: " << object_path << "\n"; + << " on process: " << processName + << " path: " << objectPath << "\n"; } else { tinyxml2::XMLDocument doc; @@ -1064,9 +1065,9 @@ void request_routes(Crow<Middlewares...> &app) { doc.Parse(introspect_xml.c_str()); tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node"); if (pRoot == nullptr) { - CROW_LOG_ERROR << "XML document failed to parse " - << process_name << " " << object_path - << "\n"; + BMCWEB_LOG_ERROR << "XML document failed to parse " + << processName << " " << objectPath + << "\n"; res.result( boost::beast::http::status::internal_server_error); @@ -1075,66 +1076,66 @@ void request_routes(Crow<Middlewares...> &app) { pRoot->FirstChildElement("node"); // if we know we're the only call, build the json directly - nlohmann::json methods_array = nlohmann::json::array(); - nlohmann::json signals_array = nlohmann::json::array(); + nlohmann::json methodsArray = nlohmann::json::array(); + nlohmann::json signalsArray = nlohmann::json::array(); tinyxml2::XMLElement *interface = pRoot->FirstChildElement("interface"); while (interface != nullptr) { - std::string iface_name = interface->Attribute("name"); + std::string ifaceName = interface->Attribute("name"); - if (iface_name == interface_name) { + if (ifaceName == interfaceName) { tinyxml2::XMLElement *methods = interface->FirstChildElement("method"); while (methods != nullptr) { - nlohmann::json args_array = nlohmann::json::array(); + nlohmann::json argsArray = nlohmann::json::array(); tinyxml2::XMLElement *arg = methods->FirstChildElement("arg"); while (arg != nullptr) { - args_array.push_back( + argsArray.push_back( {{"name", arg->Attribute("name")}, {"type", arg->Attribute("type")}, {"direction", arg->Attribute("direction")}}); arg = arg->NextSiblingElement("arg"); } - methods_array.push_back( + methodsArray.push_back( {{"name", methods->Attribute("name")}, - {"uri", "/bus/system/" + process_name + - object_path + "/" + interface_name + + {"uri", "/bus/system/" + processName + + objectPath + "/" + interfaceName + "/" + methods->Attribute("name")}, - {"args", args_array}}); + {"args", argsArray}}); methods = methods->NextSiblingElement("method"); } tinyxml2::XMLElement *signals = interface->FirstChildElement("signal"); while (signals != nullptr) { - nlohmann::json args_array = nlohmann::json::array(); + nlohmann::json argsArray = nlohmann::json::array(); tinyxml2::XMLElement *arg = signals->FirstChildElement("arg"); while (arg != nullptr) { std::string name = arg->Attribute("name"); std::string type = arg->Attribute("type"); - args_array.push_back({ + argsArray.push_back({ {"name", name}, {"type", type}, }); arg = arg->NextSiblingElement("arg"); } - signals_array.push_back( + signalsArray.push_back( {{"name", signals->Attribute("name")}, - {"args", args_array}}); + {"args", argsArray}}); signals = signals->NextSiblingElement("signal"); } - res.json_value = { + res.jsonValue = { {"status", "ok"}, - {"bus_name", process_name}, - {"interface", interface_name}, - {"methods", methods_array}, - {"object_path", object_path}, + {"bus_name", processName}, + {"interface", interfaceName}, + {"methods", methodsArray}, + {"object_path", objectPath}, {"properties", nlohmann::json::object()}, - {"signals", signals_array}}; + {"signals", signalsArray}}; break; } @@ -1150,7 +1151,7 @@ void request_routes(Crow<Middlewares...> &app) { } res.end(); }, - process_name, object_path, "org.freedesktop.DBus.Introspectable", + processName, objectPath, "org.freedesktop.DBus.Introspectable", "Introspect"); } }); diff --git a/include/pam_authenticate.hpp b/include/pam_authenticate.hpp index a66d16b347..65e47402f7 100644 --- a/include/pam_authenticate.hpp +++ b/include/pam_authenticate.hpp @@ -6,21 +6,20 @@ #include <boost/utility/string_view.hpp> // function used to get user input -inline int pam_function_conversation(int num_msg, - const struct pam_message** msg, - struct pam_response** resp, - void* appdata_ptr) { - if (appdata_ptr == nullptr) { +inline int pamFunctionConversation(int numMsg, const struct pam_message** msg, + struct pam_response** resp, + void* appdataPtr) { + if (appdataPtr == nullptr) { return PAM_AUTH_ERR; } auto* pass = reinterpret_cast<char*>( - malloc(std::strlen(reinterpret_cast<char*>(appdata_ptr)) + 1)); - std::strcpy(pass, reinterpret_cast<char*>(appdata_ptr)); + malloc(std::strlen(reinterpret_cast<char*>(appdataPtr)) + 1)); + std::strcpy(pass, reinterpret_cast<char*>(appdataPtr)); *resp = reinterpret_cast<pam_response*>( - calloc(num_msg, sizeof(struct pam_response))); + calloc(numMsg, sizeof(struct pam_response))); - for (int i = 0; i < num_msg; ++i) { + for (int i = 0; i < numMsg; ++i) { /* Ignore all PAM messages except prompting for hidden input */ if (msg[i]->msg_style != PAM_PROMPT_ECHO_OFF) { continue; @@ -33,20 +32,20 @@ inline int pam_function_conversation(int num_msg, return PAM_SUCCESS; } -inline bool pam_authenticate_user(const boost::string_view username, - const boost::string_view password) { - std::string user_str(username); - std::string pass_str(password); - const struct pam_conv local_conversation = { - pam_function_conversation, const_cast<char*>(pass_str.c_str())}; - pam_handle_t* local_auth_handle = NULL; // this gets set by pam_start +inline bool pamAuthenticateUser(const boost::string_view username, + const boost::string_view password) { + std::string userStr(username); + std::string passStr(password); + const struct pam_conv localConversation = { + pamFunctionConversation, const_cast<char*>(passStr.c_str())}; + pam_handle_t* localAuthHandle = NULL; // this gets set by pam_start - if (pam_start("webserver", user_str.c_str(), &local_conversation, - &local_auth_handle) != PAM_SUCCESS) { + if (pam_start("webserver", userStr.c_str(), &localConversation, + &localAuthHandle) != PAM_SUCCESS) { return false; } - int retval = pam_authenticate(local_auth_handle, - PAM_SILENT | PAM_DISALLOW_NULL_AUTHTOK); + int retval = + pam_authenticate(localAuthHandle, PAM_SILENT | PAM_DISALLOW_NULL_AUTHTOK); if (retval != PAM_SUCCESS) { if (retval == PAM_AUTH_ERR) { @@ -54,18 +53,18 @@ inline bool pam_authenticate_user(const boost::string_view username, } else { // printf("pam_authenticate returned %d\n", retval); } - pam_end(local_auth_handle, PAM_SUCCESS); + pam_end(localAuthHandle, PAM_SUCCESS); return false; } /* check that the account is healthy */ - if (pam_acct_mgmt(local_auth_handle, PAM_DISALLOW_NULL_AUTHTOK) != + if (pam_acct_mgmt(localAuthHandle, PAM_DISALLOW_NULL_AUTHTOK) != PAM_SUCCESS) { - pam_end(local_auth_handle, PAM_SUCCESS); + pam_end(localAuthHandle, PAM_SUCCESS); return false; } - if (pam_end(local_auth_handle, PAM_SUCCESS) != PAM_SUCCESS) { + if (pam_end(localAuthHandle, PAM_SUCCESS) != PAM_SUCCESS) { return false; } diff --git a/include/persistent_data_middleware.hpp b/include/persistent_data_middleware.hpp index 334a84de93..d43b4f2f59 100644 --- a/include/persistent_data_middleware.hpp +++ b/include/persistent_data_middleware.hpp @@ -15,55 +15,55 @@ namespace crow { -namespace PersistentData { +namespace persistent_data { class Middleware { // todo(ed) should read this from a fixed location somewhere, not CWD static constexpr const char* filename = "bmcweb_persistent_data.json"; - int json_revision = 1; + int jsonRevision = 1; public: - struct context {}; + struct Context {}; - Middleware() { read_data(); } + Middleware() { readData(); } ~Middleware() { - if (PersistentData::SessionStore::getInstance().needs_write()) { - write_data(); + if (persistent_data::SessionStore::getInstance().needsWrite()) { + writeData(); } } - void before_handle(crow::request& req, response& res, context& ctx) {} + void beforeHandle(crow::Request& req, Response& res, Context& ctx) {} - void after_handle(request& req, response& res, context& ctx) {} + void afterHandle(Request& req, Response& res, Context& ctx) {} // TODO(ed) this should really use protobuf, or some other serialization // library, but adding another dependency is somewhat outside the scope of // this application for the moment - void read_data() { - std::ifstream persistent_file(filename); - int file_revision = 0; - if (persistent_file.is_open()) { + void readData() { + std::ifstream persistentFile(filename); + int fileRevision = 0; + if (persistentFile.is_open()) { // call with exceptions disabled - auto data = nlohmann::json::parse(persistent_file, nullptr, false); + auto data = nlohmann::json::parse(persistentFile, nullptr, false); if (data.is_discarded()) { - CROW_LOG_ERROR << "Error parsing persistent data in json file."; + BMCWEB_LOG_ERROR << "Error parsing persistent data in json file."; } else { for (const auto& item : data.items()) { if (item.key() == "revision") { - file_revision = 0; + fileRevision = 0; const uint64_t* uintPtr = item.value().get_ptr<const uint64_t*>(); if (uintPtr == nullptr) { - CROW_LOG_ERROR << "Failed to read revision flag"; + BMCWEB_LOG_ERROR << "Failed to read revision flag"; } else { - file_revision = *uintPtr; + fileRevision = *uintPtr; } } else if (item.key() == "system_uuid") { const std::string* jSystemUuid = item.value().get_ptr<const std::string*>(); if (jSystemUuid != nullptr) { - system_uuid = *jSystemUuid; + systemUuid = *jSystemUuid; } } else if (item.key() == "sessions") { for (const auto& elem : item.value()) { @@ -71,16 +71,16 @@ class Middleware { UserSession::fromJson(elem); if (newSession == nullptr) { - CROW_LOG_ERROR + BMCWEB_LOG_ERROR << "Problem reading session from persistent store"; continue; } - CROW_LOG_DEBUG << "Restored session: " << newSession->csrf_token - << " " << newSession->unique_id << " " - << newSession->session_token; - SessionStore::getInstance().auth_tokens.emplace( - newSession->session_token, newSession); + BMCWEB_LOG_DEBUG << "Restored session: " << newSession->csrfToken + << " " << newSession->uniqueId << " " + << newSession->sessionToken; + SessionStore::getInstance().authTokens.emplace( + newSession->sessionToken, newSession); } } else { // Do nothing in the case of extra fields. We may have cases where @@ -91,32 +91,32 @@ class Middleware { } } } - bool need_write = false; + bool needWrite = false; - if (system_uuid.empty()) { - system_uuid = boost::uuids::to_string(boost::uuids::random_generator()()); - need_write = true; + if (systemUuid.empty()) { + systemUuid = boost::uuids::to_string(boost::uuids::random_generator()()); + needWrite = true; } - if (file_revision < json_revision) { - need_write = true; + if (fileRevision < jsonRevision) { + needWrite = true; } // write revision changes or system uuid changes immediately - if (need_write) { - write_data(); + if (needWrite) { + writeData(); } } - void write_data() { - std::ofstream persistent_file(filename); + void writeData() { + std::ofstream persistentFile(filename); nlohmann::json data{ - {"sessions", PersistentData::SessionStore::getInstance().auth_tokens}, - {"system_uuid", system_uuid}, - {"revision", json_revision}}; - persistent_file << data; + {"sessions", SessionStore::getInstance().authTokens}, + {"system_uuid", systemUuid}, + {"revision", jsonRevision}}; + persistentFile << data; } - std::string system_uuid{""}; + std::string systemUuid{""}; }; -} // namespace PersistentData +} // namespace persistent_data } // namespace crow diff --git a/include/redfish_v1.hpp b/include/redfish_v1.hpp index e8f4d7fd35..b81aa5474a 100644 --- a/include/redfish_v1.hpp +++ b/include/redfish_v1.hpp @@ -18,23 +18,23 @@ using ManagedObjectType = std::vector<std::pair< std::string, sdbusplus::message::variant<bool>>>>>; template <typename... Middlewares> -void request_routes(Crow<Middlewares...>& app) { - CROW_ROUTE(app, "/redfish/") - .methods("GET"_method)([](const crow::request& req, crow::response& res) { - res.json_value = {{"v1", "/redfish/v1/"}}; +void requestRoutes(Crow<Middlewares...>& app) { + BMCWEB_ROUTE(app, "/redfish/") + .methods("GET"_method)([](const crow::Request& req, crow::Response& res) { + res.jsonValue = {{"v1", "/redfish/v1/"}}; res.end(); }); - CROW_ROUTE(app, "/redfish/v1/AccountService/Accounts/") + BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/") .methods( - "GET"_method)([&](const crow::request& req, crow::response& res) { - crow::connections::system_bus->async_method_call( + "GET"_method)([&](const crow::Request& req, crow::Response& res) { + crow::connections::systemBus->async_method_call( [&](const boost::system::error_code ec, const ManagedObjectType& users) { if (ec) { res.result(boost::beast::http::status::internal_server_error); } else { - res.json_value = { + res.jsonValue = { {"@odata.context", "/redfish/v1/" "$metadata#ManagerAccountCollection." @@ -45,22 +45,22 @@ void request_routes(Crow<Middlewares...>& app) { {"Name", "Accounts Collection"}, {"Description", "BMC User Accounts"}, {"Members@odata.count", users.size()}}; - nlohmann::json member_array = nlohmann::json::array(); - int user_index = 0; + nlohmann::json memberArray = nlohmann::json::array(); + int userIndex = 0; for (auto& user : users) { const std::string& path = static_cast<const std::string&>(user.first); - std::size_t last_index = path.rfind("/"); - if (last_index == std::string::npos) { - last_index = 0; + std::size_t lastIndex = path.rfind("/"); + if (lastIndex == std::string::npos) { + lastIndex = 0; } else { - last_index += 1; + lastIndex += 1; } - member_array.push_back( + memberArray.push_back( {{"@odata.id", "/redfish/v1/AccountService/Accounts/" + - path.substr(last_index)}}); + path.substr(lastIndex)}}); } - res.json_value["Members"] = member_array; + res.jsonValue["Members"] = memberArray; } res.end(); }, @@ -68,12 +68,12 @@ void request_routes(Crow<Middlewares...>& app) { "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); }); - CROW_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/") - .methods("GET"_method)([](const crow::request& req, crow::response& res, + BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/") + .methods("GET"_method)([](const crow::Request& req, crow::Response& res, const std::string& account_name) { - crow::connections::system_bus->async_method_call( - [&, account_name{std::move(account_name)} ]( + crow::connections::systemBus->async_method_call( + [&, accountName{std::move(account_name)} ]( const boost::system::error_code ec, const ManagedObjectType& users) { if (ec) { @@ -82,14 +82,14 @@ void request_routes(Crow<Middlewares...>& app) { for (auto& user : users) { const std::string& path = static_cast<const std::string&>(user.first); - std::size_t last_index = path.rfind("/"); - if (last_index == std::string::npos) { - last_index = 0; + std::size_t lastIndex = path.rfind("/"); + if (lastIndex == std::string::npos) { + lastIndex = 0; } else { - last_index += 1; + lastIndex += 1; } - if (path.substr(last_index) == account_name) { - res.json_value = { + if (path.substr(lastIndex) == accountName) { + res.jsonValue = { {"@odata.context", "/redfish/v1/$metadata#ManagerAccount.ManagerAccount"}, {"@odata.id", "/redfish/v1/AccountService/Accounts/1"}, @@ -100,7 +100,7 @@ void request_routes(Crow<Middlewares...>& app) { {"Description", "User Account"}, {"Enabled", false}, {"Password", nullptr}, - {"UserName", account_name}, + {"UserName", accountName}, {"RoleId", "Administrator"}, {"Links", {{"Role", @@ -110,7 +110,7 @@ void request_routes(Crow<Middlewares...>& app) { break; } } - if (res.json_value.is_null()) { + if (res.jsonValue.is_null()) { res.result(boost::beast::http::status::not_found); } } diff --git a/include/security_headers_middleware.hpp b/include/security_headers_middleware.hpp index 19369f9711..f7bc478d97 100644 --- a/include/security_headers_middleware.hpp +++ b/include/security_headers_middleware.hpp @@ -4,47 +4,46 @@ #include <crow/http_response.h> namespace crow { -static const char* strict_transport_security_key = "Strict-Transport-Security"; -static const char* strict_transport_security_value = +static const char* strictTransportSecurityKey = "Strict-Transport-Security"; +static const char* strictTransportSecurityValue = "max-age=31536000; includeSubdomains; preload"; -static const char* ua_compatability_key = "X-UA-Compatible"; -static const char* ua_compatability_value = "IE=11"; +static const char* uaCompatabilityKey = "X-UA-Compatible"; +static const char* uaCompatabilityValue = "IE=11"; -static const char* xframe_key = "X-Frame-Options"; -static const char* xframe_value = "DENY"; +static const char* xframeKey = "X-Frame-Options"; +static const char* xframeValue = "DENY"; -static const char* xss_key = "X-XSS-Protection"; -static const char* xss_value = "1; mode=block"; +static const char* xssKey = "X-XSS-Protection"; +static const char* xssValue = "1; mode=block"; -static const char* content_security_key = "X-Content-Security-Policy"; -static const char* content_security_value = "default-src 'self'"; +static const char* contentSecurityKey = "X-Content-Security-Policy"; +static const char* contentSecurityValue = "default-src 'self'"; -static const char* pragma_key = "Pragma"; -static const char* pragma_value = "no-cache"; +static const char* pragmaKey = "Pragma"; +static const char* pragmaValue = "no-cache"; -static const char* cache_control_key = "Cache-Control"; -static const char* cache_control_value = "no-Store,no-Cache"; +static const char* cacheControlKey = "Cache-Control"; +static const char* cacheControlValue = "no-Store,no-Cache"; struct SecurityHeadersMiddleware { - struct context {}; + struct Context {}; - void before_handle(crow::request& req, response& res, context& ctx) {} + void beforeHandle(crow::Request& req, Response& res, Context& ctx) {} - void after_handle(request& req, response& res, context& ctx) { + void afterHandle(Request& req, Response& res, Context& ctx) { /* TODO(ed) these should really check content types. for example, X-UA-Compatible header doesn't make sense when retrieving a JSON or javascript file. It doesn't hurt anything, it's just ugly. */ - res.add_header(strict_transport_security_key, - strict_transport_security_value); - res.add_header(ua_compatability_key, ua_compatability_value); - res.add_header(xframe_key, xframe_value); - res.add_header(xss_key, xss_value); - res.add_header(content_security_key, content_security_value); - res.add_header(pragma_key, pragma_value); - res.add_header(cache_control_key, cache_control_value); + res.addHeader(strictTransportSecurityKey, strictTransportSecurityValue); + res.addHeader(uaCompatabilityKey, uaCompatabilityValue); + res.addHeader(xframeKey, xframeValue); + res.addHeader(xssKey, xssValue); + res.addHeader(contentSecurityKey, contentSecurityValue); + res.addHeader(pragmaKey, pragmaValue); + res.addHeader(cacheControlKey, cacheControlValue); } }; } // namespace crow diff --git a/include/sessions.hpp b/include/sessions.hpp index b4e86c721c..f7f937df07 100644 --- a/include/sessions.hpp +++ b/include/sessions.hpp @@ -14,7 +14,7 @@ namespace crow { -namespace PersistentData { +namespace persistent_data { enum class PersistenceType { TIMEOUT, // User session times out after a predetermined amount of time @@ -22,11 +22,11 @@ enum class PersistenceType { }; struct UserSession { - std::string unique_id; - std::string session_token; + std::string uniqueId; + std::string sessionToken; std::string username; - std::string csrf_token; - std::chrono::time_point<std::chrono::steady_clock> last_updated; + std::string csrfToken; + std::chrono::time_point<std::chrono::steady_clock> lastUpdated; PersistenceType persistence; /** @@ -44,20 +44,20 @@ struct UserSession { const std::string* thisValue = element.value().get_ptr<const std::string*>(); if (thisValue == nullptr) { - CROW_LOG_ERROR << "Error reading persistent store. Property " + BMCWEB_LOG_ERROR << "Error reading persistent store. Property " << element.key() << " was not of type string"; return nullptr; } if (element.key() == "unique_id") { - userSession->unique_id = *thisValue; + userSession->uniqueId = *thisValue; } else if (element.key() == "session_token") { - userSession->session_token = *thisValue; + userSession->sessionToken = *thisValue; } else if (element.key() == "csrf_token") { - userSession->csrf_token = *thisValue; + userSession->csrfToken = *thisValue; } else if (element.key() == "username") { userSession->username = *thisValue; } else { - CROW_LOG_ERROR << "Got unexpected property reading persistent file: " + BMCWEB_LOG_ERROR << "Got unexpected property reading persistent file: " << element.key(); return nullptr; } @@ -68,7 +68,7 @@ struct UserSession { // of wall clock time and steady timer time, possibly persisting values with // wall clock time instead of steady timer, but the tradeoffs of all the // corner cases involved are non-trivial, so this is done temporarily - userSession->last_updated = std::chrono::steady_clock::now(); + userSession->lastUpdated = std::chrono::steady_clock::now(); userSession->persistence = PersistenceType::TIMEOUT; return userSession; @@ -79,100 +79,99 @@ class Middleware; class SessionStore { public: - std::shared_ptr<UserSession> generate_user_session( + std::shared_ptr<UserSession> generateUserSession( const boost::string_view username, PersistenceType persistence = PersistenceType::TIMEOUT) { // TODO(ed) find a secure way to not generate session identifiers if // persistence is set to SINGLE_REQUEST static constexpr std::array<char, 62> alphanum = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', - 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'b', 'C', + 'D', 'E', 'F', 'g', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'r', 'S', 'T', 'U', 'v', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; // entropy: 30 characters, 62 possibilities. log2(62^30) = 178 bits of // entropy. OWASP recommends at least 60 // https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Session_ID_Entropy - std::string session_token; - session_token.resize(20, '0'); + std::string sessionToken; + sessionToken.resize(20, '0'); std::uniform_int_distribution<int> dist(0, alphanum.size() - 1); - for (int i = 0; i < session_token.size(); ++i) { - session_token[i] = alphanum[dist(rd)]; + for (int i = 0; i < sessionToken.size(); ++i) { + sessionToken[i] = alphanum[dist(rd)]; } // Only need csrf tokens for cookie based auth, token doesn't matter - std::string csrf_token; - csrf_token.resize(20, '0'); - for (int i = 0; i < csrf_token.size(); ++i) { - csrf_token[i] = alphanum[dist(rd)]; + std::string csrfToken; + csrfToken.resize(20, '0'); + for (int i = 0; i < csrfToken.size(); ++i) { + csrfToken[i] = alphanum[dist(rd)]; } - std::string unique_id; - unique_id.resize(10, '0'); - for (int i = 0; i < unique_id.size(); ++i) { - unique_id[i] = alphanum[dist(rd)]; + std::string uniqueId; + uniqueId.resize(10, '0'); + for (int i = 0; i < uniqueId.size(); ++i) { + uniqueId[i] = alphanum[dist(rd)]; } auto session = std::make_shared<UserSession>( - UserSession{unique_id, session_token, std::string(username), csrf_token, + UserSession{uniqueId, sessionToken, std::string(username), csrfToken, std::chrono::steady_clock::now(), persistence}); - auto it = auth_tokens.emplace(std::make_pair(session_token, session)); + auto it = authTokens.emplace(std::make_pair(sessionToken, session)); // Only need to write to disk if session isn't about to be destroyed. - need_write_ = persistence == PersistenceType::TIMEOUT; + needWrite = persistence == PersistenceType::TIMEOUT; return it.first->second; } - std::shared_ptr<UserSession> login_session_by_token( + std::shared_ptr<UserSession> loginSessionByToken( const boost::string_view token) { - apply_session_timeouts(); - auto session_it = auth_tokens.find(std::string(token)); - if (session_it == auth_tokens.end()) { + applySessionTimeouts(); + auto sessionIt = authTokens.find(std::string(token)); + if (sessionIt == authTokens.end()) { return nullptr; } - std::shared_ptr<UserSession> user_session = session_it->second; - user_session->last_updated = std::chrono::steady_clock::now(); - return user_session; + std::shared_ptr<UserSession> userSession = sessionIt->second; + userSession->lastUpdated = std::chrono::steady_clock::now(); + return userSession; } - std::shared_ptr<UserSession> get_session_by_uid( - const boost::string_view uid) { - apply_session_timeouts(); + std::shared_ptr<UserSession> getSessionByUid(const boost::string_view uid) { + applySessionTimeouts(); // TODO(Ed) this is inefficient - auto session_it = auth_tokens.begin(); - while (session_it != auth_tokens.end()) { - if (session_it->second->unique_id == uid) { - return session_it->second; + auto sessionIt = authTokens.begin(); + while (sessionIt != authTokens.end()) { + if (sessionIt->second->uniqueId == uid) { + return sessionIt->second; } - session_it++; + sessionIt++; } return nullptr; } - void remove_session(std::shared_ptr<UserSession> session) { - auth_tokens.erase(session->session_token); - need_write_ = true; + void removeSession(std::shared_ptr<UserSession> session) { + authTokens.erase(session->sessionToken); + needWrite = true; } - std::vector<const std::string*> get_unique_ids( + std::vector<const std::string*> getUniqueIds( bool getAll = true, const PersistenceType& type = PersistenceType::SINGLE_REQUEST) { - apply_session_timeouts(); + applySessionTimeouts(); std::vector<const std::string*> ret; - ret.reserve(auth_tokens.size()); - for (auto& session : auth_tokens) { + ret.reserve(authTokens.size()); + for (auto& session : authTokens) { if (getAll || type == session.second->persistence) { - ret.push_back(&session.second->unique_id); + ret.push_back(&session.second->uniqueId); } } return ret; } - bool needs_write() { return need_write_; } - int get_timeout_in_seconds() const { - return std::chrono::seconds(timeout_in_minutes).count(); + bool needsWrite() { return needWrite; } + int getTimeoutInSeconds() const { + return std::chrono::seconds(timeoutInMinutes).count(); }; - // Persistent data middleware needs to be able to serialize our auth_tokens + // Persistent data middleware needs to be able to serialize our authTokens // structure, which is private friend Middleware; @@ -185,48 +184,47 @@ class SessionStore { SessionStore& operator=(const SessionStore&) = delete; private: - SessionStore() : timeout_in_minutes(60) {} - - void apply_session_timeouts() { - auto time_now = std::chrono::steady_clock::now(); - if (time_now - last_timeout_update > std::chrono::minutes(1)) { - last_timeout_update = time_now; - auto auth_tokens_it = auth_tokens.begin(); - while (auth_tokens_it != auth_tokens.end()) { - if (time_now - auth_tokens_it->second->last_updated >= - timeout_in_minutes) { - auth_tokens_it = auth_tokens.erase(auth_tokens_it); - need_write_ = true; + SessionStore() : timeoutInMinutes(60) {} + + void applySessionTimeouts() { + auto timeNow = std::chrono::steady_clock::now(); + if (timeNow - lastTimeoutUpdate > std::chrono::minutes(1)) { + lastTimeoutUpdate = timeNow; + auto authTokensIt = authTokens.begin(); + while (authTokensIt != authTokens.end()) { + if (timeNow - authTokensIt->second->lastUpdated >= timeoutInMinutes) { + authTokensIt = authTokens.erase(authTokensIt); + needWrite = true; } else { - auth_tokens_it++; + authTokensIt++; } } } } - std::chrono::time_point<std::chrono::steady_clock> last_timeout_update; + std::chrono::time_point<std::chrono::steady_clock> lastTimeoutUpdate; boost::container::flat_map<std::string, std::shared_ptr<UserSession>> - auth_tokens; + authTokens; std::random_device rd; - bool need_write_{false}; - std::chrono::minutes timeout_in_minutes; + bool needWrite{false}; + std::chrono::minutes timeoutInMinutes; }; -} // namespace PersistentData +} // namespace persistent_data } // namespace crow // to_json(...) definition for objects of UserSession type namespace nlohmann { template <> -struct adl_serializer<std::shared_ptr<crow::PersistentData::UserSession>> { +struct adl_serializer<std::shared_ptr<crow::persistent_data::UserSession>> { static void to_json( nlohmann::json& j, - const std::shared_ptr<crow::PersistentData::UserSession>& p) { + const std::shared_ptr<crow::persistent_data::UserSession>& p) { if (p->persistence != - crow::PersistentData::PersistenceType::SINGLE_REQUEST) { - j = nlohmann::json{{"unique_id", p->unique_id}, - {"session_token", p->session_token}, + crow::persistent_data::PersistenceType::SINGLE_REQUEST) { + j = nlohmann::json{{"unique_id", p->uniqueId}, + {"session_token", p->sessionToken}, {"username", p->username}, - {"csrf_token", p->csrf_token}}; + {"csrf_token", p->csrfToken}}; } } }; diff --git a/include/ssl_key_handler.hpp b/include/ssl_key_handler.hpp index 4db4a8fdd5..4eac8035f5 100644 --- a/include/ssl_key_handler.hpp +++ b/include/ssl_key_handler.hpp @@ -1,5 +1,5 @@ #pragma once -#ifdef CROW_ENABLE_SSL +#ifdef BMCWEB_ENABLE_SSL #include <openssl/bio.h> #include <openssl/dh.h> @@ -14,15 +14,15 @@ #include <boost/asio.hpp> namespace ensuressl { -static void init_openssl(); -static void cleanup_openssl(); -static EVP_PKEY *create_rsa_key(); -static EVP_PKEY *create_ec_key(); -static void handle_openssl_error(); +static void initOpenssl(); +static void cleanupOpenssl(); +static EVP_PKEY *createRsaKey(); +static EVP_PKEY *createEcKey(); +static void handleOpensslError(); -inline bool verify_openssl_key_cert(const std::string &filepath) { - bool private_key_valid = false; - bool cert_valid = false; +inline bool verifyOpensslKeyCert(const std::string &filepath) { + bool privateKeyValid = false; + bool certValid = false; std::cout << "Checking certs in file " << filepath << "\n"; @@ -45,7 +45,7 @@ inline bool verify_openssl_key_cert(const std::string &filepath) { if (ec != nullptr) { std::cout << "Found an EC key\n"; if (EC_KEY_check_key(ec) == 1) { - private_key_valid = true; + privateKeyValid = true; } else { std::cerr << "Key not valid error number " << ERR_get_error() << "\n"; @@ -54,14 +54,14 @@ inline bool verify_openssl_key_cert(const std::string &filepath) { } } - if (private_key_valid) { + if (privateKeyValid) { X509 *x509 = PEM_read_X509(file, NULL, NULL, NULL); if (x509 == nullptr) { std::cout << "error getting x509 cert " << ERR_get_error() << "\n"; } else { rc = X509_verify(x509, pkey); if (rc == 1) { - cert_valid = true; + certValid = true; } else { std::cerr << "Error in verifying private key signature " << ERR_get_error() << "\n"; @@ -73,26 +73,26 @@ inline bool verify_openssl_key_cert(const std::string &filepath) { } fclose(file); } - return cert_valid; + return certValid; } -inline void generate_ssl_certificate(const std::string &filepath) { +inline void generateSslCertificate(const std::string &filepath) { FILE *pFile = NULL; std::cout << "Generating new keys\n"; - init_openssl(); + initOpenssl(); // std::cerr << "Generating RSA key"; // EVP_PKEY *pRsaPrivKey = create_rsa_key(); std::cerr << "Generating EC key\n"; - EVP_PKEY *pRsaPrivKey = create_ec_key(); + EVP_PKEY *pRsaPrivKey = createEcKey(); if (pRsaPrivKey != nullptr) { std::cerr << "Generating x509 Certificate\n"; // Use this code to directly generate a certificate X509 *x509; x509 = X509_new(); if (x509 != nullptr) { - // Get a random number from the RNG for the certificate serial number + // get a random number from the RNG for the certificate serial number // If this is not random, regenerating certs throws broswer errors std::random_device rd; int serial = rd(); @@ -107,7 +107,7 @@ inline void generate_ssl_certificate(const std::string &filepath) { // set the public key to the key we just generated X509_set_pubkey(x509, pRsaPrivKey); - // Get the subject name + // get the subject name X509_NAME *name; name = X509_get_subject_name(x509); @@ -146,7 +146,7 @@ inline void generate_ssl_certificate(const std::string &filepath) { // cleanup_openssl(); } -EVP_PKEY *create_rsa_key() { +EVP_PKEY *createRsaKey() { RSA *pRSA = NULL; #if OPENSSL_VERSION_NUMBER < 0x00908000L pRSA = RSA_generate_key(2048, RSA_3, NULL, NULL); @@ -160,12 +160,12 @@ EVP_PKEY *create_rsa_key() { /* pKey owns pRSA from now */ if (RSA_check_key(pRSA) <= 0) { fprintf(stderr, "RSA_check_key failed.\n"); - handle_openssl_error(); + handleOpensslError(); EVP_PKEY_free(pKey); pKey = NULL; } } else { - handle_openssl_error(); + handleOpensslError(); if (pRSA != nullptr) { RSA_free(pRSA); pRSA = NULL; @@ -178,7 +178,7 @@ EVP_PKEY *create_rsa_key() { return pKey; } -EVP_PKEY *create_ec_key() { +EVP_PKEY *createEcKey() { EVP_PKEY *pKey = NULL; int eccgrp = 0; eccgrp = OBJ_txt2nid("prime256v1"); @@ -200,7 +200,7 @@ EVP_PKEY *create_ec_key() { return pKey; } -void init_openssl() { +void initOpenssl() { #if OPENSSL_VERSION_NUMBER < 0x10100000L SSL_load_error_strings(); OpenSSL_add_all_algorithms(); @@ -208,7 +208,7 @@ void init_openssl() { #endif } -void cleanup_openssl() { +void cleanupOpenssl() { CRYPTO_cleanup_all_ex_data(); ERR_free_strings(); #if OPENSSL_VERSION_NUMBER < 0x10100000L @@ -217,44 +217,44 @@ void cleanup_openssl() { EVP_cleanup(); } -void handle_openssl_error() { ERR_print_errors_fp(stderr); } -inline void ensure_openssl_key_present_and_valid(const std::string &filepath) { - bool pem_file_valid = false; +void handleOpensslError() { ERR_print_errors_fp(stderr); } +inline void ensureOpensslKeyPresentAndValid(const std::string &filepath) { + bool pemFileValid = false; - pem_file_valid = verify_openssl_key_cert(filepath); + pemFileValid = verifyOpensslKeyCert(filepath); - if (!pem_file_valid) { + if (!pemFileValid) { std::cerr << "Error in verifying signature, regenerating\n"; - generate_ssl_certificate(filepath); + generateSslCertificate(filepath); } } -inline boost::asio::ssl::context get_ssl_context( +inline boost::asio::ssl::context getSslContext( const std::string &ssl_pem_file) { - boost::asio::ssl::context m_ssl_context{boost::asio::ssl::context::sslv23}; - m_ssl_context.set_options(boost::asio::ssl::context::default_workarounds | - boost::asio::ssl::context::no_sslv2 | - boost::asio::ssl::context::no_sslv3 | - boost::asio::ssl::context::single_dh_use | - boost::asio::ssl::context::no_tlsv1 | - boost::asio::ssl::context::no_tlsv1_1); + boost::asio::ssl::context mSslContext{boost::asio::ssl::context::sslv23}; + mSslContext.set_options(boost::asio::ssl::context::default_workarounds | + boost::asio::ssl::context::no_sslv2 | + boost::asio::ssl::context::no_sslv3 | + boost::asio::ssl::context::single_dh_use | + boost::asio::ssl::context::no_tlsv1 | + boost::asio::ssl::context::no_tlsv1_1); // m_ssl_context.set_verify_mode(boost::asio::ssl::verify_peer); - m_ssl_context.use_certificate_file(ssl_pem_file, - boost::asio::ssl::context::pem); - m_ssl_context.use_private_key_file(ssl_pem_file, - boost::asio::ssl::context::pem); + mSslContext.use_certificate_file(ssl_pem_file, + boost::asio::ssl::context::pem); + mSslContext.use_private_key_file(ssl_pem_file, + boost::asio::ssl::context::pem); // Set up EC curves to auto (boost asio doesn't have a method for this) // There is a pull request to add this. Once this is included in an asio // drop, use the right way // http://stackoverflow.com/questions/18929049/boost-asio-with-ecdsa-certificate-issue - if (SSL_CTX_set_ecdh_auto(m_ssl_context.native_handle(), 1) != 1) { - CROW_LOG_ERROR << "Error setting tmp ecdh list\n"; + if (SSL_CTX_set_ecdh_auto(mSslContext.native_handle(), 1) != 1) { + BMCWEB_LOG_ERROR << "Error setting tmp ecdh list\n"; } // From mozilla "compatibility" - std::string mozilla_compatibility_ciphers = + std::string mozillaCompatibilityCiphers = "ECDHE-ECDSA-CHACHA20-POLY1305:" "ECDHE-RSA-CHACHA20-POLY1305:" "ECDHE-ECDSA-AES128-GCM-SHA256:" @@ -288,7 +288,7 @@ inline boost::asio::ssl::context get_ssl_context( "!DSS"; // From mozilla "modern" - std::string mozilla_modern_ciphers = + std::string mozillaModernCiphers = "ECDHE-ECDSA-AES256-GCM-SHA384:" "ECDHE-RSA-AES256-GCM-SHA384:" "ECDHE-ECDSA-CHACHA20-POLY1305:" @@ -300,13 +300,13 @@ inline boost::asio::ssl::context get_ssl_context( "ECDHE-ECDSA-AES128-SHA256:" "ECDHE-RSA-AES128-SHA256"; - std::string aes_only_ciphers = "AES128+EECDH:AES128+EDH:!aNULL:!eNULL"; + std::string aesOnlyCiphers = "AES128+EECDH:AES128+EDH:!aNULL:!eNULL"; - if (SSL_CTX_set_cipher_list(m_ssl_context.native_handle(), - mozilla_compatibility_ciphers.c_str()) != 1) { - CROW_LOG_ERROR << "Error setting cipher list\n"; + if (SSL_CTX_set_cipher_list(mSslContext.native_handle(), + mozillaCompatibilityCiphers.c_str()) != 1) { + BMCWEB_LOG_ERROR << "Error setting cipher list\n"; } - return m_ssl_context; + return mSslContext; } } // namespace ensuressl diff --git a/include/token_authorization_middleware.hpp b/include/token_authorization_middleware.hpp index f151e4ff63..fcc86386fa 100644 --- a/include/token_authorization_middleware.hpp +++ b/include/token_authorization_middleware.hpp @@ -12,49 +12,49 @@ namespace crow { -namespace TokenAuthorization { +namespace token_authorization { class Middleware { public: - struct context { - std::shared_ptr<crow::PersistentData::UserSession> session; + struct Context { + std::shared_ptr<crow::persistent_data::UserSession> session; }; - void before_handle(crow::request& req, response& res, context& ctx) { - if (is_on_whitelist(req)) { + void beforeHandle(crow::Request& req, Response& res, Context& ctx) { + if (isOnWhitelist(req)) { return; } - ctx.session = perform_xtoken_auth(req); + ctx.session = performXtokenAuth(req); if (ctx.session == nullptr) { - ctx.session = perform_cookie_auth(req); + ctx.session = performCookieAuth(req); } if (ctx.session == nullptr) { - boost::string_view auth_header = req.get_header_value("Authorization"); - if (!auth_header.empty()) { + boost::string_view authHeader = req.getHeaderValue("Authorization"); + if (!authHeader.empty()) { // Reject any kind of auth other than basic or token - if (boost::starts_with(auth_header, "Token ")) { - ctx.session = perform_token_auth(auth_header); - } else if (boost::starts_with(auth_header, "Basic ")) { - ctx.session = perform_basic_auth(auth_header); + if (boost::starts_with(authHeader, "Token ")) { + ctx.session = performTokenAuth(authHeader); + } else if (boost::starts_with(authHeader, "Basic ")) { + ctx.session = performBasicAuth(authHeader); } } } if (ctx.session == nullptr) { - CROW_LOG_WARNING << "[AuthMiddleware] authorization failed"; + BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed"; // If it's a browser connecting, don't send the HTTP authenticate header, // to avoid possible CSRF attacks with basic auth - if (http_helpers::request_prefers_html(req)) { + if (http_helpers::requestPrefersHtml(req)) { res.result(boost::beast::http::status::temporary_redirect); - res.add_header("Location", "/#/login"); + res.addHeader("Location", "/#/login"); } else { res.result(boost::beast::http::status::unauthorized); // only send the WWW-authenticate header if this isn't a xhr from the // browser. most scripts, - if (req.get_header_value("User-Agent").empty()) { - res.add_header("WWW-Authenticate", "Basic"); + if (req.getHeaderValue("User-Agent").empty()) { + res.addHeader("WWW-Authenticate", "Basic"); } } @@ -62,124 +62,122 @@ class Middleware { return; } - // TODO get user privileges here and propagate it via MW context + // TODO get user privileges here and propagate it via MW Context // else let the request continue unharmed } template <typename AllContext> - void after_handle(request& req, response& res, context& ctx, - AllContext& allctx) { + void afterHandle(Request& req, Response& res, Context& ctx, + AllContext& allctx) { // TODO(ed) THis should really be handled by the persistent data // middleware, but because it is upstream, it doesn't have access to the // session information. Should the data middleware persist the current // user session? if (ctx.session != nullptr && ctx.session->persistence == - crow::PersistentData::PersistenceType::SINGLE_REQUEST) { - PersistentData::SessionStore::getInstance().remove_session(ctx.session); + crow::persistent_data::PersistenceType::SINGLE_REQUEST) { + persistent_data::SessionStore::getInstance().removeSession(ctx.session); } } private: - const std::shared_ptr<crow::PersistentData::UserSession> perform_basic_auth( + const std::shared_ptr<crow::persistent_data::UserSession> performBasicAuth( boost::string_view auth_header) const { - CROW_LOG_DEBUG << "[AuthMiddleware] Basic authentication"; + BMCWEB_LOG_DEBUG << "[AuthMiddleware] Basic authentication"; - std::string auth_data; + std::string authData; boost::string_view param = auth_header.substr(strlen("Basic ")); - if (!crow::utility::base64_decode(param, auth_data)) { + if (!crow::utility::base64Decode(param, authData)) { return nullptr; } - std::size_t separator = auth_data.find(':'); + std::size_t separator = authData.find(':'); if (separator == std::string::npos) { return nullptr; } - std::string user = auth_data.substr(0, separator); + std::string user = authData.substr(0, separator); separator += 1; - if (separator > auth_data.size()) { + if (separator > authData.size()) { return nullptr; } - std::string pass = auth_data.substr(separator); + std::string pass = authData.substr(separator); - CROW_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user; + BMCWEB_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user; - if (!pam_authenticate_user(user, pass)) { + if (!pamAuthenticateUser(user, pass)) { return nullptr; } - // TODO(ed) generate_user_session is a little expensive for basic + // TODO(ed) generateUserSession is a little expensive for basic // auth, as it generates some random identifiers that will never be // used. This should have a "fast" path for when user tokens aren't // needed. // This whole flow needs to be revisited anyway, as we can't be // calling directly into pam for every request - return PersistentData::SessionStore::getInstance().generate_user_session( - user, crow::PersistentData::PersistenceType::SINGLE_REQUEST); + return persistent_data::SessionStore::getInstance().generateUserSession( + user, crow::persistent_data::PersistenceType::SINGLE_REQUEST); } - const std::shared_ptr<crow::PersistentData::UserSession> perform_token_auth( + const std::shared_ptr<crow::persistent_data::UserSession> performTokenAuth( boost::string_view auth_header) const { - CROW_LOG_DEBUG << "[AuthMiddleware] Token authentication"; + BMCWEB_LOG_DEBUG << "[AuthMiddleware] Token authentication"; boost::string_view token = auth_header.substr(strlen("Token ")); auto session = - PersistentData::SessionStore::getInstance().login_session_by_token( - token); + persistent_data::SessionStore::getInstance().loginSessionByToken(token); return session; } - const std::shared_ptr<crow::PersistentData::UserSession> perform_xtoken_auth( - const crow::request& req) const { - CROW_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication"; + const std::shared_ptr<crow::persistent_data::UserSession> performXtokenAuth( + const crow::Request& req) const { + BMCWEB_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication"; - boost::string_view token = req.get_header_value("X-Auth-Token"); + boost::string_view token = req.getHeaderValue("X-Auth-Token"); if (token.empty()) { return nullptr; } auto session = - PersistentData::SessionStore::getInstance().login_session_by_token( - token); + persistent_data::SessionStore::getInstance().loginSessionByToken(token); return session; } - const std::shared_ptr<crow::PersistentData::UserSession> perform_cookie_auth( - const crow::request& req) const { - CROW_LOG_DEBUG << "[AuthMiddleware] Cookie authentication"; + const std::shared_ptr<crow::persistent_data::UserSession> performCookieAuth( + const crow::Request& req) const { + BMCWEB_LOG_DEBUG << "[AuthMiddleware] Cookie authentication"; - boost::string_view cookie_value = req.get_header_value("Cookie"); - if (cookie_value.empty()) { + boost::string_view cookieValue = req.getHeaderValue("Cookie"); + if (cookieValue.empty()) { return nullptr; } - auto start_index = cookie_value.find("SESSION="); - if (start_index == std::string::npos) { + auto startIndex = cookieValue.find("SESSION="); + if (startIndex == std::string::npos) { return nullptr; } - start_index += sizeof("SESSION=") - 1; - auto end_index = cookie_value.find(";", start_index); - if (end_index == std::string::npos) { - end_index = cookie_value.size(); + startIndex += sizeof("SESSION=") - 1; + auto endIndex = cookieValue.find(";", startIndex); + if (endIndex == std::string::npos) { + endIndex = cookieValue.size(); } - boost::string_view auth_key = - cookie_value.substr(start_index, end_index - start_index); + boost::string_view authKey = + cookieValue.substr(startIndex, endIndex - startIndex); - const std::shared_ptr<crow::PersistentData::UserSession> session = - PersistentData::SessionStore::getInstance().login_session_by_token( - auth_key); + const std::shared_ptr<crow::persistent_data::UserSession> session = + persistent_data::SessionStore::getInstance().loginSessionByToken( + authKey); if (session == nullptr) { return nullptr; } #ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION // RFC7231 defines methods that need csrf protection if (req.method() != "GET"_method) { - boost::string_view csrf = req.get_header_value("X-XSRF-TOKEN"); + boost::string_view csrf = req.getHeaderValue("X-XSRF-TOKEN"); // Make sure both tokens are filled - if (csrf.empty() || session->csrf_token.empty()) { + if (csrf.empty() || session->csrfToken.empty()) { return nullptr; } // Reject if csrf token not available - if (csrf != session->csrf_token) { + if (csrf != session->csrfToken) { return nullptr; } } @@ -188,7 +186,7 @@ class Middleware { } // checks if request can be forwarded without authentication - bool is_on_whitelist(const crow::request& req) const { + bool isOnWhitelist(const crow::Request& req) const { // it's allowed to GET root node without authentica tion if ("GET"_method == req.method()) { if (req.url == "/redfish/v1" || req.url == "/redfish/v1/") { @@ -217,27 +215,27 @@ class Middleware { // routes. // Possibly an init function on first construction? template <typename... Middlewares> -void request_routes(Crow<Middlewares...>& app) { +void requestRoutes(Crow<Middlewares...>& app) { static_assert( - black_magic::contains<PersistentData::Middleware, Middlewares...>::value, - "TokenAuthorization middleware must be enabled in app to use " + black_magic::Contains<persistent_data::Middleware, Middlewares...>::value, + "token_authorization middleware must be enabled in app to use " "auth routes"); - CROW_ROUTE(app, "/login") + BMCWEB_ROUTE(app, "/login") .methods( - "POST"_method)([&](const crow::request& req, crow::response& res) { - boost::string_view content_type = req.get_header_value("content-type"); + "POST"_method)([&](const crow::Request& req, crow::Response& res) { + boost::string_view contentType = req.getHeaderValue("content-type"); boost::string_view username; boost::string_view password; - bool looks_like_ibm = false; + bool looksLikeIbm = false; // This object needs to be declared at this scope so the strings // within it are not destroyed before we can use them - nlohmann::json login_credentials; + nlohmann::json loginCredentials; // Check if auth was provided by a payload - if (content_type == "application/json") { - login_credentials = nlohmann::json::parse(req.body, nullptr, false); - if (login_credentials.is_discarded()) { + if (contentType == "application/json") { + loginCredentials = nlohmann::json::parse(req.body, nullptr, false); + if (loginCredentials.is_discarded()) { res.result(boost::beast::http::status::bad_request); res.end(); return; @@ -245,54 +243,51 @@ void request_routes(Crow<Middlewares...>& app) { // check for username/password in the root object // THis method is how intel APIs authenticate - nlohmann::json::iterator user_it = login_credentials.find("username"); - nlohmann::json::iterator pass_it = login_credentials.find("password"); - if (user_it != login_credentials.end() && - pass_it != login_credentials.end()) { - const std::string* user_str = - user_it->get_ptr<const std::string*>(); - const std::string* pass_str = - pass_it->get_ptr<const std::string*>(); - if (user_str != nullptr && pass_str != nullptr) { - username = *user_str; - password = *pass_str; + nlohmann::json::iterator userIt = loginCredentials.find("username"); + nlohmann::json::iterator passIt = loginCredentials.find("password"); + if (userIt != loginCredentials.end() && + passIt != loginCredentials.end()) { + const std::string* userStr = userIt->get_ptr<const std::string*>(); + const std::string* passStr = passIt->get_ptr<const std::string*>(); + if (userStr != nullptr && passStr != nullptr) { + username = *userStr; + password = *passStr; } } else { // Openbmc appears to push a data object that contains the same // keys (username and password), attempt to use that - auto data_it = login_credentials.find("data"); - if (data_it != login_credentials.end()) { + auto dataIt = loginCredentials.find("data"); + if (dataIt != loginCredentials.end()) { // Some apis produce an array of value ["username", // "password"] - if (data_it->is_array()) { - if (data_it->size() == 2) { - nlohmann::json::iterator user_it2 = data_it->begin(); - nlohmann::json::iterator pass_it2 = data_it->begin() + 1; - looks_like_ibm = true; - if (user_it2 != data_it->end() && - pass_it2 != data_it->end()) { - const std::string* user_str = - user_it2->get_ptr<const std::string*>(); - const std::string* pass_str = - pass_it2->get_ptr<const std::string*>(); - if (user_str != nullptr && pass_str != nullptr) { - username = *user_str; - password = *pass_str; + if (dataIt->is_array()) { + if (dataIt->size() == 2) { + nlohmann::json::iterator userIt2 = dataIt->begin(); + nlohmann::json::iterator passIt2 = dataIt->begin() + 1; + looksLikeIbm = true; + if (userIt2 != dataIt->end() && passIt2 != dataIt->end()) { + const std::string* userStr = + userIt2->get_ptr<const std::string*>(); + const std::string* passStr = + passIt2->get_ptr<const std::string*>(); + if (userStr != nullptr && passStr != nullptr) { + username = *userStr; + password = *passStr; } } } - } else if (data_it->is_object()) { - nlohmann::json::iterator user_it2 = data_it->find("username"); - nlohmann::json::iterator pass_it2 = data_it->find("password"); - if (user_it2 != data_it->end() && pass_it2 != data_it->end()) { - const std::string* user_str = - user_it2->get_ptr<const std::string*>(); - const std::string* pass_str = - pass_it2->get_ptr<const std::string*>(); - if (user_str != nullptr && pass_str != nullptr) { - username = *user_str; - password = *pass_str; + } else if (dataIt->is_object()) { + nlohmann::json::iterator userIt2 = dataIt->find("username"); + nlohmann::json::iterator passIt2 = dataIt->find("password"); + if (userIt2 != dataIt->end() && passIt2 != dataIt->end()) { + const std::string* userStr = + userIt2->get_ptr<const std::string*>(); + const std::string* passStr = + passIt2->get_ptr<const std::string*>(); + if (userStr != nullptr && passStr != nullptr) { + username = *userStr; + password = *passStr; } } } @@ -300,22 +295,22 @@ void request_routes(Crow<Middlewares...>& app) { } } else { // check if auth was provided as a headers - username = req.get_header_value("username"); - password = req.get_header_value("password"); + username = req.getHeaderValue("username"); + password = req.getHeaderValue("password"); } if (!username.empty() && !password.empty()) { - if (!pam_authenticate_user(username, password)) { + if (!pamAuthenticateUser(username, password)) { res.result(boost::beast::http::status::unauthorized); } else { - auto session = PersistentData::SessionStore::getInstance() - .generate_user_session(username); + auto session = persistent_data::SessionStore::getInstance() + .generateUserSession(username); - if (looks_like_ibm) { + if (looksLikeIbm) { // IBM requires a very specific login structure, and doesn't // actually look at the status code. TODO(ed).... Fix that // upstream - res.json_value = { + res.jsonValue = { {"data", "User '" + std::string(username) + "' logged in"}, {"message", "200 OK"}, {"status", "ok"}}; @@ -329,13 +324,13 @@ void request_routes(Crow<Middlewares...>& app) { // "set-cookie" string into the value header, and get the result // we want, even though we are technicaly declaring two headers // here. - res.add_header("Set-Cookie", - "XSRF-TOKEN=" + session->csrf_token + - "; Secure\r\nSet-Cookie: SESSION=" + - session->session_token + "; Secure; HttpOnly"); + res.addHeader("Set-Cookie", + "XSRF-TOKEN=" + session->csrfToken + + "; Secure\r\nSet-Cookie: SESSION=" + + session->sessionToken + "; Secure; HttpOnly"); } else { // if content type is json, assume json token - res.json_value = {{"token", session->session_token}}; + res.jsonValue = {{"token", session->sessionToken}}; } } @@ -345,18 +340,18 @@ void request_routes(Crow<Middlewares...>& app) { res.end(); }); - CROW_ROUTE(app, "/logout") + BMCWEB_ROUTE(app, "/logout") .methods( - "POST"_method)([&](const crow::request& req, crow::response& res) { + "POST"_method)([&](const crow::Request& req, crow::Response& res) { auto& session = - app.template get_context<TokenAuthorization::Middleware>(req) + app.template getContext<token_authorization::Middleware>(req) .session; if (session != nullptr) { - PersistentData::SessionStore::getInstance().remove_session(session); + persistent_data::SessionStore::getInstance().removeSession(session); } res.end(); return; }); } -} // namespace TokenAuthorization +} // namespace token_authorization } // namespace crow diff --git a/include/web_kvm.hpp b/include/web_kvm.hpp index 82cb488c5f..ad4b352eb4 100644 --- a/include/web_kvm.hpp +++ b/include/web_kvm.hpp @@ -8,9 +8,9 @@ namespace crow { namespace kvm { -static const std::string rfb_3_3_version_string = "RFB 003.003\n"; -static const std::string rfb_3_7_version_string = "RFB 003.007\n"; -static const std::string rfb_3_8_version_string = "RFB 003.008\n"; +static const std::string rfb33VersionString = "RFB 003.003\n"; +static const std::string rfb37VersionString = "RFB 003.007\n"; +static const std::string rfb38VersionString = "RFB 003.008\n"; enum class RfbAuthScheme : uint8_t { connection_failed = 0, @@ -18,27 +18,27 @@ enum class RfbAuthScheme : uint8_t { vnc_authentication = 2 }; -struct pixel_format_struct { - boost::endian::big_uint8_t bits_per_pixel; +struct PixelFormatStruct { + boost::endian::big_uint8_t bitsPerPixel; boost::endian::big_uint8_t depth; - boost::endian::big_uint8_t is_big_endian; - boost::endian::big_uint8_t is_true_color; - boost::endian::big_uint16_t red_max; - boost::endian::big_uint16_t green_max; - boost::endian::big_uint16_t blue_max; - boost::endian::big_uint8_t red_shift; - boost::endian::big_uint8_t green_shift; - boost::endian::big_uint8_t blue_shift; + boost::endian::big_uint8_t isBigEndian; + boost::endian::big_uint8_t isTrueColor; + boost::endian::big_uint16_t redMax; + boost::endian::big_uint16_t greenMax; + boost::endian::big_uint16_t blueMax; + boost::endian::big_uint8_t redShift; + boost::endian::big_uint8_t greenShift; + boost::endian::big_uint8_t blueShift; boost::endian::big_uint8_t pad1; boost::endian::big_uint8_t pad2; boost::endian::big_uint8_t pad3; }; -struct server_initialization_msg { - boost::endian::big_uint16_t framebuffer_width; - boost::endian::big_uint16_t framebuffer_height; - pixel_format_struct pixel_format; - boost::endian::big_uint32_t name_length; +struct ServerInitializationMsg { + boost::endian::big_uint16_t framebufferWidth; + boost::endian::big_uint16_t framebufferHeight; + PixelFormatStruct pixelFormat; + boost::endian::big_uint32_t nameLength; }; enum class client_to_server_msg_type : uint8_t { @@ -58,35 +58,35 @@ enum class server_to_client_message_type : uint8_t { server_cut_text = 3 }; -struct set_pixel_format_msg { +struct SetPixelFormatMsg { boost::endian::big_uint8_t pad1; boost::endian::big_uint8_t pad2; boost::endian::big_uint8_t pad3; - pixel_format_struct pixel_format; + PixelFormatStruct pixelFormat; }; -struct frame_buffer_update_req { +struct FrameBufferUpdateReq { boost::endian::big_uint8_t incremental; - boost::endian::big_uint16_t x_position; - boost::endian::big_uint16_t y_position; + boost::endian::big_uint16_t xPosition; + boost::endian::big_uint16_t yPosition; boost::endian::big_uint16_t width; boost::endian::big_uint16_t height; }; -struct key_event_msg { - boost::endian::big_uint8_t down_flag; +struct KeyEventMsg { + boost::endian::big_uint8_t downFlag; boost::endian::big_uint8_t pad1; boost::endian::big_uint8_t pad2; boost::endian::big_uint32_t key; }; -struct pointer_event_msg { - boost::endian::big_uint8_t button_mask; - boost::endian::big_uint16_t x_position; - boost::endian::big_uint16_t y_position; +struct PointerEventMsg { + boost::endian::big_uint8_t buttonMask; + boost::endian::big_uint16_t xPosition; + boost::endian::big_uint16_t yPosition; }; -struct client_cut_text_msg { +struct ClientCutTextMsg { std::vector<uint8_t> data; }; @@ -105,7 +105,7 @@ enum class encoding_type : uint32_t { cache_enable = 0xFFFF0001, xor_enable = 0xFFFF0006, server_state_ultranvc = 0xFFFF8000, - enable_keep_alive = 0xFFFF8001, + enable_keepAlive = 0xFFFF8001, enableftp_protocol_version = 0xFFFF8002, tight_compress_level_0 = 0xFFFFFF00, tight_compress_level_9 = 0xFFFFFF09, @@ -118,7 +118,7 @@ enum class encoding_type : uint32_t { tight_quality_level_9 = 0xFFFFFFE9 }; -struct framebuffer_rectangle { +struct FramebufferRectangle { boost::endian::big_uint16_t x{}; boost::endian::big_uint16_t y{}; boost::endian::big_uint16_t width{}; @@ -127,35 +127,34 @@ struct framebuffer_rectangle { std::vector<uint8_t> data; }; -struct framebuffer_update_msg { - boost::endian::big_uint8_t message_type{}; - std::vector<framebuffer_rectangle> rectangles; +struct FramebufferUpdateMsg { + boost::endian::big_uint8_t messageType{}; + std::vector<FramebufferRectangle> rectangles; }; -inline std::string serialize(const framebuffer_update_msg& msg) { +inline std::string serialize(const FramebufferUpdateMsg& msg) { // calculate the size of the needed vector for serialization - size_t vector_size = 4; + size_t vectorSize = 4; for (const auto& rect : msg.rectangles) { - vector_size += 12 + rect.data.size(); + vectorSize += 12 + rect.data.size(); } - std::string serialized(vector_size, 0); + std::string serialized(vectorSize, 0); size_t i = 0; serialized[i++] = static_cast<char>( server_to_client_message_type::framebuffer_update); // Type serialized[i++] = 0; // Pad byte - boost::endian::big_uint16_t number_of_rectangles = msg.rectangles.size(); - std::memcpy(&serialized[i], &number_of_rectangles, - sizeof(number_of_rectangles)); - i += sizeof(number_of_rectangles); + boost::endian::big_uint16_t numberOfRectangles = msg.rectangles.size(); + std::memcpy(&serialized[i], &numberOfRectangles, sizeof(numberOfRectangles)); + i += sizeof(numberOfRectangles); for (const auto& rect : msg.rectangles) { // copy the first part of the struct - size_t buffer_size = - sizeof(framebuffer_rectangle) - sizeof(std::vector<uint8_t>); - std::memcpy(&serialized[i], &rect, buffer_size); - i += buffer_size; + size_t bufferSize = + sizeof(FramebufferRectangle) - sizeof(std::vector<uint8_t>); + std::memcpy(&serialized[i], &rect, bufferSize); + i += bufferSize; std::memcpy(&serialized[i], rect.data.data(), rect.data.size()); i += rect.data.size(); @@ -172,91 +171,90 @@ enum class VncState { MAIN_LOOP }; -class connection_metadata { +class ConnectionMetadata { public: - connection_metadata() {}; + ConnectionMetadata(){}; - VncState vnc_state{VncState::UNSTARTED}; + VncState vncState{VncState::UNSTARTED}; }; -using meta_list = std::vector<connection_metadata>; -meta_list connection_states(10); +using meta_list = std::vector<ConnectionMetadata>; +meta_list connectionStates(10); -connection_metadata meta; +ConnectionMetadata meta; template <typename... Middlewares> -void request_routes(Crow<Middlewares...>& app) { - CROW_ROUTE(app, "/kvmws") +void requestRoutes(Crow<Middlewares...>& app) { + BMCWEB_ROUTE(app, "/kvmws") .websocket() - .onopen([&](crow::websocket::connection& conn) { - if (meta.vnc_state == VncState::UNSTARTED) { - meta.vnc_state = VncState::AWAITING_CLIENT_VERSION; - conn.send_binary(rfb_3_8_version_string); + .onopen([&](crow::websocket::Connection& conn) { + if (meta.vncState == VncState::UNSTARTED) { + meta.vncState = VncState::AWAITING_CLIENT_VERSION; + conn.sendBinary(rfb38VersionString); } else { // SHould never happen conn.close(); } }) .onclose( - [&](crow::websocket::connection& conn, const std::string& reason) { - meta.vnc_state = VncState::UNSTARTED; + [&](crow::websocket::Connection& conn, const std::string& reason) { + meta.vncState = VncState::UNSTARTED; }) - .onmessage([&](crow::websocket::connection& conn, const std::string& data, + .onmessage([&](crow::websocket::Connection& conn, const std::string& data, bool is_binary) { - switch (meta.vnc_state) { + switch (meta.vncState) { case VncState::AWAITING_CLIENT_VERSION: { std::cout << "Client sent: " << data; - if (data == rfb_3_8_version_string || - data == rfb_3_7_version_string) { - std::string auth_types{1, - (uint8_t)RfbAuthScheme::no_authentication}; - conn.send_binary(auth_types); - meta.vnc_state = VncState::AWAITING_CLIENT_AUTH_METHOD; - } else if (data == rfb_3_3_version_string) { + if (data == rfb38VersionString || data == rfb37VersionString) { + std::string authTypes{1, + (uint8_t)RfbAuthScheme::no_authentication}; + conn.sendBinary(authTypes); + meta.vncState = VncState::AWAITING_CLIENT_AUTH_METHOD; + } else if (data == rfb33VersionString) { // TODO(ed) Support older protocols - meta.vnc_state = VncState::UNSTARTED; + meta.vncState = VncState::UNSTARTED; conn.close(); } else { // TODO(ed) Support older protocols - meta.vnc_state = VncState::UNSTARTED; + meta.vncState = VncState::UNSTARTED; conn.close(); } } break; case VncState::AWAITING_CLIENT_AUTH_METHOD: { - std::string security_result{{0, 0, 0, 0}}; + std::string securityResult{{0, 0, 0, 0}}; if (data[0] == (uint8_t)RfbAuthScheme::no_authentication) { - meta.vnc_state = VncState::AWAITING_CLIENT_INIT_msg; + meta.vncState = VncState::AWAITING_CLIENT_INIT_msg; } else { // Mark auth as failed - security_result[3] = 1; - meta.vnc_state = VncState::UNSTARTED; + securityResult[3] = 1; + meta.vncState = VncState::UNSTARTED; } - conn.send_binary(security_result); + conn.sendBinary(securityResult); } break; case VncState::AWAITING_CLIENT_INIT_msg: { // Now send the server initialization - server_initialization_msg server_init_msg{}; - server_init_msg.framebuffer_width = 800; - server_init_msg.framebuffer_height = 600; - server_init_msg.pixel_format.bits_per_pixel = 32; - server_init_msg.pixel_format.is_big_endian = 0; - server_init_msg.pixel_format.is_true_color = 1; - server_init_msg.pixel_format.red_max = 255; - server_init_msg.pixel_format.green_max = 255; - server_init_msg.pixel_format.blue_max = 255; - server_init_msg.pixel_format.red_shift = 16; - server_init_msg.pixel_format.green_shift = 8; - server_init_msg.pixel_format.blue_shift = 0; - server_init_msg.name_length = 0; - std::cout << "size: " << sizeof(server_init_msg); + ServerInitializationMsg serverInitMsg{}; + serverInitMsg.framebufferWidth = 800; + serverInitMsg.framebufferHeight = 600; + serverInitMsg.pixelFormat.bitsPerPixel = 32; + serverInitMsg.pixelFormat.isBigEndian = 0; + serverInitMsg.pixelFormat.isTrueColor = 1; + serverInitMsg.pixelFormat.redMax = 255; + serverInitMsg.pixelFormat.greenMax = 255; + serverInitMsg.pixelFormat.blueMax = 255; + serverInitMsg.pixelFormat.redShift = 16; + serverInitMsg.pixelFormat.greenShift = 8; + serverInitMsg.pixelFormat.blueShift = 0; + serverInitMsg.nameLength = 0; + std::cout << "size: " << sizeof(serverInitMsg); // TODO(ed) this is ugly. Crow should really have a span type // interface // to avoid the copy, but alas, today it does not. - std::string s(reinterpret_cast<char*>(&server_init_msg), - sizeof(server_init_msg)); + std::string s(reinterpret_cast<char*>(&serverInitMsg), + sizeof(serverInitMsg)); std::cout << "s.size() " << s.size(); - conn.send_binary(s); - meta.vnc_state = VncState::MAIN_LOOP; + conn.sendBinary(s); + meta.vncState = VncState::MAIN_LOOP; } break; case VncState::MAIN_LOOP: { if (data.size() >= sizeof(client_to_server_msg_type)) { @@ -274,55 +272,54 @@ void request_routes(Crow<Middlewares...>& app) { case client_to_server_msg_type::framebuffer_update_request: { // Make sure the buffer is long enough to handle what we're // about to do - if (data.size() >= sizeof(frame_buffer_update_req) + + if (data.size() >= sizeof(FrameBufferUpdateReq) + sizeof(client_to_server_msg_type)) { - auto msg = reinterpret_cast<const frame_buffer_update_req*>( - data.data() + // NOLINT + auto msg = reinterpret_cast<const FrameBufferUpdateReq*>( + data.data() + // NOLINT sizeof(client_to_server_msg_type)); // TODO(ed) find a better way to do this deserialization // Todo(ed) lifecycle of the video puller and decoder // should be // with the websocket, not recreated every time - AstVideo::SimpleVideoPuller p; + ast_video::SimpleVideoPuller p; p.initialize(); - auto out = p.read_video(); - AstVideo::AstJpegDecoder d; + auto out = p.readVideo(); + ast_video::AstJpegDecoder d; d.decode(out.buffer, out.width, out.height, out.mode, - out.y_selector, out.uv_selector); + out.ySelector, out.uvSelector); - framebuffer_update_msg buffer_update_msg; + FramebufferUpdateMsg bufferUpdateMsg; // If the viewer is requesting a full update, force write // of all pixels - framebuffer_rectangle this_rect; - this_rect.x = msg->x_position; - this_rect.y = msg->y_position; - this_rect.width = out.width; - this_rect.height = out.height; - this_rect.encoding = + FramebufferRectangle thisRect; + thisRect.x = msg->xPosition; + thisRect.y = msg->yPosition; + thisRect.width = out.width; + thisRect.height = out.height; + thisRect.encoding = static_cast<uint8_t>(encoding_type::raw); - std::cout << "Encoding is " << this_rect.encoding; - this_rect.data.reserve( - static_cast<std::size_t>(this_rect.width) * - static_cast<std::size_t>(this_rect.height) * 4); + std::cout << "Encoding is " << thisRect.encoding; + thisRect.data.reserve( + static_cast<std::size_t>(thisRect.width) * + static_cast<std::size_t>(thisRect.height) * 4); std::cout << "Width " << out.width << " Height " << out.height; for (int i = 0; i < out.width * out.height; i++) { - auto& pixel = d.OutBuffer[i]; - this_rect.data.push_back(pixel.B); - this_rect.data.push_back(pixel.G); - this_rect.data.push_back(pixel.R); - this_rect.data.push_back(0); + auto& pixel = d.outBuffer[i]; + thisRect.data.push_back(pixel.b); + thisRect.data.push_back(pixel.g); + thisRect.data.push_back(pixel.r); + thisRect.data.push_back(0); } - buffer_update_msg.rectangles.push_back( - std::move(this_rect)); - auto serialized = serialize(buffer_update_msg); + bufferUpdateMsg.rectangles.push_back(std::move(thisRect)); + auto serialized = serialize(bufferUpdateMsg); - conn.send_binary(serialized); + conn.sendBinary(serialized); } // TODO(Ed) handle error diff --git a/include/webassets.hpp b/include/webassets.hpp index 85de3addf4..161fc506f3 100644 --- a/include/webassets.hpp +++ b/include/webassets.hpp @@ -15,7 +15,7 @@ namespace webassets { namespace filesystem = std::experimental::filesystem; -struct cmp_str { +struct CmpStr { bool operator()(const char* a, const char* b) const { return std::strcmp(a, b) < 0; } @@ -24,9 +24,9 @@ struct cmp_str { static boost::container::flat_set<std::string> routes; template <typename... Middlewares> -void request_routes(Crow<Middlewares...>& app) { - const static boost::container::flat_map<const char*, const char*, cmp_str> - content_types{ +void requestRoutes(Crow<Middlewares...>& app) { + const static boost::container::flat_map<const char*, const char*, CmpStr> + contentTypes{ {{".css", "text/css;charset=UTF-8"}, {".html", "text/html;charset=UTF-8"}, {".js", "text/html;charset=UTF-8"}, @@ -46,12 +46,12 @@ void request_routes(Crow<Middlewares...>& app) { // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files {".map", "application/json"}}}; filesystem::path rootpath{"/usr/share/www/"}; - filesystem::recursive_directory_iterator dir_iter(rootpath); + filesystem::recursive_directory_iterator dirIter(rootpath); - for (const filesystem::directory_entry& dir : dir_iter) { - filesystem::path absolute_path = dir.path(); - filesystem::path relative_path{ - absolute_path.string().substr(rootpath.string().size() - 1)}; + for (const filesystem::directory_entry& dir : dirIter) { + filesystem::path absolutePath = dir.path(); + filesystem::path relativePath{ + absolutePath.string().substr(rootpath.string().size() - 1)}; // make sure we don't recurse into certain directories // note: maybe check for is_directory() here as well... @@ -59,18 +59,18 @@ void request_routes(Crow<Middlewares...>& app) { // don't recurse into hidden directories or symlinks if (boost::starts_with(dir.path().filename().string(), ".") || filesystem::is_symlink(dir)) { - dir_iter.disable_recursion_pending(); + dirIter.disable_recursion_pending(); } } else if (filesystem::is_regular_file(dir)) { - std::string extension = relative_path.extension(); - filesystem::path webpath = relative_path; - const char* content_encoding = nullptr; + std::string extension = relativePath.extension(); + filesystem::path webpath = relativePath; + const char* contentEncoding = nullptr; if (extension == ".gz") { webpath = webpath.replace_extension(""); // Use the non-gzip version for determining content type extension = webpath.extension().string(); - content_encoding = "gzip"; + contentEncoding = "gzip"; } if (boost::starts_with(webpath.filename().string(), "index.")) { @@ -83,38 +83,38 @@ void request_routes(Crow<Middlewares...>& app) { } routes.insert(webpath); - const char* content_type = nullptr; + const char* contentType = nullptr; - auto content_type_it = content_types.find(extension.c_str()); - if (content_type_it == content_types.end()) { - CROW_LOG_ERROR << "Cannot determine content-type for " << absolute_path - << " with extension " << extension; + auto contentTypeIt = contentTypes.find(extension.c_str()); + if (contentTypeIt == contentTypes.end()) { + BMCWEB_LOG_ERROR << "Cannot determine content-type for " << absolutePath + << " with extension " << extension; } else { - content_type = content_type_it->second; + contentType = contentTypeIt->second; } - app.route_dynamic(webpath)( - [absolute_path, content_type, content_encoding]( - const crow::request& req, crow::response& res) { - if (content_type != nullptr) { - res.add_header("Content-Type", content_type); + app.routeDynamic(webpath)( + [absolutePath, contentType, contentEncoding](const crow::Request& req, + crow::Response& res) { + if (contentType != nullptr) { + res.addHeader("Content-Type", contentType); } - if (content_encoding != nullptr) { - res.add_header("Content-Encoding", content_encoding); + if (contentEncoding != nullptr) { + res.addHeader("Content-Encoding", contentEncoding); } // res.set_header("Cache-Control", "public, max-age=86400"); - std::ifstream inf(absolute_path); + std::ifstream inf(absolutePath); if (!inf) { - CROW_LOG_DEBUG << "failed to read file"; + BMCWEB_LOG_DEBUG << "failed to read file"; res.result(boost::beast::http::status::internal_server_error); res.end(); return; } res.body() = {std::istreambuf_iterator<char>(inf), - std::istreambuf_iterator<char>()}; + std::istreambuf_iterator<char>()}; res.end(); }); } diff --git a/include/webserver_common.hpp b/include/webserver_common.hpp index 4d88629d26..30b567cd66 100644 --- a/include/webserver_common.hpp +++ b/include/webserver_common.hpp @@ -20,6 +20,6 @@ #include "security_headers_middleware.hpp" #include "webserver_common.hpp" -using CrowApp = crow::App<crow::PersistentData::Middleware, - crow::TokenAuthorization::Middleware, +using CrowApp = crow::App<crow::persistent_data::Middleware, + crow::token_authorization::Middleware, crow::SecurityHeadersMiddleware>; |