/* * If type==0, only last line of output is returned (exec) * If type==1, all lines will be printed and last lined returned (system) * If type==2, all lines will be saved to given array (exec with &$array) * If type==3, output will be printed binary, no lines will be saved or returned (passthru) * */ static int _Exec(int type, char *cmd, pval *array, pval *return_value) { FILE *fp; char *buf, *tmp=NULL; int buflen=0; int t, l, ret, output=1; int overflow_limit, lcmd, ldir; char *b, *c, *d=NULL; TLS_VARS; buf = (char*) emalloc(EXEC_INPUT_BUF); if (!buf) { php3_error(E_WARNING, "Unable to emalloc %d bytes", EXEC_INPUT_BUF); return -1; } buflen = EXEC_INPUT_BUF; #ifdef WIN32 (void)AllocConsole(); /* We don't care if this fails. */ #endif if (php3_ini.safe_mode) { lcmd = strlen(cmd); ldir = strlen(php3_ini.safe_mode_exec_dir); l = lcmd + ldir + 2; overflow_limit = l; c = strchr(cmd, ' '); if (c) *c = '\0'; if (strstr(cmd, "..")) { php3_error(E_WARNING, "No '..' components allowed in path"); efree(buf); return -1; } d = emalloc(l); strcpy(d, php3_ini.safe_mode_exec_dir); overflow_limit -= ldir; b = strrchr(cmd, '/'); if (b) { strcat(d, b); overflow_limit -= strlen(b); } else { strcat(d, "/"); strcat(d, cmd); overflow_limit-=(strlen(cmd)+1); } if (c) { *c = ' '; strncat(d, c, overflow_limit); } tmp = _php3_escapeshellcmd(d); efree(d); d = tmp; #if WIN32|WINNT fp = popen(d, "rb"); #else fp = popen(d, "r"); #endif if (!fp) { php3_error(E_WARNING, "Unable to fork [%s]", d); efree(d); efree(buf); return -1; } } else { /* not safe_mode */ #if WIN32|WINNT fp = popen(cmd, "rb"); #else fp = popen(cmd, "r"); #endif if (!fp) { php3_error(E_WARNING, "Unable to fork [%s]", cmd); efree(buf); return -1; } } buf[0] = '\0'; if (type == 1 || type == 3) { output=php3_header(); } if (type==2) { if (array->type != IS_ARRAY) { pval_destructor(array _INLINE_TLS); array_init(array); } } if (type != 3) { l = 0; while ( !feof(fp) || l != 0 ) { l = 0; /* Read a line or fill the buffer, whichever comes first */ do { if ( buflen <= (l+1) ) { buf = erealloc(buf, buflen + EXEC_INPUT_BUF); if ( buf == NULL ) { php3_error(E_WARNING, "Unable to erealloc %d bytes", buflen + EXEC_INPUT_BUF); return -1; } buflen += EXEC_INPUT_BUF; } if ( fgets(&(buf[l]), buflen - l, fp) == NULL ) { /* eof */ break; } l += strlen(&(buf[l])); } while ( (l > 0) && (buf[l-1] != '\n') ); if ( feof(fp) && (l == 0) ) { break; } if (type == 1) { if (output) PUTS(buf); #if APACHE # if MODULE_MAGIC_NUMBER > 19970110 if (output) rflush(GLOBAL(php3_rqst)); # else if (output) bflush(GLOBAL(php3_rqst)->connection->client); # endif #endif #if CGI_BINARY fflush(stdout); #endif #if FHTTPD /* fhttpd doesn't flush */ #endif #if USE_SAPI GLOBAL(sapi_rqst)->flush(GLOBAL(sapi_rqst)->scid); #endif } else if (type == 2) { pval tmp; /* strip trailing whitespaces */ l = strlen(buf); t = l; while (l-- && isspace((int)buf[l])); if (l < t) buf[l + 1] = '\0'; tmp.value.str.len = strlen(buf); tmp.value.str.val = estrndup(buf,tmp.value.str.len); tmp.type = IS_STRING; _php3_hash_next_index_insert(array->value.ht,(void *) &tmp, sizeof(pval), NULL); } } /* strip trailing spaces */ l = strlen(buf); t = l; while (l && isspace((int)buf[--l])); if (l < t) buf[l + 1] = '\0'; /* Return last line from the shell command */ if(php3_ini.magic_quotes_runtime) { int len; tmp = _php3_addslashes(buf, 0, &len, 0); RETVAL_STRINGL(tmp,len,0); } else { RETVAL_STRINGL(buf,l+1,1); } } else { int b, i; while ((b = fread(buf, 1, buflen, fp)) > 0) { for (i = 0; i < b; i++) if (output) PUTC(buf[i]); } } ret = pclose(fp); #ifdef HAVE_SYS_WAIT_H if (WIFEXITED(ret)) { ret = WEXITSTATUS(ret); } #endif if (d) efree(d); efree(buf); return ret; }
/* {{{ proto int ora_bind(int cursor, string php_variable_name, string sql_parameter_name, int length [, int type]) Bind a PHP variable to an Oracle parameter */ void php3_Ora_Bind(INTERNAL_FUNCTION_PARAMETERS) { /* cursor_ind, php_var_name, sql_var_name, data_len [, inout]*/ /* inout: 0 = in/out, 1 = in, 2 = out */ int argc; pval *argv[5]; oraParam *newparam, *paramptr; oraCursor *cursor; char *paramname; argc = ARG_COUNT(ht); if (argc < 4 || argc > 5 || getParametersArray(ht, argc, argv) == FAILURE){ WRONG_PARAM_COUNT; } convert_to_long(argv[0]); convert_to_string(argv[1]); convert_to_string(argv[2]); convert_to_long(argv[3]); cursor = ora_get_cursor(list, argv[0]->value.lval); if (cursor == NULL) { php3_error(E_WARNING, "Invalid cursor index %d", argv[0]->value.lval); RETURN_FALSE; } if(cursor->params == NULL){ cursor->params = (HashTable *)emalloc(sizeof(HashTable)); if (!cursor->params || _php3_hash_init(cursor->params, 19, NULL, HASH_DTOR pval_ora_param_destructor, 0) == FAILURE) { php3_error(E_ERROR, "Unable to initialize parameter list"); RETURN_FALSE; } } if((newparam = (oraParam *)emalloc(sizeof(oraParam))) == NULL){ php3_error(E_WARNING, "Out of memory for parameter"); RETURN_FALSE; } if((paramname = estrndup(argv[1]->value.str.val, argv[1]->value.str.len)) == NULL){ php3_error(E_WARNING, "Out of memory for parametername"); efree(newparam); RETURN_FALSE; } if (_php3_hash_add(cursor->params, paramname, argv[1]->value.str.len + 1, newparam, sizeof(oraParam), (void **)¶mptr) == FAILURE) { /* XXX _php3_hash_destroy */ efree(paramname); efree(newparam); php3_error(E_ERROR, "Could not make parameter placeholder"); RETURN_FALSE; } efree(newparam); efree(paramname); paramptr->progvl = argv[3]->value.lval + 1; if(argc > 4){ convert_to_long(argv[4]); paramptr->inout = (short)argv[4]->value.lval; }else{ paramptr->inout = 0; } if((paramptr->progv = (text *)emalloc(paramptr->progvl)) == NULL){ php3_error(E_WARNING, "Out of memory for parameter value"); RETURN_FALSE; } /* XXX Maximum for progvl */ paramptr->alen = paramptr->progvl; if (obndra(&cursor->cda, argv[2]->value.str.val, -1, (ub1 *)paramptr->progv, paramptr->progvl, SQLT_STR, /* ftype */ -1, /* scale */ 0/*¶mptr->ind*/, /* ind */ ¶mptr->alen, /* alen */ 0 /*¶mptr->arcode*/, 0, /* maxsize */ 0, 0, -1, -1)) { php3_error(E_WARNING, "Ora_Bind failed (%s)", ora_error(&cursor->cda)); RETURN_FALSE; } cursor->nparams++; RETURN_TRUE; }
static int checkfs(const char *pvfstype, const char *spec, const char *mntpt, char *auxopt, pid_t *pidp) { const char **argv; pid_t pid; int argc, i, status, maxargc; char *optbuf, execbase[MAXPATHLEN]; char *vfstype = NULL; const char *extra = NULL; #ifdef __GNUC__ /* Avoid vfork clobbering */ (void) &optbuf; (void) &vfstype; #endif /* * We convert the vfstype to lowercase and any spaces to underscores * to not confuse the issue * * XXX This is a kludge to make automatic filesystem type guessing * from the disklabel work for "4.2BSD" filesystems. It does a * very limited subset of transliteration to a normalised form of * filesystem name, and we do not seem to enforce a filesystem * name character set. */ vfstype = strdup(pvfstype); if (vfstype == NULL) perror("strdup(pvfstype)"); for (i = 0; i < strlen(vfstype); i++) { vfstype[i] = tolower(vfstype[i]); if (vfstype[i] == ' ') vfstype[i] = '_'; } extra = getoptions(vfstype); optbuf = NULL; if (options) catopt(&optbuf, options); if (extra) catopt(&optbuf, extra); if (auxopt) catopt(&optbuf, auxopt); else if (flags & DO_BACKGRD) catopt(&optbuf, "-B"); maxargc = 64; argv = emalloc(sizeof(char *) * maxargc); (void) snprintf(execbase, sizeof(execbase), "fsck_%s", vfstype); argc = 0; argv[argc++] = execbase; if (optbuf) mangle(optbuf, &argc, &argv, &maxargc); argv[argc++] = spec; argv[argc] = NULL; if (flags & (CHECK_DEBUG|CHECK_VERBOSE)) { (void)printf("start %s %swait", mntpt, pidp ? "no" : ""); for (i = 0; i < argc; i++) (void)printf(" %s", argv[i]); (void)printf("\n"); } switch (pid = vfork()) { case -1: /* Error. */ warn("vfork"); if (optbuf) free(optbuf); free(vfstype); return (1); case 0: /* Child. */ if ((flags & CHECK_DEBUG) && auxopt == NULL) _exit(0); /* Go find an executable. */ execvP(execbase, _PATH_SYSPATH, (char * const *)argv); if (spec) warn("exec %s for %s in %s", execbase, spec, _PATH_SYSPATH); else warn("exec %s in %s", execbase, _PATH_SYSPATH); _exit(1); /* NOTREACHED */ default: /* Parent. */ if (optbuf) free(optbuf); free(vfstype); if (pidp) { *pidp = pid; return 0; } if (waitpid(pid, &status, 0) < 0) { warn("waitpid"); return (1); } if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) return (WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { warnx("%s: %s", spec, strsignal(WTERMSIG(status))); return (1); } break; } return (0); }
static void php_hash_do_hash_hmac(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */ { char *algo, *data, *digest, *key, *K; int algo_len, data_len, key_len, i; zend_bool raw_output = raw_output_default; const php_hash_ops *ops; void *context; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|b", &algo, &algo_len, &data, &data_len, &key, &key_len, &raw_output) == FAILURE) { return; } ops = php_hash_fetch_ops(algo, algo_len); if (!ops) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown hashing algorithm: %s", algo); RETURN_FALSE; } if (isfilename) { stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS | ENFORCE_SAFE_MODE, NULL, DEFAULT_CONTEXT); if (!stream) { /* Stream will report errors opening file */ RETURN_FALSE; } } context = emalloc(ops->context_size); ops->hash_init(context); K = emalloc(ops->block_size); memset(K, 0, ops->block_size); if (key_len > ops->block_size) { /* Reduce the key first */ ops->hash_update(context, (unsigned char *) key, key_len); ops->hash_final((unsigned char *) K, context); /* Make the context ready to start over */ ops->hash_init(context); } else { memcpy(K, key, key_len); } /* XOR ipad */ for(i=0; i < ops->block_size; i++) { K[i] ^= 0x36; } ops->hash_update(context, (unsigned char *) K, ops->block_size); if (isfilename) { char buf[1024]; int n; while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) { ops->hash_update(context, (unsigned char *) buf, n); } php_stream_close(stream); } else { ops->hash_update(context, (unsigned char *) data, data_len); } digest = emalloc(ops->digest_size + 1); ops->hash_final((unsigned char *) digest, context); /* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */ for(i=0; i < ops->block_size; i++) { K[i] ^= 0x6A; } /* Feed this result into the outter hash */ ops->hash_init(context); ops->hash_update(context, (unsigned char *) K, ops->block_size); ops->hash_update(context, (unsigned char *) digest, ops->digest_size); ops->hash_final((unsigned char *) digest, context); /* Zero the key */ memset(K, 0, ops->block_size); efree(K); efree(context); if (raw_output) { digest[ops->digest_size] = 0; RETURN_STRINGL(digest, ops->digest_size, 0); } else { char *hex_digest = safe_emalloc(ops->digest_size, 2, 1); php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size); hex_digest[2 * ops->digest_size] = 0; efree(digest); RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0); } }
static sword ora_describe_define(oraCursor * cursor) { long col = 0; int i; sb2 type; sb4 dbsize; if (cursor == NULL) { return -1; } if (cursor->columns) { for(i = 0; i < cursor->ncols; i++){ if (cursor->columns[i].buf) efree(cursor->columns[i].buf); } efree(cursor->columns); } cursor->ncols = 0; while(1){ if (odescr(&cursor->cda, (sword) cursor->ncols + 1, &dbsize, (sb2 *)0, (sb1 *)0, (sb4 *)0, (sb4 *)0, (sb2 *)0, (sb2 *)0, (sb2 *)0)){ if (cursor->cda.rc == VAR_NOT_IN_LIST) { break; } else { php3_error(E_WARNING, "%s", ora_error(&cursor->cda)); cursor->ncols = 0; return -1; } } cursor->ncols++; } if (cursor->ncols > 0){ cursor->columns = (oraColumn *) emalloc(sizeof(oraColumn) * cursor->ncols); if (cursor->columns == NULL){ php3_error(E_WARNING, "Out of memory"); return -1; } } for(col = 0; col < cursor->ncols; col++){ memset(&cursor->columns[col], 0, sizeof(oraColumn)); cursor->columns[col].cbufl = ORANAMELEN; if (odescr(&cursor->cda, (sword)col + 1, &cursor->columns[col].dbsize, &cursor->columns[col].dbtype, &cursor->columns[col].cbuf[0], &cursor->columns[col].cbufl, &cursor->columns[col].dsize, &cursor->columns[col].prec, &cursor->columns[col].scale, &cursor->columns[col].nullok)) { if (cursor->cda.rc == VAR_NOT_IN_LIST) { break; } else { php3_error(E_WARNING, "%s", ora_error(&cursor->cda)); return -1; } } cursor->columns[col].cbuf[cursor->columns[col].cbufl] = '\0'; switch (cursor->columns[col].dbtype) { case SQLT_LBI: cursor->columns[col].dsize = DB_SIZE; type = SQLT_LBI; break; case SQLT_LNG: cursor->columns[col].dsize = DB_SIZE; default: type = SQLT_STR; break; } if ((cursor->columns[col].buf = (ub1 *) emalloc(cursor->columns[col].dsize + 1)) == NULL){ php3_error(E_WARNING, "Out of memory"); return -1; } /* Define an output variable for the column */ if (odefin(&cursor->cda, (sword)col + 1, cursor->columns[col].buf, cursor->columns[col].dsize + 1, type, -1, &cursor->columns[col].indp, (text *) 0, -1, -1, &cursor->columns[col].col_retlen, &cursor->columns[col].col_retcode)) { php3_error(E_WARNING, "%s", ora_error(&cursor->cda)); return -1; } } return 1; }
static void *php_xml_malloc_wrapper(size_t sz) { return emalloc(sz); }
void frdims(Dimen *d, int n, int t, int **ret) { int totpix, totpcnt, totrel; double spix, spcnt, relu, vd; int tt, trest, totpixrel, minrelu, i; int *x, *spec, *kind; if(n == 1){ *ret = x = emalloc(sizeof(int)); x[0] = t; return; } totpix = totpcnt = totrel = 0; spec = emalloc(n*sizeof(int)); kind = emalloc(n*sizeof(int)); for(i=0; i<n; i++){ spec[i] = dimenspec(d[i]); if(spec[i] < 0) spec[i] = 0; kind[i] = dimenkind(d[i]); switch(kind[i]){ case Dpixels: totpix += spec[i]; break; case Dpercent: totpcnt += spec[i]; break; case Drelative: totrel += spec[i]; break; case Dnone: totrel++; break; } } spix = spcnt = 1.0; minrelu = 0; if(totrel > 0) minrelu = Scrollsize+Scrollgap; relu = (double)minrelu; tt = totpix + t*totpcnt/100 + totrel*minrelu; if(tt < t){ if(totrel == 0){ if(totpcnt != 0) spcnt = (double)((t-totpix)*100)/(double)(t*totpcnt); else spix = (double)t/(double)totpix; }else relu += (double)(t-tt)/(double)totrel; }else{ totpixrel = totpix + totrel*minrelu; if(totpixrel < t) spcnt = (double)((t-totpixrel)*100)/(double)(t*totpcnt); else{ trest = t - totrel*minrelu; if(trest > 0) spcnt = (double)trest/(double)(totpix + (t*totpcnt/100)); else{ spcnt = (double)t/(double)tt; relu = 0.0; } spix = spcnt; } } x = emalloc(n * sizeof(int)); tt = 0; for(i=0; i<n-1; i++){ vd = (double)spec[i]; switch(kind[i]){ case Dpixels: vd = vd*spix; break; case Dpercent: vd = vd*(double)t*spcnt/100.0; break; case Drelative: vd = vd*relu; break; case Dnone: vd = relu; break; } x[i] = (int)(vd+.5); tt += x[i]; } x[n - 1] = t - tt; *ret = x; free(spec); free(kind); }
int complement_match (Representation* X_rep, Representation* Y_rep, Map * map, int map_max, int * map_ctr, int * map_best, int best_max, int parent_map){ Penalty_parametrization penalty_params; /* for SW */ double **x = X_rep->full; int * x_type = X_rep->full_type; int NX = X_rep->N_full; double **y = Y_rep->full; int * y_type = Y_rep->full_type; int NY = Y_rep->N_full; double F_effective = 0.0; double F_current; double q[4] = {0.0}, q_init[4] = {0.0}; double **x_rotated = NULL; double **tr_x_rotated = NULL; double **R; double z_scr = 0.0, *z_best; double avg, avg_sq, stdev; double alpha = options.alpha; double rmsd, best_rmsd[TOP_RMSD]; double **best_quat; double cutoff_rmsd = 3.0; /* <<<<<<<<<<<<<<<<< hardcoded */ int *x_type_fudg, *y_type_fudg; int *anchor_x, *anchor_y, no_anchors; int no_top_rmsd = TOP_RMSD, chunk; int x_ctr, y_ctr, top_ctr; int **best_triple_x; int **best_triple_y; int x_triple[3], y_triple[3]; int retval, done = 0; int best_ctr; int i, j; int t; int smaller; int my_map_ctr; int stored_new; int * x2y, map_unstable; //time_t time_now, time_start; int cull_by_dna (Representation * X_rep, int *set_of_directions_x, Representation * Y_rep, int *set_of_directions_y, int set_size, Map *map, double cutoff_rmsd); int distance_of_nearest_approach (Representation * X_rep, int *set_of_directions_x, Representation * Y_rep, int *set_of_directions_y, int set_size, double * rmsd_ptr); int same_hand_triple (Representation * X_rep, int *set_of_directions_x, Representation * Y_rep, int *set_of_directions_y, int set_size); int find_map (Penalty_parametrization * params, Representation *X_rep, Representation *Y_rep, double ** R, double alpha, double * F_effective, Map *map, int *anchor_x, int * anchor_y, int anchor_size ); int find_next_triple (double **X, double **Y, int *x_type, int *y_type, int NX, int NY, int *x_triple, int *y_triple); int gradient_descent (int first_call, double alpha, double **x, int * x_type, int NX, double **y, int * y_type, int NY, double *q_best, double *F_best_ptr) ; int map_quality_metrics (Representation *X_rep, Representation *Y_rep, double ** tr_x_rotated, Map * map, int *reasonable_angle_ct); int monte_carlo (double alpha, double **x, int * x_type, int NX, double **y, int * y_type, int NY, double *q_best, double *F_best_ptr); int opt_quat (double ** x, int NX, int *set_of_directions_x, double ** y, int NY, int *set_of_directions_y, int set_size, double * q, double * rmsd); int qmap (double *x0, double *x1, double *y0, double *y1, double * quat); int store_sorted (Map * map, int NX, int NY, int *map_best, int map_max, double * z_best, int best_ctr, double z_scr, int my_map_ctr, int *stored); map_best[0] = -1; /* it is the end-of-array flag */ if ( *map_ctr >= map_max ) { fprintf (stderr, "Map array undersized.\n"); exit (1); } smaller = (NX <= NY) ? NX : NY; /***********************/ /* memory allocation */ /***********************/ if ( ! (R=dmatrix(3,3) ) ) return 1; /* compiler is bugging me otherwise */ if ( ! (x_rotated = dmatrix (NX,3)) ) return 1; if ( ! (tr_x_rotated = dmatrix (NX,3)) ) return 1; if ( ! (best_quat = dmatrix (no_top_rmsd,4)) ) return 1; if ( ! (best_triple_x = intmatrix (no_top_rmsd,3)) ) return 1; if ( ! (best_triple_y = intmatrix (no_top_rmsd,3)) ) return 1; if ( ! (z_best = emalloc(NX*NY*sizeof(double) )) ) return 1; if ( ! (x_type_fudg = emalloc(NX*sizeof(int) )) ) return 1; if ( ! (y_type_fudg = emalloc(NY*sizeof(int) )) ) return 1; if ( ! (anchor_x = emalloc(NX*sizeof(int) )) ) return 1; if ( ! (anchor_y = emalloc(NY*sizeof(int) )) ) return 1; penalty_params.custom_gap_penalty_x = NULL; penalty_params.custom_gap_penalty_y = NULL; //if ( ! (penalty_params.custom_gap_penalty_x = emalloc(NX*sizeof(double) )) ) return 1; //if ( ! (penalty_params.custom_gap_penalty_y = emalloc(NY*sizeof(double) )) ) return 1; /***********************/ /***********************/ /* expected quantities */ /***********************/ avg = avg_sq = stdev = 0.0; //if (options.postprocess) { if (0) { if (F_moments (x, x_type, NX, y, y_type, NY, alpha, &avg, &avg_sq, &stdev)) return 1; } /***********************/ /***********************/ /* initialization */ /***********************/ best_ctr = 0; penalty_params.gap_opening = options.gap_open; penalty_params.gap_extension = options.gap_extend; penalty_params.endgap = options.endgap; penalty_params.endgap_special_treatment = options.use_endgap; /***********************/ /***************************************/ /* find reasonble triples of SSEs */ /* that correspond in type */ /* and can be mapped onto each other */ /***************************************/ for (top_ctr=0; top_ctr<no_top_rmsd; top_ctr++) { best_rmsd[top_ctr] = BAD_RMSD+1; best_triple_x[top_ctr][0] = -1; } for (x_ctr=0; x_ctr < NX-2 && !done; x_ctr++) { for (y_ctr=0; y_ctr < NY-2 && !done; y_ctr++) { if ( y_type[y_ctr] != x_type[x_ctr] ) continue; x_triple[0] = x_ctr; y_triple[0] = y_ctr; if (find_next_triple (x, y, x_type, y_type, NX, NY, x_triple, y_triple) ){ continue; } if ( x_triple[1] < 0 || x_triple[2] < 0 ) continue; if ( y_triple[1] < 0 || y_triple[2] < 0 ) continue; /* do these three have kind-of similar layout in space?*/ /* is handedness the same? */ if ( ! same_hand_triple ( X_rep, x_triple, Y_rep, y_triple, 3)) continue; /* are distances comparab;e? */ if (distance_of_nearest_approach ( X_rep, x_triple, Y_rep, y_triple, 3, &rmsd)) continue; if ( rmsd > cutoff_rmsd) continue; /* find q_init that maps the two triples as well as possible*/ if ( opt_quat ( x, NX, x_triple, y, NY, y_triple, 3, q_init, &rmsd)) continue; for (top_ctr=0; top_ctr<no_top_rmsd; top_ctr++) { if ( rmsd <= best_rmsd[top_ctr] ) { chunk = no_top_rmsd - top_ctr -1; if (chunk) { memmove (best_rmsd+top_ctr+1, best_rmsd+top_ctr, chunk*sizeof(double)); memmove (best_quat[top_ctr+1], best_quat[top_ctr], chunk*4*sizeof(double)); memmove (best_triple_x[top_ctr+1], best_triple_x[top_ctr], chunk*3*sizeof(int)); memmove (best_triple_y[top_ctr+1], best_triple_y[top_ctr], chunk*3*sizeof(int)); } best_rmsd[top_ctr] = rmsd; memcpy (best_quat[top_ctr], q_init, 4*sizeof(double)); memcpy (best_triple_x[top_ctr], x_triple, 3*sizeof(int)); memcpy (best_triple_y[top_ctr], y_triple, 3*sizeof(int)); break; } } } } # if 0 for (top_ctr=0; top_ctr<no_top_rmsd; top_ctr++) { if ( best_rmsd[top_ctr] > BAD_RMSD ) break; printf (" %3d %8.3lf ", top_ctr, best_rmsd[top_ctr]); vec_out ( best_quat[top_ctr], 4, "quat: "); for (t=0; t<3; t++ ) { printf ("\t %3d %3d \n", best_triple_x[top_ctr][t]+1, best_triple_y[top_ctr][t]+1 ); } } exit (1); # endif /*********************************************/ /* main loop */ /*********************************************/ for (top_ctr=0; top_ctr<no_top_rmsd; top_ctr++) { if ( best_rmsd[top_ctr] > BAD_RMSD ) break; quat_to_R (best_quat[top_ctr], R); rotate (x_rotated, NX, R, x); F_current = F( y, y_type, NY, x_rotated, x_type, NX, alpha); # if 0 printf ("\n***********************************\n"); printf (" %3d %8.3lf %8.3lf ", top_ctr, best_rmsd[top_ctr], F_current); vec_out ( best_quat[top_ctr], 4, "quat: "); for (t=0; t<3; t++ ) { printf ("\t %3d %3d \n", best_triple_x[top_ctr][t]+1, best_triple_y[top_ctr][t]+1 ); } # endif /* find map which uses the 2 triples as anchors */ no_anchors = 3; find_map (&penalty_params, X_rep, Y_rep, R, alpha, &F_effective, map + (*map_ctr), best_triple_x[top_ctr], best_triple_y[top_ctr], no_anchors); x2y = ( map + (*map_ctr) ) ->x2y; map_unstable = 0; for (t=0; t<3; t++ ) { if ( x2y[best_triple_x[top_ctr][t]] != best_triple_y[top_ctr][t] ) { map_unstable = 1; } } if ( map_unstable) continue; /* dna here is not DNA but "distance of nearest approach" */ cull_by_dna ( X_rep, best_triple_x[top_ctr], Y_rep, best_triple_y[top_ctr], 3, map + (*map_ctr), cutoff_rmsd ); //printf ("map after culling by dna:\n"); //print_map (stdout, map+ (*map_ctr), NULL, NULL, NULL, NULL, 1); /* monte that optimizes the aligned vectors only */ for (i=0; i<NX; i++) { x_type_fudg[i] = JACKFRUIT; } for (j=0; j<NY; j++) { y_type_fudg[j] = JACKFRUIT*2; } no_anchors = 0; for (i=0; i<NX; i++) { j = (map+(*map_ctr))->x2y[i]; if (j < 0 ) continue; x_type_fudg[i] = x_type[i]; y_type_fudg[j] = y_type[j]; anchor_x[no_anchors] = i; anchor_y[no_anchors] = j; no_anchors ++; } if ( opt_quat ( x, NX, anchor_x, y, NY, anchor_y, no_anchors, q, &rmsd)) continue; retval = monte_carlo ( alpha, x, x_type_fudg, NX, y, y_type_fudg, NY, q, &F_current); if (retval) return retval; if (options.postprocess) { z_scr = stdev ? (F_current - avg)/stdev : 0.0; } else { z_scr = 0.0; } quat_to_R (q, R); /* store_image() is waste of time, but perhaps not critical */ store_image (X_rep, Y_rep, R, alpha, map + (*map_ctr)); map_assigned_score ( X_rep, map + (*map_ctr)); //printf ("map %2d assigned score: %8.3lf z_score: %8.3lf \n\n", // *map_ctr+1, (map + (*map_ctr)) -> assigned_score, z_scr); /* store the map that passed all the filters down to here*/ my_map_ctr = *map_ctr; map[my_map_ctr].F = F_current; map[my_map_ctr].avg = avg; map[my_map_ctr].avg_sq = avg_sq; map[my_map_ctr].z_score = z_scr; memcpy ( map[my_map_ctr].q, q, 4*sizeof(double) ); /* recalculate the assigned score*/ //if (top_ctr==24) exit (1); /************************/ /* store sorted */ /************************/ /* find the place for the new z-score */ store_sorted (map, NX, NY, map_best, map_max, z_best, best_ctr, -map[my_map_ctr].assigned_score, my_map_ctr, &stored_new); if ( stored_new ) { /* we want to keep this map */ (*map_ctr) ++; best_ctr++; } /* otherwise this map space is reusable */ /* is this pretty much as good as it can get ? */ if ( fabs (map[my_map_ctr].assigned_score - smaller) < options.tol ) done = 1; } map_best[best_ctr] = -1; /******************************************************/ /* look for the sub-map of a couple of best hits */ /******************************************************/ /* initialization:*/ map_consistence ( NX, NY, NULL, NULL, NULL, NULL, NULL); best_ctr = 0; while ( map_best[best_ctr] > -1 ) { best_ctr ++; } //exit (1); if (best_ctr) { int nr_maps = (best_ctr<options.number_maps_cpl)? best_ctr : options.number_maps_cpl; int best_i; int consistent; double z; double total_assigned_score, score, best_score = -100; double gap_score; for (i=0; i<nr_maps; i++) { /* look for the complement */ best_i = map_best[i]; /*intialize the (list of) submatch map(s) */ if ( !map[best_i].submatch_best) { /* for now look for a single map only */ /* TODO - would it be worth any to look at more maps?*/ int map_max = 1; map[best_i].submatch_best = emalloc (map_max*sizeof(int) ); if (! map[best_i].submatch_best) return 1; } map[best_i].submatch_best[0] = -1; map[best_i].score_with_children = 0; map[best_i].compl_z_score = 0; for (j=0; j<best_ctr; j++) { if (i==j) continue; map_complementarity ( map+best_i, map + map_best[j], &z); map_consistence ( NX, NY, map+best_i, map + map_best[j], &total_assigned_score, &gap_score, NULL); consistent = ( (map+best_i)->assigned_score < total_assigned_score && (map + map_best[j])->assigned_score < total_assigned_score); if ( consistent ) { score = total_assigned_score; if ( score > best_score ) { best_score = score; map[best_i].submatch_best[0] = map_best[j]; map[best_i].score_with_children = total_assigned_score; map[best_i].compl_z_score = z; } } } } } /**********************/ /* garbage collection */ gradient_descent (1, 0.0, NULL, NULL, 0, NULL, NULL, 0, NULL, NULL); free_dmatrix (R); free_dmatrix (x_rotated); free_dmatrix (tr_x_rotated); free_dmatrix (best_quat); free_imatrix (best_triple_x); free_imatrix (best_triple_y); free (z_best); free (x_type_fudg); free (y_type_fudg); free (anchor_x); free (anchor_y); if (penalty_params.custom_gap_penalty_x) free (penalty_params.custom_gap_penalty_x); if (penalty_params.custom_gap_penalty_y) free (penalty_params.custom_gap_penalty_y); /*********************/ return 0; }
int wmain(int argc, wchar_t **wcargv) { char** argv; #else int main(int argc, char** argv) { #endif int eargv_size; int eargc_base; /* How many arguments in the base of eargv. */ char* emulator; char *env; int i; int need_shell = 0; #ifdef __WIN32__ int len; /* Convert argv to utf8 */ argv = malloc((argc+1) * sizeof(char*)); for (i=0; i<argc; i++) { len = WideCharToMultiByte(CP_UTF8, 0, wcargv[i], -1, NULL, 0, NULL, NULL); argv[i] = malloc(len*sizeof(char)); WideCharToMultiByte(CP_UTF8, 0, wcargv[i], -1, argv[i], len, NULL, NULL); } argv[argc] = NULL; #endif env = get_env("DIALYZER_EMULATOR"); emulator = env ? env : get_default_emulator(argv[0]); if (strlen(emulator) >= MAXPATHLEN) error("Value of environment variable DIALYZER_EMULATOR is too large"); /* * Allocate the argv vector to be used for arguments to Erlang. * Arrange for starting to pushing information in the middle of * the array, to allow easy addition of commands in the beginning. */ eargv_size = argc*4+100; eargv_base = (char **) emalloc(eargv_size*sizeof(char*)); eargv = eargv_base; eargc = 0; push_words(emulator); eargc_base = eargc; eargv = eargv + eargv_size/2; eargc = 0; free_env_val(env); /* * Push initial arguments. */ for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--wx") == 0) { PUSH("-smp"); /* wx currently requires SMP enabled */ break; } } if (argc > 1 && strcmp(argv[1], "-smp") == 0) { PUSH("-smpauto"); argc--, argv++; } if (argc > 2 && strcmp(argv[1], "+S") == 0) { PUSH3("-smp", "+S", argv[2]); argc--, argv++; argc--, argv++; } if (argc > 2 && strcmp(argv[1], "+P") == 0) { PUSH2("+P", argv[2]); argc--, argv++; argc--, argv++; } else PUSH2("+P", "1000000"); if (argc > 2 && strcmp(argv[1], "+sbt") == 0) { PUSH2("+sbt", argv[2]); argc--, argv++; argc--, argv++; } PUSH("+B"); PUSH2("-boot", "start_clean"); PUSH3("-run", "dialyzer", "plain_cl"); PUSH("-extra"); /* * Push everything except --shell. */ while (argc > 1) { if (strcmp(argv[1], "--shell") == 0) { need_shell = 1; } else { PUSH(argv[1]); } argc--, argv++; } if (!need_shell) { UNSHIFT("-noinput"); } /* * Move up the commands for invoking the emulator and adjust eargv * accordingly. */ while (--eargc_base >= 0) { UNSHIFT(eargv_base[eargc_base]); } /* * Invoke Erlang with the collected options. */ PUSH(NULL); return run_erlang(eargv[0], eargv); }
/* {{{ proto bool GmagickDraw::affine(array affine) Adjusts the current affine transformation matrix with the specified affine transformation matrix. Note that the current affine transform is adjusted rather than replaced. */ PHP_METHOD(gmagickdraw, affine) { php_gmagickdraw_object *internd; zval *affine_matrix, **ppzval; HashTable *affine; char *matrix_elements[] = { "sx", "rx", "ry", "sy", "tx", "ty" }; int i; double value; AffineMatrix *pmatrix; /* Parse parameters given to function */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &affine_matrix) == FAILURE) { return; } /* Allocate space to build matrix */ pmatrix = emalloc(sizeof(AffineMatrix)); affine = Z_ARRVAL_P(affine_matrix); zend_hash_internal_pointer_reset_ex(affine, (HashPosition *) 0); for (i = 0; i < 6 ; i++) { if (zend_hash_find(affine, matrix_elements[i], 3, (void**)&ppzval) == FAILURE) { efree(pmatrix); GMAGICK_THROW_EXCEPTION_WITH_MESSAGE(GMAGICKDRAW_CLASS, "AffineMatrix should contain keys: sx, rx, ry, sy, tx and ty", 2); } else { zval tmp_zval, *tmp_pzval; tmp_zval = **ppzval; zval_copy_ctor(&tmp_zval); tmp_pzval = &tmp_zval; convert_to_double(tmp_pzval); value = Z_DVAL(tmp_zval); if (strcmp(matrix_elements[i], "sx") == 0) { pmatrix->sx = value; } else if (strcmp(matrix_elements[i], "rx") == 0) { pmatrix->rx = value; } else if (strcmp(matrix_elements[i], "ry") == 0) { pmatrix->ry = value; } else if (strcmp(matrix_elements[i], "sy") == 0) { pmatrix->sy = value; } else if (strcmp(matrix_elements[i], "tx") == 0) { pmatrix->tx = value; } else if (strcmp(matrix_elements[i], "ty") == 0) { pmatrix->ty = value; } } } internd = (php_gmagickdraw_object *) zend_object_store_get_object(getThis() TSRMLS_CC); DrawAffine(internd->drawing_wand, pmatrix); efree(pmatrix); RETURN_TRUE; }
static void php_hash_do_hash(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */ { char *algo, *data, *digest; int algo_len, data_len; zend_bool raw_output = raw_output_default; const php_hash_ops *ops; void *context; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &algo, &algo_len, &data, &data_len, &raw_output) == FAILURE) { return; } ops = php_hash_fetch_ops(algo, algo_len); if (!ops) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown hashing algorithm: %s", algo); RETURN_FALSE; } if (isfilename) { if (CHECK_NULL_PATH(data, data_len)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid path"); RETURN_FALSE; } stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, DEFAULT_CONTEXT); if (!stream) { /* Stream will report errors opening file */ RETURN_FALSE; } } context = emalloc(ops->context_size); ops->hash_init(context); if (isfilename) { char buf[1024]; int n; while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) { ops->hash_update(context, (unsigned char *) buf, n); } php_stream_close(stream); } else { ops->hash_update(context, (unsigned char *) data, data_len); } digest = emalloc(ops->digest_size + 1); ops->hash_final((unsigned char *) digest, context); efree(context); if (raw_output) { digest[ops->digest_size] = 0; RETURN_STRINGL(digest, ops->digest_size, 0); } else { char *hex_digest = safe_emalloc(ops->digest_size, 2, 1); php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size); hex_digest[2 * ops->digest_size] = 0; efree(digest); RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0); } }
static union _zend_function *com_method_get(zend_object **object_ptr, zend_string *name, const zval *key) { zend_internal_function f, *fptr = NULL; union _zend_function *func; DISPID dummy; php_com_dotnet_object *obj = (php_com_dotnet_object*)*object_ptr; if (V_VT(&obj->v) != VT_DISPATCH) { return NULL; } if (FAILED(php_com_get_id_of_name(obj, name->val, name->len, &dummy))) { return NULL; } /* check cache */ if (obj->method_cache == NULL || NULL == (fptr = zend_hash_find_ptr(obj->method_cache, name))) { f.type = ZEND_OVERLOADED_FUNCTION; f.num_args = 0; f.arg_info = NULL; f.scope = obj->ce; f.fn_flags = ZEND_ACC_CALL_VIA_HANDLER; f.function_name = zend_string_copy(name); f.handler = PHP_FN(com_method_handler); fptr = &f; if (obj->typeinfo) { /* look for byref params */ ITypeComp *comp; ITypeInfo *TI = NULL; DESCKIND kind; BINDPTR bindptr; OLECHAR *olename; ULONG lhash; int i; if (SUCCEEDED(ITypeInfo_GetTypeComp(obj->typeinfo, &comp))) { olename = php_com_string_to_olestring(name->val, name->len, obj->code_page); lhash = LHashValOfNameSys(SYS_WIN32, LOCALE_SYSTEM_DEFAULT, olename); if (SUCCEEDED(ITypeComp_Bind(comp, olename, lhash, INVOKE_FUNC, &TI, &kind, &bindptr))) { switch (kind) { case DESCKIND_FUNCDESC: f.arg_info = ecalloc(bindptr.lpfuncdesc->cParams, sizeof(zend_arg_info)); for (i = 0; i < bindptr.lpfuncdesc->cParams; i++) { f.arg_info[i].type = ZEND_TYPE_ENCODE(0,1);; if (bindptr.lpfuncdesc->lprgelemdescParam[i].paramdesc.wParamFlags & PARAMFLAG_FOUT) { f.arg_info[i].pass_by_reference = ZEND_SEND_BY_REF; } } f.num_args = bindptr.lpfuncdesc->cParams; ITypeInfo_ReleaseFuncDesc(TI, bindptr.lpfuncdesc); break; /* these should not happen, but *might* happen if the user * screws up; lets avoid a leak in that case */ case DESCKIND_VARDESC: ITypeInfo_ReleaseVarDesc(TI, bindptr.lpvardesc); break; case DESCKIND_TYPECOMP: ITypeComp_Release(bindptr.lptcomp); break; case DESCKIND_NONE: break; } if (TI) { ITypeInfo_Release(TI); } } ITypeComp_Release(comp); efree(olename); } } zend_set_function_arg_flags((zend_function*)&f); /* save this method in the cache */ if (!obj->method_cache) { ALLOC_HASHTABLE(obj->method_cache); zend_hash_init(obj->method_cache, 2, NULL, function_dtor, 0); } zend_hash_update_mem(obj->method_cache, name, &f, sizeof(f)); } if (fptr) { /* duplicate this into a new chunk of emalloc'd memory, * since the engine will efree it */ func = emalloc(sizeof(*fptr)); memcpy(func, fptr, sizeof(*fptr)); return func; } return NULL; }
int hx509_pem_read(hx509_context context, FILE *f, hx509_pem_read_func func, void *ctx) { hx509_pem_header *headers = NULL; char *type = NULL; void *data = NULL; size_t len = 0; char buf[1024]; int ret = HX509_PARSING_KEY_FAILED; enum { BEFORE, SEARCHHEADER, INHEADER, INDATA, DONE } where; where = BEFORE; while (fgets(buf, sizeof(buf), f) != NULL) { char *p; int i; i = strcspn(buf, "\n"); if (buf[i] == '\n') { buf[i] = '\0'; if (i > 0) i--; } if (buf[i] == '\r') { buf[i] = '\0'; if (i > 0) i--; } switch (where) { case BEFORE: if (strncmp("-----BEGIN ", buf, 11) == 0) { type = strdup(buf + 11); if (type == NULL) break; p = strchr(type, '-'); if (p) *p = '\0'; where = SEARCHHEADER; } break; case SEARCHHEADER: p = strchr(buf, ':'); if (p == NULL) { where = INDATA; goto indata; } /* FALLTHOUGH */ case INHEADER: if (buf[0] == '\0') { where = INDATA; break; } p = strchr(buf, ':'); if (p) { *p++ = '\0'; while (isspace((int)*p)) p++; ret = hx509_pem_add_header(&headers, buf, p); if (ret) abort(); } break; case INDATA: indata: if (strncmp("-----END ", buf, 9) == 0) { where = DONE; break; } p = emalloc(i); i = base64_decode(buf, p); if (i < 0) { free(p); goto out; } data = erealloc(data, len + i); memcpy(((char *)data) + len, p, i); free(p); len += i; break; case DONE: abort(); } if (where == DONE) { ret = (*func)(context, type, headers, data, len, ctx); out: free(data); data = NULL; len = 0; free(type); type = NULL; where = BEFORE; hx509_pem_free_header(headers); headers = NULL; if (ret) break; } } if (where != BEFORE) { hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, "File ends before end of PEM end tag"); ret = HX509_PARSING_KEY_FAILED; } if (data) free(data); if (type) free(type); if (headers) hx509_pem_free_header(headers); return ret; }
gib_hash *gib_hash_new() { gib_hash *hash = emalloc(sizeof(gib_hash)); hash->base = gib_hash_node_new("__gib_hash_new",NULL); return hash; }
static int neoclock4x_start(int unit, struct peer *peer) { struct neoclock4x_unit *up; struct refclockproc *pp; int fd; char dev[20]; int sl232; #if defined(HAVE_TERMIOS) struct termios termsettings; #endif #if !defined(NEOCLOCK4X_FIRMWARE) int tries; #endif (void) snprintf(dev, sizeof(dev)-1, "/dev/neoclock4x-%d", unit); /* LDISC_STD, LDISC_RAW * Open serial port. Use CLK line discipline, if available. */ fd = refclock_open(dev, B2400, LDISC_STD); if(fd <= 0) { return (0); } #if defined(HAVE_TERMIOS) #if 1 if(tcgetattr(fd, &termsettings) < 0) { msyslog(LOG_CRIT, "NeoClock4X(%d): (tcgetattr) can't query serial port settings: %m", unit); (void) close(fd); return (0); } /* 2400 Baud 8N2 */ termsettings.c_iflag = IGNBRK | IGNPAR | ICRNL; termsettings.c_oflag = 0; termsettings.c_cflag = CS8 | CSTOPB | CLOCAL | CREAD; (void)cfsetispeed(&termsettings, (u_int)B2400); (void)cfsetospeed(&termsettings, (u_int)B2400); if(tcsetattr(fd, TCSANOW, &termsettings) < 0) { msyslog(LOG_CRIT, "NeoClock4X(%d): (tcsetattr) can't set serial port 2400 8N2: %m", unit); (void) close(fd); return (0); } #else if(tcgetattr(fd, &termsettings) < 0) { msyslog(LOG_CRIT, "NeoClock4X(%d): (tcgetattr) can't query serial port settings: %m", unit); (void) close(fd); return (0); } /* 2400 Baud 8N2 */ termsettings.c_cflag &= ~PARENB; termsettings.c_cflag |= CSTOPB; termsettings.c_cflag &= ~CSIZE; termsettings.c_cflag |= CS8; if(tcsetattr(fd, TCSANOW, &termsettings) < 0) { msyslog(LOG_CRIT, "NeoClock4X(%d): (tcsetattr) can't set serial port 2400 8N2: %m", unit); (void) close(fd); return (0); } #endif #elif defined(HAVE_SYSV_TTYS) if(ioctl(fd, TCGETA, &termsettings) < 0) { msyslog(LOG_CRIT, "NeoClock4X(%d): (TCGETA) can't query serial port settings: %m", unit); (void) close(fd); return (0); } /* 2400 Baud 8N2 */ termsettings.c_cflag &= ~PARENB; termsettings.c_cflag |= CSTOPB; termsettings.c_cflag &= ~CSIZE; termsettings.c_cflag |= CS8; if(ioctl(fd, TCSETA, &termsettings) < 0) { msyslog(LOG_CRIT, "NeoClock4X(%d): (TSGETA) can't set serial port 2400 8N2: %m", unit); (void) close(fd); return (0); } #else msyslog(LOG_EMERG, "NeoClock4X(%d): don't know how to set port to 2400 8N2 with this OS!", unit); (void) close(fd); return (0); #endif #if defined(TIOCMSET) && (defined(TIOCM_RTS) || defined(CIOCM_RTS)) /* turn on RTS, and DTR for power supply */ /* NeoClock4x is powered from serial line */ if(ioctl(fd, TIOCMGET, (caddr_t)&sl232) == -1) { msyslog(LOG_CRIT, "NeoClock4X(%d): can't query RTS/DTR state: %m", unit); (void) close(fd); return (0); } #ifdef TIOCM_RTS sl232 = sl232 | TIOCM_DTR | TIOCM_RTS; /* turn on RTS, and DTR for power supply */ #else sl232 = sl232 | CIOCM_DTR | CIOCM_RTS; /* turn on RTS, and DTR for power supply */ #endif if(ioctl(fd, TIOCMSET, (caddr_t)&sl232) == -1) { msyslog(LOG_CRIT, "NeoClock4X(%d): can't set RTS/DTR to power neoclock4x: %m", unit); (void) close(fd); return (0); } #else msyslog(LOG_EMERG, "NeoClock4X(%d): don't know how to set DTR/RTS to power NeoClock4X with this OS!", unit); (void) close(fd); return (0); #endif up = (struct neoclock4x_unit *) emalloc(sizeof(struct neoclock4x_unit)); if(!(up)) { msyslog(LOG_ERR, "NeoClock4X(%d): can't allocate memory for: %m",unit); (void) close(fd); return (0); } memset((char *)up, 0, sizeof(struct neoclock4x_unit)); pp = peer->procptr; pp->clockdesc = "NeoClock4X"; pp->unitptr = (caddr_t)up; pp->io.clock_recv = neoclock4x_receive; pp->io.srcclock = (caddr_t)peer; pp->io.datalen = 0; pp->io.fd = fd; /* * no fudge time is given by user! * use 169.583333 ms to compensate the serial line delay * formula is: * 2400 Baud / 11 bit = 218.18 charaters per second * (NeoClock4X timecode len) */ pp->fudgetime1 = (NEOCLOCK4X_TIMECODELEN * 11) / 2400.0; /* * Initialize miscellaneous variables */ peer->precision = -10; peer->burst = NSTAGE; memcpy((char *)&pp->refid, "neol", 4); up->leap_status = 0; up->unit = unit; strcpy(up->firmware, "?"); up->firmwaretag = '?'; strcpy(up->serial, "?"); strcpy(up->radiosignal, "?"); up->timesource = '?'; up->dststatus = '?'; up->quarzstatus = '?'; up->antenna1 = -1; up->antenna2 = -1; up->utc_year = 0; up->utc_month = 0; up->utc_day = 0; up->utc_hour = 0; up->utc_minute = 0; up->utc_second = 0; up->utc_msec = 0; #if defined(NEOCLOCK4X_FIRMWARE) #if NEOCLOCK4X_FIRMWARE == NEOCLOCK4X_FIRMWARE_VERSION_A strcpy(up->firmware, "(c) 2002 NEOL S.A. FRANCE / L0.01 NDF:A:* (compile time)"); up->firmwaretag = 'A'; #else msyslog(LOG_EMERG, "NeoClock4X(%d): unknown firmware defined at compile time for NeoClock4X", unit); (void) close(fd); pp->io.fd = -1; free(pp->unitptr); pp->unitptr = NULL; return (0); #endif #else for(tries=0; tries < 5; tries++) { NLOG(NLOG_CLOCKINFO) msyslog(LOG_INFO, "NeoClock4X(%d): checking NeoClock4X firmware version (%d/5)", unit, tries); /* wait 3 seconds for receiver to power up */ sleep(3); if(neol_query_firmware(pp->io.fd, up->unit, up->firmware, sizeof(up->firmware))) { break; } } /* can I handle this firmware version? */ if(!neol_check_firmware(up->unit, up->firmware, &up->firmwaretag)) { (void) close(fd); pp->io.fd = -1; free(pp->unitptr); pp->unitptr = NULL; return (0); } #endif if(!io_addclock(&pp->io)) { msyslog(LOG_ERR, "NeoClock4X(%d): error add peer to ntpd: %m", unit); (void) close(fd); pp->io.fd = -1; free(pp->unitptr); pp->unitptr = NULL; return (0); } NLOG(NLOG_CLOCKINFO) msyslog(LOG_INFO, "NeoClock4X(%d): receiver setup successful done", unit); return (1); }
/* * loop_config - configure the loop filter * * LOCKCLOCK: The LOOP_DRIFTINIT and LOOP_DRIFTCOMP cases are no-ops. */ void loop_config( int item, double freq ) { int i; switch (item) { case LOOP_DRIFTINIT: #ifndef LOCKCLOCK #ifdef KERNEL_PLL /* * Assume the kernel supports the ntp_adjtime() syscall. * If that syscall works, initialize the kernel time * variables. Otherwise, continue leaving no harm * behind. While at it, ask to set nanosecond mode. If * the kernel agrees, rejoice; othewise, it does only * microseconds. */ if (mode_ntpdate) break; pll_control = 1; memset(&ntv, 0, sizeof(ntv)); #ifdef STA_NANO ntv.modes = MOD_BITS | MOD_NANO; #else /* STA_NANO */ ntv.modes = MOD_BITS; #endif /* STA_NANO */ ntv.maxerror = MAXDISPERSE; ntv.esterror = MAXDISPERSE; ntv.status = STA_UNSYNC; #ifdef SIGSYS /* * Use sigsetjmp() to save state and then call * ntp_adjtime(); if it fails, then siglongjmp() is used * to return control */ newsigsys.sa_handler = pll_trap; newsigsys.sa_flags = 0; if (sigaction(SIGSYS, &newsigsys, &sigsys)) { msyslog(LOG_ERR, "sigaction() fails to save SIGSYS trap: %m"); pll_control = 0; } if (sigsetjmp(env, 1) == 0) ntp_adjtime(&ntv); if ((sigaction(SIGSYS, &sigsys, (struct sigaction *)NULL))) { msyslog(LOG_ERR, "sigaction() fails to restore SIGSYS trap: %m"); pll_control = 0; } #else /* SIGSYS */ ntp_adjtime(&ntv); #endif /* SIGSYS */ /* * Save the result status and light up an external clock * if available. */ pll_status = ntv.status; if (pll_control) { #ifdef STA_NANO if (pll_status & STA_CLK) ext_enable = 1; #endif /* STA_NANO */ NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT) msyslog(LOG_INFO, "kernel time sync status %04x", pll_status); } #endif /* KERNEL_PLL */ #endif /* LOCKCLOCK */ break; case LOOP_DRIFTCOMP: #ifndef LOCKCLOCK /* * If the frequency value is reasonable, set the initial * frequency to the given value and the state to S_FSET. * Otherwise, the drift file may be missing or broken, * so set the frequency to zero. This erases past * history should somebody break something. */ if (freq <= NTP_MAXFREQ && freq >= -NTP_MAXFREQ) { drift_comp = freq; rstclock(S_FSET, 0, 0); } else { drift_comp = 0; } #ifdef KERNEL_PLL /* * Sanity check. If the kernel is available, load the * frequency and light up the loop. Make sure the offset * is zero to cancel any previous nonsense. If you don't * want this initialization, remove the ntp.drift file. */ if (pll_control && kern_enable) { memset((char *)&ntv, 0, sizeof(ntv)); ntv.modes = MOD_OFFSET | MOD_FREQUENCY; ntv.freq = (int32)(drift_comp * 65536e6); ntp_adjtime(&ntv); } #endif /* KERNEL_PLL */ #endif /* LOCKCLOCK */ break; case LOOP_KERN_CLEAR: #ifndef LOCKCLOCK #ifdef KERNEL_PLL /* Completely turn off the kernel time adjustments. */ if (pll_control) { memset((char *)&ntv, 0, sizeof(ntv)); ntv.modes = MOD_BITS | MOD_OFFSET | MOD_FREQUENCY; ntv.status = STA_UNSYNC; ntp_adjtime(&ntv); NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT) msyslog(LOG_INFO, "kernel time sync disabled %04x", ntv.status); } #endif /* KERNEL_PLL */ #endif /* LOCKCLOCK */ break; /* * Special tinker variables for Ulrich Windl. Very dangerous. */ case LOOP_MAX: /* step threshold */ clock_max = freq; break; case LOOP_PANIC: /* panic threshold */ clock_panic = freq; break; case LOOP_PHI: /* dispersion rate */ clock_phi = freq; break; case LOOP_MINSTEP: /* watchdog bark */ clock_minstep = freq; break; case LOOP_ALLAN: /* Allan intercept */ allan_xpt = freq; break; case LOOP_HUFFPUFF: /* huff-n'-puff filter length */ if (freq < HUFFPUFF) freq = HUFFPUFF; sys_hufflen = (int)(freq / HUFFPUFF); sys_huffpuff = (double *)emalloc(sizeof(double) * sys_hufflen); for (i = 0; i < sys_hufflen; i++) sys_huffpuff[i] = 1e9; sys_mindly = 1e9; break; case LOOP_FREQ: /* initial frequency */ drift_comp = freq / 1e6; rstclock(S_FSET, 0, 0); break; } }
/* {{{ php_zlib_output_handler_ex() */ static int php_zlib_output_handler_ex(php_zlib_context *ctx, php_output_context *output_context) { int flags = Z_SYNC_FLUSH; PHP_OUTPUT_TSRMLS(output_context); if (output_context->op & PHP_OUTPUT_HANDLER_START) { /* start up */ if (Z_OK != deflateInit2(&ctx->Z, ZLIBG(output_compression_level), Z_DEFLATED, ZLIBG(compression_coding), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) { return FAILURE; } } if (output_context->op & PHP_OUTPUT_HANDLER_CLEAN) { /* free buffers */ deflateEnd(&ctx->Z); if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) { /* discard */ return SUCCESS; } else { /* restart */ if (Z_OK != deflateInit2(&ctx->Z, ZLIBG(output_compression_level), Z_DEFLATED, ZLIBG(compression_coding), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) { return FAILURE; } ctx->buffer.used = 0; } } else { if (output_context->in.used) { /* append input */ if (ctx->buffer.free < output_context->in.used) { if (!(ctx->buffer.aptr = erealloc_recoverable(ctx->buffer.data, ctx->buffer.used + ctx->buffer.free + output_context->in.used))) { deflateEnd(&ctx->Z); return FAILURE; } ctx->buffer.data = ctx->buffer.aptr; ctx->buffer.free += output_context->in.used; } memcpy(ctx->buffer.data + ctx->buffer.used, output_context->in.data, output_context->in.used); ctx->buffer.free -= output_context->in.used; ctx->buffer.used += output_context->in.used; } output_context->out.size = PHP_ZLIB_BUFFER_SIZE_GUESS(output_context->in.used); output_context->out.data = emalloc(output_context->out.size); output_context->out.free = 1; output_context->out.used = 0; ctx->Z.avail_in = ctx->buffer.used; ctx->Z.next_in = (Bytef *) ctx->buffer.data; ctx->Z.avail_out = output_context->out.size; ctx->Z.next_out = (Bytef *) output_context->out.data; if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) { flags = Z_FINISH; } else if (output_context->op & PHP_OUTPUT_HANDLER_FLUSH) { flags = Z_FULL_FLUSH; } switch (deflate(&ctx->Z, flags)) { case Z_OK: if (flags == Z_FINISH) { deflateEnd(&ctx->Z); return FAILURE; } case Z_STREAM_END: if (ctx->Z.avail_in) { memmove(ctx->buffer.data, ctx->buffer.data + ctx->buffer.used - ctx->Z.avail_in, ctx->Z.avail_in); } ctx->buffer.free += ctx->buffer.used - ctx->Z.avail_in; ctx->buffer.used = ctx->Z.avail_in; output_context->out.used = output_context->out.size - ctx->Z.avail_out; break; default: deflateEnd(&ctx->Z); return FAILURE; } if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) { deflateEnd(&ctx->Z); } } return SUCCESS; }
static void php_couchbase_get_callback(lcb_t instance, const void *cookie, lcb_error_t error, const lcb_get_resp_t *resp) { zval *retval; php_couchbase_ctx *ctx = (php_couchbase_ctx *)cookie; const void *key; size_t nkey; const void *bytes; size_t nbytes; uint32_t flags; uint64_t cas; TSRMLS_FETCH(); if (--ctx->res->seqno == 0) { pcbc_stop_loop(ctx->res); } if (resp->version != 0) { ctx->res->rc = LCB_ERROR; return; } key = resp->v.v0.key; nkey = resp->v.v0.nkey; bytes = resp->v.v0.bytes; nbytes = resp->v.v0.nbytes; flags = resp->v.v0.flags; cas = resp->v.v0.cas; ctx->res->rc = error; if (LCB_SUCCESS != error && LCB_KEY_ENOENT != error) { pcbc_stop_loop(ctx->res); return; } if (ctx->res->async) { /* get_delayed */ zval *k, *v; MAKE_STD_ZVAL(v); if (!php_couchbase_zval_from_payload(v, (char *)bytes, nbytes, flags, ctx->res->serializer, ctx->res->ignoreflags TSRMLS_CC)) { ctx->res->rc = LCB_ERROR; efree(v); return; } if (ctx->res->prefix_key_len && nkey) { if (!strncmp(key, ctx->res->prefix_key, ctx->res->prefix_key_len)) { nkey -= (ctx->res->prefix_key_len + 1); /* '_' */ key = estrndup(((const char *)key) + ctx->res->prefix_key_len + 1, nkey); } } MAKE_STD_ZVAL(retval); array_init(retval); zend_hash_next_index_insert(Z_ARRVAL_P(ctx->rv), (void **)&retval, sizeof(zval *), NULL); MAKE_STD_ZVAL(k); ZVAL_STRINGL(k, (char *)key, nkey, 1); zend_hash_add(Z_ARRVAL_P(retval), "key", sizeof("key"), (void **)&k, sizeof(zval *), NULL); zend_hash_add(Z_ARRVAL_P(retval), "value", sizeof("value"), (void **)&v, sizeof(zval *), NULL); if (ctx->flags) { zval *c; MAKE_STD_ZVAL(c); Z_TYPE_P(c) = IS_STRING; Z_STRLEN_P(c) = spprintf(&(Z_STRVAL_P(c)), 0, "%llu", cas); zend_hash_add(Z_ARRVAL_P(retval), "cas", sizeof("cas"), (void **)&c, sizeof(zval *), NULL); } if (ctx->res->prefix_key_len && nkey) { efree((void *)key); } } else { if (LCB_KEY_ENOENT == error) { return; } if (IS_ARRAY == Z_TYPE_P(ctx->rv)) { /* multi get */ zval *v; char *key_string = NULL; MAKE_STD_ZVAL(v); if (!php_couchbase_zval_from_payload(v, (char *)bytes, nbytes, flags, ctx->res->serializer, ctx->res->ignoreflags TSRMLS_CC)) { ctx->res->rc = LCB_ERROR; efree(v); return; } if (ctx->res->prefix_key_len && nkey) { if (!strncmp(key, ctx->res->prefix_key, ctx->res->prefix_key_len)) { nkey -= (ctx->res->prefix_key_len + 1); key_string = estrndup(((const char *)key) + ctx->res->prefix_key_len + 1, nkey); } } else { key_string = emalloc(nkey + 1); memcpy(key_string, key, nkey); key_string[nkey] = '\0'; } zend_hash_update((Z_ARRVAL_P(ctx->rv)), (char *)key_string, nkey + 1, (void **)&v, sizeof(zval *), NULL); if (ctx->cas) { zval *c; MAKE_STD_ZVAL(c); Z_TYPE_P(c) = IS_STRING; Z_STRLEN_P(c) = spprintf(&(Z_STRVAL_P(c)), 0, "%llu", cas); zend_hash_add(Z_ARRVAL_P(ctx->cas), (char *)key_string, nkey + 1, (void **)&c, sizeof(zval *), NULL); } efree(key_string); } else { if (ctx->res->prefix_key_len && nkey) { if (!strncmp(key, ctx->res->prefix_key, ctx->res->prefix_key_len)) { nkey -= (ctx->res->prefix_key_len + 1); key = estrndup(((const char *)key) + ctx->res->prefix_key_len + 1, nkey); } } if (!php_couchbase_zval_from_payload(ctx->rv, (char *)bytes, nbytes, flags, ctx->res->serializer, ctx->res->ignoreflags TSRMLS_CC)) { if (ctx->res->prefix_key_len && nkey) { efree((void *)key); } ctx->res->rc = LCB_ERROR; return; } if (ctx->res->prefix_key_len && nkey) { efree((void *)key); } if (ctx->cas) { Z_TYPE_P(ctx->cas) = IS_STRING; Z_STRLEN_P(ctx->cas) = spprintf(&(Z_STRVAL_P(ctx->cas)), 0, "%llu", cas); } } } }
static void fixtext1(Item **list) { Itext *text, *ntext; Item *it, *prev; Rune *s, *s1, *s2; int n; if(*list == nil) return; prev = nil; for(it=*list; it!=nil; it=prev->next){ if(it->tag!=Itexttag || forceitem(it)) goto Continue; text = (Itext *)it; s = text->s; while(*s && isspacerune(*s)) s++; if(!*s){ if(prev == nil) prev = *list = it->next; else prev->next = it->next; it->next = nil; freeitems(it); if(prev == nil) return; continue; } n = 0; while(s[n] && !isspacerune(s[n])) n++; if(!s[n]) goto Continue; s1 = runemalloc(n+1); s1 = runemove(s1, s, n); s1[n] = L'\0'; s += n; while(*s && isspacerune(*s)) s++; if(*s){ n = runestrlen(s); s2 = runemalloc(n+1); runemove(s2, s, n); s2[n] = L'\0'; ntext = emalloc(sizeof(Itext)); ntext->s = s2; ntext->ascent = text->ascent; ntext->anchorid = text->anchorid; ntext->state = text->state&~(IFbrk|IFbrksp|IFnobrk|IFcleft|IFcright); ntext->tag = text->tag; ntext->fnt = text->fnt; ntext->fg = text->fg; ntext->ul = text->ul; ntext->next = (Item *)text->next; text->next = (Item *)ntext; } free(text->s); text->s = s1; Continue: prev = it; } }
static void _php_do_opendir(INTERNAL_FUNCTION_PARAMETERS, int createobject) { pval **arg; php_dir *dirp; DIRLS_FETCH(); if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_string_ex(arg); if (php_check_open_basedir((*arg)->value.str.val)) { RETURN_FALSE; } dirp = emalloc(sizeof(php_dir)); dirp->dir = VCWD_OPENDIR((*arg)->value.str.val); #ifdef PHP_WIN32 if (!dirp->dir || dirp->dir->finished) { if (dirp->dir) { closedir(dirp->dir); } #else if (!dirp->dir) { #endif efree(dirp); php_error(E_WARNING, "OpenDir: %s (errno %d)", strerror(errno), errno); RETURN_FALSE; } dirp->id = zend_list_insert(dirp,le_dirp); php_set_default_dir(dirp->id DIRLS_CC); if (createobject) { object_init_ex(return_value, dir_class_entry_ptr); add_property_stringl(return_value, "path", (*arg)->value.str.val, (*arg)->value.str.len, 1); add_property_resource(return_value, "handle", dirp->id); zend_list_addref(dirp->id); } else { RETURN_RESOURCE(dirp->id); } } /* }}} */ /* {{{ proto int opendir(string path) Open a directory and return a dir_handle */ PHP_FUNCTION(opendir) { _php_do_opendir(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } /* }}} */ /* {{{ proto class dir(string directory) Directory class with properties, handle and class and methods read, rewind and close */ PHP_FUNCTION(getdir) { _php_do_opendir(INTERNAL_FUNCTION_PARAM_PASSTHRU,1); } /* }}} */ /* {{{ proto void closedir([int dir_handle]) Close directory connection identified by the dir_handle */ PHP_FUNCTION(closedir) { pval **id, **tmp, *myself; php_dir *dirp; DIRLS_FETCH(); FETCH_DIRP(); zend_list_delete(dirp->id); if (dirp->id == DIRG(default_dir)) { php_set_default_dir(-1 DIRLS_CC); } } /* }}} */ #if defined(HAVE_CHROOT) && !defined(ZTS) /* {{{ proto int chroot(string directory) Change root directory */ PHP_FUNCTION(chroot) { pval **arg; int ret; if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_string_ex(arg); ret = chroot((*arg)->value.str.val); if (ret != 0) { php_error(E_WARNING, "chroot: %s (errno %d)", strerror(errno), errno); RETURN_FALSE; } ret = chdir("/"); if (ret != 0) { php_error(E_WARNING, "chdir: %s (errno %d)", strerror(errno), errno); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #endif /* {{{ proto int chdir(string directory) Change the current directory */ PHP_FUNCTION(chdir) { pval **arg; int ret; PLS_FETCH(); if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_string_ex(arg); if (PG(safe_mode) && !php_checkuid((*arg)->value.str.val, NULL, CHECKUID_ALLOW_ONLY_DIR)) { RETURN_FALSE; } ret = VCWD_CHDIR((*arg)->value.str.val); if (ret != 0) { php_error(E_WARNING, "ChDir: %s (errno %d)", strerror(errno), errno); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto string getcwd(void) Gets the current directory */ PHP_FUNCTION(getcwd) { char path[MAXPATHLEN]; char *ret=NULL; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } #if HAVE_GETCWD ret = VCWD_GETCWD(path, MAXPATHLEN); #elif HAVE_GETWD ret = VCWD_GETWD(path); /* * #warning is not ANSI C * #else * #warning no proper getcwd support for your site */ #endif if (ret) { RETURN_STRING(path,1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto void rewinddir([int dir_handle]) Rewind dir_handle back to the start */ PHP_FUNCTION(rewinddir) { pval **id, **tmp, *myself; php_dir *dirp; DIRLS_FETCH(); FETCH_DIRP(); rewinddir(dirp->dir); } /* }}} */ /* {{{ proto string readdir([int dir_handle]) Read directory entry from dir_handle */ PHP_NAMED_FUNCTION(php_if_readdir) { pval **id, **tmp, *myself; php_dir *dirp; char entry[sizeof(struct dirent)+MAXPATHLEN]; struct dirent *result = (struct dirent *)&entry; /* patch for libc5 readdir problems */ DIRLS_FETCH(); FETCH_DIRP(); if (php_readdir_r(dirp->dir, (struct dirent *) entry, &result) == 0 && result) { RETURN_STRINGL(result->d_name, strlen(result->d_name), 1); } RETURN_FALSE; }
char * tcs(char *cs, char *s, long *np) { Channel *sync; Exec *e; Rune r; long i, n; void **a; uchar *us; char buf[BUFSIZE], cmd[50]; char *t, *u; int p[2], q[2]; if(s==nil || *s=='\0' || *np==0){ werrstr("tcs failed: no data"); return s; } if(cs == nil){ werrstr("tcs failed: no charset"); return s; } if(cistrncmp(cs, "utf-8", 5)==0 || cistrncmp(cs, "utf8", 4)==0) return s; for(i=0; tcstab[i].mime!=nil; i++) if(cistrncmp(cs, tcstab[i].mime, strlen(tcstab[i].mime)) == 0) break; if(tcstab[i].mime == nil){ fprint(2, "abaco: charset: %s not supported\n", cs); goto latin1; } if(cistrcmp(tcstab[i].tcs, "8859-1")==0 || cistrcmp(tcstab[i].tcs, "ascii")==0){ latin1: n = 0; for(us=(uchar*)s; *us; us++) n += runelen(*us); n++; t = emalloc(n); for(us=(uchar*)s, u=t; *us; us++){ if(*us>=Winstart && *us<=Winend) *u++ = winchars[*us-Winstart]; else{ r = *us; u += runetochar(u, &r); } } *u = 0; free(s); return t; } if(pipe(p)<0 || pipe(q)<0) error("can't create pipe"); sync = chancreate(sizeof(ulong), 0); if(sync == nil) error("can't create channel"); snprint(cmd, sizeof cmd, "tcs -f %s", tcstab[i].tcs); e = emalloc(sizeof(Exec)); e->p[0] = p[0]; e->p[1] = p[1]; e->q[0] = q[0]; e->q[1] = q[1]; e->cmd = cmd; e->sync = sync; proccreate(execproc, e, STACK); recvul(sync); chanfree(sync); close(p[0]); close(q[1]); /* in case tcs fails */ t = s; sync = chancreate(sizeof(ulong), 0); if(sync == nil) error("can't create channel"); a = emalloc(4*sizeof(void *)); a[0] = sync; a[1] = (void *)p[1]; a[2] = s; a[3] = (void *)*np; proccreate(writeproc, a, STACK); s = nil; while((n = read(q[0], buf, sizeof(buf))) > 0){ s = erealloc(s, i+n+1); memmove(s+i, buf, n); i += n; s[i] = '\0'; } n = recvul(sync); if(n != *np) fprint(2, "tcs: did not write %ld; wrote %uld\n", *np, n); *np = i; chanfree(sync); close(q[0]); if(s == nil){ fprint(2, "tcs failed: can't convert charset=%s to %s\n", cs, tcstab[i].tcs); return t; } free(t); return s; }
ZEND_METHOD(afk_app, run){/*{{{*/ zval **uri; char *c=NULL, *a=NULL; zval *arr = PG(http_globals)[TRACK_VARS_GET]; //从http_globals中寻找get参数,确认Controller和action的值。 if(arr && Z_TYPE_P(arr) == IS_ARRAY){ if(zend_hash_find(HASH_OF(arr), HTTP_CONTRONLLER_PARAM, strlen(HTTP_CONTRONLLER_PARAM)+1, (void **)&uri) == SUCCESS){ c = Z_STRVAL_PP(uri); }else{ c = "index"; } if(zend_hash_find(HASH_OF(arr), HTTP_ACTION_PARAM, strlen(HTTP_ACTION_PARAM)+1, (void **)&uri) == SUCCESS){ a = Z_STRVAL_PP(uri); }else{ a = "index"; } } //寻找对应的Controller和action方法所在的文件。 char *controller_path; spprintf(&controller_path, 0, "%s/controller/%s.php", APP_DIR, c); FILE *fp; //php_printf("%s\n", controller_path); //文件存在则引入该文件。不存在则报错。 if( (fp = fopen(controller_path, "r")) != NULL){ fclose(fp); int dummy = 1; zend_file_handle file_handle; zend_op_array *op_array; file_handle.filename = controller_path; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); if (op_array && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = controller_path; } php_printf("opened_path: %s\n", file_handle.opened_path); zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); } zend_destroy_file_handle(&file_handle TSRMLS_CC); if(op_array){ php_printf("execute op_array \n"); //保存旧的环境变量 zval ** __old_return_value_pp = EG(return_value_ptr_ptr); zend_op ** __old_opline_ptr = EG(opline_ptr); zend_op_array * __old_op_array = EG(active_op_array); zend_function_state * __old_func_state = EG(function_state_ptr); //执行op_array zval *result = NULL; EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; zend_execute(op_array TSRMLS_CC); destroy_op_array(op_array TSRMLS_CC); efree(op_array); //恢复旧的环境变量 EG(return_value_ptr_ptr) = __old_return_value_pp; EG(opline_ptr) = __old_opline_ptr; EG(active_op_array) = __old_op_array; EG(function_state_ptr) = __old_func_state; } }else{ char *error; spprintf(&error, 0, "cann't find file %s", controller_path); zend_error(1, error); } //dispatcher 调用分发的请求。 /** *在EG(class_table)查找相应的类,然后调用它的方法。 */ zend_class_entry **class = NULL; char *class_name = emalloc(strlen(c)+strlen("Controller")+1); class_name = strcpy(class_name, c); class_name = strcat(class_name, zend_str_tolower_dup("Controller", strlen("Controller")+1)); //Notice: class name need tolower. if(zend_hash_find(EG(class_table), class_name, strlen(class_name)+1, (void *)&class) != SUCCESS){ char *error; spprintf(&error, 0, "cann't find the controller class: %s ", class_name); php_printf("%s", class_name); efree(class_name); efree(class); zend_error(1, error); } efree(class_name); zval *obj, *function_name, *retval; MAKE_STD_ZVAL(obj); MAKE_STD_ZVAL(function_name); MAKE_STD_ZVAL(retval); object_init_ex(obj, *class); //php_var_dump(&obj, 1 TSRMLS_CC); ZVAL_STRINGL(function_name, "indexaction", strlen("indexaction"), 1); call_user_function(&((*class)->function_table), &obj, function_name, retval, 0, NULL TSRMLS_CC); zval_ptr_dtor(&obj); zval_ptr_dtor(&function_name); zval_ptr_dtor(&retval); //efree(class); RETURN_BOOL(1); }/*}}}*/
/* {{{ proto int ora_fetch_into(int cursor, array result [, int flags]) Fetch a row into the specified result array */ void php3_Ora_FetchInto(INTERNAL_FUNCTION_PARAMETERS) { pval *arg1, *arr, *flg, *tmp; oraCursor *cursor; int i; int flags = 0; switch(ARG_COUNT(ht)){ case 2: if (getParameters(ht, 2, &arg1, &arr) == FAILURE) { WRONG_PARAM_COUNT; } break; case 3: if (getParameters(ht, 3, &arg1, &arr, &flg) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_long(flg); flags = flg->value.lval; break; default: WRONG_PARAM_COUNT; break; } if (!ParameterPassedByReference(ht, 2)){ php3_error(E_WARNING, "Array not passed by reference in call to ora_fetch_into()"); RETURN_FALSE; } convert_to_long(arg1); /* Find the cursor */ if ((cursor = ora_get_cursor(list, arg1->value.lval)) == NULL) { RETURN_FALSE; } if (cursor->ncols == 0){ php3_error(E_WARNING, "No tuples available on this cursor"); RETURN_FALSE; } if (ofetch(&cursor->cda)) { if (cursor->cda.rc != NO_DATA_FOUND) { php3_error(E_WARNING, "Ora_Fetch_Into failed (%s)", ora_error(&cursor->cda)); } RETURN_FALSE; } cursor->fetched++; if (arr->type != IS_ARRAY){ php3tls_pval_destructor(arr); if (array_init(arr) == FAILURE){ php3_error(E_WARNING, "Can't convert to type Array"); RETURN_FALSE; } } _php3_hash_internal_pointer_reset(arr->value.ht); #if PHP_API_VERSION < 19990421 tmp = emalloc(sizeof(pval)); #endif for (i = 0; i < cursor->ncols; i++) { if (cursor->columns[i].col_retcode == 1405) { if (!(flags&ORA_FETCHINTO_NULLS)){ continue; /* don't add anything for NULL columns, unless the calles wants it */ } else { tmp->value.str.val = empty_string; tmp->value.str.len = 0; } } else if (cursor->columns[i].col_retcode != 0 && cursor->columns[i].col_retcode != 1406) { /* So error fetching column. The most common is 1405, a NULL */ /* was retreived. 1406 is ASCII or string buffer data was */ /* truncated. The converted data from the database did not fit */ /* into the buffer. Since we allocated the buffer to be large */ /* enough, this should not occur. Anyway, we probably want to */ /* return what we did get, in that case */ RETURN_FALSE; } else { #if PHP_API_VERSION >= 19990421 MAKE_STD_ZVAL(tmp); #endif tmp->type = IS_STRING; tmp->value.str.len = 0; switch(cursor->columns[i].dbtype) { case SQLT_LNG: case SQLT_LBI: { ub4 ret_len; int offset = cursor->columns[i].col_retlen; sb2 result; if (cursor->columns[i].col_retcode == 1406) { /* truncation -> get the rest! */ while (1) { cursor->columns[i].buf = erealloc(cursor->columns[i].buf,offset + DB_SIZE + 1); if (! cursor->columns[i].buf) { offset = 0; break; } result = oflng(&cursor->cda, (sword)(i + 1), cursor->columns[i].buf + offset, DB_SIZE, 1, &ret_len, offset); if (result) { break; } if (ret_len <= 0) { break; } offset += ret_len; } } if (cursor->columns[i].buf && offset) { tmp->value.str.len = offset; } else { tmp->value.str.len = 0; } } break; default: tmp->value.str.len = min(cursor->columns[i].col_retlen, cursor->columns[i].dsize); break; } tmp->value.str.val = estrndup(cursor->columns[i].buf,tmp->value.str.len); } if (flags&ORA_FETCHINTO_ASSOC){ #if PHP_API_VERSION >= 19990421 _php3_hash_update(arr->value.ht, cursor->columns[i].cbuf, cursor->columns[i].cbufl+1, (void *) &tmp, sizeof(pval*), NULL); #else _php3_hash_update(arr->value.ht, cursor->columns[i].cbuf, cursor->columns[i].cbufl+1, (void *) tmp, sizeof(pval), NULL); #endif } else { #if PHP_API_VERSION >= 19990421 _php3_hash_index_update(arr->value.ht, i, (void *) &tmp, sizeof(pval*), NULL); #else _php3_hash_index_update(arr->value.ht, i, (void *) tmp, sizeof(pval), NULL); #endif } } #if PHP_API_VERSION < 19990421 efree(tmp); #endif RETURN_LONG(cursor->ncols); }
static char *newstr(char *s, int len) { char *rv = (char *)emalloc(len + 1); rv[len] = '\0'; strncpy(rv, s, len); return rv; }
void php3_Ora_Do_Logon(INTERNAL_FUNCTION_PARAMETERS, int persistent) { char *user = NULL; char *pwd = NULL; pval *arg1, *arg2; oraConnection *db_conn; list_entry *index_ptr; char *hashed_details; int hashed_len, len, id; ORACLE_TLS_VARS; if (getParameters(ht, 2, &arg1, &arg2) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_string(arg1); convert_to_string(arg2); user = arg1->value.str.val; pwd = arg2->value.str.val; if (!ORACLE_GLOBAL(php3_oracle_module).allow_persistent) { persistent = 0; } if (ORACLE_GLOBAL(php3_oracle_module).max_links != -1 && ORACLE_GLOBAL(php3_oracle_module).num_links >= ORACLE_GLOBAL(php3_oracle_module).max_links) { php3_error(E_WARNING, "Oracle: Too many open links (%d)", ORACLE_GLOBAL(php3_oracle_module).num_links); RETURN_FALSE; } /* the user requested a persistent connection */ if (persistent && ORACLE_GLOBAL(php3_oracle_module).max_persistent != -1 && ORACLE_GLOBAL(php3_oracle_module).num_persistent >= ORACLE_GLOBAL(php3_oracle_module).max_persistent) { php3_error(E_WARNING,"Oracle: Too many open persistent links (%d)", ORACLE_GLOBAL(php3_oracle_module).num_persistent); RETURN_FALSE; } len = strlen(user) + strlen(pwd) + 9; hashed_details = emalloc(len); if (hashed_details == NULL) { php3_error(E_WARNING, "Out of memory"); RETURN_FALSE; } hashed_len = _php3_sprintf(hashed_details, "ora_%s_%s", user, pwd); /* try to find if we already have this link in our persistent list, * no matter if it is to be persistent or not */ if (_php3_hash_find(plist, hashed_details, hashed_len + 1, (void **) &index_ptr) == FAILURE) { /* the link is not in the persistent list */ list_entry new_index_ptr; if (persistent) db_conn = (oraConnection *)malloc(sizeof(oraConnection)); else db_conn = (oraConnection *)emalloc(sizeof(oraConnection)); if (db_conn == NULL){ efree(hashed_details); php3_error(E_WARNING, "Out of memory"); RETURN_FALSE; } memset((void *) db_conn,0,sizeof(oraConnection)); #if HAS_OLOG if (olog(&db_conn->lda, db_conn->hda, user, strlen(user), pwd, strlen(pwd), 0, -1, OCI_LM_DEF)) { #else if (orlon(&db_conn->lda, db_conn->hda, user, strlen(user), pwd, strlen(pwd), 0)) { #endif php3_error(E_WARNING, "Unable to connect to ORACLE (%s)", ora_error(&db_conn->lda)); /* The next line is to provide error information * for OraError && OraErrorCode calls */ db_err_conn = *db_conn; if (persistent) free(db_conn); else efree(db_conn); efree(hashed_details); RETURN_FALSE; } db_conn->open = 1; if (persistent){ /*new_le.type = ORACLE_GLOBAL(php3_oracle_module).le_pconn; new_le.ptr = db_conn;*/ RETVAL_RESOURCE(php3_plist_insert(db_conn, ORACLE_GLOBAL(php3_oracle_module).le_pconn)); new_index_ptr.ptr = (void *) return_value->value.lval; new_index_ptr.type = le_index_ptr; if (_php3_hash_update(plist,hashed_details,hashed_len + 1,(void *) &new_index_ptr, sizeof(list_entry),NULL) == FAILURE) { ologof(&db_conn->lda); free(db_conn); efree(hashed_details); php3_error(E_WARNING, "Can't update hashed details list"); RETURN_FALSE; } ORACLE_GLOBAL(php3_oracle_module).num_persistent++; } else { /* non persistent, simply add to list */ RETVAL_RESOURCE(php3_list_insert(db_conn, ORACLE_GLOBAL(php3_oracle_module).le_conn)); } ORACLE_GLOBAL(php3_oracle_module).num_links++; } else { int type; /* the link is already in the persistent list */ if (index_ptr->type != le_index_ptr) { efree(hashed_details); php3_error(E_WARNING, "Oops, something went completly wrong"); RETURN_FALSE; } id = (int) index_ptr->ptr; db_conn = (oraConnection *)php3_plist_find(id, &type); if (db_conn && (type == ORACLE_GLOBAL(php3_oracle_module).le_conn || type == ORACLE_GLOBAL(php3_oracle_module).le_pconn)){ if(!_ora_ping(db_conn)) { /* XXX Reinitialize lda, hda ? */ #if HAS_OLOG if(olog(&db_conn->lda, db_conn->hda, user, strlen(user), pwd, strlen(pwd), 0, -1, OCI_LM_DEF)) { #else if(orlon(&db_conn->lda, db_conn->hda, user, strlen(user), pwd, strlen(pwd), 0)) { #endif /* The next line is to provide error information * for OraError && OraErrorCode calls */ db_err_conn = *db_conn; php3_error(E_WARNING, "Unable to reconnect to ORACLE (%s)", ora_error(&db_conn->lda)); /* Delete list entry for this connection */ php3_plist_delete(id); /* Delete hashed list entry for this dead connection */ _php3_hash_del(plist, hashed_details, hashed_len); efree(hashed_details); RETURN_FALSE; } } RETVAL_RESOURCE(id); } } _php3_hash_add(ORACLE_GLOBAL(php3_oracle_module).conns, (void*)&db_conn, sizeof(void*), (void*)&db_conn, sizeof(void*), NULL); efree(hashed_details); } /* {{{ proto int ora_logoff(int connection) Close an Oracle connection */ void php3_Ora_Logoff(INTERNAL_FUNCTION_PARAMETERS) { /* conn_index */ int type, ind; oraConnection *conn; pval *arg; ORACLE_TLS_VARS; if (getParameters(ht, 1, &arg) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_long(arg); ind = (int)arg->value.lval; conn = (oraConnection *)php3_list_find(ind, &type); if (!conn || (type != ORACLE_GLOBAL(php3_oracle_module).le_conn && type != ORACLE_GLOBAL(php3_oracle_module).le_pconn)) { return; } php3_list_delete(ind); }
int main(int argc, char **argv) { FILE *infp, *outfp=stdout, *sc3dfp; char *sc3d; int n1,n2,i,ix,iy,it,j0,nxy,nvs; int nx,ny,nt,np; float dx,dy,dt,fx,fy,ft,x,y; int orient=1; int ierr; usghed usgh; float *xs, *ys, *ts, *ss, *time; int *nps, *indx; float *work, *s3d, *gin, *si; float gmin, gmax; float dismax; int nf; int noinput=0; /* initialization */ initargs(argc,argv); askdoc(1); /* get input parameters */ if(!getparstring("SC3D.cards",&sc3d)) err("must specify SC3D.cards"); if(!getparint("orient",&orient)) { if(!getparint("gtype",&orient)) { orient = 1; } else { /* compatible with old version */ if(orient==1) orient=4; if(orient==0) orient=1; } } if(orient!=1 && orient!=4) err(" check parameter orient"); sc3dfp = fopen(sc3d,"r"); if( getparfloat("fx",&fx) && getparfloat("dx",&dx) && getparint("nx",&nx) && getparfloat("fy",&fy) && getparfloat("dy",&dy) && getparint("ny",&ny) && getparfloat("ft",&ft) && getparfloat("dt",&dt) && getparint("nt",&nt) ) { noinput = 1; } else { infp = stdin; noinput = 0; } /* get input grid parameters */ if(noinput==0) { ierr = fgetusghdr(infp,&usgh); if(ierr!=0) err(" input grid header error "); if(usgh.orient!=0 && orient!=usgh.orient) err(" check orient in grid header "); gmin = usgh.gmax; gmax = usgh.gmin; if(orient==1) { ft = usgh.o1; dt = usgh.d1; nt = usgh.n1; nvs = usgh.n1; fx = usgh.o2; dx = usgh.d2; nx = usgh.n2; fy = usgh.o3; dy = usgh.d3; ny = usgh.n3; } else if(orient==4) { ft = usgh.o3; dt = usgh.d3; nt = usgh.n3; nvs = usgh.n3; fx = usgh.o1; dx = usgh.d1; nx = usgh.n1; fy = usgh.o2; dy = usgh.d2; ny = usgh.n2; } } else { /* update output grid parameters */ nvs = nt; usgh.scale = 1.; usgh.dtype = 4; usgh.n4 = 1; usgh.n5 = 1; usgh.o4 = 0.; usgh.o5 = 0.; usgh.d4 = 1.; usgh.d5 = 1.; usgh.ocdp2 = 1; usgh.dcdp2 = 1; usgh.dline3 = 1; usgh.oline3 = 1; if(orient==1) { usgh.o1 = ft; usgh.d1 = dt; usgh.n1 = nt; usgh.o2 = fx; usgh.d2 = dx; usgh.n2 = nx; usgh.o3 = fy; usgh.d3 = dy; usgh.n3 = ny; usgh.orient = 1; } else if(orient==4) { usgh.o3 = ft; usgh.d3 = dt; usgh.n3 = nt; usgh.o1 = fx; usgh.d1 = dx; usgh.n1 = nx; usgh.o2 = fy; usgh.d2 = dy; usgh.n2 = ny; usgh.orient = 4; } } /* at most 4096 input (x,y) SC3D cards with at most 256 time-scal pairs each */ if( !getparint("ncdmax",&n2) ) n2 = 4096; if( !getparint("nprmax",&n1) ) n1 = 256; if( !getparint("nf",&nf) ) nf = 0; if( !getparfloat("dismax",&dismax) ) dismax = 10000; /* arrays used to store all SCAL card's x, y, time and scale */ xs = (float*)malloc(n2*sizeof(int)); ys = (float*)malloc(n2*sizeof(int)); ts = (float*)malloc(n1*n2*sizeof(float)); ss = (float*)malloc(n1*n2*sizeof(float)); nps = (int*)malloc(n2*sizeof(int)); bzero(nps,n2*sizeof(int)); /* read in SC3D cards */ nxy = 0; sc3dread(sc3dfp,xs,ys,ts,ss,&nxy,nps,n1,n2); fprintf(stderr," %d SC3D cards read \n",nxy); if (nxy==0) err("No SC3D card input ! Job aborted"); time = (float*)malloc(nvs*sizeof(float)); for(i=0;i<nvs;i++) time[i] = ft + i*dt; si = (float*) emalloc(nxy*nvs*sizeof(float)); indx = (int*) emalloc(nvs*sizeof(int)); for(i=0;i<nxy;i++) { fprintf(stderr, "%d t/z-scale pairs read at x=%f y=%f location\n", nps[i],xs[i],ys[i]); j0 = i*nvs; np = nps[i]; /* interpolate sc3d to nvs times */ lin1d_(ts+i*n1,ss+i*n1,&np,time, si+j0,&nvs,indx); } free(indx); if(noinput==1) { gmin = si[0]; gmax = si[0]; } /* apply scale to input grid and output */ if(orient==1) { s3d = (float*) malloc(nt*sizeof(float)); work = (float*) malloc(nxy*sizeof(float)); gin = (float*) malloc(nt*sizeof(float)); indx = (int*) malloc(nxy*sizeof(int)); for(iy=0;iy<ny;iy++) { y = fy + iy*dy; for(ix=0;ix<nx;ix++) { x = fx + ix*dx; if(nxy>1) { if(nf==0) { plint_(xs,ys,si,&nvs,&nxy,&x,&y, s3d,work,&dismax,indx); } else { np = nf; intp2d_(xs,ys,si,&nvs,&nxy,&x,&y, s3d,&np,indx,work); } } else { for(it=0;it<nvs;it++) s3d[it] = si[it]; } if(noinput==0) { efread(gin,sizeof(float),nt,infp); } else { for(it=0;it<nt;it++) gin[it] = 1.0; } for(it=0;it<nt;it++) { gin[it] *= s3d[it]; if(gmin>gin[it]) gmin = gin[it]; if(gmax<gin[it]) gmax = gin[it]; } efwrite(gin,sizeof(float),nt,outfp); } } } else if(orient==4) { s3d = (float*) emalloc(nx*ny*nt*sizeof(float)); work = (float*) emalloc(nxy*sizeof(float)); indx = (int*) emalloc(nxy*sizeof(int)); gin = (float*) emalloc(nx*ny*sizeof(float)); for(iy=0;iy<ny;iy++) { y = fy + iy*dy; for(ix=0;ix<nx;ix++) { x = fx + ix*dx; j0 = ix*nt+iy*nx*nt; if(nf==0) { plint_(xs,ys,si,&nvs,&nxy,&x,&y, s3d+j0,work,&dismax,indx); } else { np = nf; intp2d_(xs,ys,si,&nvs,&nxy,&x,&y, s3d+j0,&np,indx,work); } } } for(it=0;it<nt;it++) { if(noinput==0) { efread(gin,sizeof(float),nx*ny,infp); } else { for(ix=0;ix<nx*ny;ix++) gin[ix] = 1.0; } for(iy=0;iy<ny;iy++) { for(ix=0;ix<nx;ix++) { j0 = iy*nx+ix; gin[j0] *= s3d[it+j0*nt]; if(gmin>gin[j0]) gmin = gin[j0]; if(gmax<gin[j0]) gmax = gin[j0]; } } efwrite(gin,sizeof(float),nx*ny,outfp); } } usgh.gmin = gmin; usgh.gmax = gmax; ierr = fputusghdr(outfp,&usgh); if(ierr!=0) err("error in fputusghdr"); exit(0); }
/* {{{ proto int ora_do(int connection, int cursor) Parse and execute a statement and fetch first result row */ void php3_Ora_Do(INTERNAL_FUNCTION_PARAMETERS) { pval *argv[2]; oraConnection *conn = NULL; oraCursor *cursor = NULL; text *query; if (ARG_COUNT(ht) != 2 || getParametersArray(ht, 2, argv) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_long(argv[0]); convert_to_string(argv[1]); conn = ora_get_conn(list,plist, argv[0]->value.lval); if (conn == NULL) { RETURN_FALSE; } if ((cursor = (oraCursor *)emalloc(sizeof(oraCursor))) == NULL){ php3_error(E_WARNING, "Out of memory"); RETURN_FALSE; } memset(cursor, 0, sizeof(oraCursor)); query = (text *) estrndup(argv[1]->value.str.val,argv[1]->value.str.len); if (query == NULL) { php3_error(E_WARNING, "Invalid query in Ora_Do"); RETURN_FALSE; } cursor->query = query; if (oopen(&cursor->cda, &conn->lda, (text *) 0, -1, -1, (text *) 0, -1)) { php3_error(E_WARNING, "Unable to open new cursor (%s)", ora_error(&cursor->cda)); efree(cursor); RETURN_FALSE; } cursor->open = 1; cursor->conn_ptr = conn; cursor->conn_id = argv[0]->value.lval; /* Prepare stmt */ if (oparse(&cursor->cda, query, (sb4) - 1, 1, VERSION_7)){ php3_error(E_WARNING, "Ora_Do failed (%s)", ora_error(&cursor->cda)); _close_oracur(cursor); RETURN_FALSE; } /* Execute stmt (and fetch 1st row for selects) */ if (cursor->cda.ft == FT_SELECT) { if (ora_describe_define(cursor) < 0){ /* error message is given by ora_describe_define() */ _close_oracur(cursor); RETURN_FALSE; } if (oexfet(&cursor->cda, 1, 0, 0)) { php3_error(E_WARNING, "Ora_Do failed (%s)", ora_error(&cursor->cda)); _close_oracur(cursor); RETURN_FALSE; } cursor->fetched = 1; } else { if (oexec(&cursor->cda)) { php3_error(E_WARNING, "Ora_Do failed (%s)", ora_error(&cursor->cda)); _close_oracur(cursor); RETURN_FALSE; } } RETURN_RESOURCE(ora_add_cursor(list, cursor)); }
php_bz2iop_write, php_bz2iop_read, php_bz2iop_close, php_bz2iop_flush, "BZip2", NULL, /* seek */ NULL, /* cast */ NULL, /* stat */ NULL /* set_option */ }; /* {{{ Bzip2 stream openers */ PHP_BZ2_API php_stream *_php_stream_bz2open_from_BZFILE(BZFILE *bz, const char *mode, php_stream *innerstream STREAMS_DC) { struct php_bz2_stream_data_t *self; self = emalloc(sizeof(*self)); self->stream = innerstream; self->bz_file = bz; return php_stream_alloc_rel(&php_stream_bz2io_ops, self, 0, mode); } PHP_BZ2_API php_stream *_php_stream_bz2open(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC) { php_stream *retstream = NULL, *stream = NULL;
void viewer(Document *dd) { int i, fd, n, oldpage; int nxt; Menu menu, midmenu; Mouse m; Event e; Point dxy, oxy, xy0; Rectangle r; Image *tmp; static char *fwditems[] = { "this page", "next page", "exit", 0 }; static char *miditems[] = { "orig size", "zoom in", "fit window", "rotate 90", "upside down", "", "next", "prev", "zerox", "", "reverse", "discard", "write", "", "quit", 0 }; char *s; enum { Eplumb = 4 }; Plumbmsg *pm; doc = dd; /* save global for menuhit */ ul = screen->r.min; einit(Emouse|Ekeyboard); if(doc->addpage != nil) eplumb(Eplumb, "image"); esetcursor(&reading); r.min = ZP; /* * im is a global pointer to the current image. * eventually, i think we will have a layer between * the display routines and the ps/pdf/whatever routines * to perhaps cache and handle images of different * sizes, etc. */ im = 0; page = reverse ? doc->npage-1 : 0; if(doc->fwdonly) { menu.item = fwditems; menu.gen = 0; menu.lasthit = 0; } else { menu.item = 0; menu.gen = menugen; menu.lasthit = 0; } midmenu.item = miditems; midmenu.gen = 0; midmenu.lasthit = Next; if(doc->docname != nil) setlabel(doc->docname); showpage(page, &menu); esetcursor(nil); nxt = 0; for(;;) { /* * throughout, if doc->fwdonly is set, we restrict the functionality * a fair amount. we don't care about doc->npage anymore, and * all that can be done is select the next page. */ unlockdisplay(display); i = eread(Emouse|Ekeyboard|Eplumb, &e); lockdisplay(display); switch(i){ case Ekeyboard: if(e.kbdc <= 0xFF && isdigit(e.kbdc)) { nxt = nxt*10+e.kbdc-'0'; break; } else if(e.kbdc != '\n') nxt = 0; switch(e.kbdc) { case 'r': /* reverse page order */ if(doc->fwdonly) break; reverse = !reverse; menu.lasthit = doc->npage-1-menu.lasthit; /* * the theory is that if we are reversing the * document order and are on the first or last * page then we're just starting and really want * to view the other end. maybe the if * should be dropped and this should happen always. */ if(page == 0 || page == doc->npage-1) { page = doc->npage-1-page; showpage(page, &menu); } break; case 'w': /* write bitmap of current screen */ esetcursor(&reading); s = writebitmap(); if(s) string(screen, addpt(screen->r.min, Pt(5,5)), display->black, ZP, display->defaultfont, s); esetcursor(nil); flushimage(display, 1); break; case 'd': /* remove image from working set */ if(doc->rmpage && page < doc->npage) { if(doc->rmpage(doc, page) >= 0) { if(doc->npage < 0) wexits(0); if(page >= doc->npage) page = doc->npage-1; showpage(page, &menu); } } break; case 'q': case 0x04: /* ctrl-d */ wexits(0); case 'u': if(im==nil) break; angle = (angle+180) % 360; showpage(page, &menu); break; case '-': case '\b': case Kleft: if(page > 0 && !doc->fwdonly) { --page; showpage(page, &menu); } break; case '\n': if(nxt) { nxt--; if(nxt >= 0 && nxt < doc->npage && !doc->fwdonly) showpage(page=nxt, &menu); nxt = 0; break; } goto Gotonext; case Kright: case ' ': Gotonext: if(doc->npage && ++page >= doc->npage && !doc->fwdonly) wexits(0); showpage(page, &menu); break; /* * The upper y coordinate of the image is at ul.y in screen->r. * Panning up means moving the upper left corner down. If the * upper left corner is currently visible, we need to go back a page. */ case Kup: if(screen->r.min.y <= ul.y && ul.y < screen->r.max.y){ if(page > 0 && !doc->fwdonly){ --page; showbottom = 1; showpage(page, &menu); } } else { i = Dy(screen->r)/2; if(i > 10) i -= 10; if(i+ul.y > screen->r.min.y) i = screen->r.min.y - ul.y; translate(Pt(0, i)); } break; /* * If the lower y coordinate is on the screen, we go to the next page. * The lower y coordinate is at ul.y + Dy(im->r). */ case Kdown: i = ul.y + Dy(im->r); if(screen->r.min.y <= i && i <= screen->r.max.y){ ul.y = screen->r.min.y; goto Gotonext; } else { i = -Dy(screen->r)/2; if(i < -10) i += 10; if(i+ul.y+Dy(im->r) <= screen->r.max.y) i = screen->r.max.y - Dy(im->r) - ul.y - 1; translate(Pt(0, i)); } break; default: esetcursor(&query); sleep(1000); esetcursor(nil); break; } break; case Emouse: m = e.mouse; switch(m.buttons){ case Left: oxy = m.xy; xy0 = oxy; do { dxy = subpt(m.xy, oxy); oxy = m.xy; translate(dxy); unlockdisplay(display); m = emouse(); lockdisplay(display); } while(m.buttons == Left); if(m.buttons) { dxy = subpt(xy0, oxy); translate(dxy); } break; case Middle: if(doc->npage == 0) break; unlockdisplay(display); n = emenuhit(Middle, &m, &midmenu); lockdisplay(display); if(n == -1) break; switch(n){ case Next: /* next */ if(reverse) page--; else page++; if(page < 0) { if(reverse) return; else page = 0; } if((page >= doc->npage) && !doc->fwdonly) return; showpage(page, &menu); nxt = 0; break; case Prev: /* prev */ if(reverse) page++; else page--; if(page < 0) { if(reverse) return; else page = 0; } if((page >= doc->npage) && !doc->fwdonly && !reverse) return; showpage(page, &menu); nxt = 0; break; case Zerox: /* prev */ zerox(); break; case Zin: /* zoom in */ { double delta; Rectangle r; r = egetrect(Middle, &m); if((rectclip(&r, rectaddpt(im->r, ul)) == 0) || Dx(r) == 0 || Dy(r) == 0) break; /* use the smaller side to expand */ if(Dx(r) < Dy(r)) delta = (double)Dx(im->r)/(double)Dx(r); else delta = (double)Dy(im->r)/(double)Dy(r); esetcursor(&reading); tmp = xallocimage(display, Rect(0, 0, (int)((double)Dx(im->r)*delta), (int)((double)Dy(im->r)*delta)), im->chan, 0, DBlack); if(tmp == nil) { fprint(2, "out of memory during zoom: %r\n"); wexits("memory"); } resample(im, tmp); im = tmp; delayfreeimage(tmp); esetcursor(nil); ul = screen->r.min; redraw(screen); flushimage(display, 1); break; } case Fit: /* fit */ { double delta; Rectangle r; delta = (double)Dx(screen->r)/(double)Dx(im->r); if((double)Dy(im->r)*delta > Dy(screen->r)) delta = (double)Dy(screen->r)/(double)Dy(im->r); r = Rect(0, 0, (int)((double)Dx(im->r)*delta), (int)((double)Dy(im->r)*delta)); esetcursor(&reading); tmp = xallocimage(display, r, im->chan, 0, DBlack); if(tmp == nil) { fprint(2, "out of memory during fit: %r\n"); wexits("memory"); } resample(im, tmp); im = tmp; delayfreeimage(tmp); esetcursor(nil); ul = screen->r.min; redraw(screen); flushimage(display, 1); break; } case Rot: /* rotate 90 */ angle = (angle+90) % 360; showpage(page, &menu); break; case Upside: /* upside-down */ angle = (angle+180) % 360; showpage(page, &menu); break; case Restore: /* restore */ showpage(page, &menu); break; case Reverse: /* reverse */ if(doc->fwdonly) break; reverse = !reverse; menu.lasthit = doc->npage-1-menu.lasthit; if(page == 0 || page == doc->npage-1) { page = doc->npage-1-page; showpage(page, &menu); } break; case Write: /* write */ esetcursor(&reading); s = writebitmap(); if(s) string(screen, addpt(screen->r.min, Pt(5,5)), display->black, ZP, display->defaultfont, s); esetcursor(nil); flushimage(display, 1); break; case Del: /* delete */ if(doc->rmpage && page < doc->npage) { if(doc->rmpage(doc, page) >= 0) { if(doc->npage < 0) wexits(0); if(page >= doc->npage) page = doc->npage-1; showpage(page, &menu); } } break; case Exit: /* exit */ return; case Empty1: case Empty2: case Empty3: break; }; case Right: if(doc->npage == 0) break; oldpage = page; unlockdisplay(display); n = emenuhit(RMenu, &m, &menu); lockdisplay(display); if(n == -1) break; if(doc->fwdonly) { switch(n){ case 0: /* this page */ break; case 1: /* next page */ showpage(++page, &menu); break; case 2: /* exit */ return; } break; } if(n == doc->npage) return; else page = reverse ? doc->npage-1-n : n; if(oldpage != page) showpage(page, &menu); nxt = 0; break; } break; case Eplumb: pm = e.v; if(pm->ndata <= 0){ plumbfree(pm); break; } if(plumbquit(pm)) exits(nil); if(showdata(pm)) { s = estrdup("/tmp/pageplumbXXXXXXX"); fd = opentemp(s); write(fd, pm->data, pm->ndata); /* lose fd reference on purpose; the file is open ORCLOSE */ } else if(pm->data[0] == '/') { s = estrdup(pm->data); } else { s = emalloc(strlen(pm->wdir)+1+pm->ndata+1); sprint(s, "%s/%s", pm->wdir, pm->data); cleanname(s); } if((i = doc->addpage(doc, s)) >= 0) { page = i; unhide(); showpage(page, &menu); } free(s); plumbfree(pm); break; } } }
/* The search string can be either: * a) a file name * b) a CLSID, major, minor e.g. "{00000200-0000-0010-8000-00AA006D2EA4},2,0" * c) a Type Library name e.g. "Microsoft OLE DB ActiveX Data Objects 1.0 Library" */ PHP_COM_DOTNET_API ITypeLib *php_com_load_typelib(char *search_string, int codepage) { ITypeLib *TL = NULL; char *strtok_buf, *major, *minor; CLSID clsid; OLECHAR *p; HRESULT hr; search_string = php_strtok_r(search_string, ",", &strtok_buf); if (search_string == NULL) { return NULL; } major = php_strtok_r(NULL, ",", &strtok_buf); minor = php_strtok_r(NULL, ",", &strtok_buf); p = php_com_string_to_olestring(search_string, strlen(search_string), codepage); if (SUCCEEDED(CLSIDFromString(p, &clsid))) { WORD major_i = 1, minor_i = 0; /* pick up the major/minor numbers; if none specified, default to 1,0 */ if (major && minor) { major_i = (WORD)atoi(major); minor_i = (WORD)atoi(minor); } /* Load the TypeLib by GUID */ hr = LoadRegTypeLib((REFGUID)&clsid, major_i, minor_i, LANG_NEUTRAL, &TL); /* if that failed, assumed that the GUID is actually a CLSID and * attempt to get the library via an instance of that class */ if (FAILED(hr) && (major == NULL || minor == NULL)) { IDispatch *disp = NULL; ITypeInfo *info = NULL; UINT idx; if (SUCCEEDED(hr = CoCreateInstance(&clsid, NULL, CLSCTX_SERVER, &IID_IDispatch, (LPVOID*)&disp)) && SUCCEEDED(hr = IDispatch_GetTypeInfo(disp, 0, LANG_NEUTRAL, &info))) { hr = ITypeInfo_GetContainingTypeLib(info, &TL, &idx); } if (info) { ITypeInfo_Release(info); } if (disp) { IDispatch_Release(disp); } } } else { /* Try to load it from a file; if it fails, do a really painful search of * the registry */ if (FAILED(LoadTypeLib(p, &TL))) { HKEY hkey, hsubkey; DWORD SubKeys, MaxSubKeyLength; char *keyname; unsigned int i, j; DWORD VersionCount; char version[20]; char *libname; long libnamelen; if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, "TypeLib", 0, KEY_READ, &hkey) && ERROR_SUCCESS == RegQueryInfoKey(hkey, NULL, NULL, NULL, &SubKeys, &MaxSubKeyLength, NULL, NULL, NULL, NULL, NULL, NULL)) { MaxSubKeyLength++; /* make room for NUL */ keyname = emalloc(MaxSubKeyLength); libname = emalloc(strlen(search_string) + 1); for (i = 0; i < SubKeys && TL == NULL; i++) { if (ERROR_SUCCESS == RegEnumKey(hkey, i, keyname, MaxSubKeyLength) && ERROR_SUCCESS == RegOpenKeyEx(hkey, keyname, 0, KEY_READ, &hsubkey)) { if (ERROR_SUCCESS == RegQueryInfoKey(hsubkey, NULL, NULL, NULL, &VersionCount, NULL, NULL, NULL, NULL, NULL, NULL, NULL)) { for (j = 0; j < VersionCount; j++) { if (ERROR_SUCCESS != RegEnumKey(hsubkey, j, version, sizeof(version))) { continue; } /* get the default value for this key and compare */ libnamelen = (long)strlen(search_string)+1; if (ERROR_SUCCESS == RegQueryValue(hsubkey, version, libname, &libnamelen)) { if (0 == stricmp(libname, search_string)) { char *str = NULL; int major_tmp, minor_tmp; /* fetch the GUID and add the version numbers */ if (2 != sscanf(version, "%d.%d", &major_tmp, &minor_tmp)) { major_tmp = 1; minor_tmp = 0; } spprintf(&str, 0, "%s,%d,%d", keyname, major_tmp, minor_tmp); /* recurse */ TL = php_com_load_typelib(str, codepage); efree(str); break; } } } } RegCloseKey(hsubkey); } } RegCloseKey(hkey); efree(keyname); efree(libname); } } } efree(p); return TL; }