static int test_packet_id_write_teardown(void **state) { free(*state); return 0; }
int interpret_config_parse_manufactuer_id_product_id (conffile_t cf, const char *str, struct ipmi_interpret_config_file_ids ids[IPMI_INTERPRET_CONFIG_FILE_MANUFACTURER_ID_MAX], unsigned int *ids_count) { char *tmpstr = NULL; char *manufacturer_id_ptr; char *manufacturer_id_lasts; unsigned int i; int rv = -1; assert (cf); assert (str); assert (ids_count); (*ids_count) = 0; if (!(tmpstr = strdup (str))) { conffile_seterrnum (cf, CONFFILE_ERR_OUTMEM); goto cleanup; } manufacturer_id_ptr = strtok_r (tmpstr, ",", &manufacturer_id_lasts); while (manufacturer_id_ptr && (*ids_count) < IPMI_INTERPRET_CONFIG_FILE_MANUFACTURER_ID_MAX) { char *product_ids_ptr; char *ptr; uint32_t tmp; if (!(ptr = strchr (manufacturer_id_ptr, ':'))) { conffile_seterrnum (cf, CONFFILE_ERR_PARSE_ARG_INVALID); goto cleanup; } (*ptr) = '\0'; product_ids_ptr = ptr + 1; if (interpret_config_parse_strtoul (cf, manufacturer_id_ptr, 0x00FFFFFF, /* 24 bit manufacturer ID */ &tmp) < 0) goto cleanup; ids[(*ids_count)].manufacturer_id = tmp; if ((ptr = strchr (product_ids_ptr, '-'))) { char *product_id1_ptr; char *product_id2_ptr; uint16_t product_id1; uint16_t product_id2; product_id1_ptr = product_ids_ptr; (*ptr) = '\0'; product_id2_ptr = ptr + 1; if (interpret_config_parse_strtoul (cf, product_id1_ptr, USHRT_MAX, &tmp) < 0) goto cleanup; product_id1 = tmp; if (interpret_config_parse_strtoul (cf, product_id2_ptr, USHRT_MAX, &tmp) < 0) goto cleanup; product_id2 = tmp; if (product_id1 > product_id2) { conffile_seterrnum (cf, CONFFILE_ERR_PARSE_ARG_INVALID); return (-1); } if ((product_id2 - product_id1 + 1) > IPMI_INTERPRET_CONFIG_FILE_PRODUCT_ID_MAX) { conffile_seterrnum (cf, CONFFILE_ERR_PARSE_ARG_TOOMANY); return (-1); } for (i = 0; i < (product_id2 - product_id1 + 1) ; i++) ids[(*ids_count)].product_ids[i] = product_id1 + i; ids[(*ids_count)].product_ids_count = product_id2 - product_id1 + 1; } else if ((ptr = strchr (product_ids_ptr, '+'))) { unsigned int index = 0; uint16_t product_id; while ((ptr = strchr (product_ids_ptr, '+')) && index < IPMI_INTERPRET_CONFIG_FILE_PRODUCT_ID_MAX) { char *product_id_ptr; product_id_ptr = product_ids_ptr; (*ptr) = '\0'; product_ids_ptr = ptr + 1; if (interpret_config_parse_strtoul (cf, product_id_ptr, USHRT_MAX, &tmp) < 0) goto cleanup; product_id = tmp; ids[(*ids_count)].product_ids[index] = product_id; index++; } if (interpret_config_parse_strtoul (cf, product_ids_ptr, USHRT_MAX, &tmp) < 0) goto cleanup; product_id = tmp; ids[(*ids_count)].product_ids[index] = product_id; index++; ids[(*ids_count)].product_ids_count = index; } else { if (interpret_config_parse_strtoul (cf, product_ids_ptr, USHRT_MAX, &tmp) < 0) goto cleanup; ids[(*ids_count)].product_ids[0] = tmp; ids[(*ids_count)].product_ids_count = 1; } (*ids_count)++; manufacturer_id_ptr = strtok_r (NULL, ",", &manufacturer_id_lasts); } rv = 0; cleanup: free (tmpstr); return (rv); }
void readCommand() { /* allocate files used for redirection of stderr, stdin, stdout */ char **file = calloc(3, sizeof(char*)); if (!file) { memoryError(); } for (int i = 0; i < 3; i++) { file[i] = calloc(MAX_INPUT_LENGTH + 1, sizeof(char)); if (!file[i]) { memoryError(); } } /* initialize status to designate different modes as identified in #defines */ status parseStatus = 0; char** args = readArgs(&parseStatus, file); /* determine whether shell should exit after executing command */ bool terminate = EOF_FOUND & parseStatus; //Bit masking is used to use a single value for status. switch(parseStatus & (INVALID_SYNTAX | INVALID_ESCAPE)){ case INVALID_SYNTAX: printf("Error: Invalid syntax.\n"); if (terminate) do_exit(); return; case INVALID_ESCAPE: printf("Error: Unrecognized escape sequence.\n"); if (terminate) do_exit(); return; } /* if "exit" is inputted, quit the shell */ if (args[0]) { if (args[1] == NULL && strncmp(args[0], EXIT_COMMAND, strlen(EXIT_COMMAND)) == 0) { do_exit(); } } int restore_stdout = 0; int restore_stdin = 0; int restore_stderr = 0; int f = -1; /* check if any redirection was requested and set up proper files */ if (parseStatus & REDIR_STDOUT) { /*open afile with read and write permissions for the user. */ /*Create it if needed, and truncate it if opened*/ f = open(file[STDOUT],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (f == -1) //-1 indicates that there was a problem with the file { printf("Error: Invalid syntax.\n"); if (terminate) {//if it is EOF, terminate do_exit(); } return; //otherwise, print another prompt } /*Open a file with the path "file" and the intention to read and write from it. */ /*If it does not exist create it and give read and write permissions to the user*/ restore_stdout = dup(STDOUT); //keep a copy of STDOUT close(STDOUT); //Close STDOUT dup(f); //Copy the same file descriptor but set it to the newly closed STDOUT close(f); //Close original file } if (parseStatus & REDIR_STDERR) { f = open(file[STDERR],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (f == -1) { printf("Error: Invalid syntax.\n"); if (terminate) { do_exit(); } return; } restore_stderr = dup(STDERR); //keep a copy of STDOUT close(STDERR); //Close STDOUT dup(f); //Copy the same file descriptor but set it to the newly closed STDOUT close(f); //Close original file } if (parseStatus & REDIR_STDIN)//type==(2<<STDIN)) { /*Do not create a file, as it would be empty and useless to STDIN*/ /*Open as read only because it is an input source*/ f = open(file[STDIN],O_RDONLY); if (f == -1) { printf("Error: Unable to open redirection file.\n"); if (terminate) { do_exit(); } return; } restore_stdin = dup(STDIN); close(STDIN); dup(f); close(f); } /* workaround to allow 'cd' command */ if(args[0] && strncmp(args[0], "cd", 2) == 0) { int error = 0; if(args[1]) error = chdir(args[1]); else error = chdir("/home"); if(error) printf("cd: %s: No such file or directory\n",args[1]); return; } pid_t parent = fork(); if (parent < 0) { printf("Error: process creation failed"); do_exit(); } /* if we are in the child process, execute the command */ else if (!parent) { if (execvp(args[0], args)) { if((*args)[0]) { printf("Error: "); switch(errno) { //based on values in `man errno` case 1: printf("Permission denied.\n"); break; case 2: printf("Command not found.\n"); break; case 13: printf("Permission denied.\n"); break; default: printf("Unkown error.\n"); break; } } } exit(0); } else { /* in parent, wait for child if not a background process */ if (!(parseStatus & BACKGROUND)) { waitpid(parent, NULL, 0); } if (terminate) { do_exit(); } } /* restore any file redirections as necessary */ if(restore_stdin) { close(STDIN); dup(restore_stdin); close(restore_stdin); } if(restore_stdout) { close(STDOUT); dup(restore_stdout); close(restore_stdout); } if(restore_stderr) { close(STDERR); dup(restore_stderr); close(restore_stderr); } /* free all allocated memory */ for (int i = 0; i < 3; i++) { free(file[i]); } free(file); deleteArgs(args); free(args); }
static void dnode_free(dnode_t *node, void *context) { free(node); }
static void construct(dict_t *d) { input_t in; int done = 0; dict_load_t dl; dnode_t *dn; char *tok1, *tok2, *val; const char *key; char *help = "p turn prompt on\n" "q finish construction\n" "a <key> <val> add new entry\n"; if (!dict_isempty(d)) puts("warning: dictionary not empty!"); dict_load_begin(&dl, d); while (!done) { if (prompt) putchar('>'); fflush(stdout); if (!fgets(in, sizeof(input_t), stdin)) break; switch (in[0]) { case '?': puts(help); break; case 'p': prompt = 1; break; case 'q': done = 1; break; case 'a': if (tokenize(in+1, &tok1, &tok2, (char **) 0) != 2) { puts("what?"); break; } key = dupstring(tok1); val = dupstring(tok2); dn = dnode_create(val); if (!key || !val || !dn) { puts("out of memory"); free((void *) key); free(val); if (dn) dnode_destroy(dn); } dict_load_next(&dl, dn, key); break; default: putchar('?'); putchar('\n'); break; } } dict_load_end(&dl); }
/* * Read commands until we are told to stop. */ static void doCommands(void) { const char * cp; char * endbuf; char * newname; int len; NUM num1; NUM num2; BOOL have1; BOOL have2; char buf[USERSIZE]; while (TRUE) { intFlag = FALSE; printf(": "); fflush(stdout); if (fgets(buf, sizeof(buf), stdin) == NULL) return; len = strlen(buf); if (len == 0) return; endbuf = &buf[len - 1]; if (*endbuf != '\n') { fprintf(stderr, "Command line too long\n"); do { len = fgetc(stdin); } while ((len != EOF) && (len != '\n')); continue; } while ((endbuf > buf) && isBlank(endbuf[-1])) endbuf--; *endbuf = '\0'; cp = buf; while (isBlank(*cp)) cp++; have1 = FALSE; have2 = FALSE; if ((curNum == 0) && (lastNum > 0)) { curNum = 1; curLine = lines.next; } if (!getNum(&cp, &have1, &num1)) continue; while (isBlank(*cp)) cp++; if (*cp == ',') { cp++; if (!getNum(&cp, &have2, &num2)) continue; if (!have1) num1 = 1; if (!have2) num2 = lastNum; have1 = TRUE; have2 = TRUE; } if (!have1) num1 = curNum; if (!have2) num2 = num1; switch (*cp++) { case 'a': addLines(num1 + 1); break; case 'c': deleteLines(num1, num2); addLines(num1); break; case 'd': deleteLines(num1, num2); break; case 'f': if (*cp && !isBlank(*cp)) { fprintf(stderr, "Bad file command\n"); break; } while (isBlank(*cp)) cp++; if (*cp == '\0') { if (fileName) printf("\"%s\"\n", fileName); else printf("No file name\n"); break; } newname = strdup(cp); if (newname == NULL) { fprintf(stderr, "No memory for file name\n"); break; } if (fileName) free(fileName); fileName = newname; break; case 'i': addLines(num1); break; case 'k': while (isBlank(*cp)) cp++; if ((*cp < 'a') || (*cp > 'a') || cp[1]) { fprintf(stderr, "Bad mark name\n"); break; } marks[*cp - 'a'] = num2; break; case 'l': printLines(num1, num2, TRUE); break; case 'p': printLines(num1, num2, FALSE); break; case 'q': while (isBlank(*cp)) cp++; if (have1 || *cp) { fprintf(stderr, "Bad quit command\n"); break; } if (!dirty) return; printf("Really quit? "); fflush(stdout); buf[0] = '\0'; fgets(buf, sizeof(buf), stdin); cp = buf; while (isBlank(*cp)) cp++; if ((*cp == 'y') || (*cp == 'Y')) return; break; case 'r': if (*cp && !isBlank(*cp)) { fprintf(stderr, "Bad read command\n"); break; } while (isBlank(*cp)) cp++; if (*cp == '\0') { fprintf(stderr, "No file name\n"); break; } if (!have1) num1 = lastNum; if (readLines(cp, num1 + 1)) break; if (fileName == NULL) fileName = strdup(cp); break; case 's': subCommand(cp, num1, num2); break; case 'w': if (*cp && !isBlank(*cp)) { fprintf(stderr, "Bad write command\n"); break; } while (isBlank(*cp)) cp++; if (!have1) { num1 = 1; num2 = lastNum; } if (*cp == '\0') cp = fileName; if (cp == NULL) { fprintf(stderr, "No file name specified\n"); break; } writeLines(cp, num1, num2); break; case 'z': switch (*cp) { case '-': printLines(curNum-21, curNum, FALSE); break; case '.': printLines(curNum-11, curNum+10, FALSE); break; default: printLines(curNum, curNum+21, FALSE); break; } break; case '.': if (have1) { fprintf(stderr, "No arguments allowed\n"); break; } printLines(curNum, curNum, FALSE); break; case '-': if (setCurNum(curNum - 1)) printLines(curNum, curNum, FALSE); break; case '=': printf("%d\n", num1); break; case '\0': if (have1) { printLines(num2, num2, FALSE); break; } if (setCurNum(curNum + 1)) printLines(curNum, curNum, FALSE); break; default: fprintf(stderr, "Unimplemented command\n"); break; } } }
int SyncTex::SourceToDoc(const WCHAR* srcfilename, UINT line, UINT col, UINT* page, Vec<RectI>& rects) { if (IsIndexDiscarded()) { if (RebuildIndex() != PDFSYNCERR_SUCCESS) return PDFSYNCERR_SYNCFILE_CANNOT_BE_OPENED; } AssertCrash(this->scanner); AutoFreeW srcfilepath; // convert the source file to an absolute path if (PathIsRelative(srcfilename)) srcfilepath.Set(PrependDir(srcfilename)); else srcfilepath.SetCopy(srcfilename); if (!srcfilepath) return PDFSYNCERR_OUTOFMEMORY; bool isUtf8 = true; char* mb_srcfilepath = str::conv::ToUtf8(srcfilepath).StealData(); TryAgainAnsi: if (!mb_srcfilepath) return PDFSYNCERR_OUTOFMEMORY; int ret = synctex_display_query(this->scanner, mb_srcfilepath, line, col); free(mb_srcfilepath); // recent SyncTeX versions encode in UTF-8 instead of ANSI if (isUtf8 && -1 == ret) { isUtf8 = false; mb_srcfilepath = str::conv::ToAnsi(srcfilepath).StealData(); goto TryAgainAnsi; } if (-1 == ret) return PDFSYNCERR_UNKNOWN_SOURCEFILE; if (0 == ret) return PDFSYNCERR_NOSYNCPOINT_FOR_LINERECORD; synctex_node_t node; int firstpage = -1; rects.Reset(); while ((node = synctex_next_result(this->scanner)) != nullptr) { if (firstpage == -1) { firstpage = synctex_node_page(node); if (firstpage <= 0 || firstpage > engine->PageCount()) continue; *page = (UINT)firstpage; } if (synctex_node_page(node) != firstpage) continue; RectD rc; rc.x = synctex_node_box_visible_h(node); rc.y = synctex_node_box_visible_v(node) - synctex_node_box_visible_height(node); rc.dx = synctex_node_box_visible_width(node), rc.dy = synctex_node_box_visible_height(node) + synctex_node_box_visible_depth(node); rects.Push(rc.Round()); } if (firstpage <= 0) return PDFSYNCERR_NOSYNCPOINT_FOR_LINERECORD; return PDFSYNCERR_SUCCESS; }
int swWorker_onTask(swFactory *factory, swEventData *task) { swServer *serv = factory->ptr; swString *package = NULL; swDgramPacket *header; #ifdef SW_USE_OPENSSL swConnection *conn; #endif factory->last_from_id = task->info.from_id; //worker busy serv->workers[SwooleWG.id].status = SW_WORKER_BUSY; switch (task->info.type) { //no buffer case SW_EVENT_TCP: //ringbuffer shm package case SW_EVENT_PACKAGE: //discard data if (swWorker_discard_data(serv, task) == SW_TRUE) { break; } do_task: { serv->onReceive(serv, task); SwooleWG.request_count++; sw_atomic_fetch_add(&SwooleStats->request_count, 1); } if (task->info.type == SW_EVENT_PACKAGE_END) { package->length = 0; } break; //chunk package case SW_EVENT_PACKAGE_START: case SW_EVENT_PACKAGE_END: //discard data if (swWorker_discard_data(serv, task) == SW_TRUE) { break; } package = swWorker_get_buffer(serv, task->info.from_id); //merge data to package buffer memcpy(package->str + package->length, task->data, task->info.len); package->length += task->info.len; //package end if (task->info.type == SW_EVENT_PACKAGE_END) { goto do_task; } break; case SW_EVENT_UDP: case SW_EVENT_UDP6: case SW_EVENT_UNIX_DGRAM: package = swWorker_get_buffer(serv, task->info.from_id); swString_append_ptr(package, task->data, task->info.len); if (package->offset == 0) { header = (swDgramPacket *) package->str; package->offset = header->length; } //one packet if (package->offset == package->length - sizeof(swDgramPacket)) { SwooleWG.request_count++; sw_atomic_fetch_add(&SwooleStats->request_count, 1); serv->onPacket(serv, task); swString_clear(package); } break; case SW_EVENT_CLOSE: #ifdef SW_USE_OPENSSL conn = swServer_connection_verify_no_ssl(serv, task->info.fd); if (conn && conn->ssl_client_cert.length > 0) { free(conn->ssl_client_cert.str); bzero(&conn->ssl_client_cert, sizeof(conn->ssl_client_cert.str)); } #endif factory->end(factory, task->info.fd); break; case SW_EVENT_CONNECT: #ifdef SW_USE_OPENSSL //SSL client certificate if (task->info.len > 0) { conn = swServer_connection_verify_no_ssl(serv, task->info.fd); conn->ssl_client_cert.str = strndup(task->data, task->info.len); conn->ssl_client_cert.size = conn->ssl_client_cert.length = task->info.len; } #endif if (serv->onConnect) { serv->onConnect(serv, &task->info); } break; case SW_EVENT_BUFFER_FULL: if (serv->onBufferFull) { serv->onBufferFull(serv, &task->info); } break; case SW_EVENT_BUFFER_EMPTY: if (serv->onBufferFull) { serv->onBufferEmpty(serv, &task->info); } break; case SW_EVENT_FINISH: serv->onFinish(serv, task); break; case SW_EVENT_PIPE_MESSAGE: serv->onPipeMessage(serv, task); break; default: swWarn("[Worker] error event[type=%d]", (int )task->info.type); break; } //worker idle serv->workers[SwooleWG.id].status = SW_WORKER_IDLE; //maximum number of requests, process will exit. if (!SwooleWG.run_always && SwooleWG.request_count >= SwooleWG.max_request) { SwooleG.running = 0; SwooleG.main_reactor->running = 0; } return SW_OK; }
static int parse_license_file(geoipupdate_s * up) { say_if(up->verbose, "%s\n", PACKAGE_STRING); FILE *fh = fopen(up->license_file, "rb"); exit_unless(!!fh, "Can't open license file %s\n", up->license_file); say_if(up->verbose, "Opened License file %s\n", up->license_file); const char *sep = " \t\r\n"; size_t bsize = 1024; char *buffer = (char *)xmalloc(bsize); ssize_t read_bytes; while ((read_bytes = my_getline(&buffer, &bsize, fh)) != -1) { size_t idx = strspn(buffer, sep); char *strt = &buffer[idx]; if (*strt == '#') { continue; } if (sscanf(strt, "UserId %d", &up->license.user_id) == 1) { say_if(up->verbose, "UserId %d\n", up->license.user_id); continue; } if (sscanf(strt, "LicenseKey %12s", &up->license.license_key[0]) == 1) { say_if(up->verbose, "LicenseKey %s\n", up->license.license_key); continue; } char *p, *last; if ((p = strtok_r(strt, sep, &last))) { if (!strcmp(p, "ProductIds")) { while ((p = strtok_r(NULL, sep, &last))) { product_insert_once(up, p); } } else if (!strcmp(p, "SkipPeerVerification")) { p = strtok_r(NULL, sep, &last); exit_if(NULL == p || (0 != strcmp(p, "0") && 0 != strcmp(p, "1")), "SkipPeerVerification must be 0 or 1\n"); up->skip_peer_verification = atoi(p); } else if (!strcmp(p, "Protocol")) { p = strtok_r(NULL, sep, &last); exit_if(NULL == p || (0 != strcmp(p, "http") && 0 != strcmp(p, "https")), "Protocol must be http or https\n"); free(up->proto); up->proto = strdup(p); } else if (!strcmp(p, "SkipHostnameVerification")) { p = strtok_r(NULL, sep, &last); exit_if(NULL == p || (0 != strcmp(p, "0") && 0 != strcmp(p, "1")), "SkipHostnameVerification must be 0 or 1\n"); up->skip_hostname_verification = atoi(p); } else if (!strcmp(p, "Host")) { p = strtok_r(NULL, sep, &last); exit_if(NULL == p, "Host must be defined\n"); free(up->host); up->host = strdup(p); } else if (!strcmp(p, "DatabaseDirectory")) { if (!up->do_not_overwrite_database_directory) { p = strtok_r(NULL, sep, &last); exit_if(NULL == p, "DatabaseDirectory must be defined\n"); free(up->database_dir); up->database_dir = strdup(p); } } else if (!strcmp(p, "Proxy")) { p = strtok_r(NULL, sep, &last); exit_if(NULL == p, "Proxy must be defined 1.2.3.4:12345\n"); free(up->proxy); up->proxy = strdup(p); } else if (!strcmp(p, "ProxyUserPassword")) { p = strtok_r(NULL, sep, &last); exit_if(NULL == p, "ProxyUserPassword must be defined xyz:abc\n"); free(up->proxy_user_password); up->proxy_user_password = strdup(p); } else { say_if(up->verbose, "Skip unknown directive: %s\n", p); } } } free(buffer); exit_if(-1 == fclose(fh), "Error closing stream: %s", strerror(errno)); say_if(up->verbose, "Read in license key %s\nNumber of product ids %d\n", up->license_file, product_count(up)); return 1; }
/////////////////////////////////////////////////////////////////////// //load, compile and set the shaders void setShaders() { char *vs,*fs,*gs; v = glCreateShader(GL_VERTEX_SHADER); f = glCreateShader(GL_FRAGMENT_SHADER); g = glCreateShader(GL_GEOMETRY_SHADER); vs = textFileRead("./shader01.vert"); fs = textFileRead("./shader01.frag"); gs = textFileRead("./shader01.geom"); const char * ff = fs; const char * vv = vs; const char * gg = gs; GL_CHECK(glShaderSource(v, 1, &vv,NULL)); GL_CHECK(glShaderSource(f, 1, &ff,NULL)); GL_CHECK(glShaderSource(g, 1, &gg,NULL)); free(vs);free(fs);free(gs); GL_CHECK(glCompileShader(v)); GL_CHECK(glCompileShader(f)); GL_CHECK(glCompileShader(g)); GLint blen = 0; GLsizei slen = 0; glGetShaderiv(v, GL_INFO_LOG_LENGTH , &blen); if (blen > 1) { GLchar* compiler_log = (GLchar*)malloc(blen); glGetShaderInfoLog(v, blen, &slen, compiler_log); std::cout << "compiler_log vertex shader:\n" << compiler_log << std::endl; free (compiler_log); } blen = 0; slen = 0; glGetShaderiv(f, GL_INFO_LOG_LENGTH , &blen); if (blen > 1) { GLchar* compiler_log = (GLchar*)malloc(blen); glGetShaderInfoLog(f, blen, &slen, compiler_log); std::cout << "compiler_log fragment shader:\n" << compiler_log << std::endl; free (compiler_log); } blen = 0; slen = 0; glGetShaderiv(g, GL_INFO_LOG_LENGTH , &blen); if (blen > 1) { GLchar* compiler_log = (GLchar*)malloc(blen); glGetShaderInfoLog(g, blen, &slen, compiler_log); std::cout << "compiler_log geometry shader:\n" << compiler_log << std::endl; free (compiler_log); } p = glCreateProgram(); GL_CHECK(glAttachShader(p,f)); GL_CHECK(glAttachShader(p,v)); GL_CHECK(glAttachShader(p,g)); GL_CHECK(glLinkProgram(p)); //comment out this line to not use the shader GL_CHECK(glUseProgram(p)); }
struct uwsgi_buffer *uwsgi_routing_translate(struct wsgi_request *wsgi_req, struct uwsgi_route *ur, char *subject, uint16_t subject_len, char *data, size_t data_len) { // cannot fail char *pass1 = uwsgi_regexp_apply_ovec(subject, subject_len, data, data_len, ur->ovector, ur->ovn); size_t pass1_len = strlen(pass1); struct uwsgi_buffer *ub = uwsgi_buffer_new(pass1_len); size_t i; int status = 0; char *key = NULL; size_t keylen = 0; for(i=0;i<pass1_len;i++) { switch(status) { case 0: if (pass1[i] == '$') { status = 1; break; } if (uwsgi_buffer_append(ub, pass1 + i, 1)) goto error; break; case 1: if (pass1[i] == '{') { status = 2; key = pass1+i+1; keylen = 0; break; } status = 0; key = NULL; keylen = 0; if (uwsgi_buffer_append(ub, "$", 1)) goto error; if (uwsgi_buffer_append(ub, pass1 + i, 1)) goto error; break; case 2: if (pass1[i] == '}') { uint16_t vallen = 0; char *value = uwsgi_get_var(wsgi_req, key, keylen, &vallen); if (value) { if (uwsgi_buffer_append(ub, value, vallen)) goto error; } status = 0; key = NULL; keylen = 0; break; } keylen++; break; default: break; } } // fix the buffer if (status == 1) { if (uwsgi_buffer_append(ub, "$", 1)) goto error; } else if (status == 2) { if (uwsgi_buffer_append(ub, "${", 2)) goto error; if (keylen > 0) { if (uwsgi_buffer_append(ub, key, keylen)) goto error; } } free(pass1); return ub; error: uwsgi_buffer_destroy(ub); return NULL; }
static int open_sgi(audio_output_t *ao) { int current_dev; ALport port = NULL; ALconfig config = alNewConfig(); ao->userptr = NULL; /* Test for correct completion */ if(config == 0) { error1("open_sgi: %s", alGetErrorString(oserror())); return -1; } /* Setup output device to specified device name. If there is no device name specified in ao structure, use the default for output */ if((ao->device) != NULL) { current_dev = alGetResourceByName(AL_SYSTEM, ao->device, AL_OUTPUT_DEVICE_TYPE); debug2("Dev: %s %i", ao->device, current_dev); if(!current_dev) { int i, numOut; char devname[32]; ALpv pv[1]; ALvalue *alvalues; error2("Invalid audio resource: %s (%s)", ao->device, alGetErrorString(oserror())); if((numOut= alQueryValues(AL_SYSTEM,AL_DEFAULT_OUTPUT,0,0,0,0))>=0) fprintf(stderr, "There are %d output devices on this system.\n", numOut); else { fprintf(stderr, "Can't find output devices. alQueryValues failed: %s\n", alGetErrorString(oserror())); goto open_sgi_bad; } alvalues = malloc(sizeof(ALvalue) * numOut); i = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, alvalues, numOut, pv, 0); if(i == -1) error1("alQueryValues: %s", alGetErrorString(oserror())); else { for(i=0; i < numOut; i++) { pv[0].param = AL_NAME; pv[0].value.ptr = devname; pv[0].sizeIn = 32; alGetParams(alvalues[i].i, pv, 1); fprintf(stderr, "%i: %s\n", i, devname); } } free(alvalues); goto open_sgi_bad; } if(alSetDevice(config, current_dev) < 0) { error1("open: alSetDevice : %s",alGetErrorString(oserror())); goto open_sgi_bad; } } else current_dev = AL_DEFAULT_OUTPUT; /* Set the device */ if(alSetDevice(config, current_dev) < 0) { error1("open_sgi: %s", alGetErrorString(oserror())); goto open_sgi_bad; } /* Set port parameters */ if(alSetQueueSize(config, 131069) < 0) { error1("open_sgi: setting audio buffer failed: %s", alGetErrorString(oserror())); goto open_sgi_bad; } if( set_format(ao, config) < 0 || set_rate(ao, config) < 0 || set_channels(ao, config) < 0 ) goto open_sgi_bad; /* Open the audio port */ port = alOpenPort("mpg123-VSC", "w", config); if(port == NULL) { error1("Unable to open audio channel: %s", alGetErrorString(oserror())); goto open_sgi_bad; } ao->userptr = (void*)port; alFreeConfig(config); return 1; open_sgi_bad: /* clean up and return error */ alFreeConfig(config); return -1; }
EAPI Eeze_Udev_Watch * eeze_udev_watch_add(Eeze_Udev_Type type, int event, Eeze_Udev_Watch_Cb cb, void *user_data) { _udev_monitor *mon = NULL; int fd; Ecore_Fd_Handler *handler; Eeze_Udev_Watch *watch = NULL; struct _store_data *store = NULL; if (!(store = calloc(1, sizeof(struct _store_data)))) return NULL; if (!(watch = malloc(sizeof(Eeze_Udev_Watch)))) goto error; if (!(mon = udev_monitor_new_from_netlink(udev, "udev"))) goto error; #ifndef OLD_UDEV_RRRRRRRRRRRRRR switch (type) { case EEZE_UDEV_TYPE_KEYBOARD: udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL); break; case EEZE_UDEV_TYPE_MOUSE: udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL); break; case EEZE_UDEV_TYPE_TOUCHPAD: udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL); break; case EEZE_UDEV_TYPE_DRIVE_MOUNTABLE: case EEZE_UDEV_TYPE_DRIVE_INTERNAL: udev_monitor_filter_add_match_subsystem_devtype(mon, "block", NULL); break; case EEZE_UDEV_TYPE_DRIVE_REMOVABLE: case EEZE_UDEV_TYPE_DRIVE_CDROM: break; case EEZE_UDEV_TYPE_POWER_AC: case EEZE_UDEV_TYPE_POWER_BAT: udev_monitor_filter_add_match_subsystem_devtype(mon, "power_supply", NULL); break; case EEZE_UDEV_TYPE_NET: udev_monitor_filter_add_match_subsystem_devtype(mon, "net", NULL); break; case EEZE_UDEV_TYPE_IS_IT_HOT_OR_IS_IT_COLD_SENSOR: udev_monitor_filter_add_match_subsystem_devtype(mon, "hwmon", NULL); break; /* case EEZE_UDEV_TYPE_ANDROID: udev_monitor_filter_add_match_subsystem_devtype(mon, "input", "usb_interface"); break; */ case EEZE_UDEV_TYPE_V4L: udev_monitor_filter_add_match_subsystem_devtype(mon, "video4linux", NULL); break; case EEZE_UDEV_TYPE_BLUETOOTH: udev_monitor_filter_add_match_subsystem_devtype(mon, "bluetooth", NULL); break; default: break; } #endif if (udev_monitor_enable_receiving(mon)) goto error; fd = udev_monitor_get_fd(mon); store->func = cb; store->data = user_data; store->mon = mon; store->type = type; store->watch = watch; store->event = event; if (!(handler = ecore_main_fd_handler_add(fd, ECORE_FD_READ, _get_syspath_from_watch, store, NULL, NULL))) goto error; watch->mon = mon; watch->handler = handler; return watch; error: if (store) free(store); if (watch) free(watch); if (mon) udev_monitor_unref(mon); ERR("Could not create watch!"); return NULL; }
/* * Initialize the given notification and add it to * the queue. Replace notification with id if id > 0. */ int notification_init(notification * n, int id) { if (n == NULL) return -1; if (strcmp("DUNST_COMMAND_PAUSE", n->summary) == 0) { pause_display = true; return 0; } if (strcmp("DUNST_COMMAND_RESUME", n->summary) == 0) { pause_display = false; return 0; } n->script = NULL; n->text_to_render = NULL; n->format = settings.format; rule_apply_all(n); n->urls = notification_extract_markup_urls(&(n->body)); n->msg = string_replace_all("\\n", "\n", g_strdup(n->format)); n->msg = notification_replace_format("%a", n->appname, n->msg, false, true); n->msg = notification_replace_format("%s", n->summary, n->msg, n->allow_markup, n->plain_text); n->msg = notification_replace_format("%b", n->body, n->msg, n->allow_markup, n->plain_text); if (n->icon) { n->msg = notification_replace_format("%I", basename(n->icon), n->msg, false, true); n->msg = notification_replace_format("%i", n->icon, n->msg, false, true); } if (n->progress) { char pg[10]; sprintf(pg, "[%3d%%]", n->progress - 1); n->msg = string_replace_all("%p", pg, n->msg); } else { n->msg = string_replace_all("%p", "", n->msg); } n->msg = g_strstrip(n->msg); if (id == 0) { n->id = ++next_notification_id; } else { notification_close_by_id(id, -1); n->id = id; } n->dup_count = 0; /* check if n is a duplicate */ if (settings.stack_duplicates) { for (GList * iter = g_queue_peek_head_link(queue); iter; iter = iter->next) { notification *orig = iter->data; if (strcmp(orig->appname, n->appname) == 0 && strcmp(orig->summary, n->summary) == 0 && strcmp(orig->body, n->body) == 0) { /* If the progress differs this was probably intended to replace the notification * but notify-send was used. So don't increment dup_count in this case */ if (orig->progress == n->progress) { orig->dup_count++; } else { orig->progress = n->progress; } /* notifications that differ only in progress hints should be expected equal, * but we want the latest message, with the latest hint value */ free(orig->msg); orig->msg = strdup(n->msg); notification_free(n); wake_up(); return orig->id; } } for (GList * iter = g_queue_peek_head_link(displayed); iter; iter = iter->next) { notification *orig = iter->data; if (strcmp(orig->appname, n->appname) == 0 && strcmp(orig->summary, n->summary) == 0 && strcmp(orig->body, n->body) == 0) { /* notifications that differ only in progress hints should be expected equal, * but we want the latest message, with the latest hint value */ free(orig->msg); orig->msg = strdup(n->msg); /* If the progress differs this was probably intended to replace the notification * but notify-send was used. So don't increment dup_count in this case */ if (orig->progress == n->progress) { orig->dup_count++; } else { orig->progress = n->progress; } orig->start = time(NULL); notification_free(n); wake_up(); return orig->id; } } } /* urgency > CRIT -> array out of range */ n->urgency = n->urgency > CRIT ? CRIT : n->urgency; if (!n->color_strings[ColFG]) { n->color_strings[ColFG] = xctx.color_strings[ColFG][n->urgency]; } if (!n->color_strings[ColBG]) { n->color_strings[ColBG] = xctx.color_strings[ColBG][n->urgency]; } n->timeout = n->timeout == -1 ? settings.timeouts[n->urgency] : n->timeout; n->start = 0; if (n->icon == NULL) { n->icon = strdup(settings.icons[n->urgency]); } else if (strlen(n->icon) <= 0) { free(n->icon); n->icon = strdup(settings.icons[n->urgency]); } if (n->category == NULL) { n->category = ""; } n->timestamp = time(NULL); n->redisplayed = false; n->first_render = true; if (strlen(n->msg) == 0) { notification_close(n, 2); printf("skipping notification: %s %s\n", n->body, n->summary); } else { g_queue_insert_sorted(queue, n, notification_cmp_data, NULL); } char *tmp = g_strconcat(n->summary, " ", n->body, NULL); char *tmp_urls = extract_urls(tmp); if (tmp_urls != NULL) { if (n->urls != NULL) { n->urls = string_append(n->urls, tmp_urls, "\n"); free(tmp_urls); } else { n->urls = tmp_urls; } } if (n->actions) { n->actions->dmenu_str = NULL; for (int i = 0; i < n->actions->count; i += 2) { char *human_readable = n->actions->actions[i + 1]; string_replace_char('[', '(', human_readable); // kill square brackets string_replace_char(']', ')', human_readable); char *act_str = g_strdup_printf("#%s [%s]", human_readable, n->appname); if (act_str) { n->actions->dmenu_str = string_append(n->actions->dmenu_str, act_str, "\n"); free(act_str); } } } free(tmp); if (settings.print_notifications) notification_print(n); return n->id; }
// main int main(int argc, char *argv[]) { signal(SIGINT, depuracion); signal(SIGUSR1, depuracion); // Definicion de variables seguirEjecutando = 1; // Mediante la señal SIGUSR1 se puede dejar de ejecutar el cpu // Obtengo datos de archivo de configuracion y se crea el logger variables = list_create(); config = config_create("../cpu.config"); strcpy(umvip, config_get_string_value(config, "UMV_IP")); strcpy(kernelip, config_get_string_value(config, "KERNEL_IP")); port_kernel = config_get_int_value(config, "PORT_KERNEL"); port_umv = config_get_int_value(config, "PORT_UMV"); config_destroy(config); logger = log_create("../logcpu.log", "CPU", true, LOG_LEVEL_INFO); log_info(logger, "Se leyo el arch de config y se creo el logger satisfactoriamente."); // Me conecto al kernel ConectarA(&sockKernel, &port_kernel, kernelip, &kernel_addr, logger); log_info(logger, "Conectado al kernel."); // Obtengo datos de la umv ConectarA(&sockUmv, &port_umv, umvip, &umv_addr, logger); log_info(logger, "Conectado a la UMV."); // Handshake con el kernel mensaje.id_proceso = CPU; mensaje.tipo = HANDSHAKE; strcpy(mensaje.mensaje, "Hola kernel."); send(sockKernel, &mensaje, sizeof(t_mensaje), 0); if (recv(sockKernel, &mensaje, sizeof(t_mensaje), 0) == 0) { log_error(logger, "Kernel desconectado."); depuracion(SIGINT); } if (mensaje.tipo == HANDSHAKEOK) { log_info(logger, "Handshake con kernel satisfactorio."); } else { log_error(logger, "Handshake con kernel erroneo."); depuracion(SIGINT); } // Handshake con la UMV msg_handshake.tipo = CPU; send(sockUmv, &msg_handshake, sizeof(t_msg_handshake), 0); if (recv(sockUmv, &msg_handshake, sizeof(t_msg_handshake), 0) == 0) { log_error(logger, "UMV desconectada."); depuracion(SIGINT); } if (msg_handshake.tipo == UMV) { log_info(logger, "Handshake con UMV satisfactorio."); } else { log_error(logger, "Handshake con UMV erroneo."); depuracion(SIGINT); } t_mensaje msg_aux; int i; int j; int quantum, retardo; int salir_bucle = 0; int inicio_instruccion = 0; int cantidad_letras_instruccion = 0; int pos_en_instruccion = 0; char buf[82]; // Variable auxiliar para almacenar la linea de codigo char instruccion[82]; int bufferaux[2]; if (recv(sockKernel, &mensaje, sizeof(t_mensaje), 0) == 0) { log_error(logger, "Kernel desconectado."); depuracion(SIGINT); } quantum = mensaje.datosNumericos; if (recv(sockKernel, &mensaje, sizeof(t_mensaje), 0) == 0) { log_error(logger, "Kernel desconectado."); depuracion(SIGINT); } retardo = mensaje.datosNumericos; if (recv(sockKernel, &mensaje, sizeof(t_mensaje), 0) == 0) { log_error(logger, "Kernel desconectado."); depuracion(SIGINT); } stack = mensaje.datosNumericos; char cadena_aux[15]; // Bucle principal del proceso while(seguirEjecutando) { // Recibo el pcb del kernel if (recv(sockKernel, &pcb, sizeof(t_pcb), 0) == 0) { log_error(logger, "Kernel desconectado."); depuracion(SIGINT); } log_info(logger,"Recibi PCB de Kernel"); // Regenero diccionario de variables regenerarDiccionario(); for (i = 0; i < quantum; i++) { if (proceso_bloqueado == 0 && proceso_finalizo == 0) { salir_bucle = 0; inicio_instruccion = 0; cantidad_letras_instruccion = 0; // Preparo mensaje para la UMV msg_solicitud_bytes.base = pcb.instruction_index; msg_solicitud_bytes.offset = pcb.program_counter * 8; msg_solicitud_bytes.tamanio = 8; msg_cambio_proceso_activo.id_programa = pcb.unique_id; mensaje.tipo = SOLICITUDBYTES; send(sockUmv, &mensaje, sizeof(t_mensaje), 0); send(sockUmv, &msg_cambio_proceso_activo, sizeof(t_msg_cambio_proceso_activo), 0); send(sockUmv, &msg_solicitud_bytes, sizeof(t_msg_solicitud_bytes), 0); // Espero la respuesta de la UMV if (recv(sockUmv, &mensaje, sizeof(t_mensaje), 0) == 0) { log_error(logger, "UMV desconectada."); depuracion(SIGINT); } if (recv(sockUmv, &bufferaux, 8, 0) == 0) { log_error(logger, "UMV desconectada."); depuracion(SIGINT); } // Preparo mensaje para la UMV msg_solicitud_bytes.base = pcb.code_segment; msg_solicitud_bytes.offset = bufferaux[0]; msg_solicitud_bytes.tamanio = bufferaux[1]; msg_cambio_proceso_activo.id_programa = pcb.unique_id; mensaje.tipo = SOLICITUDBYTES; send(sockUmv, &mensaje, sizeof(t_mensaje), 0); send(sockUmv, &msg_cambio_proceso_activo, sizeof(t_msg_cambio_proceso_activo), 0); send(sockUmv, &msg_solicitud_bytes, sizeof(t_msg_solicitud_bytes), 0); // Espero la respuesta de la UMV if (recv(sockUmv, &mensaje, sizeof(t_mensaje), 0) == 0) { log_error(logger, "UMV desconectada."); depuracion(SIGINT); } if (recv(sockUmv, &buf, bufferaux[1], 0) == 0) { log_error(logger, "UMV desconectada."); depuracion(SIGINT); } buf[bufferaux[1]] = '\0'; // Verifico limites de instruccion while (salir_bucle != 1) { if(buf[inicio_instruccion] == '\t' || buf[inicio_instruccion] == '\0') { inicio_instruccion++; } else { salir_bucle = 1; } } salir_bucle = 0; pos_en_instruccion = inicio_instruccion; while (salir_bucle != 1) { if(buf[pos_en_instruccion] != '\n') { cantidad_letras_instruccion++; } else { salir_bucle = 1; } pos_en_instruccion++; } memcpy(&instruccion[0], &buf[inicio_instruccion], cantidad_letras_instruccion); instruccion[cantidad_letras_instruccion] = '\0'; // Analizo la instruccion y ejecuto primitivas necesarias log_info(logger, "Me llego la instruccion: %s.", instruccion); usleep(retardo); analizadorLinea(strdup(instruccion), &primitivas, &primitivasKernel); log_info(logger, "Se termino de procesar la instruccion: %s.", instruccion); // Actualizo el pcb pcb.program_counter++; } else { break; } } // Aviso al kernel que termino el quantum del proceso y devuelvo pcb actualizado if (proceso_finalizo == 1) { // Envio a consola de programa el valor final de las variables proceso_finalizo = 0; silverstack_imprimirTexto("Valor final de variables:\n"); for (j = 0; j < list_size(variables); j++) { nueva_var = list_get(variables, j); cadena_aux[0] = nueva_var->id; cadena_aux[1] = ' '; cadena_aux[2] = '='; cadena_aux[3] = ' '; cadena_aux[4] = '\0'; silverstack_imprimirTexto(cadena_aux); silverstack_imprimir(nueva_var->valor); } mensaje.id_proceso = CPU; mensaje.tipo = PROGRAMFINISH; send(sockKernel, &mensaje, sizeof(t_mensaje), 0); log_info(logger, "Envie PROGRAMFINISH al kernel."); send(sockKernel, &pcb, sizeof(t_pcb), 0); log_info(logger, "Envie PCB al kernel."); proceso_finalizo = 0; proceso_imprimir_valores_finales = 1; } else { mensaje.id_proceso = CPU; mensaje.tipo = QUANTUMFINISH; send(sockKernel, &mensaje, sizeof(t_mensaje), 0); log_info(logger,"Envie QUANTUMFINISH al Kernel"); send(sockKernel, &pcb, sizeof(t_pcb), 0); log_info(logger,"Envie PCB al Kernel"); proceso_bloqueado = 0; } } log_info(logger, "Se deja de dar servicio a sistema."); // Libero memoria log_destroy(logger); config_destroy(config); free(variables); // Cierro los sockets close(sockKernel); close(sockUmv); return 0; }
static int gunzip_and_replace(geoipupdate_s * gu, const char *gzipfile, const char *geoip_filename, const char *expected_file_md5) { gzFile gz_fh; FILE *fh = fopen(gzipfile, "rb"); exit_if(NULL == fh, "Can't open %s\n", gzipfile); size_t bsize = 8096; char *buffer = (char *)xmalloc(bsize); ssize_t read_bytes = my_getline(&buffer, &bsize, fh); exit_if(-1 == fclose(fh), "Error closing stream: %s", strerror(errno)); if (read_bytes < 0) { fprintf(stderr, "Read error %s\n", gzipfile); unlink(gzipfile); free(buffer); return ERROR; } const char *no_new_upd = "No new updates available"; if (!strncmp(no_new_upd, buffer, strlen(no_new_upd))) { say_if(gu->verbose, "%s\n", no_new_upd); unlink(gzipfile); free(buffer); return OK; } if (strncmp(buffer, "\x1f\x8b", 2)) { // error not a zip file unlink(gzipfile); printf("%s is not a valid gzip file\n", gzipfile); return ERROR; } // We do this here as we have to check that there is an update before // we check for the header. exit_unless( 32 == strnlen(expected_file_md5, 33), "Did not receive a valid expected database MD5 from server\n"); char *file_path_test; xasprintf(&file_path_test, "%s.test", geoip_filename); say_if(gu->verbose, "Uncompress file %s to %s\n", gzipfile, file_path_test); gz_fh = gzopen(gzipfile, "rb"); exit_if(gz_fh == NULL, "Can't open %s\n", gzipfile); FILE *fhw = fopen(file_path_test, "wb"); exit_if(fhw == NULL, "Can't open %s\n", file_path_test); for (;; ) { int amt = gzread(gz_fh, buffer, bsize); if (amt == 0) { break; // EOF } exit_if(amt == -1, "Gzip read error while reading from %s\n", gzipfile); exit_unless(fwrite(buffer, 1, amt, fhw) == (size_t)amt, "Gzip write error\n"); } exit_if(-1 == fclose(fhw), "Error closing stream: %s", strerror(errno)); exit_if(gzclose(gz_fh) != Z_OK, "Gzip read error while closing from %s\n", gzipfile); free(buffer); char actual_md5[33]; md5hex(file_path_test, actual_md5); exit_if(strncasecmp(actual_md5, expected_file_md5, 32), "MD5 of new database (%s) does not match expected MD5 (%s)", actual_md5, expected_file_md5); say_if(gu->verbose, "Rename %s to %s\n", file_path_test, geoip_filename); int err = rename(file_path_test, geoip_filename); exit_if(err, "Rename %s to %s failed\n", file_path_test, geoip_filename); // fsync directory to ensure the rename is durable int dirfd = open(gu->database_dir, O_DIRECTORY); exit_if(-1 == dirfd, "Error opening database directory: %s", strerror(errno)); exit_if(-1 == fsync(dirfd), "Error syncing database directory: %s", strerror(errno)); exit_if(-1 == close(dirfd), "Error closing database directory: %s", strerror(errno)); exit_if(-1 == unlink(gzipfile), "Error unlinking %s: %s", gzipfile, strerror(errno)); free(file_path_test); return OK; }
/* Return a string from the Win32 Registry or NULL in case of error. Caller must release the return value with g_free (). A NULL for root is an alias for HKEY_CURRENT_USER with a fallback for HKEY_LOCAL_MACHINE. */ char * read_w32_registry_string (const char *root, const char *dir, const char *name) { HKEY root_key; HKEY key_handle; DWORD n1; DWORD nbytes; DWORD type; char *result = NULL; root_key = get_root_key (root); if (! root_key) return NULL; if (RegOpenKeyEx (root_key, dir, 0, KEY_READ, &key_handle)) { if (root) /* No need for a RegClose, so return directly. */ return NULL; /* It seems to be common practise to fall back to HKLM. */ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, dir, 0, KEY_READ, &key_handle)) /* Still no need for a RegClose, so return directly. */ return NULL; } nbytes = 1; if (RegQueryValueEx (key_handle, name, 0, NULL, NULL, &nbytes)) { if (root) goto leave; /* Try to fallback to HKLM also for a missing value. */ RegCloseKey (key_handle); if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, dir, 0, KEY_READ, &key_handle)) return NULL; if (RegQueryValueEx( key_handle, name, 0, NULL, NULL, &nbytes)) goto leave; } n1 = nbytes + 1; result = g_malloc (n1); if (RegQueryValueEx (key_handle, name, 0, &type, result, &n1)) { g_free (result); result = NULL; goto leave; } /* Make sure it is really a string. */ result[nbytes] = 0; if (type == REG_EXPAND_SZ && strchr (result, '%')) { char *tmp; n1 += 1000; tmp = g_malloc (n1 + 1); nbytes = ExpandEnvironmentStrings (result, tmp, n1); if (nbytes && nbytes > n1) { free (tmp); n1 = nbytes; tmp = g_malloc (n1 + 1); nbytes = ExpandEnvironmentStrings (result, tmp, n1); if (nbytes && nbytes > n1) { /* Oops: truncated, better don't expand at all. */ free (tmp); goto leave; } tmp[nbytes] = 0; g_free (result); result = tmp; } else if (nbytes) { /* Okay, reduce the length. */ tmp[nbytes] = 0; free (result); result = g_malloc (strlen (tmp) + 1); strcpy (result, tmp); g_free (tmp); } else { /* Error - don't expand. */ g_free (tmp); } } leave: RegCloseKey (key_handle); return result; }
static void FreeCalBuffer(char **buf) { free(buf[0]); free(buf); }
/* * Do the substitute command. * The current line is set to the last substitution done. */ static void subCommand(const char * cmd, NUM num1, NUM num2) { int delim; char * cp; char * oldStr; char * newStr; LEN oldLen; LEN newLen; LEN deltaLen; LEN offset; LINE * lp; LINE * nlp; BOOL globalFlag; BOOL printFlag; BOOL didSub; BOOL needPrint; char buf[USERSIZE]; if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) { fprintf(stderr, "Bad line range for substitute\n"); return; } globalFlag = FALSE; printFlag = FALSE; didSub = FALSE; needPrint = FALSE; /* * Copy the command so we can modify it. */ strcpy(buf, cmd); cp = buf; if (isBlank(*cp) || (*cp == '\0')) { fprintf(stderr, "Bad delimiter for substitute\n"); return; } delim = *cp++; oldStr = cp; cp = strchr(cp, delim); if (cp == NULL) { fprintf(stderr, "Missing 2nd delimiter for substitute\n"); return; } *cp++ = '\0'; newStr = cp; cp = strchr(cp, delim); if (cp) *cp++ = '\0'; else cp = ""; while (*cp) switch (*cp++) { case 'g': globalFlag = TRUE; break; case 'p': printFlag = TRUE; break; default: fprintf(stderr, "Unknown option for substitute\n"); return; } if (*oldStr == '\0') { if (searchString[0] == '\0') { fprintf(stderr, "No previous search string\n"); return; } oldStr = searchString; } if (oldStr != searchString) strcpy(searchString, oldStr); lp = findLine(num1); if (lp == NULL) return; oldLen = strlen(oldStr); newLen = strlen(newStr); deltaLen = newLen - oldLen; offset = 0; nlp = NULL; while (num1 <= num2) { offset = findString(lp, oldStr, oldLen, offset); if (offset < 0) { if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } offset = 0; lp = lp->next; num1++; continue; } needPrint = printFlag; didSub = TRUE; dirty = TRUE; /* * If the replacement string is the same size or shorter * than the old string, then the substitution is easy. */ if (deltaLen <= 0) { memcpy(&lp->data[offset], newStr, newLen); if (deltaLen) { memcpy(&lp->data[offset + newLen], &lp->data[offset + oldLen], lp->len - offset - oldLen); lp->len += deltaLen; } offset += newLen; if (globalFlag) continue; if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } lp = lp->next; num1++; continue; } /* * The new string is larger, so allocate a new line * structure and use that. Link it in in place of * the old line structure. */ nlp = (LINE *) malloc(sizeof(LINE) + lp->len + deltaLen); if (nlp == NULL) { fprintf(stderr, "Cannot get memory for line\n"); return; } nlp->len = lp->len + deltaLen; memcpy(nlp->data, lp->data, offset); memcpy(&nlp->data[offset], newStr, newLen); memcpy(&nlp->data[offset + newLen], &lp->data[offset + oldLen], lp->len - offset - oldLen); nlp->next = lp->next; nlp->prev = lp->prev; nlp->prev->next = nlp; nlp->next->prev = nlp; if (curLine == lp) curLine = nlp; free(lp); lp = nlp; offset += newLen; if (globalFlag) continue; if (needPrint) { printLines(num1, num1, FALSE); needPrint = FALSE; } lp = lp->next; num1++; } if (!didSub) fprintf(stderr, "No substitutions found for \"%s\"\n", oldStr); }
int rsDataObjCreate( rsComm_t *rsComm, dataObjInp_t *dataObjInp ) { int l1descInx; int status; rodsObjStat_t *rodsObjStatOut = NULL; int remoteFlag; rodsServerHost_t *rodsServerHost; specCollCache_t *specCollCache = NULL; char *lockType = NULL; // JMC - backport 4604 int lockFd = -1; // JMC - backport 4604 resolveLinkedPath( rsComm, dataObjInp->objPath, &specCollCache, &dataObjInp->condInput ); remoteFlag = getAndConnRemoteZone( rsComm, dataObjInp, &rodsServerHost, REMOTE_CREATE ); if ( remoteFlag < 0 ) { return remoteFlag; } else if ( remoteFlag == REMOTE_HOST ) { openStat_t *openStat = NULL; addKeyVal( &dataObjInp->condInput, CROSS_ZONE_CREATE_KW, "" ); status = rcDataObjCreateAndStat( rodsServerHost->conn, dataObjInp, &openStat ); /* rm it to avoid confusion */ rmKeyVal( &dataObjInp->condInput, CROSS_ZONE_CREATE_KW ); if ( status < 0 ) { return status; } l1descInx = allocAndSetL1descForZoneOpr( status, dataObjInp, rodsServerHost, openStat ); if ( openStat != NULL ) { free( openStat ); } return l1descInx; } // =-=-=-=-=-=-=- // working on the "home zone", determine if we need to redirect to a different // server in this zone for this operation. if there is a RESC_HIER_STR_KW then // we know that the redirection decision has already been made char* resc_hier = getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW ); if ( NULL == resc_hier ) { std::string hier; irods::error ret = irods::resolve_resource_hierarchy( irods::CREATE_OPERATION, rsComm, dataObjInp, hier ); if ( !ret.ok() ) { std::stringstream msg; msg << "failed in irods::resolve_resource_hierarchy for ["; msg << dataObjInp->objPath << "]"; irods::log( PASSMSG( msg.str(), ret ) ); return ret.code(); } // =-=-=-=-=-=-=- // we resolved the redirect and have a host, set the hier str for subsequent // api calls, etc. addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() ); } // if keyword // =-=-=-=-=-=-=- // JMC - backport 4604 lockType = getValByKey( &dataObjInp->condInput, LOCK_TYPE_KW ); if ( lockType != NULL ) { lockFd = rsDataObjLock( rsComm, dataObjInp ); if ( lockFd >= 0 ) { /* rm it so it won't be done again causing deadlock */ rmKeyVal( &dataObjInp->condInput, LOCK_TYPE_KW ); } else { rodsLogError( LOG_ERROR, lockFd, "rsDataObjCreate: rsDataObjLock error for %s. lockType = %s", dataObjInp->objPath, lockType ); return lockFd; } } // =-=-=-=-=-=-=- // Gets here means local zone operation stat dataObj addKeyVal( &dataObjInp->condInput, SEL_OBJ_TYPE_KW, "dataObj" ); status = rsObjStat( rsComm, dataObjInp, &rodsObjStatOut ); if ( rodsObjStatOut != NULL && rodsObjStatOut->objType == COLL_OBJ_T ) { if ( lockFd >= 0 ) { char fd_string[NAME_LEN]; snprintf( fd_string, sizeof( fd_string ), "%-d", lockFd ); addKeyVal( &dataObjInp->condInput, LOCK_FD_KW, fd_string ); rsDataObjUnlock( rsComm, dataObjInp ); // JMC - backport 4604 } freeRodsObjStat( rodsObjStatOut ); return USER_INPUT_PATH_ERR; } if ( rodsObjStatOut != NULL && rodsObjStatOut->specColl != NULL && rodsObjStatOut->specColl->collClass == LINKED_COLL ) { /* should not be here because if has been translated */ if ( lockFd >= 0 ) { char fd_string[NAME_LEN]; snprintf( fd_string, sizeof( fd_string ), "%-d", lockFd ); addKeyVal( &dataObjInp->condInput, LOCK_FD_KW, fd_string ); rsDataObjUnlock( rsComm, dataObjInp ); // JMC - backport 4604 } freeRodsObjStat( rodsObjStatOut ); return SYS_COLL_LINK_PATH_ERR; } if ( rodsObjStatOut == NULL || ( rodsObjStatOut->objType == UNKNOWN_OBJ_T && rodsObjStatOut->specColl == NULL ) ) { /* does not exist. have to create one */ /* use L1desc[l1descInx].replStatus & OPEN_EXISTING_COPY instead */ /* newly created. take out FORCE_FLAG since it could be used by put */ /* rmKeyVal (&dataObjInp->condInput, FORCE_FLAG_KW); */ l1descInx = _rsDataObjCreate( rsComm, dataObjInp ); } else if ( rodsObjStatOut->specColl != NULL && rodsObjStatOut->objType == UNKNOWN_OBJ_T ) { /* newly created. take out FORCE_FLAG since it could be used by put */ /* rmKeyVal (&dataObjInp->condInput, FORCE_FLAG_KW); */ l1descInx = specCollSubCreate( rsComm, dataObjInp ); } else { /* dataObj exist */ if ( getValByKey( &dataObjInp->condInput, FORCE_FLAG_KW ) != NULL ) { dataObjInp->openFlags |= O_TRUNC | O_RDWR; // =-=-=-=-=-=-=- // re-determine the resource hierarchy since this is an open instead of a create std::string hier; irods::error ret = irods::resolve_resource_hierarchy( irods::WRITE_OPERATION, rsComm, dataObjInp, hier ); if ( !ret.ok() ) { std::stringstream msg; msg << __FUNCTION__; msg << " :: failed in irods::resolve_resource_hierarchy for ["; msg << dataObjInp->objPath << "]"; irods::log( PASSMSG( msg.str(), ret ) ); freeRodsObjStat( rodsObjStatOut ); return ret.code(); } // =-=-=-=-=-=-=- // we resolved the redirect and have a host, set the hier str for subsequent // api calls, etc. addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() ); std::string top_resc; irods::hierarchy_parser parser; parser.set_string( hier ); parser.first_resc( top_resc ); addKeyVal( &dataObjInp->condInput, DEST_RESC_NAME_KW, top_resc.c_str() ); l1descInx = _rsDataObjOpen( rsComm, dataObjInp ); } else { l1descInx = OVERWRITE_WITHOUT_FORCE_FLAG; } } freeRodsObjStat( rodsObjStatOut ); // =-=-=-=-=-=-=- // JMC - backport 4604 if ( lockFd >= 0 ) { if ( l1descInx >= 0 ) { L1desc[l1descInx].lockFd = lockFd; } else { char fd_string[NAME_LEN]; snprintf( fd_string, sizeof( fd_string ), "%-d", lockFd ); addKeyVal( &dataObjInp->condInput, LOCK_FD_KW, fd_string ); rsDataObjUnlock( rsComm, dataObjInp ); } } // =-=-=-=-=-=-=- return l1descInx; }
void mltds_binding_buffer_finalize(value buffer) { struct binding_buffer* buf = buffer_ptr(buffer); free(buf->data); free(buf); }
int l3CreateByObjInfo( rsComm_t *rsComm, dataObjInp_t *dataObjInp, dataObjInfo_t *dataObjInfo ) { int chkType = 0; // JMC - backport 4774 // =-=-=-=-=-=-=- // extract the host location from the resource hierarchy std::string location; irods::error ret = irods::get_loc_for_hier_string( dataObjInfo->rescHier, location ); if ( !ret.ok() ) { irods::log( PASSMSG( "l3CreateByObjInfo - failed in get_loc_for_hier_string", ret ) ); return -1; } fileCreateInp_t fileCreateInp; memset( &fileCreateInp, 0, sizeof( fileCreateInp ) ); rstrcpy( fileCreateInp.resc_name_, location.c_str(), MAX_NAME_LEN ); rstrcpy( fileCreateInp.resc_hier_, dataObjInfo->rescHier, MAX_NAME_LEN ); rstrcpy( fileCreateInp.objPath, dataObjInfo->objPath, MAX_NAME_LEN ); rstrcpy( fileCreateInp.addr.hostAddr, location.c_str(), NAME_LEN ); rstrcpy( fileCreateInp.fileName, dataObjInfo->filePath, MAX_NAME_LEN ); fileCreateInp.mode = getFileMode( dataObjInp ); // =-=-=-=-=-=-=- // JMC - backport 4774 chkType = getchkPathPerm( rsComm, dataObjInp, dataObjInfo ); if ( chkType == DISALLOW_PATH_REG ) { clearKeyVal( &fileCreateInp.condInput ); return PATH_REG_NOT_ALLOWED; } else if ( chkType == NO_CHK_PATH_PERM ) { fileCreateInp.otherFlags |= NO_CHK_PERM_FLAG; // JMC - backport 4758 } rstrcpy( fileCreateInp.in_pdmo, dataObjInfo->in_pdmo, MAX_NAME_LEN ); //loop until we find a valid filename int retryCnt = 0; int l3descInx; do { fileCreateOut_t* create_out = NULL; l3descInx = rsFileCreate( rsComm, &fileCreateInp, &create_out ); // update the dataObjInfo with the potential changes made by the resource - hcj if ( create_out != NULL ) { rstrcpy( dataObjInfo->rescHier, fileCreateInp.resc_hier_, MAX_NAME_LEN ); rstrcpy( dataObjInfo->filePath, create_out->file_name, MAX_NAME_LEN ); free( create_out ); } //update the filename in case of a retry rstrcpy( fileCreateInp.fileName, dataObjInfo->filePath, MAX_NAME_LEN ); retryCnt++; } while ( getErrno( l3descInx ) == EEXIST && resolveDupFilePath( rsComm, dataObjInfo, dataObjInp ) >= 0 && l3descInx <= 2 && retryCnt < 100 ); clearKeyVal( &fileCreateInp.condInput ); return l3descInx; }
void dnode_destroy(dnode_t *dnode) { assert (!dnode_is_in_a_dict(dnode)); free(dnode); }
BasicStatementTask::~BasicStatementTask() { free((void*)m_sql); }
int main(void) { input_t in; dict_t darray[10]; dict_t *d = &darray[0]; dnode_t *dn; size_t i; char *tok1, *tok2, *val; const char *key; char *help = "a <key> <val> add value to dictionary\n" "d <key> delete value from dictionary\n" "l <key> lookup value in dictionary\n" "( <key> lookup lower bound\n" ") <key> lookup upper bound\n" "< <key> lookup strict lower bound\n" "> <key> lookup strict upper bound\n" "# <num> switch to alternate dictionary (0-9)\n" "j <num> <num> merge two dictionaries\n" "f free the whole dictionary\n" "k allow duplicate keys\n" "c show number of entries\n" "t dump whole dictionary in sort order\n" "m make dictionary out of sorted items\n" "p turn prompt on\n" "s switch to non-functioning allocator\n" "q quit"; for (i = 0; i < sizeof darray / sizeof *darray; i++) dict_init(&darray[i], DICTCOUNT_T_MAX, comparef); for (;;) { if (prompt) putchar('>'); fflush(stdout); if (!fgets(in, sizeof(input_t), stdin)) break; switch(in[0]) { case '?': puts(help); break; case 'a': if (tokenize(in+1, &tok1, &tok2, (char **) 0) != 2) { puts("what?"); break; } key = dupstring(tok1); val = dupstring(tok2); if (!key || !val) { puts("out of memory"); free((void *) key); free(val); } if (!dict_alloc_insert(d, key, val)) { puts("dict_alloc_insert failed"); free((void *) key); free(val); break; } break; case 'd': if (tokenize(in+1, &tok1, (char **) 0) != 1) { puts("what?"); break; } dn = dict_lookup(d, tok1); if (!dn) { puts("dict_lookup failed"); break; } val = (char *) dnode_get(dn); key = (char *) dnode_getkey(dn); dict_delete_free(d, dn); free(val); free((void *) key); break; case 'f': dict_free_nodes(d); break; case 'l': case '(': case ')': case '<': case '>': if (tokenize(in+1, &tok1, (char **) 0) != 1) { puts("what?"); break; } dn = 0; switch (in[0]) { case 'l': dn = dict_lookup(d, tok1); break; case '(': dn = dict_lower_bound(d, tok1); break; case ')': dn = dict_upper_bound(d, tok1); break; case '<': dn = dict_strict_lower_bound(d, tok1); break; case '>': dn = dict_strict_upper_bound(d, tok1); break; } if (!dn) { puts("lookup failed"); break; } val = (char *) dnode_get(dn); puts(val); break; case 'm': construct(d); break; case 'k': dict_allow_dupes(d); break; case 'c': printf("%lu\n", (unsigned long) dict_count(d)); break; case 't': for (dn = dict_first(d); dn; dn = dict_next(d, dn)) { printf("%s\t%s\n", (char *) dnode_getkey(dn), (char *) dnode_get(dn)); } break; case 'q': exit(0); break; case '\0': break; case 'p': prompt = 1; break; case 's': dict_set_allocator(d, new_node, del_node, NULL); break; case '#': if (tokenize(in+1, &tok1, (char **) 0) != 1) { puts("what?"); break; } else { int dictnum = atoi(tok1); if (dictnum < 0 || dictnum > 9) { puts("invalid number"); break; } d = &darray[dictnum]; } break; case 'j': if (tokenize(in+1, &tok1, &tok2, (char **) 0) != 2) { puts("what?"); break; } else { int dict1 = atoi(tok1), dict2 = atoi(tok2); if (dict1 < 0 || dict1 > 9 || dict2 < 0 || dict2 > 9) { puts("invalid number"); break; } dict_merge(&darray[dict1], &darray[dict2]); } break; default: putchar('?'); putchar('\n'); break; } } return 0; }
/*********************************************************************** * ReaderFunc *********************************************************************** * **********************************************************************/ static void ReaderFunc( void * _r ) { hb_reader_t * r = _r; hb_fifo_t ** fifos; hb_buffer_t * buf; hb_list_t * list; int n; int chapter = -1; int chapter_end = r->job->chapter_end; if ( r->title->type == HB_BD_TYPE ) { if ( !( r->bd = hb_bd_init( r->title->path ) ) ) return; } else if ( r->title->type == HB_DVD_TYPE ) { if ( !( r->dvd = hb_dvd_init( r->title->path ) ) ) return; } else if ( r->title->type == HB_STREAM_TYPE || r->title->type == HB_FF_STREAM_TYPE ) { if ( !( r->stream = hb_stream_open( r->title->path, r->title ) ) ) return; } else { // Unknown type, should never happen return; } hb_buffer_t *ps = hb_buffer_init( HB_DVD_READ_BUFFER_SIZE ); if (r->bd) { if( !hb_bd_start( r->bd, r->title ) ) { hb_bd_close( &r->bd ); hb_buffer_close( &ps ); return; } if ( r->job->start_at_preview ) { // XXX code from DecodePreviews - should go into its own routine hb_bd_seek( r->bd, (float)r->job->start_at_preview / ( r->job->seek_points ? ( r->job->seek_points + 1.0 ) : 11.0 ) ); } else if ( r->job->pts_to_start ) { hb_bd_seek_pts( r->bd, r->job->pts_to_start ); r->job->pts_to_start = 0; r->start_found = 1; } else { hb_bd_seek_chapter( r->bd, r->job->chapter_start ); } if (r->job->angle > 1) { hb_bd_set_angle( r->bd, r->job->angle - 1 ); } } else if (r->dvd) { /* * XXX this code is a temporary hack that should go away if/when * chapter merging goes away in libhb/dvd.c * map the start and end chapter numbers to on-media chapter * numbers since chapter merging could cause the handbrake numbers * to diverge from the media numbers and, if our chapter_end is after * a media chapter that got merged, we'll stop ripping too early. */ int start = r->job->chapter_start; hb_chapter_t *chap = hb_list_item( r->title->list_chapter, chapter_end - 1 ); chapter_end = chap->index; if (start > 1) { chap = hb_list_item( r->title->list_chapter, start - 1 ); start = chap->index; } /* end chapter mapping XXX */ if( !hb_dvd_start( r->dvd, r->title, start ) ) { hb_dvd_close( &r->dvd ); hb_buffer_close( &ps ); return; } if (r->job->angle) { hb_dvd_set_angle( r->dvd, r->job->angle ); } if ( r->job->start_at_preview ) { // XXX code from DecodePreviews - should go into its own routine hb_dvd_seek( r->dvd, (float)r->job->start_at_preview / ( r->job->seek_points ? ( r->job->seek_points + 1.0 ) : 11.0 ) ); } } else if ( r->stream && r->job->start_at_preview ) { // XXX code from DecodePreviews - should go into its own routine hb_stream_seek( r->stream, (float)( r->job->start_at_preview - 1 ) / ( r->job->seek_points ? ( r->job->seek_points + 1.0 ) : 11.0 ) ); } else if ( r->stream && r->job->pts_to_start ) { int64_t pts_to_start = r->job->pts_to_start; // Find out what the first timestamp of the stream is // and then seek to the appropriate offset from it if ( hb_stream_read( r->stream, ps ) ) { if ( ps->start > 0 ) pts_to_start += ps->start; } if ( hb_stream_seek_ts( r->stream, pts_to_start ) >= 0 ) { // Seek takes us to the nearest I-frame before the timestamp // that we want. So we will retrieve the start time of the // first packet we get, subtract that from pts_to_start, and // inspect the reset of the frames in sync. r->start_found = 2; r->job->pts_to_start = pts_to_start; } } else if( r->stream ) { /* * Standard stream, seek to the starting chapter, if set, and track the * end chapter so that we end at the right time. */ int start = r->job->chapter_start; hb_chapter_t *chap = hb_list_item( r->title->list_chapter, chapter_end - 1 ); chapter_end = chap->index; if (start > 1) { chap = hb_list_item( r->title->list_chapter, start - 1 ); start = chap->index; } /* * Seek to the start chapter. */ hb_stream_seek_chapter( r->stream, start ); } list = hb_list_init(); while( !*r->die && !r->job->done ) { if (r->bd) chapter = hb_bd_chapter( r->bd ); else if (r->dvd) chapter = hb_dvd_chapter( r->dvd ); else if (r->stream) chapter = hb_stream_chapter( r->stream ); if( chapter < 0 ) { hb_log( "reader: end of the title reached" ); break; } if( chapter > chapter_end ) { hb_log( "reader: end of chapter %d (media %d) reached at media chapter %d", r->job->chapter_end, chapter_end, chapter ); break; } if (r->bd) { if( !hb_bd_read( r->bd, ps ) ) { break; } } else if (r->dvd) { if( !hb_dvd_read( r->dvd, ps ) ) { break; } } else if (r->stream) { if ( !hb_stream_read( r->stream, ps ) ) { break; } if ( r->start_found == 2 ) { // We will inspect the timestamps of each frame in sync // to skip from this seek point to the timestamp we // want to start at. if ( ps->start > 0 && ps->start < r->job->pts_to_start ) { r->job->pts_to_start -= ps->start; } else if ( ps->start >= r->job->pts_to_start ) { r->job->pts_to_start = 0; r->start_found = 1; } } } if( r->job->indepth_scan ) { /* * Need to update the progress during a subtitle scan */ hb_state_t state; #define p state.param.working state.state = HB_STATE_WORKING; p.progress = (double)chapter / (double)r->job->chapter_end; if( p.progress > 1.0 ) { p.progress = 1.0; } p.rate_avg = 0.0; p.hours = -1; p.minutes = -1; p.seconds = -1; hb_set_state( r->job->h, &state ); } (hb_demux[r->title->demuxer])( ps, list, &r->demux ); while( ( buf = hb_list_item( list, 0 ) ) ) { hb_list_rem( list, buf ); fifos = GetFifoForId( r->job, buf->id ); if ( fifos && ! r->saw_video && !r->job->indepth_scan ) { // The first data packet with a PTS from an audio or video stream // that we're decoding defines 'time zero'. Discard packets until // we get one. if ( buf->start != -1 && buf->renderOffset != -1 && ( buf->id == r->title->video_id || is_audio( r, buf->id ) ) ) { // force a new scr offset computation r->scr_changes = r->demux.scr_changes - 1; // create a stream state if we don't have one so the // offset will get computed correctly. id_to_st( r, buf, 1 ); r->saw_video = 1; hb_log( "reader: first SCR %"PRId64" id %d DTS %"PRId64, r->demux.last_scr, buf->id, buf->renderOffset ); } else { fifos = NULL; } } if( fifos ) { if ( buf->renderOffset != -1 ) { if ( r->scr_changes != r->demux.scr_changes ) { // This is the first audio or video packet after an SCR // change. Compute a new scr offset that would make this // packet follow the last of this stream with the // correct average spacing. stream_timing_t *st = id_to_st( r, buf, 0 ); // if this is the video stream and we don't have // audio yet or this is an audio stream // generate a new scr if ( st->is_audio || ( st == r->stream_timing && !r->saw_audio ) ) { new_scr_offset( r, buf ); } else { // defer the scr change until we get some // audio since audio has a timestamp per // frame but video & subtitles don't. Clear // the timestamps so the decoder will generate // them from the frame durations. buf->start = -1; buf->renderOffset = -1; } } } if ( buf->start != -1 ) { int64_t start = buf->start - r->scr_offset; if ( !r->start_found ) UpdateState( r, start ); if ( !r->start_found && start >= r->job->pts_to_start ) { // pts_to_start point found r->start_found = 1; } // This log is handy when you need to debug timing problems //hb_log("id %x scr_offset %ld start %ld --> %ld", // buf->id, r->scr_offset, buf->start, // buf->start - r->scr_offset); buf->start -= r->scr_offset; } if ( buf->renderOffset != -1 ) { if ( r->scr_changes == r->demux.scr_changes ) { // This packet is referenced to the same SCR as the last. // Adjust timestamp to remove the System Clock Reference // offset then update the average inter-packet time // for this stream. buf->renderOffset -= r->scr_offset; update_ipt( r, buf ); } } if ( !r->start_found ) { hb_buffer_close( &buf ); continue; } buf->sequence = r->sequence++; /* if there are mutiple output fifos, send a copy of the * buffer down all but the first (we have to not ship the * original buffer or we'll race with the thread that's * consuming the buffer & inject garbage into the data stream). */ for( n = 1; fifos[n] != NULL; n++) { hb_buffer_t *buf_copy = hb_buffer_init( buf->size ); hb_buffer_copy_settings( buf_copy, buf ); memcpy( buf_copy->data, buf->data, buf->size ); push_buf( r, fifos[n], buf_copy ); } push_buf( r, fifos[0], buf ); } else { hb_buffer_close( &buf ); } } } // send empty buffers downstream to video & audio decoders to signal we're done. if( !*r->die && !r->job->done ) { push_buf( r, r->job->fifo_mpeg2, hb_buffer_init(0) ); hb_audio_t *audio; for( n = 0; (audio = hb_list_item( r->job->title->list_audio, n)); ++n ) { if ( audio->priv.fifo_in ) push_buf( r, audio->priv.fifo_in, hb_buffer_init(0) ); } hb_subtitle_t *subtitle; for( n = 0; (subtitle = hb_list_item( r->job->title->list_subtitle, n)); ++n ) { if ( subtitle->fifo_in && subtitle->source == VOBSUB) push_buf( r, subtitle->fifo_in, hb_buffer_init(0) ); } } hb_list_empty( &list ); hb_buffer_close( &ps ); if (r->bd) { hb_bd_stop( r->bd ); hb_bd_close( &r->bd ); } else if (r->dvd) { hb_dvd_stop( r->dvd ); hb_dvd_close( &r->dvd ); } else if (r->stream) { hb_stream_close(&r->stream); } if ( r->stream_timing ) { free( r->stream_timing ); } hb_log( "reader: done. %d scr changes", r->demux.scr_changes ); if ( r->demux.dts_drops ) { hb_log( "reader: %d drops because DTS out of range", r->demux.dts_drops ); } free( r ); _r = NULL; }
/** * getJNIEnv: A helper function to get the JNIEnv* for the given thread. * If no JVM exists, then one will be created. JVM command line arguments * are obtained from the LIBHDFS_OPTS environment variable. * * @param: None. * @return The JNIEnv* corresponding to the thread. */ JNIEnv* getJNIEnv(void) { const jsize vmBufLength = 1; JavaVM* vmBuf[vmBufLength]; JNIEnv *env; jint rv = 0; jint noVMs = 0; // Only the first thread should create the JVM. The other trheads should // just use the JVM created by the first thread. LOCK_JVM_MUTEX(); rv = JNI_GetCreatedJavaVMs(&(vmBuf[0]), vmBufLength, &noVMs); if (rv != 0) { fprintf(stderr, "JNI_GetCreatedJavaVMs failed with error: %d\n", rv); UNLOCK_JVM_MUTEX(); return NULL; } if (noVMs == 0) { //Get the environment variables for initializing the JVM char *hadoopClassPath = getenv("CLASSPATH"); if (hadoopClassPath == NULL) { fprintf(stderr, "Environment variable CLASSPATH not set!\n"); UNLOCK_JVM_MUTEX(); return NULL; } char *hadoopClassPathVMArg = "-Djava.class.path="; size_t optHadoopClassPathLen = strlen(hadoopClassPath) + strlen(hadoopClassPathVMArg) + 1; char *optHadoopClassPath = malloc(sizeof(char)*optHadoopClassPathLen); snprintf(optHadoopClassPath, optHadoopClassPathLen, "%s%s", hadoopClassPathVMArg, hadoopClassPath); int noArgs = 1; //determine how many arguments were passed as LIBHDFS_OPTS env var char *hadoopJvmArgs = getenv("LIBHDFS_OPTS"); char jvmArgDelims[] = " "; if (hadoopJvmArgs != NULL) { char hadoopJvmArgs_cpy[strlen(hadoopJvmArgs)+1]; strcpy(hadoopJvmArgs_cpy, hadoopJvmArgs); char *result = NULL; result = strtok( hadoopJvmArgs, jvmArgDelims ); result = strtok( hadoopJvmArgs_cpy, jvmArgDelims ); while ( result != NULL ) { noArgs++; result = strtok( NULL, jvmArgDelims); } } JavaVMOption options[noArgs]; options[0].optionString = optHadoopClassPath; //fill in any specified arguments if (hadoopJvmArgs != NULL) { char hadoopJvmArgs_cpy[strlen(hadoopJvmArgs)+1]; strcpy(hadoopJvmArgs_cpy, hadoopJvmArgs); char *result = NULL; result = strtok( hadoopJvmArgs_cpy, jvmArgDelims ); int argNum = 1; for (;argNum < noArgs ; argNum++) { options[argNum].optionString = result; //optHadoopArg; result = strtok( NULL, jvmArgDelims); } } //Create the VM JavaVMInitArgs vm_args; JavaVM *vm; vm_args.version = JNI_VERSION_1_2; vm_args.options = options; vm_args.nOptions = noArgs; vm_args.ignoreUnrecognized = 1; rv = JNI_CreateJavaVM(&vm, (void*)&env, &vm_args); if (rv != 0) { fprintf(stderr, "Call to JNI_CreateJavaVM failed " "with error: %d\n", rv); UNLOCK_JVM_MUTEX(); return NULL; } free(optHadoopClassPath); } else { //Attach this thread to the VM JavaVM* vm = vmBuf[0]; rv = (*vm)->AttachCurrentThread(vm, (void*)&env, 0); if (rv != 0) { fprintf(stderr, "Call to AttachCurrentThread " "failed with error: %d\n", rv); UNLOCK_JVM_MUTEX(); return NULL; } } UNLOCK_JVM_MUTEX(); return env; }
Datum set_timetravel(PG_FUNCTION_ARGS) { Name relname = PG_GETARG_NAME(0); int32 on = PG_GETARG_INT32(1); char *rname; char *d; char *s; int32 ret; TTOffList *prev, *pp; prev = NULL; for (pp = TTOff; pp; prev = pp, pp = pp->next) { if (namestrcmp(relname, pp->name) == 0) break; } if (pp) { /* OFF currently */ if (on != 0) { /* turn ON */ if (prev) prev->next = pp->next; else TTOff = pp->next; free(pp); } ret = 0; } else { /* ON currently */ if (on == 0) { /* turn OFF */ s = rname = DatumGetCString(DirectFunctionCall1(nameout, NameGetDatum(relname))); if (s) { pp = malloc(offsetof(TTOffList, name) + strlen(rname) + 1); if (pp) { pp->next = NULL; d = pp->name; while (*s) *d++ = tolower((unsigned char) *s++); *d = '\0'; if (prev) prev->next = pp; else TTOff = pp; } pfree(rname); } } ret = 1; } PG_RETURN_INT32(ret); }
static int soo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) { struct sockaddr *sa; struct inpcb *inpcb; struct unpcb *unpcb; struct socket *so; int error; kif->kf_type = KF_TYPE_SOCKET; so = fp->f_data; kif->kf_un.kf_sock.kf_sock_domain0 = so->so_proto->pr_domain->dom_family; kif->kf_un.kf_sock.kf_sock_type0 = so->so_type; kif->kf_un.kf_sock.kf_sock_protocol0 = so->so_proto->pr_protocol; kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb; switch (kif->kf_un.kf_sock.kf_sock_domain0) { case AF_INET: case AF_INET6: if (kif->kf_un.kf_sock.kf_sock_protocol0 == IPPROTO_TCP) { if (so->so_pcb != NULL) { inpcb = (struct inpcb *)(so->so_pcb); kif->kf_un.kf_sock.kf_sock_inpcb = (uintptr_t)inpcb->inp_ppcb; kif->kf_un.kf_sock.kf_sock_sendq = sbused(&so->so_snd); kif->kf_un.kf_sock.kf_sock_recvq = sbused(&so->so_rcv); } } break; case AF_UNIX: if (so->so_pcb != NULL) { unpcb = (struct unpcb *)(so->so_pcb); if (unpcb->unp_conn) { kif->kf_un.kf_sock.kf_sock_unpconn = (uintptr_t)unpcb->unp_conn; kif->kf_un.kf_sock.kf_sock_rcv_sb_state = so->so_rcv.sb_state; kif->kf_un.kf_sock.kf_sock_snd_sb_state = so->so_snd.sb_state; kif->kf_un.kf_sock.kf_sock_sendq = sbused(&so->so_snd); kif->kf_un.kf_sock.kf_sock_recvq = sbused(&so->so_rcv); } } break; } error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa); if (error == 0 && sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_local)) { bcopy(sa, &kif->kf_un.kf_sock.kf_sa_local, sa->sa_len); free(sa, M_SONAME); } error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa); if (error == 0 && sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_peer)) { bcopy(sa, &kif->kf_un.kf_sock.kf_sa_peer, sa->sa_len); free(sa, M_SONAME); } strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name, sizeof(kif->kf_path)); return (0); }
int main(int argc, char **argv) { int i, j = 1024 * 1024 * 1; char *buffer = malloc(8 * j + 4); #ifndef BENCH has_t* h = has_hash_new(64); has_t* vals = has_new(j); #else has_t* h = has_hash_new(j); #endif double t1, t2; t1 = epoch_double(); for(i = 0; i < j; i++) { sprintf(buffer + i * 8, "%08x", i); #ifndef BENCH has_string_init(&(vals[i]), buffer + i * 8, 8, false); #endif } t2 = epoch_double(); printf("Init: %f\n", t2 - t1); t1 = epoch_double(); for(i = 0; i < j; i++) { #ifndef BENCH has_hash_set(h, buffer + i * 8, 8, &(vals[i])); #else has_hash_set(h, buffer + i * 8, 8, NULL); #endif } t2 = epoch_double(); printf("Adding: %f\n", t2 - t1); t1 = epoch_double(); for(i = 0; i < j; i++) { assert(has_hash_get(h, buffer + i * 8, 8)); } t2 = epoch_double(); printf("Looking up: %f\n", t2 - t1); t1 = epoch_double(); for(i = 0; i < j; i++) { has_hash_remove(h, buffer + i * 8, 8); } t2 = epoch_double(); printf("Individual removal: %f\n", t2 - t1); t1 = epoch_double(); for(i = 0; i < j; i++) { #ifndef BENCH has_hash_set(h, buffer + i * 8, 8, &(vals[i])); #else has_hash_set(h, buffer + i * 8, 8, NULL); #endif } t2 = epoch_double(); printf("Adding: %f\n", t2 - t1); t1 = epoch_double(); for(i = 0; i < j; i++) { #ifndef BENCH has_hash_set(h, buffer + i * 8, 8, &(vals[i])); #else has_hash_set(h, buffer + i * 8, 8, NULL); #endif } t2 = epoch_double(); printf("Adding again: %f\n", t2 - t1); t1 = epoch_double(); has_free(h); t2 = epoch_double(); printf("Deleting: %f\n", t2 - t1); #ifndef BENCH free(vals); #endif free(buffer); return 0; }