Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create persistence.h #60

Merged
merged 3 commits into from
Jan 26, 2025
Merged

Create persistence.h #60

merged 3 commits into from
Jan 26, 2025

Conversation

bearycool11
Copy link
Owner

@bearycool11 bearycool11 commented Jan 26, 2025

#ifndef PERSISTENCE_H
#define PERSISTENCE_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <openssl/rsa.h>
#include "io_socket.h"
#include "pml_logic_loop.h"
#include "memory_silo.h"
#include "knowledge.h"
#include "PMLL_ARLL_EFLL.h"

// Constants
#define MAX_KNOWLEDGE_NODES 4096
#define SESSION_TIMEOUT_MS 5000
#define ENCRYPTION_KEY_SIZE 2048
#define PACKAGE_TYPE_KNOWLEDGE_UPDATE 1

// Session context structure
typedef struct {
io_socket_t io_socket;
PMLL_ARLL_EFLL_State state;
Graph *knowledge_graph;
RSA *encryption_key;
memory_silo_t *persistent_silo;
} SessionContext;

// Function declarations
SessionContext* create_session(const char *ip, int port,
int max_retries, int feedback_threshold,
const char *encryption_key_file);
void process_chatlog(SessionContext *ctx, const char *input); void send_secure_graph_update(SessionContext *ctx); void save_session_state(SessionContext ctx, const char filename); void handle_network_error(SessionContext *ctx);
void run_session_loop(SessionContext *ctx);

// Utility function declarations (assumed to be implemented elsewhere) RSA* load_rsa_key(const char filename);
RSA
generate_rsa_key(int key_size);
void save_rsa_key(const char *filename, RSA key); char sanitize_input(const char input);
EncryptedNode
encrypt_node_data(RSA *key, const char *data); int add_encrypted_node(Graph *graph, EncryptedNode *enode); void update_arll_weights(PMLL_ARLL_EFLL_State state, int hash); unsigned char serialize_graph(Graph *graph, size_t *size); size_t rsa_encrypt(RSA *key, const unsigned char *data, size_t data_size,
unsigned char encrypted, size_t encrypted_size);
unsigned char
rsa_encrypt_buffer(RSA *key, const unsigned char *data, size_t data_size,
size_t *encrypted_size);
unsigned int calculate_checksum(const unsigned char *data, size_t size); void write_file_atomically(const char *filename, const unsigned char *data, size_t size); unsigned int calculate_graph_hash(Graph graph);
memory_silo_t
connect_memory_silo(int silo_type); void load_initial_knowledge(SessionContext *ctx, const char *filename); void perform_garbage_collection(Graph *graph);
void optimize_memory_usage(memory_silo_t *silo);
void initiate_graceful_shutdown(SessionContext *ctx); void validate_session_integrity(SessionContext *ctx); int initialize_subsystems(SessionContext *ctx);
int process_queued_messages(SessionContext *ctx);
void handle_runtime_error(SessionContext *ctx);
int attempt_state_recovery(SessionContext *ctx);
void destroy_session(SessionContext *ctx);

#endif // PERSISTENCE_H

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive session management system with secure knowledge graph processing.
    • Added advanced encryption and data persistence capabilities.
    • Implemented robust error handling and state recovery mechanisms.
    • Enhanced GitHub Actions workflow to support Go environment setup.
  • Chores

    • Created new header file for system-level session and knowledge management infrastructure.
  • Security Improvements

    • Added RSA key management and encryption functions.
    • Implemented input sanitization and secure data handling.

#ifndef PERSISTENCE_H
#define PERSISTENCE_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <openssl/rsa.h>
#include "io_socket.h"
#include "pml_logic_loop.h"
#include "memory_silo.h"
#include "knowledge.h"
#include "PMLL_ARLL_EFLL.h"

// Constants
#define MAX_KNOWLEDGE_NODES 4096
#define SESSION_TIMEOUT_MS 5000
#define ENCRYPTION_KEY_SIZE 2048
#define PACKAGE_TYPE_KNOWLEDGE_UPDATE 1

// Session context structure
typedef struct {
    io_socket_t io_socket;
    PMLL_ARLL_EFLL_State state;
    Graph *knowledge_graph;
    RSA *encryption_key;
    memory_silo_t *persistent_silo;
} SessionContext;

// Function declarations
SessionContext* create_session(const char *ip, int port, 
                              int max_retries, int feedback_threshold,
                              const char *encryption_key_file);
void process_chatlog(SessionContext *ctx, const char *input);
void send_secure_graph_update(SessionContext *ctx);
void save_session_state(SessionContext *ctx, const char* filename);
void handle_network_error(SessionContext *ctx);
void run_session_loop(SessionContext *ctx);

// Utility function declarations (assumed to be implemented elsewhere)
RSA* load_rsa_key(const char *filename);
RSA* generate_rsa_key(int key_size);
void save_rsa_key(const char *filename, RSA *key);
char* sanitize_input(const char *input);
EncryptedNode* encrypt_node_data(RSA *key, const char *data);
int add_encrypted_node(Graph *graph, EncryptedNode *enode);
void update_arll_weights(PMLL_ARLL_EFLL_State *state, int hash);
unsigned char* serialize_graph(Graph *graph, size_t *size);
size_t rsa_encrypt(RSA *key, const unsigned char *data, size_t data_size, 
                   unsigned char *encrypted, size_t encrypted_size);
unsigned char* rsa_encrypt_buffer(RSA *key, const unsigned char *data, size_t data_size, 
                                  size_t *encrypted_size);
unsigned int calculate_checksum(const unsigned char *data, size_t size);
void write_file_atomically(const char *filename, const unsigned char *data, size_t size);
unsigned int calculate_graph_hash(Graph *graph);
memory_silo_t* connect_memory_silo(int silo_type);
void load_initial_knowledge(SessionContext *ctx, const char *filename);
void perform_garbage_collection(Graph *graph);
void optimize_memory_usage(memory_silo_t *silo);
void initiate_graceful_shutdown(SessionContext *ctx);
void validate_session_integrity(SessionContext *ctx);
int initialize_subsystems(SessionContext *ctx);
int process_queued_messages(SessionContext *ctx);
void handle_runtime_error(SessionContext *ctx);
int attempt_state_recovery(SessionContext *ctx);
void destroy_session(SessionContext *ctx);

#endif // PERSISTENCE_H

Signed-off-by: J. K. Edwards <joed6834@colorado.edu>
Copy link

coderabbitai bot commented Jan 26, 2025

Walkthrough

The pull request introduces a new header file persistence.h that defines a comprehensive session management system for a knowledge graph-based application. The header establishes a SessionContext structure and provides a wide range of functions for session initialization, secure communication, graph updates, error handling, and system lifecycle management. It includes capabilities for RSA encryption, input sanitization, memory optimization, and persistent storage interactions. Additionally, a new step is added to the GitHub Actions workflow to set up a Go environment.

Changes

File Change Summary
persistence.h - Added SessionContext structure
- Defined constants for knowledge graph and session management
- Implemented multiple functions for session creation, processing, security, and lifecycle management
.github/workflows/build.yml - Added new step for setting up Go environment using actions/setup-go@v5.3.0 with optional parameters like go-version, check-latest, and cache

Sequence Diagram

sequenceDiagram
    participant User
    participant SessionContext
    participant Graph
    participant MemorySilo
    participant NetworkSocket

    User->>SessionContext: Initiate Session
    SessionContext->>NetworkSocket: Establish Connection
    SessionContext->>Graph: Initialize Knowledge Graph
    SessionContext->>MemorySilo: Connect Storage
    User->>SessionContext: Send Input
    SessionContext->>SessionContext: Process & Sanitize Input
    SessionContext->>Graph: Update Knowledge
    SessionContext->>NetworkSocket: Send Secure Update
    SessionContext->>MemorySilo: Save Session State
Loading

Poem

🐰 In realms of code, a session springs to life,
Graphs encrypted, knowledge cuts like a knife,
Persistent memory, secure and bright,
Rabbit's wisdom dancing in digital light!
Persistence reigns, our data takes flight! 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 25a9402 and 050fb90.

📒 Files selected for processing (1)
  • .github/workflows/build.yml (1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/build.yml

69-69: could not parse as YAML: yaml: line 69: mapping values are not allowed in this context

(syntax-check)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
.github/workflows/build.yml (1)

69-86: ⚠️ Potential issue

Fix YAML syntax and configure Go setup properly.

The new Go setup step has syntax errors and incomplete configuration. Here's how to fix it:

-            - name: Setup Go environment
-  uses: actions/setup-go@v5.3.0
-  with:
-    # The Go version to download (if necessary) and use. Supports semver spec and ranges. Be sure to enclose this option in single quotation marks.
-    go-version: # optional
-    # Path to the go.mod or go.work file.
-    go-version-file: # optional
-    # Set this option to true if you want the action to always check for the latest available version that satisfies the version spec
-    check-latest: # optional
-    # Used to pull Go distributions from go-versions. Since there's a default, this is typically not supplied by the user. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting.
-    token: # optional, default is ${{ github.server_url == 'https://github.com' && github.token || '' }}
-    # Used to specify whether caching is needed. Set to true, if you'd like to enable caching.
-    cache: # optional, default is true
-    # Used to specify the path to a dependency file - go.sum
-    cache-dependency-path: # optional
-    # Target architecture for Go to use. Examples: x86, x64. Will use system architecture by default.
-    architecture: # optional
-          
+      - name: Setup Go environment
+        uses: actions/setup-go@v5.3.0
+        with:
+          go-version: '1.21'  # Specify your required Go version

Please verify:

  1. Is Go actually needed in this workflow? The main workflow is CMake-based, suggesting a C/C++ project.
  2. If Go is required, ensure you have a go.mod file in your repository.

Run this script to check for Go-related files:

🧰 Tools
🪛 actionlint (1.7.4)

69-69: could not parse as YAML: yaml: line 69: mapping values are not allowed in this context

(syntax-check)


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (1)
persistence.h (1)

4-14: Consider organizing headers and documenting dependencies.

The headers are logically organized, but consider:

  1. Grouping project-specific headers based on their dependencies
  2. Documenting the minimum required OpenSSL version for security compliance
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
 #include <time.h>
+// Require OpenSSL >= 1.1.1 for security compliance
 #include <openssl/rsa.h>
+
+// Core system headers
 #include "io_socket.h"
 #include "pml_logic_loop.h"
 #include "memory_silo.h"
+
+// Knowledge processing headers
 #include "knowledge.h"
 #include "PMLL_ARLL_EFLL.h"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d61cb7c and 25a9402.

📒 Files selected for processing (1)
  • persistence.h (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
persistence.h (1)

16-20: Review constant values for scalability and security.

Several concerns about the constant values:

  1. MAX_KNOWLEDGE_NODES (4096) might limit scalability for large knowledge graphs
  2. SESSION_TIMEOUT_MS (5000ms) might be too short for complex graph operations
  3. ENCRYPTION_KEY_SIZE (2048 bits) should be reviewed periodically for security compliance

Consider making these configurable at runtime or compile-time based on deployment requirements. For the encryption key size, follow NIST guidelines for minimum RSA key lengths.

Comment on lines +55 to +67
void write_file_atomically(const char *filename, const unsigned char *data, size_t size);
unsigned int calculate_graph_hash(Graph *graph);
memory_silo_t* connect_memory_silo(int silo_type);
void load_initial_knowledge(SessionContext *ctx, const char *filename);
void perform_garbage_collection(Graph *graph);
void optimize_memory_usage(memory_silo_t *silo);
void initiate_graceful_shutdown(SessionContext *ctx);
void validate_session_integrity(SessionContext *ctx);
int initialize_subsystems(SessionContext *ctx);
int process_queued_messages(SessionContext *ctx);
void handle_runtime_error(SessionContext *ctx);
int attempt_state_recovery(SessionContext *ctx);
void destroy_session(SessionContext *ctx);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve modularity and error handling in utility functions.

Consider:

  1. Splitting utilities into logical modules (e.g., crypto, persistence, memory)
  2. Adding error handling for all critical operations
  3. Documenting cleanup requirements

These functions should be moved to separate header files based on their functionality:

  • crypto.h: RSA and encryption-related functions
  • persistence.h: File and state management
  • memory.h: Memory silo and garbage collection

This would improve maintainability and make dependencies clearer.

Comment on lines +22 to +29
// Session context structure
typedef struct {
io_socket_t io_socket;
PMLL_ARLL_EFLL_State state;
Graph *knowledge_graph;
RSA *encryption_key;
memory_silo_t *persistent_silo;
} SessionContext;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add documentation and clarify memory ownership.

The SessionContext structure needs:

  1. Documentation for each field explaining its purpose and lifecycle
  2. Clear ownership semantics for pointer members
  3. Initialization requirements and cleanup responsibilities
 // Session context structure
+/**
+ * @brief Encapsulates the state and resources for a session
+ * 
+ * Memory ownership:
+ * - knowledge_graph: Owned by the session, must be freed in destroy_session
+ * - encryption_key: Owned by the session, must be freed using RSA_free
+ * - persistent_silo: External ownership, must not be freed by the session
+ */
 typedef struct {
     io_socket_t io_socket;
     PMLL_ARLL_EFLL_State state;
     Graph *knowledge_graph;
     RSA *encryption_key;
     memory_silo_t *persistent_silo;
 } SessionContext;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Session context structure
typedef struct {
io_socket_t io_socket;
PMLL_ARLL_EFLL_State state;
Graph *knowledge_graph;
RSA *encryption_key;
memory_silo_t *persistent_silo;
} SessionContext;
/**
* @brief Encapsulates the state and resources for a session
*
* Memory ownership:
* - knowledge_graph: Owned by the session, must be freed in destroy_session
* - encryption_key: Owned by the session, must be freed using RSA_free
* - persistent_silo: External ownership, must not be freed by the session
*/
typedef struct {
io_socket_t io_socket;
PMLL_ARLL_EFLL_State state;
Graph *knowledge_graph;
RSA *encryption_key;
memory_silo_t *persistent_silo;
} SessionContext;

Comment on lines +31 to +39
// Function declarations
SessionContext* create_session(const char *ip, int port,
int max_retries, int feedback_threshold,
const char *encryption_key_file);
void process_chatlog(SessionContext *ctx, const char *input);
void send_secure_graph_update(SessionContext *ctx);
void save_session_state(SessionContext *ctx, const char* filename);
void handle_network_error(SessionContext *ctx);
void run_session_loop(SessionContext *ctx);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve function signatures for error handling and thread safety.

Core functions need:

  1. Error return values for failure cases
  2. Const correctness for input parameters
  3. Documentation for thread safety guarantees
-SessionContext* create_session(const char *ip, int port, 
-                              int max_retries, int feedback_threshold,
-                              const char *encryption_key_file);
-void process_chatlog(SessionContext *ctx, const char *input);
-void send_secure_graph_update(SessionContext *ctx);
-void save_session_state(SessionContext *ctx, const char* filename);
-void handle_network_error(SessionContext *ctx);
-void run_session_loop(SessionContext *ctx);
+/**
+ * @brief Creates a new session with the specified parameters
+ * @return NULL on failure with errno set
+ * @thread_safety Thread-unsafe
+ */
+SessionContext* create_session(const char *ip, int port,
+                             int max_retries, int feedback_threshold,
+                             const char *encryption_key_file);
+
+/**
+ * @brief Processes chat log input
+ * @return 0 on success, negative error code on failure
+ * @thread_safety Thread-safe
+ */
+int process_chatlog(SessionContext * restrict ctx, const char * restrict input);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +41 to +54
// Utility function declarations (assumed to be implemented elsewhere)
RSA* load_rsa_key(const char *filename);
RSA* generate_rsa_key(int key_size);
void save_rsa_key(const char *filename, RSA *key);
char* sanitize_input(const char *input);
EncryptedNode* encrypt_node_data(RSA *key, const char *data);
int add_encrypted_node(Graph *graph, EncryptedNode *enode);
void update_arll_weights(PMLL_ARLL_EFLL_State *state, int hash);
unsigned char* serialize_graph(Graph *graph, size_t *size);
size_t rsa_encrypt(RSA *key, const unsigned char *data, size_t data_size,
unsigned char *encrypted, size_t encrypted_size);
unsigned char* rsa_encrypt_buffer(RSA *key, const unsigned char *data, size_t data_size,
size_t *encrypted_size);
unsigned int calculate_checksum(const unsigned char *data, size_t size);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Address security concerns in encryption functions.

The encryption-related functions need:

  1. Buffer size parameters to prevent overflows
  2. Error handling for encryption failures
  3. Secure memory handling for sensitive data
-unsigned char* rsa_encrypt_buffer(RSA *key, const unsigned char *data, size_t data_size, 
-                                  size_t *encrypted_size);
+/**
+ * @brief Encrypts data using RSA with secure memory handling
+ * @param key RSA key for encryption
+ * @param data Input data to encrypt
+ * @param data_size Size of input data
+ * @param max_output_size Maximum size of the output buffer
+ * @param encrypted_size [out] Actual size of encrypted data
+ * @return Encrypted data in secure memory (must be freed with OPENSSL_clear_free)
+ */
+unsigned char* rsa_encrypt_buffer(RSA *key,
+                                const unsigned char *data,
+                                size_t data_size,
+                                size_t max_output_size,
+                                size_t *encrypted_size);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Utility function declarations (assumed to be implemented elsewhere)
RSA* load_rsa_key(const char *filename);
RSA* generate_rsa_key(int key_size);
void save_rsa_key(const char *filename, RSA *key);
char* sanitize_input(const char *input);
EncryptedNode* encrypt_node_data(RSA *key, const char *data);
int add_encrypted_node(Graph *graph, EncryptedNode *enode);
void update_arll_weights(PMLL_ARLL_EFLL_State *state, int hash);
unsigned char* serialize_graph(Graph *graph, size_t *size);
size_t rsa_encrypt(RSA *key, const unsigned char *data, size_t data_size,
unsigned char *encrypted, size_t encrypted_size);
unsigned char* rsa_encrypt_buffer(RSA *key, const unsigned char *data, size_t data_size,
size_t *encrypted_size);
unsigned int calculate_checksum(const unsigned char *data, size_t size);
// Utility function declarations (assumed to be implemented elsewhere)
RSA* load_rsa_key(const char *filename);
RSA* generate_rsa_key(int key_size);
void save_rsa_key(const char *filename, RSA *key);
char* sanitize_input(const char *input);
EncryptedNode* encrypt_node_data(RSA *key, const char *data);
int add_encrypted_node(Graph *graph, EncryptedNode *enode);
void update_arll_weights(PMLL_ARLL_EFLL_State *state, int hash);
unsigned char* serialize_graph(Graph *graph, size_t *size);
size_t rsa_encrypt(RSA *key, const unsigned char *data, size_t data_size,
unsigned char *encrypted, size_t encrypted_size);
/**
* @brief Encrypts data using RSA with secure memory handling
* @param key RSA key for encryption
* @param data Input data to encrypt
* @param data_size Size of input data
* @param max_output_size Maximum size of the output buffer
* @param encrypted_size [out] Actual size of encrypted data
* @return Encrypted data in secure memory (must be freed with OPENSSL_clear_free)
*/
unsigned char* rsa_encrypt_buffer(RSA *key,
const unsigned char *data,
size_t data_size,
size_t max_output_size,
size_t *encrypted_size);
unsigned int calculate_checksum(const unsigned char *data, size_t size);

Comment on lines +1 to +69
#ifndef PERSISTENCE_H
#define PERSISTENCE_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <openssl/rsa.h>
#include "io_socket.h"
#include "pml_logic_loop.h"
#include "memory_silo.h"
#include "knowledge.h"
#include "PMLL_ARLL_EFLL.h"

// Constants
#define MAX_KNOWLEDGE_NODES 4096
#define SESSION_TIMEOUT_MS 5000
#define ENCRYPTION_KEY_SIZE 2048
#define PACKAGE_TYPE_KNOWLEDGE_UPDATE 1

// Session context structure
typedef struct {
io_socket_t io_socket;
PMLL_ARLL_EFLL_State state;
Graph *knowledge_graph;
RSA *encryption_key;
memory_silo_t *persistent_silo;
} SessionContext;

// Function declarations
SessionContext* create_session(const char *ip, int port,
int max_retries, int feedback_threshold,
const char *encryption_key_file);
void process_chatlog(SessionContext *ctx, const char *input);
void send_secure_graph_update(SessionContext *ctx);
void save_session_state(SessionContext *ctx, const char* filename);
void handle_network_error(SessionContext *ctx);
void run_session_loop(SessionContext *ctx);

// Utility function declarations (assumed to be implemented elsewhere)
RSA* load_rsa_key(const char *filename);
RSA* generate_rsa_key(int key_size);
void save_rsa_key(const char *filename, RSA *key);
char* sanitize_input(const char *input);
EncryptedNode* encrypt_node_data(RSA *key, const char *data);
int add_encrypted_node(Graph *graph, EncryptedNode *enode);
void update_arll_weights(PMLL_ARLL_EFLL_State *state, int hash);
unsigned char* serialize_graph(Graph *graph, size_t *size);
size_t rsa_encrypt(RSA *key, const unsigned char *data, size_t data_size,
unsigned char *encrypted, size_t encrypted_size);
unsigned char* rsa_encrypt_buffer(RSA *key, const unsigned char *data, size_t data_size,
size_t *encrypted_size);
unsigned int calculate_checksum(const unsigned char *data, size_t size);
void write_file_atomically(const char *filename, const unsigned char *data, size_t size);
unsigned int calculate_graph_hash(Graph *graph);
memory_silo_t* connect_memory_silo(int silo_type);
void load_initial_knowledge(SessionContext *ctx, const char *filename);
void perform_garbage_collection(Graph *graph);
void optimize_memory_usage(memory_silo_t *silo);
void initiate_graceful_shutdown(SessionContext *ctx);
void validate_session_integrity(SessionContext *ctx);
int initialize_subsystems(SessionContext *ctx);
int process_queued_messages(SessionContext *ctx);
void handle_runtime_error(SessionContext *ctx);
int attempt_state_recovery(SessionContext *ctx);
void destroy_session(SessionContext *ctx);

#endif // PERSISTENCE_H
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Security concerns found in dependent components

The header dependencies are satisfied, but there are security concerns:

  • Multiple instances of unsafe string functions (strcpy, strcat, sprintf, gets, scanf) found in the codebase
  • These functions are vulnerable to buffer overflows and should be replaced with safer alternatives:
    • Use strncpy, strncat, snprintf instead
    • Replace gets with fgets
    • Use scanf with field width limits or safer alternatives
🔗 Analysis chain

Verify header dependencies and security requirements.

Please ensure all required headers are available and security requirements are met.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify header dependencies and OpenSSL version

# Check for required headers
echo "Checking for required headers..."
for header in io_socket.h pml_logic_loop.h memory_silo.h knowledge.h PMLL_ARLL_EFLL.h; do
  if ! fd -t f "$header"; then
    echo "Missing required header: $header"
  fi
done

# Check OpenSSL version and security requirements
echo "Checking OpenSSL version..."
if command -v pkg-config &> /dev/null; then
  pkg-config --print-requires openssl
  pkg-config --modversion openssl
fi

# Check for potential security issues in the codebase
echo "Checking for potential security issues..."
rg -i "strcpy|strcat|sprintf|gets|scanf" || echo "No unsafe string functions found"

Length of output: 3706

Signed-off-by: J. K. Edwards <joed6834@colorado.edu>
@bearycool11 bearycool11 merged commit 7a238d3 into main Jan 26, 2025
1 of 14 checks passed
@bearycool11 bearycool11 deleted the bearycool11-patch-17 branch January 26, 2025 05:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant