Fix the errors: [code] errors: quicserver.cpp: In function ‘int main()’:…
- User
Fix the errors:
// quic_server.cpp #include <msquic.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/x509v3.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <map> #include <memory> using UniqueX509 = std::unique_ptr<X509, decltype(&X509_free)>; using UniqueEVP = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>; using UniqueBIO = std::unique_ptr<BIO, decltype(&BIO_free_all)>; // Globals & Constants const QUIC_REGISTRATION_CONFIG RegConfig{ "game_sample", QUIC_EXECUTION_PROFILE_LOW_LATENCY }; const QUIC_BUFFER Alpn{ (uint32_t)strlen("gameplay"), (uint8_t*)"gameplay" }; const uint16_t Port = 7890; const QUIC_API_TABLE* MsQuic = nullptr; HQUIC Registration = nullptr; HQUIC Configuration = nullptr; HQUIC Listener = nullptr; struct ClientContext { std::string Username; }; std::map<HQUIC, ClientContext> ConnectedClients; // Generate RSA key and self-signed cert with EVP_PKEY_keygen (OpenSSL 3.x friendly) bool GenerateSelfSignedCert(std::string& certPem, std::string& keyPem) { bool ok = false; UniqueEVP pkey(nullptr, EVP_PKEY_free); { EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr); if (!ctx) return false; if (EVP_PKEY_keygen_init(ctx) <= 0) { EVP_PKEY_CTX_free(ctx); return false; } if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048) <= 0) { EVP_PKEY_CTX_free(ctx); return false; } EVP_PKEY* raw_pkey = nullptr; if (EVP_PKEY_keygen(ctx, &raw_pkey) <= 0) { EVP_PKEY_CTX_free(ctx); return false; } pkey.reset(raw_pkey); EVP_PKEY_CTX_free(ctx); } UniqueX509 x509(X509_new(), X509_free); if (!x509) return false; ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), 1); X509_gmtime_adj(X509_get_notBefore(x509.get()), 0); X509_gmtime_adj(X509_get_notAfter(x509.get()), 315360000L); // 10 years X509_set_pubkey(x509.get(), pkey.get()); X509_NAME* name = X509_get_subject_name(x509.get()); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char*)"localhost", -1, -1, 0); X509_set_issuer_name(x509.get(), name); if (X509_sign(x509.get(), pkey.get(), EVP_sha256()) == 0) return false; // PEM encode private key UniqueBIO bioKey(BIO_new(BIO_s_mem()), BIO_free_all); if (!bioKey) return false; if (!PEM_write_bio_PrivateKey(bioKey.get(), pkey.get(), nullptr, nullptr, 0, nullptr, nullptr)) return false; // PEM encode cert UniqueBIO bioCert(BIO_new(BIO_s_mem()), BIO_free_all); if (!bioCert) return false; if (!PEM_write_bio_X509(bioCert.get(), x509.get())) return false; char* data = nullptr; long size = BIO_get_mem_data(bioKey.get(), &data); if (size > 0) keyPem.assign(data, size); size = BIO_get_mem_data(bioCert.get(), &data); if (size > 0) certPem.assign(data, size); return true; } // Forward declarations for callbacks QUIC_STATUS QUIC_API ServerStreamCallback(HQUIC Stream, void* Context, QUIC_STREAM_EVENT* Event); QUIC_STATUS QUIC_API ServerConnectionCallback(HQUIC Connection, void* Context, QUIC_CONNECTION_EVENT* Event); QUIC_STATUS QUIC_API ServerListenerCallback(HQUIC Listener, void* Context, QUIC_LISTENER_EVENT* Event); // Callback implementations QUIC_STATUS QUIC_API ServerStreamCallback(HQUIC Stream, void* Context, QUIC_STREAM_EVENT* Event) { auto Connection = (HQUIC)Context; switch (Event->Type) { case QUIC_STREAM_EVENT_RECEIVE: if (Event->RECEIVE.BufferCount == 1) { auto& buf = Event->RECEIVE.Buffers[0]; std::string username(reinterpret_cast<const char*>(buf.Buffer), buf.Length); auto it = ConnectedClients.find(Connection); if (it != ConnectedClients.end() && it->second.Username.empty()) { it->second.Username = username; printf("[server] Client %p username: %s\n", Connection, username.c_str()); std::string welcome = "Welcome, " + username + "!\n"; QUIC_BUFFER sendBuf{ (uint32_t)welcome.size(), (uint8_t*)welcome.data() }; MsQuic->StreamSend(Stream, &sendBuf, 1, QUIC_SEND_FLAG_NONE, nullptr); } } break; case QUIC_STREAM_EVENT_SHUTDOWN_COMPLETE: MsQuic->StreamClose(Stream); break; default: break; } return QUIC_STATUS_SUCCESS; } QUIC_STATUS QUIC_API ServerConnectionCallback(HQUIC Connection, void* /*Context*/, QUIC_CONNECTION_EVENT* Event) { switch (Event->Type) { case QUIC_CONNECTION_EVENT_CONNECTED: printf("[server] Connection connected %p\n", Connection); ConnectedClients[Connection] = {}; break; case QUIC_CONNECTION_EVENT_SHUTDOWN_COMPLETE: printf("[server] Connection %p shutdown\n", Connection); ConnectedClients.erase(Connection); MsQuic->ConnectionClose(Connection); break; case QUIC_CONNECTION_EVENT_PEER_STREAM_STARTED: MsQuic->SetCallbackHandler(Event->PEER_STREAM_STARTED.Stream, (void*)ServerStreamCallback, Connection); break; default: break; } return QUIC_STATUS_SUCCESS; } QUIC_STATUS QUIC_API ServerListenerCallback(HQUIC /*Listener*/, void* /*Context*/, QUIC_LISTENER_EVENT* Event) { if (Event->Type == QUIC_LISTENER_EVENT_NEW_CONNECTION) { MsQuic->SetCallbackHandler(Event->NEW_CONNECTION.Connection, (void*)ServerConnectionCallback, nullptr); return MsQuic->ConnectionSetConfiguration(Event->NEW_CONNECTION.Connection, Configuration); } return QUIC_STATUS_NOT_SUPPORTED; } int main() { int ret = -1; if (QUIC_FAILED(MsQuicOpen2(&MsQuic))) { fprintf(stderr, "MsQuicOpen2 failed\n"); return ret; } if (QUIC_FAILED(MsQuic->RegistrationOpen(&RegConfig, &Registration))) { fprintf(stderr, "RegistrationOpen failed\n"); goto cleanup_msquic; } std::string certPem, keyPem; if (!GenerateSelfSignedCert(certPem, keyPem)) { fprintf(stderr, "Failed to generate self-signed cert\n"); goto cleanup_registration; } printf("Server Certificate PEM:\n%s\n", certPem.c_str()); printf("Server Private Key PEM:\n%s\n", keyPem.c_str()); printf("Copy above certificate PEM to client for trust.\n\n"); // Write PEM files const char* certFileName = "tmp_server_cert.pem"; const char* keyFileName = "tmp_server_key.pem"; FILE* certFile = fopen(certFileName, "wb"); if (!certFile) { fprintf(stderr, "Failed to open cert file for writing\n"); goto cleanup_registration; } fwrite(certPem.data(), 1, certPem.size(), certFile); fclose(certFile); FILE* keyFile = fopen(keyFileName, "wb"); if (!keyFile) { fprintf(stderr, "Failed to open key file for writing\n"); remove(certFileName); goto cleanup_registration; } fwrite(keyPem.data(), 1, keyPem.size(), keyFile); fclose(keyFile); QUIC_CERTIFICATE_FILE certFileConfig{}; certFileConfig.CertificateFile = (char*)certFileName; certFileConfig.PrivateKeyFile = (char*)keyFileName; QUIC_CREDENTIAL_CONFIG credConfig{}; credConfig.Type = QUIC_CREDENTIAL_TYPE_CERTIFICATE_FILE; credConfig.CertificateFile = &certFileConfig; credConfig.Flags = QUIC_CREDENTIAL_FLAG_NONE; QUIC_SETTINGS settings{}; settings.IdleTimeoutMs = 60000; // ms settings.IsSet.IdleTimeoutMs = TRUE; settings.PeerBidiStreamCount = 1; settings.IsSet.PeerBidiStreamCount = TRUE; if (QUIC_FAILED(MsQuic->ConfigurationOpen(Registration, &Alpn, 1, &settings, sizeof(settings), nullptr, &Configuration))) { fprintf(stderr, "ConfigurationOpen failed\n"); goto cleanup_files; } if (QUIC_FAILED(MsQuic->ConfigurationLoadCredential(Configuration, &credConfig))) { fprintf(stderr, "ConfigurationLoadCredential failed\n"); goto cleanup_config; } if (QUIC_FAILED(MsQuic->ListenerOpen(Registration, ServerListenerCallback, nullptr, &Listener))) { fprintf(stderr, "ListenerOpen failed\n"); goto cleanup_config; } QUIC_ADDR addr{}; QuicAddrSetFamily(&addr, QUIC_ADDRESS_FAMILY_UNSPEC); QuicAddrSetPort(&addr, Port); if (QUIC_FAILED(MsQuic->ListenerStart(Listener, &Alpn, 1, &addr))) { fprintf(stderr, "ListenerStart failed\n"); goto cleanup_listener; } printf("Server listening on UDP port %u. Press Enter to exit...\n", Port); getchar(); // Wait for user input to exit ret = 0; // success cleanup_listener: if (Listener) { MsQuic->ListenerClose(Listener); Listener = nullptr; } cleanup_config: if (Configuration) { MsQuic->ConfigurationClose(Configuration); Configuration = nullptr; } cleanup_files: remove(certFileName); remove(keyFileName); cleanup_registration: if (Registration) { MsQuic->RegistrationClose(Registration); Registration = nullptr; } cleanup_msquic: MsQuicClose(MsQuic); MsQuic = nullptr; return ret; }errors:
quic_server.cpp: In function ‘int main()’: quic_server.cpp:248:1: error: jump to label ‘cleanup_config’ 248 | cleanup_config: | ^~~~~~~~~~~~~~ quic_server.cpp:225:14: note: from here 225 | goto cleanup_config; | ^~~~~~~~~~~~~~ quic_server.cpp:228:15: note: crosses initialization of ‘QUIC_ADDR addr’ 228 | QUIC_ADDR addr{}; | ^~~~ quic_server.cpp:248:1: error: jump to label ‘cleanup_config’ 248 | cleanup_config: | ^~~~~~~~~~~~~~ quic_server.cpp:220:14: note: from here 220 | goto cleanup_config; | ^~~~~~~~~~~~~~ quic_server.cpp:228:15: note: crosses initialization of ‘QUIC_ADDR addr’ 228 | QUIC_ADDR addr{}; | ^~~~ quic_server.cpp:254:1: error: jump to label ‘cleanup_files’ 254 | cleanup_files: | ^~~~~~~~~~~~~ quic_server.cpp:215:14: note: from here 215 | goto cleanup_files; | ^~~~~~~~~~~~~ quic_server.cpp:228:15: note: crosses initialization of ‘QUIC_ADDR addr’ 228 | QUIC_ADDR addr{}; | ^~~~ quic_server.cpp:258:1: error: jump to label ‘cleanup_registration’ 258 | cleanup_registration: | ^~~~~~~~~~~~~~~~~~~~ quic_server.cpp:193:14: note: from here 193 | goto cleanup_registration; | ^~~~~~~~~~~~~~~~~~~~ quic_server.cpp:228:15: note: crosses initialization of ‘QUIC_ADDR addr’ 228 | QUIC_ADDR addr{}; | ^~~~ quic_server.cpp:207:19: note: crosses initialization of ‘QUIC_SETTINGS settings’ 207 | QUIC_SETTINGS settings{}; | ^~~~~~~~ quic_server.cpp:202:28: note: crosses initialization of ‘QUIC_CREDENTIAL_CONFIG credConfig’ 202 | QUIC_CREDENTIAL_CONFIG credConfig{}; | ^~~~~~~~~~ quic_server.cpp:198:27: note: crosses initialization of ‘QUIC_CERTIFICATE_FILE certFileConfig’ 198 | QUIC_CERTIFICATE_FILE certFileConfig{}; | ^~~~~~~~~~~~~~ quic_server.cpp:258:1: error: jump to label ‘cleanup_registration’ 258 | cleanup_registration: | ^~~~~~~~~~~~~~~~~~~~ quic_server.cpp:184:14: note: from here 184 | goto cleanup_registration; | ^~~~~~~~~~~~~~~~~~~~ quic_server.cpp:228:15: note: crosses initialization of ‘QUIC_ADDR addr’ 228 | QUIC_ADDR addr{}; | ^~~~ quic_server.cpp:207:19: note: crosses initialization of ‘QUIC_SETTINGS settings’ 207 | QUIC_SETTINGS settings{}; | ^~~~~~~~ quic_server.cpp:202:28: note: crosses initialization of ‘QUIC_CREDENTIAL_CONFIG credConfig’ 202 | QUIC_CREDENTIAL_CONFIG credConfig{}; | ^~~~~~~~~~ quic_server.cpp:198:27: note: crosses initialization of ‘QUIC_CERTIFICATE_FILE certFileConfig’ 198 | QUIC_CERTIFICATE_FILE certFileConfig{}; | ^~~~~~~~~~~~~~ quic_server.cpp:189:11: note: crosses initialization of ‘FILE* keyFile’ 189 | FILE* keyFile = fopen(keyFileName, "wb"); | ^~~~~~~ quic_server.cpp:258:1: error: jump to label ‘cleanup_registration’ 258 | cleanup_registration: | ^~~~~~~~~~~~~~~~~~~~ quic_server.cpp:170:14: note: from here 170 | goto cleanup_registration; | ^~~~~~~~~~~~~~~~~~~~ quic_server.cpp:228:15: note: crosses initialization of ‘QUIC_ADDR addr’ 228 | QUIC_ADDR addr{}; | ^~~~ quic_server.cpp:207:19: note: crosses initialization of ‘QUIC_SETTINGS settings’ 207 | QUIC_SETTINGS settings{}; | ^~~~~~~~ quic_server.cpp:202:28: note: crosses initialization of ‘QUIC_CREDENTIAL_CONFIG credConfig’ 202 | QUIC_CREDENTIAL_CONFIG credConfig{}; | ^~~~~~~~~~ quic_server.cpp:198:27: note: crosses initialization of ‘QUIC_CERTIFICATE_FILE certFileConfig’ 198 | QUIC_CERTIFICATE_FILE certFileConfig{}; | ^~~~~~~~~~~~~~ quic_server.cpp:189:11: note: crosses initialization of ‘FILE* keyFile’ 189 | FILE* keyFile = fopen(keyFileName, "wb"); | ^~~~~~~ quic_server.cpp:181:11: note: crosses initialization of ‘FILE* certFile’ 181 | FILE* certFile = fopen(certFileName, "wb"); | ^~~~~~~~ quic_server.cpp:179:17: note: crosses initialization of ‘const char* keyFileName’ 179 | const char* keyFileName = "tmp_server_key.pem"; | ^~~~~~~~~~~ quic_server.cpp:178:17: note: crosses initialization of ‘const char* certFileName’ 178 | const char* certFileName = "tmp_server_cert.pem"; | ^~~~~~~~~~~~ quic_server.cpp:264:1: error: jump to label ‘cleanup_msquic’ 264 | cleanup_msquic: | ^~~~~~~~~~~~~~ quic_server.cpp:164:14: note: from here 164 | goto cleanup_msquic; | ^~~~~~~~~~~~~~ quic_server.cpp:228:15: note: crosses initialization of ‘QUIC_ADDR addr’ 228 | QUIC_ADDR addr{}; | ^~~~ quic_server.cpp:207:19: note: crosses initialization of ‘QUIC_SETTINGS settings’ 207 | QUIC_SETTINGS settings{}; | ^~~~~~~~ quic_server.cpp:202:28: note: crosses initialization of ‘QUIC_CREDENTIAL_CONFIG credConfig’ 202 | QUIC_CREDENTIAL_CONFIG credConfig{}; | ^~~~~~~~~~ quic_server.cpp:198:27: note: crosses initialization of ‘QUIC_CERTIFICATE_FILE certFileConfig’ 198 | QUIC_CERTIFICATE_FILE certFileConfig{}; | ^~~~~~~~~~~~~~ quic_server.cpp:189:11: note: crosses initialization of ‘FILE* keyFile’ 189 | FILE* keyFile = fopen(keyFileName, "wb"); | ^~~~~~~ quic_server.cpp:181:11: note: crosses initialization of ‘FILE* certFile’ 181 | FILE* certFile = fopen(certFileName, "wb"); | ^~~~~~~~ quic_server.cpp:179:17: note: crosses initialization of ‘const char* keyFileName’ 179 | const char* keyFileName = "tmp_server_key.pem"; | ^~~~~~~~~~~ quic_server.cpp:178:17: note: crosses initialization of ‘const char* certFileName’ 178 | const char* certFileName = "tmp_server_cert.pem"; | ^~~~~~~~~~~~ quic_server.cpp:167:26: note: crosses initialization of ‘std::string keyPem’ 167 | std::string certPem, keyPem; | ^~~~~~ quic_server.cpp:167:17: note: crosses initialization of ‘std::string certPem’ 167 | std::string certPem, keyPem; | ^~~~~~~
- Assistant
The errors you are encountering all stem from using
gotostatements to jump backward over local variable initializations, which is disallowed in C++. Thegotocannot skip variable initializations between the jump point and the label—it must only jump forward or in such a way that it doesn't cross initialization of variables with non-trivial constructors or destructors.How to fix
You have multiple variables declared in the middle of your
main()function and thengotothat jumps backward to cleanup labels declared earlier.
Solution:- Move all your local variable declarations at the top of the function, before any
gotostatements. - Alternatively, rewrite the control flow to avoid backward
gotos or useboolflags andif/elsechains. - Also, ensure your cleanup labels are placed after all variable declarations.
Here is a fixed version of your
main()function addressing those issues:int main() { int ret = -1; // Declare all variables here, before any control flow with gotos const char* certFileName = "tmp_server_cert.pem"; const char* keyFileName = "tmp_server_key.pem"; std::string certPem, keyPem; FILE* certFile = nullptr; FILE* keyFile = nullptr; QUIC_CERTIFICATE_FILE certFileConfig{}; QUIC_CREDENTIAL_CONFIG credConfig{}; QUIC_SETTINGS settings{}; QUIC_ADDR addr{}; // NULL / zero initialize handles Registration = nullptr; Configuration = nullptr; Listener = nullptr; if (QUIC_FAILED(MsQuicOpen2(&MsQuic))) { fprintf(stderr, "MsQuicOpen2 failed\n"); return ret; } if (QUIC_FAILED(MsQuic->RegistrationOpen(&RegConfig, &Registration))) { fprintf(stderr, "RegistrationOpen failed\n"); goto cleanup_msquic; } if (!GenerateSelfSignedCert(certPem, keyPem)) { fprintf(stderr, "Failed to generate self-signed cert\n"); goto cleanup_registration; } printf("Server Certificate PEM:\n%s\n", certPem.c_str()); printf("Server Private Key PEM:\n%s\n", keyPem.c_str()); printf("Copy above certificate PEM to client for trust.\n\n"); certFile = fopen(certFileName, "wb"); if (!certFile) { fprintf(stderr, "Failed to open cert file for writing\n"); goto cleanup_registration; } fwrite(certPem.data(), 1, certPem.size(), certFile); fclose(certFile); certFile = nullptr; keyFile = fopen(keyFileName, "wb"); if (!keyFile) { fprintf(stderr, "Failed to open key file for writing\n"); remove(certFileName); goto cleanup_registration; } fwrite(keyPem.data(), 1, keyPem.size(), keyFile); fclose(keyFile); keyFile = nullptr; certFileConfig.CertificateFile = (char*)certFileName; certFileConfig.PrivateKeyFile = (char*)keyFileName; credConfig.Type = QUIC_CREDENTIAL_TYPE_CERTIFICATE_FILE; credConfig.CertificateFile = &certFileConfig; credConfig.Flags = QUIC_CREDENTIAL_FLAG_NONE; settings.IdleTimeoutMs = 60000; // 1 minute settings.IsSet.IdleTimeoutMs = TRUE; settings.PeerBidiStreamCount = 1; settings.IsSet.PeerBidiStreamCount = TRUE; if (QUIC_FAILED(MsQuic->ConfigurationOpen(Registration, &Alpn, 1, &settings, sizeof(settings), nullptr, &Configuration))) { fprintf(stderr, "ConfigurationOpen failed\n"); goto cleanup_files; } if (QUIC_FAILED(MsQuic->ConfigurationLoadCredential(Configuration, &credConfig))) { fprintf(stderr, "ConfigurationLoadCredential failed\n"); goto cleanup_config; } if (QUIC_FAILED(MsQuic->ListenerOpen(Registration, ServerListenerCallback, nullptr, &Listener))) { fprintf(stderr, "ListenerOpen failed\n"); goto cleanup_config; } QuicAddrSetFamily(&addr, QUIC_ADDRESS_FAMILY_UNSPEC); QuicAddrSetPort(&addr, Port); if (QUIC_FAILED(MsQuic->ListenerStart(Listener, &Alpn, 1, &addr))) { fprintf(stderr, "ListenerStart failed\n"); goto cleanup_listener; } printf("Server listening on UDP port %u. Press Enter to exit...\n", Port); getchar(); // Wait for user input to exit ret = 0; // success cleanup_listener: if (Listener) { MsQuic->ListenerClose(Listener); Listener = nullptr; } cleanup_config: if (Configuration) { MsQuic->ConfigurationClose(Configuration); Configuration = nullptr; } cleanup_files: remove(certFileName); remove(keyFileName); cleanup_registration: if (Registration) { MsQuic->RegistrationClose(Registration); Registration = nullptr; } cleanup_msquic: MsQuicClose(MsQuic); MsQuic = nullptr; // Just in case files are still open (shouldn't happen, but be safe) if (certFile) fclose(certFile); if (keyFile) fclose(keyFile); return ret; }Key changes:
-
Move variable declarations to the top:
All variables, including
certFileName,keyFileName,certPem,keyPem,FILE*pointers,QUIC_CERTIFICATE_FILE,QUIC_CREDENTIAL_CONFIG,QUIC_SETTINGS, andQUIC_ADDRare declared before anygotoor labels. -
Close files immediately after writing and set their pointers nullptr,
so you don't carry open file handles into the cleanup.
-
Added safety checks to fclose in cleanup,
though logically those files are always closed before goto jumps.
-
All
gotostatements jump forward only,so no crossing initialization.
Why this fixes the error?
In C++,
gotocannot jump over initializations of variables that have non-trivial constructors or destructors because it would skip their initialization, leading to undefined behavior. Moving all variables up front means thegotostatements only jump downward past labels or forward, not skipping any initializations.
Additional suggestions:
- Consider rewriting using RAII wrappers instead of manual resource management and
goto. For example, use smart pointers or custom wrapper objects for your handles. - Moving away from
gotowill make the code modern and more maintainable. - If the project allows, use C++ exceptions and try/catch blocks to manage errors and cleanup.
Let me know if you want me to help you rewrite the function with RAII or cleaner error handling!
- Move all your local variable declarations at the top of the function, before any
- User
Provide the complete code with all imports etc.
- Assistant
Certainly! Here's the complete fixed version of your
quic_server.cppincluding all includes, the fixedmain()function with all variable declarations moved up to avoidgotojumps over initializations, and your original code unchanged otherwise.// quic_server.cpp #include <msquic.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/x509v3.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <map> #include <memory> // Unique pointer alias for OpenSSL types using UniqueX509 = std::unique_ptr<X509, decltype(&X509_free)>; using UniqueEVP = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>; using UniqueBIO = std::unique_ptr<BIO, decltype(&BIO_free_all)>; // Globals & Constants const QUIC_REGISTRATION_CONFIG RegConfig{ "game_sample", QUIC_EXECUTION_PROFILE_LOW_LATENCY }; const QUIC_BUFFER Alpn{ (uint32_t)strlen("gameplay"), (uint8_t*)"gameplay" }; const uint16_t Port = 7890; const QUIC_API_TABLE* MsQuic = nullptr; HQUIC Registration = nullptr; HQUIC Configuration = nullptr; HQUIC Listener = nullptr; struct ClientContext { std::string Username; }; std::map<HQUIC, ClientContext> ConnectedClients; // Generate RSA key and self-signed cert with EVP_PKEY_keygen (OpenSSL 3.x friendly) bool GenerateSelfSignedCert(std::string& certPem, std::string& keyPem) { bool ok = false; UniqueEVP pkey(nullptr, EVP_PKEY_free); { EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr); if (!ctx) return false; if (EVP_PKEY_keygen_init(ctx) <= 0) { EVP_PKEY_CTX_free(ctx); return false; } if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048) <= 0) { EVP_PKEY_CTX_free(ctx); return false; } EVP_PKEY* raw_pkey = nullptr; if (EVP_PKEY_keygen(ctx, &raw_pkey) <= 0) { EVP_PKEY_CTX_free(ctx); return false; } pkey.reset(raw_pkey); EVP_PKEY_CTX_free(ctx); } UniqueX509 x509(X509_new(), X509_free); if (!x509) return false; ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), 1); X509_gmtime_adj(X509_get_notBefore(x509.get()), 0); X509_gmtime_adj(X509_get_notAfter(x509.get()), 315360000L); // 10 years X509_set_pubkey(x509.get(), pkey.get()); X509_NAME* name = X509_get_subject_name(x509.get()); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char*)"localhost", -1, -1, 0); X509_set_issuer_name(x509.get(), name); if (X509_sign(x509.get(), pkey.get(), EVP_sha256()) == 0) return false; // PEM encode private key UniqueBIO bioKey(BIO_new(BIO_s_mem()), BIO_free_all); if (!bioKey) return false; if (!PEM_write_bio_PrivateKey(bioKey.get(), pkey.get(), nullptr, nullptr, 0, nullptr, nullptr)) return false; // PEM encode cert UniqueBIO bioCert(BIO_new(BIO_s_mem()), BIO_free_all); if (!bioCert) return false; if (!PEM_write_bio_X509(bioCert.get(), x509.get())) return false; char* data = nullptr; long size = BIO_get_mem_data(bioKey.get(), &data); if (size > 0) keyPem.assign(data, size); size = BIO_get_mem_data(bioCert.get(), &data); if (size > 0) certPem.assign(data, size); return true; } // Forward declarations for callbacks QUIC_STATUS QUIC_API ServerStreamCallback(HQUIC Stream, void* Context, QUIC_STREAM_EVENT* Event); QUIC_STATUS QUIC_API ServerConnectionCallback(HQUIC Connection, void* Context, QUIC_CONNECTION_EVENT* Event); QUIC_STATUS QUIC_API ServerListenerCallback(HQUIC Listener, void* Context, QUIC_LISTENER_EVENT* Event); // Callback implementations QUIC_STATUS QUIC_API ServerStreamCallback(HQUIC Stream, void* Context, QUIC_STREAM_EVENT* Event) { auto Connection = (HQUIC)Context; switch (Event->Type) { case QUIC_STREAM_EVENT_RECEIVE: if (Event->RECEIVE.BufferCount == 1) { auto& buf = Event->RECEIVE.Buffers[0]; std::string username(reinterpret_cast<const char*>(buf.Buffer), buf.Length); auto it = ConnectedClients.find(Connection); if (it != ConnectedClients.end() && it->second.Username.empty()) { it->second.Username = username; printf("[server] Client %p username: %s\n", Connection, username.c_str()); std::string welcome = "Welcome, " + username + "!\n"; QUIC_BUFFER sendBuf{ (uint32_t)welcome.size(), (uint8_t*)welcome.data() }; MsQuic->StreamSend(Stream, &sendBuf, 1, QUIC_SEND_FLAG_NONE, nullptr); } } break; case QUIC_STREAM_EVENT_SHUTDOWN_COMPLETE: MsQuic->StreamClose(Stream); break; default: break; } return QUIC_STATUS_SUCCESS; } QUIC_STATUS QUIC_API ServerConnectionCallback(HQUIC Connection, void* /*Context*/, QUIC_CONNECTION_EVENT* Event) { switch (Event->Type) { case QUIC_CONNECTION_EVENT_CONNECTED: printf("[server] Connection connected %p\n", Connection); ConnectedClients[Connection] = {}; break; case QUIC_CONNECTION_EVENT_SHUTDOWN_COMPLETE: printf("[server] Connection %p shutdown\n", Connection); ConnectedClients.erase(Connection); MsQuic->ConnectionClose(Connection); break; case QUIC_CONNECTION_EVENT_PEER_STREAM_STARTED: MsQuic->SetCallbackHandler(Event->PEER_STREAM_STARTED.Stream, (void*)ServerStreamCallback, Connection); break; default: break; } return QUIC_STATUS_SUCCESS; } QUIC_STATUS QUIC_API ServerListenerCallback(HQUIC /*Listener*/, void* /*Context*/, QUIC_LISTENER_EVENT* Event) { if (Event->Type == QUIC_LISTENER_EVENT_NEW_CONNECTION) { MsQuic->SetCallbackHandler(Event->NEW_CONNECTION.Connection, (void*)ServerConnectionCallback, nullptr); return MsQuic->ConnectionSetConfiguration(Event->NEW_CONNECTION.Connection, Configuration); } return QUIC_STATUS_NOT_SUPPORTED; } int main() { int ret = -1; // Move variable declarations to top (to avoid goto-into-scope errors) const char* certFileName = "tmp_server_cert.pem"; const char* keyFileName = "tmp_server_key.pem"; std::string certPem, keyPem; FILE* certFile = nullptr; FILE* keyFile = nullptr; QUIC_CERTIFICATE_FILE certFileConfig{}; QUIC_CREDENTIAL_CONFIG credConfig{}; QUIC_SETTINGS settings{}; QUIC_ADDR addr{}; // Initialize global handles to nullptr for cleanup safety Registration = nullptr; Configuration = nullptr; Listener = nullptr; if (QUIC_FAILED(MsQuicOpen2(&MsQuic))) { fprintf(stderr, "MsQuicOpen2 failed\n"); return ret; } if (QUIC_FAILED(MsQuic->RegistrationOpen(&RegConfig, &Registration))) { fprintf(stderr, "RegistrationOpen failed\n"); goto cleanup_msquic; } if (!GenerateSelfSignedCert(certPem, keyPem)) { fprintf(stderr, "Failed to generate self-signed cert\n"); goto cleanup_registration; } printf("Server Certificate PEM:\n%s\n", certPem.c_str()); printf("Server Private Key PEM:\n%s\n", keyPem.c_str()); printf("Copy above certificate PEM to client for trust.\n\n"); certFile = fopen(certFileName, "wb"); if (!certFile) { fprintf(stderr, "Failed to open cert file for writing\n"); goto cleanup_registration; } fwrite(certPem.data(), 1, certPem.size(), certFile); fclose(certFile); certFile = nullptr; keyFile = fopen(keyFileName, "wb"); if (!keyFile) { fprintf(stderr, "Failed to open key file for writing\n"); remove(certFileName); goto cleanup_registration; } fwrite(keyPem.data(), 1, keyPem.size(), keyFile); fclose(keyFile); keyFile = nullptr; certFileConfig.CertificateFile = (char*)certFileName; certFileConfig.PrivateKeyFile = (char*)keyFileName; credConfig.Type = QUIC_CREDENTIAL_TYPE_CERTIFICATE_FILE; credConfig.CertificateFile = &certFileConfig; credConfig.Flags = QUIC_CREDENTIAL_FLAG_NONE; settings.IdleTimeoutMs = 60000; // 1 minute settings.IsSet.IdleTimeoutMs = TRUE; settings.PeerBidiStreamCount = 1; settings.IsSet.PeerBidiStreamCount = TRUE; if (QUIC_FAILED(MsQuic->ConfigurationOpen(Registration, &Alpn, 1, &settings, sizeof(settings), nullptr, &Configuration))) { fprintf(stderr, "ConfigurationOpen failed\n"); goto cleanup_files; } if (QUIC_FAILED(MsQuic->ConfigurationLoadCredential(Configuration, &credConfig))) { fprintf(stderr, "ConfigurationLoadCredential failed\n"); goto cleanup_config; } if (QUIC_FAILED(MsQuic->ListenerOpen(Registration, ServerListenerCallback, nullptr, &Listener))) { fprintf(stderr, "ListenerOpen failed\n"); goto cleanup_config; } QuicAddrSetFamily(&addr, QUIC_ADDRESS_FAMILY_UNSPEC); QuicAddrSetPort(&addr, Port); if (QUIC_FAILED(MsQuic->ListenerStart(Listener, &Alpn, 1, &addr))) { fprintf(stderr, "ListenerStart failed\n"); goto cleanup_listener; } printf("Server listening on UDP port %u. Press Enter to exit...\n", Port); getchar(); // Wait for user input to exit ret = 0; // success cleanup_listener: if (Listener) { MsQuic->ListenerClose(Listener); Listener = nullptr; } cleanup_config: if (Configuration) { MsQuic->ConfigurationClose(Configuration); Configuration = nullptr; } cleanup_files: remove(certFileName); remove(keyFileName); cleanup_registration: if (Registration) { MsQuic->RegistrationClose(Registration); Registration = nullptr; } cleanup_msquic: MsQuicClose(MsQuic); MsQuic = nullptr; if (certFile) fclose(certFile); if (keyFile) fclose(keyFile); return ret; }
Summary of changes:
- All local variables in
main()that were originally scattered have been declared at the very start of the function. - You can now freely
gotoanycleanup_*label without crossing non-trivial initializations. - The rest of your code, including the callbacks and helper functions, is untouched.
- Added safe
fclosecalls at cleanup just in case of misplaced file handles.
This fixes the compilation errors you provided and retains your original functionality.
If you run into any further issues or want a version with C++ RAII style resource management, just ask!
- All local variables in