NSAPI_PUBLIC int add_agent_header(pblock *param, Session *sn, Request *rq) { const char *thisfunc = "add_agent_header()"; int requestResult = REQ_ABORTED; char *host = NULL ; char *host_name = NULL; void *args[] = { (void *)rq }; am_status_t ret = AM_FAILURE; char *header_str = NULL; // NSAPI function pblock_pblock2str expects "full-headers" // to be non-null value. Therefore, add a logic to check whether // "full-headers" is null and if it is, return error to the client. // - Forward port of fix in CRT (657). pb_param *hdr_pp = pblock_find("full-headers", rq->reqpb); if (hdr_pp != NULL && hdr_pp->value == NULL) { am_web_log_error ("add_agent_header():Header not found."); return REQ_ABORTED; } header_str = pblock_pblock2str(rq->reqpb, NULL); am_web_log_max_debug("%s: Headers: %s", thisfunc, header_str); system_free(header_str); requestResult = request_header ("host",&host,sn,rq ); if (REQ_PROCEED == requestResult && host != NULL) { host_name = strdup (host); if (host_name == NULL){ am_web_log_debug("%s: Unable to allocate memory for host_name", thisfunc); am_web_free_memory(host); return REQ_ABORTED; } am_web_log_max_debug("%s: Host = %s ", thisfunc, host_name); ret = set_header("ampxy_host",host_name,args); if (ret == AM_SUCCESS) { header_str = pblock_pblock2str(rq->reqpb, NULL); am_web_log_max_debug("%s: headers = %s", thisfunc, header_str); system_free(header_str); requestResult = REQ_NOACTION; am_web_log_max_debug("%s: Host replace success %d ", thisfunc, requestResult); } else { am_web_log_max_debug("%s: Host replace failed", thisfunc); } if(host_name != NULL) { free(host_name); } } else { am_web_log_error ("%s: Header not found.", thisfunc); } return requestResult; }
// Remove all entries from a hash table. Reclaim all memory. // Call this routine to delete a hash table or to reset a hash table to the empty state. void systemHashClear(Hash *hash) { HashElement *element; // For looping over all elements of the table assert(hash != 0); element = hash->First; hash->First = 0; system_free(hash->Table); hash->Table = 0; hash->TableSize = 0; while(element) { HashElement *nextElement = element->Next; system_free(element); element = nextElement; } hash->Count = 0; }
/* ** Free memory that might be associated with a particular database connection. */ void systemCtxFree(appContext *db, void *p) { assert(db == 0 || system_mutex_held(db->mutex)); if (db) { if (db->pnBytesFreed) { *db->pnBytesFreed += systemCtxMallocSize(db, p); return; } if (isLookaside(db, p)) { LookasideSlot *pBuf = (LookasideSlot*)p; pBuf->pNext = db->lookaside.pFree; db->lookaside.pFree = pBuf; db->lookaside.nOut--; return; } } assert(systemMemdebugHasType(p, MEMTYPE_DB)); assert(systemMemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)); assert(db != 0 || systemMemdebugNoType(p, MEMTYPE_LOOKASIDE)); systemMemdebugSetType(p, MEMTYPE_HEAP); system_free(p); }
// Resize the hash table so that it cantains "new_size" buckets. // The hash table might fail to resize if system_malloc() fails or if the new size is the same as the prior size. // Return TRUE if the resize occurs and false if not. static int rehash(Hash *pH, unsigned int newSize) { struct _hashTable *newHashTable; // The new hash table HashElement *element, *nextElement; // For looping over existing elements #if SYSTEM_MALLOC_SOFTLIMIT > 0 if (newSize*sizeof(struct _hashTable) > SYSTEM_MALLOC_SOFTLIMIT) newSize = SYSTEM_MALLOC_SOFTLIMIT/sizeof(struct _hashTable); if (newSize == pH->TableSize) return 0; #endif // The inability to allocates space for a larger hash table is a performance hit but it is not a fatal error. So mark the allocation as a benign. systemBeginBenignMalloc(); newHashTable = (struct _hashTable *)systemMalloc(newSize*sizeof(struct _hashTable)); systemEndBenignMalloc(); if (newHashTable == 0) return 0; system_free(pH->Table); pH->Table = newHashTable; pH->TableSize = newSize = systemMallocSize(newHashTable)/sizeof(struct _hashTable); memset(newHashTable, 0, newSize*sizeof(struct _hashTable)); for(element = pH->First, pH->First = 0; element; element = nextElement) { unsigned int h = strHash(element->pKey, element->nKey) % newSize; nextElement = element->Next; insertElement(pH, &newHashTable[h], element); } return 1; }
// Remove a single entry from the hash table given a pointer to that element and a hash on the element's key. static void removeElementGivenHash ( Hash *pH, // The pH containing "elem" HashElement* element, // The element to be removed from the pH unsigned int h // Hash value for the element ) { struct _hashTable *pEntry; if (element->Prev) element->Prev->Next = element->Next; else pH->First = element->Next; if (element->Next) element->Next->Prev = element->Prev; if (pH->Table) { pEntry = &pH->Table[h]; if (pEntry->Chain == element) pEntry->Chain = element->Next; pEntry->Count--; assert(pEntry->Count >= 0); } system_free(element); pH->Count--; if (pH->Count <= 0) { assert(pH->first == 0); assert(pH->count == 0); systemHashClear(pH); } }
/** * manages the running of the program, initialises data structures, loads * data and handles the processing of options. The bulk of this function * should simply be calling other functions to get the job done. **/ int main(int argc, char **argv) { /* validate command line arguments */ if(argc != ARGSNUMS) { fprintf(stderr,"Error : Invalid command line args!"); fprintf(stderr, "Usage: %s <s> <coinsfile>\n", argv[0]); return EXIT_FAILURE; } /* represents the data structures to manage the system */ BOOLEAN quit= FALSE; struct menu_item menu[NUM_OF_OPTS]; struct ppd_system system; int menu_choice; /* init the system */ system_init(&system); /* load data */ load_data(&system, argv[1],argv[2]); /* test if everything has been initialised correctly */ if(!system_init(&system) || !load_data(&system, argv[1],argv[2])) { fprintf(stderr,"ERROR, QUTING PROGRAM NOW..."); return EXIT_FAILURE; } /* initialise the menu system */ init_menu(menu); /* loop, asking for options from the menu */ do{ display_menu(menu); get_integer(&menu_choice,LEN_USER_INPUT, MIN_OPT,MAX_OPT); menu[menu_choice-1].function(&system); if(menu_choice==3 || menu_choice== 9) { quit=TRUE; } }while(!quit); system_free(&system); return EXIT_SUCCESS; }
int main() { load_protocols(); read_config("test"); system_init(); printf("================simulate a client\n"); listen_packet(); printf("================end simulate a client\n"); system_free(); return 1; }
void teardown() { malloc_zone_t * zone = malloc_default_zone(); while (tail > keep_list) { tail--; system_free(zone, *tail); } zone->malloc = system_malloc; zone->free = system_free; }
void myfree(malloc_zone_t *zone, void *ptr) { size_t sz = zone->size(zone, ptr); if (sz >= KEEP_SIZE) { // big? if ((tail - keep_list) < KEEP_NUM) { // space available? *tail = ptr; tail++; //fprintf(stderr, "kept %d, %d on list\n", sz, keep_list - tail); return; } } // fprintf(stderr, "free %d\n", sz); system_free(zone, ptr); }
// Disable an I2C port void i2c_disable(int port) { if (port >= 0 && port < I2C_N_PORTS && i2c_ports[port]) { i2c_port *p = i2c_ports[port]; U32 pinmask = p->scl_pin | p->sda_pin; *AT91C_PIOA_ODR = pinmask; system_free((byte *)p); i2c_ports[port] = NULL; build_active_list(); sp_reset(port); } }
/** * @param system a pointer to a ppd_system struct that contains * all the information for managing the system. * @return true when a save succeeds and false when it does not **/ BOOLEAN save_system(struct ppd_system * system) { if(save_coin_file(system) == FALSE) { printf("Returning to menu.\n\n"); return FALSE; } if(save_stock_file(system) == FALSE) { printf("Returning to menu.\n\n"); return FALSE; } printf("Current data successfully saved to file.\n"); printf("Now exitting the system\n\n"); system_free(system); exit(EXIT_SUCCESS); return TRUE; }
/* ** Change the size of an existing memory allocation */ void *systemRealloc(void *pOld, int nBytes) { int nOld, nNew; void *pNew; if (pOld == 0) return systemMalloc(nBytes); /* IMP: R-28354-25769 */ if (nBytes <= 0) { system_free(pOld); /* IMP: R-31593-10574 */ return 0; } if (nBytes>=0x7fffff00) /* The 0x7ffff00 limit term is explained in comments on systemMalloc() */ return 0; nOld = systemMallocSize(pOld); /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second argument to xRealloc is always a value returned by a prior call to ** xRoundup. */ nNew = systemGlobalConfig.m.xRoundup(nBytes); if (nOld == nNew) pNew = pOld; else if (systemGlobalConfig.bMemstat) { system_mutex_enter(mem0.mutex); systemStatusSet(SYSTEM_MEMSTATUS_MALLOC_SIZE, nBytes); if (systemStatusValue(SYSTEM_MEMSTATUS_MEMORY_USED)+nNew-nOld >= mem0.alarmThreshold) systemMallocAlarm(nNew-nOld); assert(systemMemdebugHasType(pOld, MEMTYPE_HEAP)); assert(systemMemdebugNoType(pOld, ~MEMTYPE_HEAP)); pNew = systemGlobalConfig.m.xRealloc(pOld, nNew); if (pNew == 0 && mem0.alarmCallback) { systemMallocAlarm(nBytes); pNew = systemGlobalConfig.m.xRealloc(pOld, nNew); } if (pNew) { nNew = systemMallocSize(pNew); systemStatusAdd(SYSTEM_MEMSTATUS_MEMORY_USED, nNew-nOld); } system_mutex_leave(mem0.mutex); } else pNew = systemGlobalConfig.m.xRealloc(pOld, nNew); assert(EIGHT_BYTE_ALIGNMENT(pNew)); /* IMP: R-04675-44850 */ return pNew; }
static int handle_notification(Session *sn, Request *rq, void* agent_config) { int result; char *content_length_header; size_t content_length; /* fixme GETPOST use new getRequestBody() routine here.... */ result = request_header(CONTENT_LENGTH_HDR, &content_length_header, sn,rq); if (REQ_PROCEED == result && NULL != content_length_header && sscanf(content_length_header, "%u", &content_length) == 1) { char ch; size_t data_length = 0; char *buf = NULL; buf = system_malloc(content_length); if (buf != NULL) { for (data_length = 0; data_length < content_length; data_length++){ ch = netbuf_getc(sn->inbuf); if (ch == IO_ERROR || ch == IO_EOF) { break; } buf[data_length] = (char) ch; } am_web_handle_notification(buf, data_length, agent_config); system_free(buf); } else { am_web_log_error("handle_notification() unable to allocate memory " "for notification data, size = %u", content_length); } result = REQ_PROCEED; } else { am_web_log_error("handle_notification() %s content-length header", (REQ_PROCEED == result && NULL != content_length_header) ? "unparsable" : "missing"); } return result; }
/** * release the system resources associated with the specified usart device. */ void usart_free(usart *us) { usart_disable(us); system_free((byte *)us); }
void intercept_free(gpointer ptr) { return system_free(ptr); }
/* * Function Name: validate_session_policy * This is the NSAPI directive funtion which gets called for each request * It does session validation and policy check for each request. * Input: As defined by a SAF * Output: As defined by a SAF */ NSAPI_PUBLIC int validate_session_policy(pblock *param, Session *sn, Request *rq) { const char *thisfunc = "validate_session_policy()"; char *dpro_cookie = NULL; am_status_t status = AM_SUCCESS; int requestResult = REQ_ABORTED; int notifResult = REQ_ABORTED; const char *ruser = NULL; am_map_t env_parameter_map = NULL; am_policy_result_t result = AM_POLICY_RESULT_INITIALIZER; void *args[] = { (void *)rq }; char *request_url = NULL; char *orig_req = NULL ; char *response = NULL; char *clf_req = NULL; char *server_protocol = NULL; void *agent_config = NULL; char *logout_url = NULL; char *uri_hdr = NULL; char *pathInfo_hdr = NULL; char *method_hdr = NULL; char *method = NULL; char *virtHost_hdr = NULL; char *query_hdr = NULL; char *query = NULL; char *protocol = "HTTP"; const char *clientIP_hdr_name = NULL; char *clientIP_hdr = NULL; char *clientIP = NULL; const char *clientHostname_hdr_name = NULL; char *clientHostname_hdr = NULL; char *clientHostname = NULL; am_status_t cdStatus = AM_FAILURE; // check if agent is initialized. // if not initialized, then call agent init function // This needs to be synchronized as only one time agent // initialization needs to be done. if(agentInitialized != B_TRUE){ //Start critical section crit_enter(initLock); if(agentInitialized != B_TRUE){ am_web_log_debug("%s: Will call init.", thisfunc); init_at_request(); if(agentInitialized != B_TRUE){ am_web_log_error("%s: Agent is still not intialized", thisfunc); //deny the access requestResult = do_deny(sn, rq, status); status = AM_FAILURE; } else { am_web_log_debug("%s: Agent intialized"); } } //end critical section crit_exit(initLock); } if (status == AM_SUCCESS) { // Get the agent configuration agent_config = am_web_get_agent_configuration(); // Dump the entire set of request headers if (am_web_is_max_debug_on()) { char *header_str = pblock_pblock2str(rq->reqpb, NULL); am_web_log_max_debug("%s: Headers: %s", thisfunc, header_str); system_free(header_str); } } // Get header values if (status == AM_SUCCESS) { status = get_header_value(rq->reqpb, REQUEST_URI, B_TRUE, &uri_hdr, B_FALSE, NULL); } if (status == AM_SUCCESS) { status = get_header_value(rq->vars, PATH_INFO, B_FALSE, &pathInfo_hdr, B_FALSE, NULL); } if (status == AM_SUCCESS) { status = get_header_value(rq->reqpb, REQUEST_METHOD, B_TRUE, &method_hdr, B_TRUE, &method); } if (status == AM_SUCCESS) { status = get_header_value(rq->headers, "ampxy_host", B_TRUE, &virtHost_hdr, B_FALSE, NULL); } if (status == AM_SUCCESS) { status = get_header_value(rq->reqpb, REQUEST_QUERY, B_FALSE, &query_hdr, B_TRUE, &query); } if (security_active) { protocol = "HTTPS"; } // Get the request URL if (status == AM_SUCCESS) { if (am_web_is_proxy_override_host_port_set(agent_config) == AM_FALSE) { status = am_web_get_request_url(virtHost_hdr, protocol, NULL, 0, uri_hdr, query, &request_url, agent_config); if(status == AM_SUCCESS) { am_web_log_debug("%s: Request_url: %s", thisfunc, request_url); } else { am_web_log_error("%s: Could not get the request URL. " "Failed with error: %s.", thisfunc, am_status_to_string(status)); } } } if (status == AM_SUCCESS) { if (am_web_is_proxy_override_host_port_set(agent_config) == AM_TRUE) { const char *agent_host = am_web_get_agent_server_host(agent_config); int agent_port = am_web_get_agent_server_port(agent_config); if (agent_host != NULL) { char *temp = NULL; temp = replace_host_port(request_url, agent_host, agent_port, agent_config); if (temp != NULL) { free(request_url); request_url = temp; } } am_web_log_debug("%s: Request_url after overriding " "host and port: %s", thisfunc, request_url); } } if (status == AM_SUCCESS) { // Check for magic notification URL if (B_TRUE == am_web_is_notification(request_url, agent_config)) { am_web_free_memory(request_url); am_web_delete_agent_configuration(agent_config); if(query != NULL) { free(query); query = NULL; } if(method != NULL) { free(method); method = NULL; } return REQ_PROCEED; } } // Check if the SSO token is in the cookie header if (status == AM_SUCCESS) { requestResult = getISCookie(pblock_findval(COOKIE_HDR, rq->headers), &dpro_cookie, agent_config); if (requestResult == REQ_ABORTED) { status = AM_FAILURE; } else if (dpro_cookie != NULL) { am_web_log_debug("%s: SSO token found in cookie header.", thisfunc); } } // Create the environment map if( status == AM_SUCCESS) { status = am_map_create(&env_parameter_map); if( status != AM_SUCCESS) { am_web_log_error("%s: Unable to create map, status = %s (%d)", thisfunc, am_status_to_string(status), status); } } // If there is a proxy in front of the agent, the user can set in the // properties file the name of the headers that the proxy uses to set // the real client IP and host name. In that case the agent needs // to use the value of these headers to process the request // // Get the client IP address header set by the proxy, if there is one if (status == AM_SUCCESS) { clientIP_hdr_name = am_web_get_client_ip_header_name(agent_config); if (clientIP_hdr_name != NULL) { status = get_header_value(rq->headers, clientIP_hdr_name, B_FALSE, &clientIP_hdr, B_FALSE, NULL); } } // Get the client host name header set by the proxy, if there is one if (status == AM_SUCCESS) { clientHostname_hdr_name = am_web_get_client_hostname_header_name(agent_config); if (clientHostname_hdr_name != NULL) { status = get_header_value(rq->headers, clientHostname_hdr_name, B_FALSE, &clientHostname_hdr, B_FALSE, NULL); } } // If the client IP and host name headers contain more than one // value, take the first value. if (status == AM_SUCCESS) { if ((clientIP_hdr != NULL) || (clientHostname_hdr != NULL)) { status = am_web_get_client_ip_host(clientIP_hdr, clientHostname_hdr, &clientIP, &clientHostname); } } // Set the IP address and host name in the environment map if ((status == AM_SUCCESS) && (clientIP != NULL)) { status = am_web_set_host_ip_in_env_map(clientIP, clientHostname, env_parameter_map, agent_config); } // If the client IP was not obtained previously, // get it from the REMOTE_ADDR header. if ((status == AM_SUCCESS) && (clientIP == NULL)) { status = get_header_value(sn->client, REQUEST_IP_ADDR, B_FALSE, &clientIP_hdr, B_TRUE, &clientIP); } // In CDSSO mode, check if the sso token is in the post data if( status == AM_SUCCESS) { if((am_web_is_cdsso_enabled(agent_config) == B_TRUE) && (strcmp(method, REQUEST_METHOD_POST) == 0)) { if((dpro_cookie == NULL) && (am_web_is_url_enforced(request_url, pathInfo_hdr, clientIP, agent_config) == B_TRUE)) { // Set original method to GET orig_req = strdup(REQUEST_METHOD_GET); if (orig_req != NULL) { am_web_log_debug("%s: Request method set to GET.", thisfunc); } else { am_web_log_error("%s: Not enough memory to ", "allocate orig_req.", thisfunc); status = AM_NO_MEMORY; } // Check if dpro_cookie is in post data if( status == AM_SUCCESS) { response = get_post_assertion_data(sn, rq, request_url); status = am_web_check_cookie_in_post(args, &dpro_cookie, &request_url, &orig_req, method, response, B_FALSE, set_cookie, set_method, agent_config); if( status == AM_SUCCESS) { am_web_log_debug("%s: SSO token found in " "assertion.",thisfunc); } else { am_web_log_debug("%s: SSO token not found in " "assertion. Redirecting to login page.", thisfunc); status = AM_INVALID_SESSION; } } // Set back the original clf-request attribute if (status == AM_SUCCESS) { int clf_reqSize = 0; if ((query != NULL) && (strlen(query) > 0)) { clf_reqSize = strlen(orig_req) + strlen(uri_hdr) + strlen (query) + strlen(protocol) + 4; } else { clf_reqSize = strlen(orig_req) + strlen(uri_hdr) + strlen(protocol) + 3; } clf_req = malloc(clf_reqSize); if (clf_req == NULL) { am_web_log_error("%s: Unable to allocate %i " "bytes for clf_req", thisfunc, clf_reqSize); status = AM_NO_MEMORY; } else { memset (clf_req,'\0',clf_reqSize); strcpy(clf_req, orig_req); strcat(clf_req, " "); strcat(clf_req, uri_hdr); if ((query != NULL) && (strlen(query) > 0)) { strcat(clf_req, "?"); strcat(clf_req, query); } strcat(clf_req, " "); strcat(clf_req, protocol); am_web_log_debug("%s: clf-request set to %s", thisfunc, clf_req); } pblock_nvinsert(REQUEST_CLF, clf_req, rq->reqpb); } } } } // Check if access is allowed. if( status == AM_SUCCESS) { if (dpro_cookie != NULL) { am_web_log_debug("%s: SSO token = %s", thisfunc, dpro_cookie); } else { am_web_log_debug("%s: SSO token not found.", thisfunc); } status = am_web_is_access_allowed(dpro_cookie, request_url, pathInfo_hdr, method, clientIP, env_parameter_map, &result, agent_config); am_map_destroy(env_parameter_map); } switch(status) { case AM_SUCCESS: // Set remote user and authentication type ruser = result.remote_user; if (ruser != NULL) { pb_param *pbuser = pblock_remove(AUTH_USER_VAR, rq->vars); pb_param *pbauth = pblock_remove(AUTH_TYPE_VAR, rq->vars); if (pbuser != NULL) { param_free(pbuser); } pblock_nvinsert(AUTH_USER_VAR, ruser, rq->vars); if (pbauth != NULL) { param_free(pbauth); } pblock_nvinsert(AUTH_TYPE_VAR, AM_WEB_AUTH_TYPE_VALUE, rq->vars); am_web_log_debug("%s: access allowed to %s", thisfunc, ruser); } else { am_web_log_debug("%s: Remote user not set, " "allowing access to the url as it is in not " "enforced list", thisfunc); } if (am_web_is_logout_url(request_url, agent_config) == B_TRUE) { (void)am_web_logout_cookies_reset(reset_cookie, args, agent_config); } // set LDAP user attributes to http header status = am_web_result_attr_map_set(&result, set_header, set_cookie_in_response, set_header_attr_as_cookie, get_cookie_sync, args, agent_config); if (status != AM_SUCCESS) { am_web_log_error("%s: am_web_result_attr_map_set failed, " "status = %s (%d)", thisfunc, am_status_to_string(status), status); requestResult = REQ_ABORTED; } else { requestResult = REQ_PROCEED; } break; case AM_ACCESS_DENIED: am_web_log_debug("%s: Access denied to %s", thisfunc, result.remote_user ? result.remote_user : "******"); requestResult = do_redirect(sn, rq, status, &result, request_url, method, agent_config); break; case AM_INVALID_SESSION: if (am_web_is_cdsso_enabled(agent_config) == B_TRUE) { cdStatus = am_web_do_cookie_domain_set(set_cookie, args, EMPTY_STRING, agent_config); if(cdStatus != AM_SUCCESS) { am_web_log_error("%s: CDSSO reset cookie failed", thisfunc); } } am_web_do_cookies_reset(reset_cookie, args, agent_config); requestResult = do_redirect(sn, rq, status, &result, request_url, method, agent_config); break; case AM_INVALID_FQDN_ACCESS: // Redirect to self with correct FQDN - no post preservation requestResult = do_redirect(sn, rq, status, &result, request_url, method, agent_config); break; case AM_REDIRECT_LOGOUT: status = am_web_get_logout_url(&logout_url, agent_config); if(status == AM_SUCCESS) { do_url_redirect(sn,rq,logout_url); } else { requestResult = REQ_ABORTED; am_web_log_debug("validate_session_policy(): " "am_web_get_logout_url failed. "); } break; case AM_INVALID_ARGUMENT: case AM_NO_MEMORY: default: am_web_log_error("validate_session_policy() Status: %s (%d)", am_status_to_string(status), status); requestResult = REQ_ABORTED; break; } // Cleaning am_web_clear_attributes_map(&result); am_policy_result_destroy(&result); am_web_free_memory(dpro_cookie); am_web_free_memory(request_url); am_web_free_memory(logout_url); am_web_delete_agent_configuration(agent_config); if (orig_req != NULL) { free(orig_req); orig_req = NULL; } if (response != NULL) { free(response); response = NULL; } if (clf_req != NULL) { free(clf_req); clf_req = NULL; } if(query != NULL) { free(query); query = NULL; } if(method != NULL) { free(method); method = NULL; } if(clientIP != NULL) { am_web_free_memory(clientIP); } if(clientHostname != NULL) { am_web_free_memory(clientHostname); } am_web_log_max_debug("%s: Completed handling request with status: %s.", thisfunc, am_status_to_string(status)); return requestResult; }
NSAPI_PUBLIC int web_agent_init(pblock *param, Session *sn, Request *rq) { am_status_t status; int nsapi_status = REQ_PROCEED; char *temp_buf = NULL; char *agent_bootstrap_file = NULL; char *agent_config_file = NULL; initLock = crit_init(); temp_buf = pblock_findval(DSAME_CONF_DIR, param); if (temp_buf != NULL) { agent_bootstrap_file = system_malloc(strlen(temp_buf) + sizeof(AGENT_BOOTSTRAP_FILE)); agent_config_file = system_malloc(strlen(temp_buf) + sizeof(AGENT_CONFIG_FILE)); if (agent_bootstrap_file != NULL) { strcpy(agent_bootstrap_file, temp_buf); strcat(agent_bootstrap_file, AGENT_BOOTSTRAP_FILE); } else { log_error(LOG_FAILURE, "URL Access Agent: ", sn, rq, "web_agent_init() unable to allocate memory for bootstrap " "file name", DSAME_CONF_DIR); nsapi_status = REQ_ABORTED; } if (agent_config_file != NULL) { strcpy(agent_config_file, temp_buf); strcat(agent_config_file, AGENT_CONFIG_FILE); } else { log_error(LOG_FAILURE, "URL Access Agent: ", sn, rq, "web_agent_init() unable to allocate memory for local config " "file name", DSAME_CONF_DIR); nsapi_status = REQ_ABORTED; } status = am_properties_create(&agent_props.agent_bootstrap_props); if(status == AM_SUCCESS) { status = am_properties_load(agent_props.agent_bootstrap_props, agent_bootstrap_file); if(status == AM_SUCCESS) { //this is where the agent config info is passed from filter code //to amsdk. Not sure why agent_props is required. status = am_web_init(agent_bootstrap_file, agent_config_file); system_free(agent_bootstrap_file); system_free(agent_config_file); if (AM_SUCCESS != status) { log_error(LOG_FAILURE, "URL Access Agent: ", sn, rq, "Initialization of the agent failed: " "status = %s (%d)", am_status_to_string(status), status); nsapi_status = REQ_ABORTED; } } else { log_error(LOG_FAILURE, "web_agent_init():", sn, rq, "Error while creating properties object= %s", am_status_to_string(status)); nsapi_status = REQ_ABORTED; } } else { log_error(LOG_FAILURE, "web_agent_init():", sn, rq, "Error while creating properties object= %s", am_status_to_string(status)); nsapi_status = REQ_ABORTED; } } else { log_error(LOG_FAILURE, "URL Access Agent: ", sn, rq, "web_agent_init() %s variable not defined in magnus.conf", DSAME_CONF_DIR); nsapi_status = REQ_ABORTED; } if(nsapi_status == REQ_PROCEED) { daemon_atrestart(&agent_cleanup, NULL); } return nsapi_status; }
/* Mingw32/64 have a broken vsnprintf implementation that fails when * using a zero-byte limit in order to retrieve the required size for malloc. * So we use a one byte buffer instead. */ char tmp[1]; int len = vsnprintf (tmp, 1, fmt, ap) + 1; char *res = (char *)malloc((unsigned int)len); if (res == NULL) return -1; *strp = res; return vsnprintf(res, (unsigned int)len, fmt, ap); } #endif #ifdef USING_SYSTEM_ALLOCATOR_LIBRARY /* Ruby Enterprise Edition with tcmalloc */ void vasprintf_free (void *p) { system_free(p); }
/** * manages the running of the program, initialises data structures, loads * data and handles the processing of options. The bulk of this function * should simply be calling other functions to get the job done. **/ int main(int argc, char **argv) { /* Represents the data structures to manage the system */ struct ppd_system system; struct menu_item menu[NUM_MENU_ITEMS]; char input[NUM_MENU_INPUT], *error; int option, i; BOOLEAN exit = FALSE; /* Validate command line arguments */ if ( argc != NUM_ARGS) { printf("Usage: ./playme <stock> <coins>\n\n"); return EXIT_FAILURE; } else { if(argv[ITEM_FILE_INDEX] == 0) { printf("stock_file failed!\n"); printf("Please make sure to input file name correctly.\n\n"); return EXIT_FAILURE; } if(argv[COIN_FILE_INDEX] == 0) { printf("coins_file failed!\n"); printf("Please make sure to input file name correctly.\n\n"); return EXIT_FAILURE; } } /* Init the system */ if(system_init(&system) != TRUE) { printf("System failed to initialise!\n"); system_free(&system); return EXIT_FAILURE; } /* Load data */ if(load_data(&system, argv[COIN_FILE_INDEX], argv[ITEM_FILE_INDEX]) != TRUE) { printf("Failed to load data!\n"); system_free(&system); return EXIT_FAILURE; } /* Test if everything has been initialised correctly */ #if 0 if(!display_items(&system) || !display_coins(&system)) abort_program(&system); #endif /* Initialise the menu system */ init_menu(menu); while(!exit) { /* Loop, asking for options from the menu */ for(i = 0; i < NUM_MENU_ITEMS; i++) { if(i == SELECT_DEFAULT) printf("\n\n== Default Selections ==\n========================\n"); else if(i == SELECT_ADMIN) printf("\n== Admin Selections ==\n========================\n"); printf("%d. %s\n", i + 1, menu[i].name); } while(!exit) { printf("\nPlease select what you would like to do: "); /* Get user input and assign to variable */ i = get_user_input(input, NUM_MENU_INPUT); /* Check for return to menu */ if(i == RTM) { printf("You have no where to return to!\n"); continue; } /* Check for invalid input */ if(i == FAILURE) { printf("Your text was too long!\n"); continue; } /* Convert given input to int and assign to option */ option = (int) strtol(input, &error, 0) - 1; /* Check if converted string inside menu range */ if(option >= 0 && option <= NUM_MENU_ITEMS) exit = TRUE; /* For all other values, echo output outside of range */ else printf("Input outside of range!\n"); } /* Reset exit BOOLEAN for part 2 */ exit = FALSE; /* Run each option selected */ if(menu[option].function(&system) != TRUE) printf("Option '%s' failed to complete!\n", menu[option].name); } return EXIT_SUCCESS; }
int main(int argc, char** argv) { int input; char *stockfile = NULL, *coinsfile = NULL; char charInput[MENUINPUT + EXTRA_SPACES]; tm_type tm; BOOLEAN quit = FALSE; /* check command line arguments */ if (argc != 3){ printf("Usage: tm <stock.csv> <coins.csv>\n"); exit(EXIT_FAILURE); } else{ /*Check if what the user has entered as arguments match stock.csv and coins.csv*/ if (strcmp(argv[1], FNAME1) && strcmp(argv[2], FNAME2) != 0){ printf("\nError: Cannot load stock.csv and coins.csv! Exiting...\n\n"); exit(EXIT_FAILURE); } } /* initialise data structures */ system_init(&tm); /* load data */ load_data(&tm, argv[1], argv[2]); /* test that everything has gone in initialisation and loading */ while(!quit) { /* display menu */ printf("\nMain Menu\n"); printf("1) Purchase Ticket\n"); printf("2) Display Tickets\n"); printf("3) Save and Exit\n"); printf("Administrator-Only Menu\n"); printf("4) Add Ticket\n"); printf("5) Remove Ticket\n"); printf("6) Display Coins\n"); printf("7) Restock Tickets\n"); printf("8) Restock Coins\n"); printf("9) Abort\n\n"); printf("Select your option (1-9): "); /* perform menu choice */ fgets(charInput, MENUINPUT + EXTRA_SPACES, stdin); /*Convert menu input to an int for use in switch statement*/ input = atoi(charInput); switch(input){ case 0: printf("Error: Not a valid option! Please try again.\n\n"); break; case 1: purchase_ticket(&tm); break; case 2: display_tickets(&tm); break; case 3: save_data(&tm, stockfile, coinsfile); system_free(&tm); exit(EXIT_SUCCESS); break; case 4: add_ticket(&tm); break; case 5: delete_ticket(&tm); break; case 6: display_coins(&tm); break; case 7: restock_tickets(&tm); break; case 8: restock_coins(&tm); break; case 9: quit = TRUE; break; } } /* free memory */ system_free(&tm); /* leave program */ exit(EXIT_SUCCESS); }
BOOLEAN abort_program(struct ppd_system *system) { system_free(system); exit(EXIT_SUCCESS); return FALSE; }