static int get_path_info ( void ) { FILE *f; char buffer[PATH_MAX + 1]; app_pref_path = NULL; // to signal that it's not got yet /* Get base path (where executable is */ #ifdef __EMSCRIPTEN__ app_base_path = strdup("/files/"); #else app_base_path = SDL_GetBasePath(); if (!app_base_path) { ERROR_WINDOW("Cannot query base directory: %s", ERRSTR()); return 1; } #endif /* Check for pref dir override file in the same directory where executable is (base path) */ snprintf(buffer, sizeof buffer, "%s%cxep128.dir", app_base_path, DIRSEP[0]); f = fopen(buffer, "r"); if (f) { char *p = fgets(buffer, sizeof buffer, f); fclose(f); if (p) { p = strchr(buffer, 13); if (p) *p = 0; p = strchr(buffer, 10); if (p) *p = 0; if (*buffer == '.') app_pref_path = strdup(app_base_path); else if (*buffer) app_pref_path = strdup(buffer); } } /* Pref dir stuff */ if (app_pref_path) { printf("CONFIG: Overriding pref path to: %s" NL, app_pref_path); } else { #ifdef __EMSCRIPTEN__ app_pref_path = strdup("/files/"); #else app_pref_path = SDL_GetPrefPath("nemesys.lgb", "xep128"); if (!app_pref_path) { ERROR_WINDOW("Cannot query preferences directory: %s", ERRSTR()); return 1; } #endif } /* Get current directory */ #ifdef __EMSCRIPTEN__ mkdir("/files", 0777); chdir("/files"); #endif if (getcwd(current_directory, sizeof current_directory) == NULL) { ERROR_WINDOW("Cannot query current directory: %s", ERRSTR()); return 1; } strcat(current_directory, DIRSEP); return 0; }
static BOOL CreateSystemPalettePixelUse() { int i; /* create system palette pixel use counter once */ if (SystemPalettePixelUse) return (TRUE); /* create system palette pixel use counter */ if (!(SystemPalettePixelUse = (LPINT) WinMalloc(SystemPaletteSize * sizeof(INT)))) { ERRSTR((LF_WARNING,"%s: Unable to create color palette.\n", "CreateSystemPalettePixelUse")); return (FALSE); } /* initialize system palette pixel use counter */ for (i = 0; i < SystemPaletteSize; i++) { SystemPalettePixelUse[i] = -1; } return (TRUE); }
static BOOL CreateSystemPaletteMapper() { int i; /* create system palette mapper once */ if (SystemPaletteMapper) return (TRUE); /* create system palette mapper */ if (!(SystemPaletteMapper = (LPDWORD) WinMalloc(SystemPaletteSize * sizeof(DWORD)))) { ERRSTR((LF_WARNING, "%s: Unable to create color table.\n", "CreateSystemPaletteMapper")); return (FALSE); } /* initialize system palette mapper */ for (i = 0; i < SystemPaletteSize; i++) { SystemPaletteMapper[i] = pixel0 | (i * pixel_mask0); } return (TRUE); }
/***************************************************************************** Prototype : display_sysfs_cfg Description : cfg driver by sysfs Input : const char *attribute const char *value Output : None Return Value : static Calls : Called By : History : 1.Date : 2012/8/28 Author : Sun Modification : Created function *****************************************************************************/ static Int32 display_sysfs_cfg(const char *attribute, const char *value) { int sysfd = -1; char initVal[32]; char attrTag[128]; bzero(initVal, sizeof(initVal)); strcpy(attrTag, "/sys/class/davinci_display/ch0/"); strcat(attrTag, attribute); sysfd = open(attrTag, O_RDWR); if (!sysfd) { ERRSTR("cannot open %s", attrTag); return E_IO; } read(sysfd, initVal, sizeof(initVal)); lseek(sysfd, 0, SEEK_SET); write(sysfd, value, 1 + strlen(value)); lseek(sysfd, 0, SEEK_SET); bzero(initVal, sizeof(initVal)); read(sysfd, initVal, sizeof(initVal)); lseek(sysfd, 0, SEEK_SET); DBG("Display, changed %s to %s", attribute, initVal); close(sysfd); return E_NO; }
static void main_loop(int flag, LogLevel_t level, const char *logName) { int cnt = 0; DBG("Log Test Start: %d.", cnt++); INFO("Info: %d", cnt++); ERR("Err: %d", cnt++); FILE *fp = fopen("not_exit", "b"); ERRSTR("Open none exist file"); LogHandle hLog; hLog = log_create(level, flag, logName, 1024 * 1024); assert(hLog != NULL); for(level = LOG_LEVEL_DBG; level < LOG_LEVEL_MAX; level++) { log_print(hLog, "Log level: %d", level); log_set_level(hLog, level); log_debug(hLog, "Debug info, log name %s", logName); log_warning(hLog,"Warning, flag: %u, level: %d", flag, level); log_error(hLog,"Error, log handle addr: 0x%X", hLog); } const char *pErr = str_err((int)E_BUSY); printf("Err string: %s\n", pErr); log_print(hLog, "Log test success!"); }
FILE *open_emu_file ( const char *name, const char *mode, char *pathbuffer ) { const char *name_used = name; const char *policy = "guessing"; const char *prefixes[] = { #ifdef __EMSCRIPTEN__ "/files/", #else current_directory, // try in the current directory first app_pref_path, // try at pref path (user writable area) app_base_path, // try at base path (where executable is) #ifndef _WIN32 DATADIR "/", // try in the DATADIR, it makes sense on UNIX like sys #endif #endif NULL }; int a = 0; FILE *f; // try to detect absolute path, Win32 related part tries to detect the possibility of X:\... syntax if ( name[0] == DIRSEP[0] #ifdef _WIN32 || (strlen(name) > 3 && name[1] == ':' && name[2] == DIRSEP[0]) #endif ) { prefixes[0] = ""; prefixes[1] = NULL; policy = "absolute"; } else if (name[0] == '@') { // @ means user preference directory related path names #ifdef __EMSCRIPTEN__ prefixes[0] = "/files/"; #else prefixes[0] = app_pref_path; #endif prefixes[1] = NULL; name_used = name + 1; policy = "pref-dir"; } while (prefixes[a] != NULL) if (strcmp(prefixes[a], "?")) { snprintf(pathbuffer, PATH_MAX, "%s%s", prefixes[a], name_used); DEBUGPRINT("OPEN: trying file \"%s\" [mode: %s] as path \"%s\" [%s]: ", name, mode, pathbuffer, policy ); f = fopen(pathbuffer, mode); if (f == NULL) { a++; DEBUGPRINT("*FAILED*: %s" NL, ERRSTR()); } else { DEBUGPRINT("(fd=%d) OK" NL, fileno(f)); return f; } } DEBUGPRINT("OPEN: no file could be open for \"%s\"" NL, name); strcpy(pathbuffer, name); return NULL; }
/***************************************************************************** Prototype : tcp_accept Description : accept tcp connection Input : CamCtrlSrvEnv *envp int listenSock Output : None Return Value : static Calls : Called By : History : 1.Date : 2012/4/23 Author : Sun Modification : Created function *****************************************************************************/ static Int32 tcp_accept(CamCtrlSrvEnv *envp, int listenSock) { int connectSock; socklen_t len; struct sockaddr_in clientAddr; pthread_t pid; /* Accept connections */ len = sizeof(clientAddr); bzero(&clientAddr, sizeof(clientAddr)); connectSock = accept(listenSock, (struct sockaddr *)&(clientAddr), &len); if(connectSock < 0) { ERRSTR("accept err"); return E_CONNECT; } DBG("%s, %s connected...", PROGRAM_NAME, inet_ntoa(clientAddr.sin_addr)); /* create new thread to reponse this connection */ CamCtrlThrParams *params = malloc(sizeof(CamCtrlThrParams)); if(!params) { ERR("can't alloc param for thread...."); close(connectSock); return E_NOMEM; } params->sock = connectSock; params->dataBuf = envp->transBuf; params->bufLen = envp->bufLen; params->hCamCtrl = envp->hCamCtrl; params->mutex = &envp->mutex; params->armProg = envp->armProg; params->fpgaFirmware = envp->fpgaFirmware; if(pthread_create(&pid, NULL, cam_ctrl_thread, params) < 0) { ERRSTR("create thread failed"); close(connectSock); return E_NOSPC; } return E_NO; }
/***************************************************************************** Prototype : vid_enc_thr Description : image encode thread Input : void *arg Output : None Return Value : void Calls : Called By : History : 1.Date : 2012/3/8 Author : Sun Modification : Created function *****************************************************************************/ void *vid_enc_thr(void *arg) { VidEncThrEnv env; CommonMsg msgBuf; Int32 ret; Int32 fdMsg, fdMax; fd_set rdSet; ret = vid_enc_thr_init((VidEncThrArg *)arg, (VidEncThrEnv *)&env); assert(ret == E_NO); if(ret) goto exit; fdMsg = msg_get_fd(env.hMsg); fdMax = fdMsg + 1; /* start main loop */ while(!env.exit) { /* wait data ready */ FD_ZERO(&rdSet); FD_SET(fdMsg, &rdSet); ret = select(fdMax, &rdSet, NULL, NULL, NULL); if(ret < 0 && errno != EINTR) { ERRSTR("select err"); break; } /* no data ready */ if(!ret) continue; if(FD_ISSET(fdMsg, &rdSet)) { /* process msg */ msg_process(&env, &msgBuf); } } exit: if(env.hH264Enc) h264_enc_delete(env.hH264Enc); if(env.hOsd) osd_delete(env.hOsd); if(env.hBufEnc) buffer_free(env.hBufEnc); if(env.hMsg) msg_delete(env.hMsg); INFO("vid encode thread exit..."); pthread_exit(0); }
static BYTE WindowByte(int Func, HWND hWnd, int nIndex, BYTE bNewByte) { HWND32 hWndTmp32; LPSTR ptr; BYTE bTemp = 0; if (!(hWndTmp32 = GETHWND32(hWnd))) { ERRSTR((LF_ERROR, "WindowByte: Bad Window: %x\n", hWnd)); return 0; } if (nIndex < 0) { ERRSTR((LF_ERROR, "WindowByte: Unknown Index: %d\n", nIndex)); } else { ptr = (LPSTR)(hWndTmp32->lpWndExtra) + nIndex; bTemp = ptr[0]; switch(Func) { case WND_OR: bTemp |= bNewByte; *ptr = bTemp; break; case WND_AND: bTemp &= ~bNewByte; *ptr = bTemp; break; case WND_XOR: bTemp = ~(bTemp ^ ~bNewByte); *ptr = bTemp; break; case WND_TEST: bTemp &= bNewByte; break; case WND_SET: *ptr = bNewByte; break; } } RELEASEWININFO(hWndTmp32); return(bTemp); }
/***************************************************************************** Prototype : encoder_run Description : run this module Input : EncoderHandle hEnc Output : None Return Value : Calls : Called By : History : 1.Date : 2012/3/20 Author : Sun Modification : Created function *****************************************************************************/ Int32 encoder_run(EncoderHandle hEnc) { Int32 err; /* create thread and run our thread */ err = pthread_create(&hEnc->pid, NULL, encoder_thread, hEnc); if(err < 0) { ERRSTR("create data capture thread failed..."); return E_NOMEM; } return E_NO; }
/***************************************************************************** Prototype : display_dev_open Description : open device Input : DisplayHanlde hDisplay Uint32 chanId Output : None Return Value : static Calls : Called By : History : 1.Date : 2012/8/28 Author : Sun Modification : Created function *****************************************************************************/ static Int32 display_dev_open(DisplayHanlde hDisplay, Uint32 chanId) { /* open device if necessary */ if(hDisplay->fdDisplay <= 0) { char devName[32]; snprintf(devName, sizeof(devName), "/dev/video%u", chanId + 2); hDisplay->fdDisplay = open(devName, O_RDWR); if(hDisplay->fdDisplay < 0) { ERRSTR("can't open device: %s", devName); return E_IO; } DBG("open %s ok.", devName); } return E_NO; }
static Bool main_loop(TestParams *params) { Bool ret = FALSE; pthread_t *pid = calloc(params->thrNum, sizeof(pthread_t)); int i; raw_trans_test(); for(i = 0; i < params->thrNum; i++) { TaskEnv *env = malloc(sizeof(TaskEnv)); if(!env) { ERR("alloc thr env failed."); break; } env->params = params; env->id = i; sprintf(env->name, "%s%d", params->baseName, i); if(i == params->thrNum - 1) sprintf(env->dest, "%s0", params->baseName); else sprintf(env->dest, "%s%d", params->baseName, i+1); if(pthread_create(&pid[i], NULL, thr_msg, env) < 0) { free(env); ERRSTR("create thread"); break; } usleep(1000); } int j; for(j = 0; j < i; j++) { pthread_join(pid[j], NULL); } ret = TRUE; //exit: if(pid) free(pid); return ret; }
/***************************************************************************** Prototype : udp_cmd_send Description : send udp cmd Input : Int32 sock UdpCmdHeader *header void *buf struct sockaddr_in *addr Output : None Return Value : Calls : Called By : History : 1.Date : 2012/4/23 Author : Sun Modification : Created function *****************************************************************************/ Int32 udp_cmd_send(Int32 sock, UdpCmdHeader *header, void *buf, struct sockaddr_in *addr) { Int32 ret; UdpCmd *cmd; Int32 len; Int8 sendBuf[UDP_BUF_LEN]; /* validate data */ if(sock < 0 || !header || !addr) return E_INVAL; if(header->dataLen && !buf) { ERR("buf should not be null while datalen is bigger than 0"); return E_INVAL; } /* set sync code and header */ cmd = (UdpCmd *)sendBuf; cmd->syncCode = UDP_CMD_RESP_START; cmd->header = *header; if(header->dataLen) { if(header->dataLen > sizeof(sendBuf) - sizeof(UdpCmd) - sizeof(Uint32)) { ERR("not enough buf for send"); return E_NOMEM; } memcpy(sendBuf + sizeof(UdpCmd), buf, header->dataLen); } len = sizeof(*cmd) + header->dataLen; *(Uint32 *)(sendBuf + len) = UDP_CMD_RESP_END; len += sizeof(Uint32); /* send data */ ret = sendto(sock, sendBuf, len, 0, (struct sockaddr *)addr, sizeof(struct sockaddr_in)); if(ret != len) { ERRSTR("sendto error"); return E_TRANS; } return E_NO; }
/***************************************************************************** Prototype : encoder_thread Description : encode thread Input : void *arg Output : None Return Value : void Calls : Called By : History : 1.Date : 2012/3/8 Author : Sun Modification : Created function *****************************************************************************/ void *encoder_thread(void *arg) { EncoderHandle hEnc = (EncoderHandle)arg; CommonMsg msgBuf; Int32 ret; Int32 fdMsg, fdMax; fd_set rdSet; assert(arg); fdMsg = msg_get_fd(hEnc->hMsg); fdMax = fdMsg + 1; DBG("%s thread start", hEnc->name); /* start main loop */ while(!hEnc->exit) { /* wait data ready */ FD_ZERO(&rdSet); FD_SET(fdMsg, &rdSet); ret = select(fdMax, &rdSet, NULL, NULL, NULL); if(ret < 0 && errno != EINTR) { ERRSTR("select err"); break; } /* no data ready */ if(!ret) continue; if(FD_ISSET(fdMsg, &rdSet)) { /* process msg */ msg_process(hEnc, &msgBuf); } } INFO("<%s> encode thread exit...", hEnc->name); pthread_exit(0); }
/***************************************************************************** Prototype : udp_cmd_recv Description : recv tdp cmd Input : Int32 sock UdpCmdHeader *header void *buf Uint32 bufLen struct sockaddr_in *addr Output : None Return Value : Calls : Called By : History : 1.Date : 2012/4/23 Author : Sun Modification : Created function *****************************************************************************/ Int32 udp_cmd_recv(Int32 sock, UdpCmdHeader *header, void *buf, Uint32 bufLen, struct sockaddr_in *addr) { Int32 ret; socklen_t len = sizeof(struct sockaddr_in); Int8 recvBuf[UDP_BUF_LEN]; /* validate data */ if(sock < 0 || !header || !addr) return E_INVAL; /* recv header */ ret = recvfrom(sock, recvBuf, sizeof(recvBuf), 0, (struct sockaddr *)addr, &len); if(ret < 0) { ERRSTR("recv header data failed: %d", ret); return E_TRANS; } /* validate data */ if(*(Uint32 *)recvBuf != UDP_CMD_SYNC_START) { ERR("invalid sync start"); return E_CHECKSUM; } *header = *(UdpCmdHeader *)(recvBuf + sizeof(Uint32)); /* recv data */ if( header->dataLen > 0) { if(ret - sizeof(*header) < header->dataLen) { ERR("recv data len: %d, not equal to len in header: %d", ret - sizeof(*header), header->dataLen); return E_TRANS; } if(!buf || bufLen < header->dataLen) { ERR("buf not enough for addtive data"); return E_NOMEM; } memcpy(buf, recvBuf + sizeof(UdpCmd), header->dataLen); } return E_NO; }
/***************************************************************************** Prototype : display_osd_disable Description : disable osd layer Input : None Output : None Return Value : static Calls : Called By : History : 1.Date : 2012/9/5 Author : Sun Modification : Created function *****************************************************************************/ static Int32 display_osd_disable() { int fd; const char *devName[] = {OSD0_DEV, OSD1_DEV, FBVID0_DEV, FBVID1_DEV}; int i, err = E_NO; for(i = 0; i < ARRAY_SIZE(devName); ++i) { fd = open(devName[i], O_RDWR); if(fd < 0) { //ERRSTR("open %s failed", devName[i]); err = E_IO; continue; } if(ioctl(fd, FBIOBLANK, 1) < 0) { ERRSTR("disable window %s failed.", devName[i]); err = E_IO; } close(fd); } return err; }
static int spec_cap_test(int fd, int cnt) { int err; struct hdcam_spec_cap_cfg cfg; cfg.exposureTime = 4000; cfg.globalGain = 100; cfg.strobeCtrl = 0x03; cfg.aeMinExpTime = 100; cfg.aeMaxExpTime = 4000; cfg.aeMinGain = 0; cfg.aeMaxGain = 200; cfg.aeTargetVal = 70; cfg.flags = HDCAM_SPEC_CAP_AE_EN; err = ioctl(fd, IMGCTRL_S_SPECCAP, &cfg); if(err) { ERRSTR("set spec cap failed"); return E_IO; } int i; __u16 id; for(i = 0; i < cnt; ++i) { err = ioctl(fd, IMGCTRL_SPECTRIG, &id); if(err) break; DBG("<%d> spec trig next id: %u", i, (unsigned)id); usleep(100000); } if(!err) DBG("spec cap test success."); return err; }
/***************************************************************************** Prototype : display_buf_alloc Description : alloc buffer for display Input : DisplayHanlde hDisplay Output : None Return Value : static Calls : Called By : History : 1.Date : 2012/8/28 Author : Sun Modification : Created function *****************************************************************************/ static Int32 display_buf_alloc(DisplayHanlde hDisplay) { Uint32 size; CMEM_AllocParams *allocAttrs = &hDisplay->memAllocParams; Int32 i, err = E_NO; allocAttrs->alignment = 256; allocAttrs->flags = CMEM_NONCACHED; allocAttrs->type = CMEM_POOL; size = DISPLAY_BUF_SIZE; for(i = 0; i < DISPLAY_BUF_NUM; i++) { hDisplay->displayBuf[i].userAddr = CMEM_alloc(size, allocAttrs); if(!hDisplay->displayBuf[i].userAddr) { ERR("Alloc buffer mem failed."); err = E_NOMEM; break; } hDisplay->displayBuf[i].index = i; hDisplay->displayBuf[i].bufSize = size; hDisplay->displayBuf[i].phyAddr = 0; } /* request buffers from driver */ struct v4l2_requestbuffers req; req.count = DISPLAY_BUF_NUM; req.type = V4L2_BUF_TYPE_VIDEO_OUTPUT; req.memory = V4L2_MEMORY_USERPTR; err = ioctl(hDisplay->fdDisplay, VIDIOC_REQBUFS, &req); if(err < 0) { ERRSTR("cannot request buf"); return E_IO; } return err; }
/* test between process */ static void *transfer_thread(void *arg) { Bool ret = FALSE; int fd; int err = 0; TestParams *params = (TestParams *)arg; DBG("%s thread start!", params->chanName); fd = chan_open(params->devName, params->baseAddr, params->chanName); if(fd < 0) goto exit; int i = 0; int len = params->bufSize; char *buf_in = malloc(len + sizeof(SysMsg)); char *buf_out = malloc(len + sizeof(SysMsg)); SysMsg *msg_out = (SysMsg *)buf_out; char *data_out = buf_out + sizeof(SysMsg); SysMsg *msg_in = (SysMsg *)buf_in; char *data_in = buf_in + sizeof(SysMsg); assert(buf_in && buf_out); msg_out->cmd = 0; msg_out->dataLen = len; for(i = 0; i < len; ++i) data_out[i] = i; i= 0; struct timeval tmStart,tmEnd; float timeRd, timeWr; fd_set rdSet, wrSet; int fdMax; int errCnt = 0; uint32_t cmdBase = 0; DBG("%s, start read write loop!", params->chanName); while(1) { FD_ZERO(&rdSet); FD_SET(fd, &rdSet); FD_ZERO(&wrSet); FD_SET(fd, &wrSet); fdMax = fd + 1; /* recv msg */ memset(buf_in, 0, len); #if 1 err = select(fdMax, &rdSet, NULL, NULL, NULL); if(err < 0) { ERRSTR("%s, select err", params->chanName); usleep(1000); continue; } if(!FD_ISSET(fd, &rdSet)) { ERR("%s, fd is not set for rd", params->chanName); continue; } #endif //usleep(500000); bzero(data_in, len); gettimeofday(&tmStart,NULL); err = sys_commu_read(fd, msg_in, len + sizeof(SysMsg)); gettimeofday(&tmEnd,NULL); timeRd = 1000000*(tmEnd.tv_sec-tmStart.tv_sec)+tmEnd.tv_usec-tmStart.tv_usec; if(err) { ERR("<%d> %s, read from dsp err: %d", i, params->chanName, err); if(err != E_CHECKSUM) continue; } else { DBG("<%d> %s, got msg, cmd: %d, data len: %u", i, params->chanName, msg_in->cmd, msg_in->dataLen); if(cmdBase) assert(msg_in->cmd == cmdBase + 1); cmdBase = msg_in->cmd; } #if 1 err = select(fdMax, NULL, &wrSet, NULL, NULL); if(err < 0) { ERRSTR("%s, select err", params->chanName); usleep(1000); continue; } if(!FD_ISSET(fd, &wrSet)) { ERR("%s, fd is not set for wr", params->chanName); continue; } #endif /* echo msg back */ //*msg_out = *msg_in; gettimeofday(&tmStart,NULL); err = sys_commu_write(fd, msg_in); //msg_out gettimeofday(&tmEnd,NULL); timeWr = 1000000*(tmEnd.tv_sec-tmStart.tv_sec)+tmEnd.tv_usec-tmStart.tv_usec; if(err < 0) { ERR("%s, write err.", params->chanName); usleep(1000); continue; } DBG("<%d> %s, rw success, len: %d/%d, w/r time cost: %.2f-%.2f ms", i, params->chanName, msg_in->dataLen, msg_in->transLen, timeWr/1000, timeRd/1000); #if 0 if( msg_in->dataLen != msg_out->dataLen || memcmp(data_in, data_out, msg_in->dataLen) ) { ERR("\n<%d> %s, len diff: %d-%d, or mem cmp diff!\n", i, params->chanName, msg_out->dataLen, msg_in->dataLen); errCnt++; } else DBG("<%d> %s, rw success, len: %d/%d, time cost: %.2f-%.2f ms", i, params->chanName, msg_out->dataLen, msg_in->transLen, timeWr/1000, timeRd/1000); msg_out->cmd = i; //msg_out->dataLen = RAND(0, len); #endif usleep(1000); ++i; if(params->loopCnt > 0 && i > params->loopCnt) break; } ret = TRUE; exit: close(fd); free(buf_in); free(buf_out); DBG("%s, sys_commu, data trans err cnt: %d", params->chanName, errCnt); pthread_exit(0); }
/***************************************************************************** Prototype : buf_pool_create Description : create buffer pool Input : Uint32 bufSize Uint32 bufNum BufAllocAttrs *attrs Output : None Return Value : Calls : Called By : History : 1.Date : 2012/1/11 Author : Sun Modification : Created function *****************************************************************************/ BufPoolHandle buf_pool_create(Uint32 bufSize, Uint32 bufNum, BufAllocAttrs *attrs) { if(!bufSize || !bufNum) return NULL; BufPoolHandle hPool; /* Alloc memory for pool handle */ hPool = calloc(1, sizeof(BufPoolObj)); if(!hPool) { ERRSTR("Calloc buf pool obj failed."); return NULL; } /* Alloc memory for buf handle array */ hPool->pBufs = calloc(bufNum, sizeof(BufHandle)); if(!hPool->pBufs) { ERRSTR("Calloc buf handle failed."); goto exit; } /* Alloc buffers */ Int32 i; for(i = 0; i < bufNum; i++) { BufHandle hBuf; hBuf = buffer_alloc(bufSize, attrs); if(!hBuf) { ERR("Alloc buffer failed, allocated buf num: %d", hPool->bufNum); break; } hBuf->bufPool = (void *)hPool; hBuf->index = i; hBuf->flag = 0; hPool->bufNum++; hPool->pBufs[i] = hBuf; } if(hPool->bufNum <= 0) { ERR("Can't alloc any buffer..."); goto exit; } /* Init mutex and condition */ if(pthread_mutex_init(&hPool->mutex, NULL)) goto exit; if(pthread_cond_init(&hPool->cond, NULL)) goto exit; hPool->bufSize = bufSize; return hPool; exit: if(hPool && hPool->pBufs) free(hPool->pBufs); if(hPool) free(hPool); return NULL; }
static PyObject * _get_peer_alt_names (X509 *certificate) { /* this code follows the procedure outlined in OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() function to extract the STACK_OF(GENERAL_NAME), then iterates through the stack to add the names. */ int i, j; PyObject *peer_alt_names = Py_None; PyObject *v, *t; X509_EXTENSION *ext = NULL; GENERAL_NAMES *names = NULL; GENERAL_NAME *name; X509V3_EXT_METHOD *method; BIO *biobuf = NULL; char buf[2048]; char *vptr; int len; const unsigned char *p; if (certificate == NULL) return peer_alt_names; /* get a memory buffer */ biobuf = BIO_new(BIO_s_mem()); i = 0; while ((i = X509_get_ext_by_NID( certificate, NID_subject_alt_name, i)) >= 0) { if (peer_alt_names == Py_None) { peer_alt_names = PyList_New(0); if (peer_alt_names == NULL) goto fail; } /* now decode the altName */ ext = X509_get_ext(certificate, i); if(!(method = X509V3_EXT_get(ext))) { PyErr_SetString (PySSLErrorObject, ERRSTR("No method for internalizing subjectAltName!")); goto fail; } p = ext->value->data; if (method->it) names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, &p, ext->value->length, ASN1_ITEM_ptr(method->it))); else names = (GENERAL_NAMES*) (method->d2i(NULL, &p, ext->value->length)); for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { /* get a rendering of each name in the set of names */ name = sk_GENERAL_NAME_value(names, j); if (name->type == GEN_DIRNAME) { /* we special-case DirName as a tuple of tuples of attributes */ t = PyTuple_New(2); if (t == NULL) { goto fail; } v = PyUnicode_FromString("DirName"); if (v == NULL) { Py_DECREF(t); goto fail; } PyTuple_SET_ITEM(t, 0, v); v = _create_tuple_for_X509_NAME (name->d.dirn); if (v == NULL) { Py_DECREF(t); goto fail; } PyTuple_SET_ITEM(t, 1, v); } else { /* for everything else, we use the OpenSSL print form */ (void) BIO_reset(biobuf); GENERAL_NAME_print(biobuf, name); len = BIO_gets(biobuf, buf, sizeof(buf)-1); if (len < 0) { _setSSLError(NULL, 0, __FILE__, __LINE__); goto fail; } vptr = strchr(buf, ':'); if (vptr == NULL) goto fail; t = PyTuple_New(2); if (t == NULL) goto fail; v = PyUnicode_FromStringAndSize(buf, (vptr - buf)); if (v == NULL) { Py_DECREF(t); goto fail; } PyTuple_SET_ITEM(t, 0, v); v = PyUnicode_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1))); if (v == NULL) { Py_DECREF(t); goto fail; } PyTuple_SET_ITEM(t, 1, v); } /* and add that rendering to the list */ if (PyList_Append(peer_alt_names, t) < 0) { Py_DECREF(t); goto fail; } Py_DECREF(t); } } BIO_free(biobuf); if (peer_alt_names != Py_None) { v = PyList_AsTuple(peer_alt_names); Py_DECREF(peer_alt_names); return v; } else { return peer_alt_names; } fail: if (biobuf != NULL) BIO_free(biobuf); if (peer_alt_names != Py_None) { Py_XDECREF(peer_alt_names); } return NULL; }
int sram_load_segment ( int seg ) { int a; char path[PATH_MAX + 1]; FILE *f = sram_open(seg, "rb", path); DEBUGPRINT("MEM: SRAM: loading SRAM segment %02Xh from file %s" NL, seg, path); if (!f) { ERROR_WINDOW("Cannot open file for loading SRAM segment %02Xh because of file I/O error: %s\nFile name was: %s", seg, ERRSTR(), path); return 1; } a = fread(memory + (seg << 14), 0x4000, 1, f); if (a != 1) ERROR_WINDOW("Cannot load SRAM segment %02Xh because of file I/O error: %s\nFile name was: %s", seg, ERRSTR(), path); fclose(f); return a != 1; }
static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, enum py_ssl_server_or_client socket_type, enum py_ssl_cert_requirements certreq, enum py_ssl_version proto_version, char *cacerts_file) { PySSLObject *self; char *errstr = NULL; int ret; int verification_mode; self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ if (self == NULL) return NULL; self->peer_cert = NULL; self->ssl = NULL; self->ctx = NULL; self->Socket = NULL; /* Make sure the SSL error state is initialized */ (void) ERR_get_state(); ERR_clear_error(); if ((key_file && !cert_file) || (!key_file && cert_file)) { errstr = ERRSTR("Both the key & certificate files " "must be specified"); goto fail; } if ((socket_type == PY_SSL_SERVER) && ((key_file == NULL) || (cert_file == NULL))) { errstr = ERRSTR("Both the key & certificate files " "must be specified for server-side operation"); goto fail; } PySSL_BEGIN_ALLOW_THREADS if (proto_version == PY_SSL_VERSION_TLS1) self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ else if (proto_version == PY_SSL_VERSION_SSL3) self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ else if (proto_version == PY_SSL_VERSION_SSL2) self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ else if (proto_version == PY_SSL_VERSION_SSL23) self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ PySSL_END_ALLOW_THREADS if (self->ctx == NULL) { errstr = ERRSTR("Invalid SSL protocol variant specified."); goto fail; } if (certreq != PY_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = ERRSTR("No root certificates specified for " "verification of other-side certificates."); goto fail; } else { PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_load_verify_locations(self->ctx, cacerts_file, NULL); PySSL_END_ALLOW_THREADS if (ret != 1) { _setSSLError(NULL, 0, __FILE__, __LINE__); goto fail; } } } if (key_file) { PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM); PySSL_END_ALLOW_THREADS if (ret != 1) { _setSSLError(NULL, ret, __FILE__, __LINE__); goto fail; } PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_use_certificate_chain_file(self->ctx, cert_file); PySSL_END_ALLOW_THREADS if (ret != 1) { /* fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); */ if (ERR_peek_last_error() != 0) { _setSSLError(NULL, ret, __FILE__, __LINE__); goto fail; } } } /* ssl compatibility */ SSL_CTX_set_options(self->ctx, SSL_OP_ALL); verification_mode = SSL_VERIFY_NONE; if (certreq == PY_SSL_CERT_OPTIONAL) verification_mode = SSL_VERIFY_PEER; else if (certreq == PY_SSL_CERT_REQUIRED) verification_mode = (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT); SSL_CTX_set_verify(self->ctx, verification_mode, NULL); /* set verify lvl */ PySSL_BEGIN_ALLOW_THREADS self->ssl = SSL_new(self->ctx); /* New ssl struct */ PySSL_END_ALLOW_THREADS SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ /* If the socket is in non-blocking mode or timeout mode, set the BIO * to non-blocking mode (blocking is the default) */ if (Sock->sock_timeout >= 0.0) { /* Set both the read and write BIO's to non-blocking mode */ BIO_set_nbio(SSL_get_rbio(self->ssl), 1); BIO_set_nbio(SSL_get_wbio(self->ssl), 1); } PySSL_BEGIN_ALLOW_THREADS if (socket_type == PY_SSL_CLIENT) SSL_set_connect_state(self->ssl); else SSL_set_accept_state(self->ssl); PySSL_END_ALLOW_THREADS self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); return self; fail: if (errstr) PyErr_SetString(PySSLErrorObject, errstr); Py_DECREF(self); return NULL; }
/* test between process */ static Bool main_loop(TestParams *params) { Bool ret = FALSE; #ifndef PARENT_ONLY pid_t pid; if((pid = fork()) < 0) { ERRSTR("fork err"); goto exit; } else if(pid == 0) { /* child */ MsgHandle hMsg0 = msg_create(CHILD_MSG, PARENT_MSG, 0); if(!hMsg0) { ERR("create child msg failed"); goto exit; } sleep(1); /* we just send msg */ Int32 cnt0; MsgData msgData0; Int32 err0, dataLen0; DBG("msg test client start..."); for(cnt0 = 0; cnt0 < params->loopCnt; cnt0++) { memset(&msgData0.buf, 0, sizeof(msgData0.buf)); msgData0.header.cmd = cnt0; msgData0.header.index = cnt0; msgData0.header.type = MSG_TYPE_REQU; msgData0.header.dataLen = sprintf(msgData0.buf, "child msg [%d]", cnt0) + 1; //msgData0.header.dataLen= ROUND_UP(msgData0.header.dataLen,4); dataLen0 = msgData0.header.dataLen + sizeof(msgData0.header); err0 = msg_send(hMsg0, NULL, &msgData0.header, 0); if(err0) ERR("<%d> child send msg err", cnt0); else DBG("<%d> child send msg ok...", cnt0); err0 = msg_recv(hMsg0, &msgData0.header, sizeof(msgData0), 0); if(err0 < 0) { ERR("child wait reply err"); } else DBG("<%d> child recv reply: %s", cnt0, msgData0.buf); usleep(100000); } DBG("child exit"); } else #endif { /* parent */ MsgHandle hMsg1 = msg_create(PARENT_MSG, CHILD_MSG, 0); if(!hMsg1) { ERR("create parent msg failed"); goto exit; } sleep(1); /* we just send msg */ Int32 cnt1; MsgData msgData1; Int32 err1; DBG("msg test server start..."); for(cnt1 = 0; cnt1 < params->loopCnt; cnt1++) { memset(&msgData1.buf, 0, sizeof(msgData1.buf)); err1 = msg_recv(hMsg1, &msgData1.header, sizeof(msgData1), 0); if(err1 < 0) { ERR("<%d> parent recv msg err", cnt1); continue; } else DBG("<%d> parent recv msg: %s...", cnt1, msgData1.buf); usleep(100000); /* reply msg */ msgData1.header.type = MSG_TYPE_RESP; err1 = msg_send(hMsg1, NULL, &msgData1.header, 0); if(err1 < 0) ERR("<%d> send reply msg err", cnt1); else DBG("<%d> parent reply msg ok"); } DBG("parent exit"); } ret = TRUE; exit: return ret; }
/* This function also re-initializes the whole memory! Do not call it after you defined RAM for the system, but only before! */ int roms_load ( void ) { int seg, last = 0; char path[PATH_MAX + 1]; if (reloading) // in case of already defined (reloading) memory model, we want to back our SRAM segments up - if any at all ... sram_save_all_segments(); for (seg = 0; seg < 0x100; seg++ ) { memory_segment_map[seg] = (seg >= 0xFC ? VRAM_SEGMENT : UNUSED_SEGMENT); // 64K VRAM is default, you cannot override that! if (reloading && rom_name_tab[seg]) free((void*)rom_name_tab[seg]); // already defined (reloading) situation, we want to free used memory as well rom_name_tab[seg] = NULL; } reloading = 1; // set reloading flag, in next invocation of roms_load(), it will be done in config reload mode! memset(memory, 0xFF, 0x400000); xep_rom_seg = -1; for (seg = 0; seg < 0x100; seg++ ) { void *option = config_getopt("rom", seg, NULL); if (option) { const char *name; int lseg = seg; FILE *f; config_getopt_pointed(option, &name); if (!strcasecmp(name, "XEP") && seg) { if (memory_segment_map[seg] == UNUSED_SEGMENT) { DEBUG("CONFIG: ROM: segment %02Xh assigned to internal XEP ROM" NL, seg); xep_rom_seg = seg; memory_segment_map[seg] = XEPROM_SEGMENT; } else ERROR_WINDOW("XEP ROM forced segment assignment cannot be done since segment %02X is not unused", seg); continue; } DEBUG("CONFIG: ROM: segment %02Xh file %s" NL, seg, name); f = open_emu_file(name, "rb", path); if (f == NULL) { ERROR_WINDOW("Cannot open ROM image \"%s\" (to be used from segment %02Xh): %s", name, seg, ERRSTR()); if (!strcmp(name, COMBINED_ROM_FN)) { // this should be the auto-install functionality, with downloading stuff? } return -1; } DEBUG("CONFIG: ROM: ... file path is %s" NL, path); rom_name_tab[seg] = SDL_strdup(path); CHECK_MALLOC(rom_name_tab[seg]); for (;;) { int ret; // Note: lseg overflow is not needed to be tested, as VRAM marks will stop reading of ROM image in the worst case ... if (memory_segment_map[lseg] != UNUSED_SEGMENT) { fclose(f); forget_emu_file(path); ERROR_WINDOW("While reading ROM image \"%s\" into segment %02Xh: already used segment (\"%s\")!", path, lseg, memory_segment_map[lseg]); return -1; } ret = fread(memory + (lseg << 14), 1, 0x4000, f); if (ret) DEBUG("CONFIG: ROM: ... trying read 0x4000 bytes in segment %02Xh, result is %d" NL, lseg, ret); if (ret < 0) { ERROR_WINDOW("Cannot read ROM image \"%s\" (to be used in segment %02Xh): %s", path, lseg, ERRSTR()); fclose(f); forget_emu_file(path); return -1; } else if (ret == 0) { if (lseg == seg) { fclose(f); forget_emu_file(path); ERROR_WINDOW("Null-sized ROM image \"%s\" (to be used in segment %02Xh).", path, lseg); return -1; } break; } else if (ret != 0x4000) { fclose(f); forget_emu_file(path); ERROR_WINDOW("Bad ROM image \"%s\": not multiple of 16K bytes!", path); return -1; } // check if ROM image contains XEP128_ROM segment signature, if so, try to use XEP ROM from here if (!memcmp(memory + (lseg << 14), "XEP__ROM", 8) && xep_rom_seg == -1) { xep_rom_seg = lseg; memory_segment_map[lseg] = XEPROM_SEGMENT; } else memory_segment_map[lseg] = ROM_SEGMENT; if (lseg > last) last = lseg; if (ret != 0x4000) break; lseg++; } fclose(f); forget_emu_file(path); } else if (!seg) { ERROR_WINDOW("Fatal ROM image error: No ROM defined for segment 00h, no EXOS is requested!"); return -1; } } /* XEP ROM: guess where to place it, or disable it ... */ if (config_getopt_int("xeprom")) { // XEP ROM is enabled with 'xeprom' directive if (xep_rom_seg == -1) { // not assigned manually, try to find a place for it ... xep_rom_seg = last + 1; // ... with simply using the segment after the last used ROM segment DEBUGPRINT("CONFIG: ROM: automatic XEP ROM image placer selected segment is %02Xh" NL, xep_rom_seg); } } else { // XEP ROM is disabled (with 'xeprom' directive), _IF_ it was not assigned manually if (xep_rom_seg == -1) { DEBUGPRINT("CONFIG: ROM: XEP ROM is disabled by configuration!" NL); INFO_WINDOW("XEP internal ROM image is disabled by configuration.\nXep128 will work, but no XEP feature will be available."); } } /* XEP ROM: now install our internal ROM, if it's allowed/OK to do so */ if (xep_rom_seg > 0) { if (memory_segment_map[xep_rom_seg] == UNUSED_SEGMENT || memory_segment_map[xep_rom_seg] == XEPROM_SEGMENT) { xep_rom_addr = xep_rom_seg << 14; memset(memory + xep_rom_addr, 0, 0x4000); memcpy(memory + xep_rom_addr, xep_rom_image, sizeof xep_rom_image); memory_segment_map[xep_rom_seg] = XEPROM_SEGMENT; xep_set_default_device_name(NULL); DEBUGPRINT("CONFIG: ROM: XEP internal ROM image has been installed in segment %02Xh" NL, xep_rom_seg); } else { DEBUGPRINT("CONFIG: ROM: XEP internal ROM image CANNOT be installed because segment %02Xh is used!!" NL, xep_rom_seg); ERROR_WINDOW("XEP internal ROM image cannot be installed.\nXep128 will work, but no XEP feature will be available."); xep_rom_seg = -1; } } else xep_rom_seg = -1; return 0; }
static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) { int ret; int err; int sockstate; /* Actually negotiate SSL connection */ /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ sockstate = 0; do { PySocketSockObject *sock = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); if (((PyObject*)sock) == Py_None) { _setSSLError("Underlying socket connection gone", PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); return NULL; } PySSL_BEGIN_ALLOW_THREADS ret = SSL_do_handshake(self->ssl); err = SSL_get_error(self->ssl, ret); PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { return NULL; } if (err == SSL_ERROR_WANT_READ) { sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { sockstate = check_socket_and_wait_for_timeout(sock, 1); } else { sockstate = SOCKET_OPERATION_OK; } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; } } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); if (ret < 1) return PySSL_SetError(self, ret, __FILE__, __LINE__); self->ssl->debug = 1; if (self->peer_cert) X509_free (self->peer_cert); PySSL_BEGIN_ALLOW_THREADS self->peer_cert = SSL_get_peer_certificate(self->ssl); PySSL_END_ALLOW_THREADS Py_INCREF(Py_None); return Py_None; }
LRESULT WINAPI SendMessage(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) { #ifdef STRICT WNDPROC lpfnWndProc; #else FARPROC lpfnWndProc; #endif DWORD rc; BOOL cInSendMessage; MSG msg; HWND32 hWnd32; #ifdef DEBUG memset((LPSTR)&msg,'\0',sizeof(MSG)); #endif if(hWnd == HWND_BROADCAST) { msg.message = wMsg; msg.wParam = wParam; msg.lParam = lParam; /*send to all top level windows */ return EnumWindows((WNDENUMPROC)MultiSendMsg,(LONG)&msg); } /* * Is this a valid window? */ if (!(hWnd32 = CHECKHWND32(hWnd))) return 0; /* * Does the window have a valid task? */ if (GetWindowTask(hWnd) == 0 || !TWIN_IsLiveTask(GetWindowTask(hWnd))) { RELEASEWININFO(hWnd32); return 0; } /* * Is this window dead? */ if (hWnd32->dwWinFlags & WFDEAD) { RELEASEWININFO(hWnd32); return 0; } /* * Window is a good destination. Intertask send? */ if (hWnd != 0 && GetWindowTask(hWnd) != GetCurrentTask()) { ITSMINFO smse; /* save current InSendMessage Flag */ cInSendMessage = bInSendMessage; /* we are now in sendmessage */ bInSendMessage = TRUE; smse.hSendingTask = GetCurrentTask(); smse.hReceivingTask = GetWindowTask(hWnd); smse.msg.hwnd = hWnd; smse.msg.message = wMsg; smse.msg.wParam = wParam; smse.msg.lParam = lParam; smse.bSendReceived = FALSE; smse.bSendCompleted = FALSE; smse.lpPrev = lpSendMessageStack; lpSendMessageStack = &smse; DirectedYield(smse.hReceivingTask); while (!smse.bSendCompleted) { TWIN_ReceiveMessage(TRUE); } lpSendMessageStack = smse.lpPrev; /* back to what it was before... */ bInSendMessage = cInSendMessage; RELEASEWININFO(hWnd32); return smse.lResult; } if ((lpfnWndProc = #ifdef STRICT (WNDPROC) #else (FARPROC) #endif GetWindowLong(hWnd, GWL_WNDPROC)) == NULL) { ERRSTR((LF_WARNING,"SendMessage: Null wndproc!\n")); RELEASEWININFO(hWnd32); return(0L); } /* save current InSendMessage Flag */ cInSendMessage = bInSendMessage; /* we are now in sendmessage */ bInSendMessage = TRUE; if (lpHookList[WH_CALLWNDPROC+1]) { ATOM atmClassName; HOOKINFO hki; if ((atmClassName = GetClassWord(hWnd,GCW_ATOM)) != atmGlobalLookup[LOOKUP_FRAME]) { hki.hWnd = hWnd; hki.msg = wMsg; hki.wParam = wParam; hki.lParam = lParam; msg.hwnd = hWnd; msg.message = wMsg; msg.wParam = wParam; msg.lParam = lParam; lpHookList[WH_CALLWNDPROC+1]->lpfnHookProc(0,0,(LPARAM)&hki); } } rc = TWIN_CallWindowProc(lpfnWndProc,0,hWnd, wMsg, wParam, lParam); RELEASEWININFO(hWnd32); /* back to what it was before... */ bInSendMessage = cInSendMessage; return rc; }
int sram_save_segment ( int seg ) { int a; char path[PATH_MAX + 1]; FILE *f = sram_open(seg, "wb", path); DEBUGPRINT("MEM: SRAM: saving SRAM segment %02Xh to file %s" NL, seg, path); if (!f) { ERROR_WINDOW("Cannot create file for saving SRAM segment %02Xh because of file I/O error: %s\nFile name was: %s", seg, ERRSTR(), path); return 1; } a = fwrite(memory + (seg << 14), 0x4000, 1, f); if (a != 1) ERROR_WINDOW("Cannot save SRAM segment %02Xh because of file I/O error: %s\nFile name was: %s", seg, ERRSTR(), path); fclose(f); return a != 1; }
/***************************************************************************** Prototype : main_loop Description : main loop for cam ctrl server Input : CamCtrlSrvEnv *envp Output : None Return Value : static Calls : Called By : History : 1.Date : 2012/4/23 Author : Sun Modification : Created function *****************************************************************************/ static Int32 main_loop(CamCtrlSrvEnv *envp) { int ret = E_NO; Bool exit = FALSE; int listenSock, udpScok, fdMax; fd_set rdSet; UdpProcEnv udpProcEnv; /* alloc buffer for communication */ envp->transBuf = calloc(1, envp->bufLen); assert(envp->transBuf); /* create socket */ listenSock = socket_tcp_server(envp->tcpPort, CAM_CTRL_LISTEN_NUM); if(listenSock < 0) { ERR("create server socket failed"); return E_IO; } /* set to non-blocking and use select for wait */ set_sock_block(listenSock, FALSE); /* create udp server socket */ udpScok = socket_udp_server(envp->udpPort); if(udpScok < 0) { ERR("create udp server socket failed"); return E_IO; } /* set timeout */ set_sock_send_timeout(udpScok, CAM_CTRL_TIMEOUT); set_sock_recv_timeout(udpScok, CAM_CTRL_TIMEOUT); udpProcEnv.cmdListenPort = envp->tcpPort; udpProcEnv.needReboot = FALSE; /* create icam ctrl handle */ envp->hCamCtrl = icam_ctrl_create(CAM_CTRL_MSG, 0, CAM_CTRL_TIMEOUT); if(!envp->hCamCtrl) { ERR("create cam ctrl handle failed"); ret = E_IO; goto quit; } /* init mutex for sync */ pthread_mutex_init(&envp->mutex, NULL); /* ignore signal when socket is closed by server */ signal(SIGPIPE, SIG_IGN); DBG("%s, port %u waiting for connection...", PROGRAM_NAME, envp->tcpPort); /* choose max fd */ fdMax = MAX(listenSock, udpScok) + 1; while(!exit) { /* wait data ready */ FD_ZERO(&rdSet); FD_SET(listenSock, &rdSet); FD_SET(udpScok, &rdSet); ret = select(fdMax, &rdSet, NULL, NULL, NULL); if(ret < 0 && errno != EINTR) { ERRSTR("select err"); break; } /* no data ready */ if(!ret) continue; /* check which is ready */ if(FD_ISSET(listenSock, &rdSet)){ /* accept connection */ tcp_accept(envp, listenSock); } if(FD_ISSET(udpScok, &rdSet)){ /* process udp cmd */ udp_process(udpScok, &udpProcEnv); if(udpProcEnv.needReboot) break; } } quit: if(listenSock > 0) close(listenSock); if(envp->hCamCtrl) icam_ctrl_delete(envp->hCamCtrl); pthread_mutex_destroy(&envp->mutex); free(envp->transBuf); if(udpProcEnv.needReboot) system("shutdown -r now\n"); return ret; }
static Int32 raw_trans_test() { Int8 bufTx[1024], bufRx[1024]; MsgHandle hMsgTx = msg_create("/tmp/RawSend", "/tmp/RawRecv", 0); MsgHandle hMsgRx = msg_create("/tmp/RawRecv", "/tmp/RawSend", 0); assert(hMsgTx && hMsgRx); int fdTx, fdRx; fdTx = msg_get_fd(hMsgTx); fdRx = msg_get_fd(hMsgRx); Int32 i; for(i = 0; i < sizeof(bufTx); i++) { bufTx[i] = i; } struct sockaddr_un serverAddr; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sun_family = AF_UNIX; strncpy(serverAddr.sun_path, "/tmp/RawRecv", sizeof(serverAddr.sun_path)); if(sendto( fdTx, bufTx, 64, 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 64) { ERRSTR("<0> sendto data err"); return E_IO; } if(sendto( fdTx, bufTx, 128, 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 128) { ERRSTR("<1> sendto data err"); return E_IO; } if(sendto( fdTx, bufTx, 256, 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 256) { ERRSTR("<2> sendto data err"); return E_IO; } Int32 rcv; socklen_t len; len = sizeof(serverAddr); rcv = recvfrom(fdRx, bufRx, 512, 0, (struct sockaddr *)&serverAddr, &len); DBG("recv len %d", rcv); rcv = recvfrom(fdRx, bufRx, 512, 0, (struct sockaddr *)&serverAddr, &len); DBG("recv len %d", rcv); rcv = recvfrom(fdRx, bufRx, 512, 0, (struct sockaddr *)&serverAddr, &len); DBG("recv len %d", rcv); msg_delete(hMsgTx); msg_delete(hMsgRx); return E_NO; }