//----------------------------------------------------------------// void MOAIHttpTaskCurl::SetCookieSrc ( const char *file ) { CURLcode result = curl_easy_setopt( this->mEasyHandle, CURLOPT_COOKIEJAR, file ); PrintError ( result ); }
s32 DeviceOpen() { char tempname[256]; UINT drivetype; DWORD errcode; if(conf.devicename[0] == 0) return(-1); if(devicehandle != NULL) return(0); #ifdef VERBOSE_FUNCTION_DEVICE PrintLog("CDVDiso device: DeviceOpen()"); #endif /* VERBOSE_FUNCTION_DEVICE */ // InitConf(); // LoadConf(); // Should be done at least once before this call // Root Directory reference if(conf.devicename[1] == 0) { sprintf(tempname, "%s:\\", conf.devicename); } else if((conf.devicename[1] == ':') && (conf.devicename[2] == 0)) { sprintf(tempname, "%s\\", conf.devicename); } else { sprintf(tempname, "%s", conf.devicename); } // ENDIF- Not a single drive letter? (or a letter/colon?) Copy the name in. drivetype = GetDriveType(tempname); if(drivetype != DRIVE_CDROM) { #ifdef VERBOSE_WARNING_DEVICE PrintLog("CDVDiso device: Not a CD-ROM!"); PrintLog("CDVDiso device: (Came back: %u)", drivetype); errcode = GetLastError(); if(errcode > 0) PrintError("CDVDiso device", errcode); #endif /* VERBOSE_WARNING_DEVICE */ return(-1); } // ENDIF- Not a CD-ROM? Say so! // Hmm. Do we want to include DRIVE_REMOVABLE... just in case? // Device Reference if(conf.devicename[1] == 0) { sprintf(tempname, "\\\\.\\%s:", conf.devicename); } else if((conf.devicename[1] == ':') && (conf.devicename[2] == 0)) { sprintf(tempname, "\\\\.\\%s", conf.devicename); } else { sprintf(tempname, "%s", conf.devicename); } // ENDIF- Not a single drive letter? (or a letter/colon?) Copy the name in. devicehandle = CreateFile(tempname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if(devicehandle == INVALID_HANDLE_VALUE) { #ifdef VERBOSE_WARNING_DEVICE PrintLog("CDVDiso device: Couldn't open device read-only! Read-Write perhaps?"); errcode = GetLastError(); PrintError("CDVDiso device", errcode); #endif /* VERBOSE_WARNING_DEVICE */ devicehandle = CreateFile(tempname, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN, NULL); } // ENDIF- Couldn't open for read? Try read/write (for those drives that insist) if(devicehandle == INVALID_HANDLE_VALUE) { #ifdef VERBOSE_WARNING_DEVICE PrintLog("CDVDiso device: Couldn't open device!"); errcode = GetLastError(); PrintError("CDVDiso device", errcode); #endif /* VERBOSE_WARNING_DEVICE */ devicehandle = NULL; return(-1); } // ENDIF- Couldn't open that way either? Abort. waitevent.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(waitevent.hEvent == INVALID_HANDLE_VALUE) { #ifdef VERBOSE_WARNING_DEVICE PrintLog("CDVDiso device: Couldn't open event handler!"); errcode = GetLastError(); PrintError("CDVDiso device", errcode); #endif /* VERBOSE_WARNING_DEVICE */ waitevent.hEvent = NULL; CloseHandle(devicehandle); devicehandle = NULL; } // ENDIF- Couldn't create an "Wait for I/O" handle? Abort. // More here... DeviceIoControl? for Drive Capabilities // DEVICE_CAPABILITIES? ////// Should be done just after the first DeviceOpen(); // InitDisc(); // ? // DeviceTrayStatus(); return(0); } // END DeviceOpen()
//Transmission and reception of HTTP protocol size_t __fastcall HTTPRequest( const char *OriginalSend, const size_t SendSize, char *OriginalRecv, const size_t RecvSize) { //Initialization SOCKET_DATA HTTPSocketData = {0}; memset(OriginalRecv, 0, RecvSize); //Socket initialization if (Parameter.HTTP_Address_IPv6.Storage.ss_family > 0 && //IPv6 (Parameter.HTTP_Protocol == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv6 || //Auto select Parameter.HTTP_Protocol == REQUEST_MODE_IPV6 || //IPv6 Parameter.HTTP_Protocol == REQUEST_MODE_IPV4 && Parameter.HTTP_Address_IPv4.Storage.ss_family == 0)) //Non-IPv4 { HTTPSocketData.SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&HTTPSocketData.SockAddr)->sin6_addr = Parameter.HTTP_Address_IPv6.IPv6.sin6_addr; ((PSOCKADDR_IN6)&HTTPSocketData.SockAddr)->sin6_port = Parameter.HTTP_Address_IPv6.IPv6.sin6_port; HTTPSocketData.AddrLen = sizeof(sockaddr_in6); HTTPSocketData.Socket = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); } else if (Parameter.HTTP_Address_IPv4.Storage.ss_family > 0 && //IPv4 (Parameter.HTTP_Protocol == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv4 || //Auto select Parameter.HTTP_Protocol == REQUEST_MODE_IPV4 || //IPv4 Parameter.HTTP_Protocol == REQUEST_MODE_IPV6 && Parameter.HTTP_Address_IPv6.Storage.ss_family == 0)) //Non-IPv6 { HTTPSocketData.SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&HTTPSocketData.SockAddr)->sin_addr = Parameter.HTTP_Address_IPv4.IPv4.sin_addr; ((PSOCKADDR_IN)&HTTPSocketData.SockAddr)->sin_port = Parameter.HTTP_Address_IPv4.IPv4.sin_port; HTTPSocketData.AddrLen = sizeof(sockaddr_in); HTTPSocketData.Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } else { return EXIT_FAILURE; } //Socket check if (!SocketSetting(HTTPSocketData.Socket, SOCKET_SETTING_INVALID_CHECK, nullptr)) { PrintError(LOG_ERROR_NETWORK, L"HTTP socket initialization error", 0, nullptr, 0); return EXIT_FAILURE; } //Non-blocking mode setting if (!SocketSetting(HTTPSocketData.Socket, SOCKET_SETTING_NON_BLOCKING_MODE, nullptr)) { shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); PrintError(LOG_ERROR_NETWORK, L"Socket non-blocking mode setting error", 0, nullptr, 0); return EXIT_FAILURE; } //Selecting structure setting fd_set ReadFDS = {0}, WriteFDS = {0}; timeval Timeout = {0}; //HTTP CONNECT request if (Parameter.HTTP_TargetDomain == nullptr || Parameter.HTTP_Version == nullptr || !HTTP_CONNECTRequest(&HTTPSocketData, &ReadFDS, &WriteFDS, &Timeout, OriginalRecv, RecvSize)) { shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); return EXIT_FAILURE; } //Add length of request packet(It must be written in header when transpot with TCP protocol). std::shared_ptr<char> SendBuffer(new char[LARGE_PACKET_MAXSIZE]()); memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); memcpy_s(SendBuffer.get(), RecvSize, OriginalSend, SendSize); SSIZE_T RecvLen = AddLengthDataToHeader(SendBuffer.get(), SendSize, RecvSize); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) { shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); return EXIT_FAILURE; } //Socket timeout setting #if defined(PLATFORM_WIN) Timeout.tv_sec = Parameter.HTTP_SocketTimeout / SECOND_TO_MILLISECOND; Timeout.tv_usec = Parameter.HTTP_SocketTimeout % SECOND_TO_MILLISECOND * MICROSECOND_TO_MILLISECOND; #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) Timeout.tv_sec = Parameter.HTTP_SocketTimeout.tv_sec; Timeout.tv_usec = Parameter.HTTP_SocketTimeout.tv_usec; #endif //Data exchange RecvLen = ProxySocketSelecting(HTTPSocketData.Socket, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), RecvLen, OriginalRecv, RecvSize, DNS_PACKET_MINSIZE, nullptr); shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); //Server response check if (RecvLen >= (SSIZE_T)DNS_PACKET_MINSIZE && ntohs(((uint16_t *)OriginalRecv)[0]) >= DNS_PACKET_MINSIZE && RecvLen >= ntohs(((uint16_t *)OriginalRecv)[0])) { RecvLen = ntohs(((uint16_t *)OriginalRecv)[0]); memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(uint16_t), RecvLen); //Responses check RecvLen = CheckResponseData( REQUEST_PROCESS_HTTP, OriginalRecv, RecvLen, RecvSize, nullptr); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) return EXIT_FAILURE; //Mark DNS cache. if (Parameter.CacheType > 0) MarkDomainCache(OriginalRecv, RecvLen); return RecvLen; } return EXIT_FAILURE; }
/*! \brief Create a structure to store the parameters of the joints. * * \param type: the joint type. * * \return the joint data. */ p3d_read_jnt_data * p3d_create_read_jnt_data(p3d_type_joint type) { p3d_read_jnt_data * data; int i; data = MY_ALLOC(p3d_read_jnt_data, 1); if (data == NULL) { PrintError(("Not enough memory !!!\n")); return NULL; } data->type = type; p3d_jnt_get_nb_param(type, &(data->nb_dof), &(data->nb_param)); data->v = MY_ALLOC(double, data->nb_dof); data->v_pos0 = MY_ALLOC(double, data->nb_dof); data->vmin = MY_ALLOC(double, data->nb_dof); data->vmax = MY_ALLOC(double, data->nb_dof); data->vmin_rand = MY_ALLOC(double, data->nb_dof); data->vmax_rand = MY_ALLOC(double, data->nb_dof); data->velocity_max = MY_ALLOC(double, data->nb_dof); data->acceleration_max = MY_ALLOC(double, data->nb_dof); data->jerk_max = MY_ALLOC(double, data->nb_dof); data->torque_max = MY_ALLOC(double, data->nb_dof); data->is_user = MY_ALLOC(int, data->nb_dof); data->is_active_for_planner = MY_ALLOC(int, data->nb_dof); if ((data->nb_dof>0) && ((data->v == NULL) || (data->v_pos0 == NULL) || (data->vmin == NULL) || (data->vmax == NULL) || (data->vmin_rand == NULL) || (data->vmax_rand == NULL) || (data->is_user == NULL) || (data->is_active_for_planner == NULL) || ( data->velocity_max == NULL) || (data->acceleration_max == NULL) || ( data->jerk_max == NULL) )) { PrintError(("Not enough memory !!!\n")); return NULL; } data->flag_v = FALSE; data->flag_v_pos0 = FALSE; data->flag_vmin = FALSE; data->flag_vmax = FALSE; data->flag_velocity_max = FALSE; data->flag_acceleration_max = FALSE; data->flag_jerk_max = FALSE; data->flag_torque_max = FALSE; data->flag_vmin_rand = FALSE; data->flag_vmax_rand = FALSE; data->flag_is_user = FALSE; data->flag_is_active_for_planner = FALSE; for(i=0; i<data->nb_dof; i++) { data->v[i] = 0.0; } data->param = MY_ALLOC(double, data->nb_param); if ((data->nb_param>0) && (data->param == NULL)) { PrintError(("Not enough memory !!!\n")); return NULL; } data->flag_param = FALSE; data->flag_pos = FALSE; data->flag_relative_pos = FALSE; data->prev_jnt = 0; data->flag_prev_jnt = FALSE; data->flag_name = FALSE; data->nb_links = 0; data->link_array = NULL; return data; }
int TScaner::Scaner(TypeLex l) { int fl=0; int fl_len_const=0; int i; // текущая длина лексемы for (i=0;i<MAX_LEX;i++) l[i]=0; //очистили поле лексемы i=0; // лексема заполняется с позиции i start: // все игнорируемые элементы: while((t[uk]==' ') || (t[uk]=='\n') || (t[uk]=='\t')) { /////////////////////// if (t[uk]=='\n'){ if(i_mas==0){ mass_str[i_mas++]=uk; } else{ for(int j=0;j<i_mas;j++) if(mass_str[j]==uk){ fl=1; break; } if(!fl){ mass_str[i_mas++]=uk; } fl=0; } stroka++; } ////////////////////// uk++; } // пропуск незначащих элементов if ( (t[uk]=='/') && (t[uk+1]=='/') ) { // начался комментарий, надо пропустить текст до "\n" uk=uk+2; while ( (t[uk]!='\n')/*&&(t[uk]!='\0')&&(t[uk]!='#')*/) uk++; /////////////////// if (t[uk]=='\n'){ if(i_mas==0){ mass_str[i_mas++]=uk; } else{ for(int j=0;j<i_mas;j++) if(mass_str[j]==uk){ fl=1; break; } if(!fl){ mass_str[i_mas++]=uk; } fl=0; } //stroka++; } ////////////////// goto start; } // пропуск незначащих элементов if ( (t[uk]=='/') && (t[uk+1]=='*') ) { uk=uk+2;//////////////////////////////////////////////////////////////// // начался комментарий, надо пропустить текст до */ while ( (t[uk]!='*')||(t[uk+1]!='/')) { if(t[uk]=='#'||t[uk]=='\0') {fl=1; break;} uk++; } if(fl){ PrintError("Неоконченный комментарий",l); return TError; } else{ uk=uk+2;} goto start; } /*uk=uk+2; while ((t[uk]!='*')&&(t[uk+1]!='/')) uk++; uk=uk+2; goto start; }*/ if (t[uk]=='\0') {l[0]='#'; return TEnd;} if (Number) { l[i++]=t[uk++]; while (Number) if (i<=MAX_CONST) l[i++]=t[uk++]; else {uk++; fl_len_const=1;} if(!fl_len_const) return TConstInt10; else {PrintError("Длинная числовая константа",l); return TError; } } else if(LetterBig||LetterSmall){ //начинается идентификатор l[i++]=t[uk++]; while(Number||LetterBig||LetterSmall) if (i<MAX_LEX-1) l[i++]=t[uk++]; else uk++; //длинный идентификатор обрезали int j; // проверка на ключевое слово for (j=0; j<MAX_KEYW; j++) if (strcmp(l,Keyword[j])==0) return IndexKeyword[j]; return TIdent; } else if (t[uk]=='\'') { uk++; // не будем включать кавычки константу if (t[uk+1]!='\'') { while( (t[uk]!='\'')&& (t[uk]!='\n')&& (t[uk]!='\0') && (t[uk]!='#') ){ if (i<MAX_LEX-1) l[i++]=t[uk++]; else uk++; // длинный идентификатор обрезали } ///////////////////// if (t[uk]=='\n'){ if(i_mas==0){ mass_str[i_mas++]=uk; } else{ for(int j=0;j<i_mas;j++) if(mass_str[j]==uk){ fl=1; break; } if(!fl){ mass_str[i_mas++]=uk; } fl=0; } //stroka++; //simvol=1; } /////////////////////// if(t[uk]=='\'') uk++; PrintError("Неверная символьная константа",l); return TError; } else { if (t[uk]!='\n'&&t[uk]!='\0') {l[i++]=t[uk++]; uk++; // закрывающая кавычка return TConstSymvol; }else { //simvol=simvol-i+1; if(t[uk]=='\n'){ if(i_mas==0){ mass_str[i_mas++]=uk; } else{ for(int j=0;j<i_mas;j++) if(mass_str[j]==uk){ fl=1; break; } if(!fl){ mass_str[i_mas++]=uk; } } //simvol=1; //stroka++; } //else { PrintError("Неверная символьная константа",l); return TError; } } } ///////////////////////////////// else if (t[uk]==',') { l[i++]=t[uk++]; return TZap; } else if (t[uk]==';') { l[i++]=t[uk++]; return TTochkaZap; } else if (t[uk]=='(') { l[i++]=t[uk++]; return TLSkob; } else if (t[uk]==')') { l[i++]=t[uk++]; return TRSkob; } else if (t[uk]=='{') { l[i++]=t[uk++]; return TLFigScob; } else if (t[uk]=='}') { l[i++]=t[uk++]; return TRFigScob; } else if (t[uk]=='[') { l[i++]=t[uk++]; return TLKvScob; } else if (t[uk]==']') { l[i++]=t[uk++]; return TRKvScob; } else if (t[uk]=='+') { l[i++]=t[uk++]; if (t[uk]=='+') { l[i++]=t[uk++]; return TPlusPlus; } return TPlus; } else if (t[uk]=='-') { l[i++]=t[uk++]; if (t[uk]=='-') { l[i++]=t[uk++]; return TMinusMinus; }return TMinus; } else if (t[uk]=='*') { l[i++]=t[uk++]; return TMul; } else if (t[uk]=='/') { l[i++]=t[uk++]; return TDiv; } else if (t[uk]=='%') { l[i++]=t[uk++]; return TMod; } else if (t[uk]=='<') { l[i++]=t[uk++]; if (t[uk]=='=') { l[i++]=t[uk++]; return TMensheRavno; }return TMenshe; } else if (t[uk]=='>') { l[i++]=t[uk++]; if (t[uk]=='=') { l[i++]=t[uk++]; return TBolsheRavno; }return TBolshe; } else if (t[uk]=='!') { l[i++]=t[uk++]; if (t[uk]=='=') { l[i++]=t[uk++]; return TNeRavno ; } else { PrintError("Неверный символ",l); // ошибка return TError;} } else if (t[uk]=='=') { l[i++]=t[uk++]; if (t[uk]=='=') { l[i++]=t[uk++]; return TRavno; } else return TPris; } else { PrintError("Неверный символ",l); // ошибка //uk++; l[i++]=t[uk++]; //а то когда ошибку выводит, не выводит символ return TError; } }
bool j1Console::ProcessString(const char* input) { bool ret = false; last_message.Clear(); if(input != nullptr && strlen(input) > 0 && strlen(input) < MAX_INPUT_LINE_SIZE) { char line[MAX_INPUT_LINE_SIZE]; strcpy_s(line, MAX_INPUT_LINE_SIZE, input); char* context = nullptr; char* token = strtok_s(line, " ", &context); arguments.Clear(); do { arguments.PushBack(p2SString(token)); } while(token = strtok_s(NULL, " ", &context)); uint nargs = arguments.Count() - 1; const Command* com = FindCommand(arguments[0].GetString()); if(com != nullptr && com->listener != nullptr) { if(nargs >= com->min_arguments && nargs <= com->max_arguments) { // If we reach this point we are ready to call a listener if(ret = com->listener->OnCommand(com, arguments, last_message)) last_error.create("No error"); else { last_error = last_message; last_message.Clear(); } } else last_error.create("Command arguments mismatch"); } else { const CVar* var = FindCVar(arguments[0].GetString()); if(var == nullptr) last_error.create("Command / CVar not found"); else { switch(nargs) { case 1: { if(((CVar*)var)->SetFromString(arguments[1].GetString()) == true) { if(var->listener != nullptr) var->listener->OnCVar(var); } } case 0: { char output[COMMAND_NAME_SIZE + 25]; sprintf_s(output, COMMAND_NAME_SIZE + 25, "%s: %s", var->name, var->Printable()); last_message += output; ret = true; } break; default: last_error.create("Command arguments mismatch"); break; } } } } else last_error.create("Invalid input line"); if(ret == true) Print(last_message.GetString()); else PrintError(last_error.GetString()); return ret; }
// Main entry point int __cdecl wmain() { HRESULT hr = S_OK; WS_ERROR* error = NULL; WS_XML_WRITER* writer = NULL; WS_XML_READER* reader = NULL; WS_HEAP* heap = NULL; // Create an error object for storing rich error information hr = WsCreateError( NULL, 0, &error); if (FAILED(hr)) { goto Exit; } // Create a heap to store deserialized data hr = WsCreateHeap( /*maxSize*/ 2048, /*trimSize*/ 512, NULL, 0, &heap, error); if (FAILED(hr)) { goto Exit; } // Create an XML writer hr = WsCreateWriter( NULL, 0, &writer, error); if (FAILED(hr)) { goto Exit; } // Setup the output WS_XML_WRITER_BUFFER_OUTPUT bufferOutput; ZeroMemory(&bufferOutput, sizeof(bufferOutput)); bufferOutput.output.outputType = WS_XML_WRITER_OUTPUT_TYPE_BUFFER; // Setup the encoding WS_XML_WRITER_BINARY_ENCODING writerEncoding; ZeroMemory(&writerEncoding, sizeof(writerEncoding)); writerEncoding.encoding.encodingType = WS_XML_WRITER_ENCODING_TYPE_BINARY; writerEncoding.staticDictionary = &objectsDictionary.dictionary; writerEncoding.dynamicStringCallback = DynamicStringCallback; writerEncoding.dynamicStringCallbackState = NULL; // Setup the writer hr = WsSetOutput( writer, &writerEncoding.encoding, &bufferOutput.output, NULL, 0, error); if (FAILED(hr)) { goto Exit; } hr = WsWriteStartElement( writer, NULL, &objectsDictionary.objects, &objectsDictionary.ns, error); if (FAILED(hr)) { goto Exit; } // Write some xml using strings from all the dictionaries static const WS_XML_STRING* shapes[3] = { &shapeDictionary.triangle, &shapeDictionary.square, &shapeDictionary.circle }; static const WS_XML_STRING* colors[3] = { &colorDictionary.green, &colorDictionary.blue, &colorDictionary.red }; for (ULONG i = 0; i < 3; i++) { hr = WsWriteStartElement( writer, NULL, shapes[i], &objectsDictionary.ns, error); if (FAILED(hr)) { goto Exit; } hr = WsWriteStartAttribute( writer, NULL, &objectsDictionary.color, &objectsDictionary.ns, FALSE, error); if (FAILED(hr)) { goto Exit; } hr = WsWriteType( writer, WS_ATTRIBUTE_TYPE_MAPPING, WS_XML_STRING_TYPE, NULL, WS_WRITE_REQUIRED_VALUE, colors[i], sizeof(*colors[i]), error); if (FAILED(hr)) { goto Exit; } hr = WsWriteEndAttribute( writer, error); if (FAILED(hr)) { goto Exit; } hr = WsWriteEndElement( writer, error); if (FAILED(hr)) { goto Exit; } } hr = WsWriteEndElement( writer, error); if (FAILED(hr)) { goto Exit; } WS_BYTES bytes; hr = WsGetWriterProperty( writer, WS_XML_WRITER_PROPERTY_BYTES, &bytes, sizeof(bytes), error); if (FAILED(hr)) { goto Exit; } // Create an XML reader hr = WsCreateReader( NULL, 0, &reader, error); if (FAILED(hr)) { goto Exit; } // Setup the input WS_XML_READER_BUFFER_INPUT bufferInput; ZeroMemory(&bufferInput, sizeof(bufferInput)); bufferInput.input.inputType = WS_XML_READER_INPUT_TYPE_BUFFER; bufferInput.encodedData = bytes.bytes; bufferInput.encodedDataSize = bytes.length; // Setup the encoding WS_XML_READER_BINARY_ENCODING readerEncoding; ZeroMemory( &readerEncoding, sizeof(readerEncoding)); readerEncoding.encoding.encodingType = WS_XML_READER_ENCODING_TYPE_BINARY; readerEncoding.staticDictionary = &objectsDictionary.dictionary; readerEncoding.dynamicDictionary = &mergedDictionary.dictionary; // Setup the reader hr = WsSetInput( reader, &readerEncoding.encoding, &bufferInput.input, NULL, 0, error); if (FAILED(hr)) { goto Exit; } hr = WsReadToStartElement( reader, &objectsDictionary.objects, &objectsDictionary.ns, NULL, error); if (FAILED(hr)) { goto Exit; } hr = WsReadStartElement( reader, error); if (FAILED(hr)) { goto Exit; } for (;;) { BOOL found; hr = WsReadToStartElement( reader, NULL, NULL, &found, error); if (FAILED(hr)) { goto Exit; } if (!found) { break; } const WS_XML_NODE* node; hr = WsGetReaderNode( reader, &node, error); if (FAILED(hr)) { goto Exit; } const WS_XML_ELEMENT_NODE* elementNode = (WS_XML_ELEMENT_NODE*)node; printf("%.*s: ", elementNode->localName->length, elementNode->localName->bytes); ULONG index; hr = WsFindAttribute( reader, &objectsDictionary.color, &objectsDictionary.ns, TRUE, &index, error); if (FAILED(hr)) { goto Exit; } hr = WsReadStartAttribute( reader, index, error); if (FAILED(hr)) { goto Exit; } WS_XML_STRING color; hr = WsReadType( reader, WS_ATTRIBUTE_TYPE_MAPPING, WS_XML_STRING_TYPE, NULL, WS_READ_REQUIRED_VALUE, heap, &color, sizeof(color), error); if (FAILED(hr)) { goto Exit; } printf( "%.*s\n", color.length, color.bytes); hr = WsReadEndAttribute( reader, error); if (FAILED(hr)) { goto Exit; } hr = WsSkipNode( reader, error); if (FAILED(hr)) { goto Exit; } } hr = WsReadEndElement( reader, error); if (FAILED(hr)) { goto Exit; } Exit: if (FAILED(hr)) { // Print out the error PrintError(hr, error); } if (writer != NULL) { WsFreeWriter(writer); } if (reader != NULL) { WsFreeReader(reader); } if (heap != NULL) { WsFreeHeap(heap); } if (error != NULL) { WsFreeError(error); } fflush(stdout); return SUCCEEDED(hr) ? 0 : -1; }
/* TODO */ void PrintHistogram(RGIndex *index, RGBinary *rg, int whichStrand, int numThreads) { char *FnName = "PrintHistogram"; int64_t i, j; int64_t *starts, *ends; pthread_t *threads=NULL; ThreadData *data=NULL; int errCode; void *status; FILE *fp; int64_t numDifferent, numTotal, cur, sum, totalForward, totalReverse; int numCountsLeft; /* Allocate memory for the thread starts and ends */ starts = malloc(sizeof(int64_t)*numThreads); if(NULL == starts) { PrintError(FnName, "starts", "Could not allocate memory", Exit, OutOfRange); } ends = malloc(sizeof(int64_t)*numThreads); if(NULL == ends) { PrintError(FnName, "ends", "Could not allocate memory", Exit, OutOfRange); } /* Allocate memory for threads */ threads=malloc(sizeof(pthread_t)*numThreads); if(NULL==threads) { PrintError(FnName, "threads", "Could not allocate memory", Exit, MallocMemory); } /* Allocate memory to pass data to threads */ data=malloc(sizeof(ThreadData)*numThreads); if(NULL==data) { PrintError(FnName, "data", "Could not allocate memory", Exit, MallocMemory); } /* Get pivots */ GetPivots(index, rg, starts, ends, numThreads); /* Initialize thread data */ numTotal = 0; for(i=0;i<numThreads;i++) { data[i].startIndex = starts[i]; data[i].endIndex = ends[i]; numTotal += ends[i] - starts[i] + 1; data[i].index = index; data[i].rg = rg; data[i].c.counts = NULL; data[i].c.maxCount = NULL; data[i].whichStrand = whichStrand; data[i].numDifferent = 0; data[i].threadID = i+1; } assert(numTotal == index->length || (ColorSpace == rg->space && numTotal == index->length - 1)); fprintf(stderr, "In total, will examine %lld reads.\n", (long long int)(index->length)); fprintf(stderr, "For a given thread, out of %lld, currently on:\n0", (long long int)(index->length/numThreads) ); /* Open threads */ for(i=0;i<numThreads;i++) { /* Start thread */ errCode = pthread_create(&threads[i], /* thread struct */ NULL, /* default thread attributes */ PrintHistogramThread, /* start routine */ &data[i]); /* data to routine */ if(0!=errCode) { PrintError(FnName, "pthread_create: errCode", "Could not start thread", Exit, ThreadError); } } /* Wait for threads to return */ for(i=0;i<numThreads;i++) { /* Wait for the given thread to return */ errCode = pthread_join(threads[i], &status); /* Check the return code of the thread */ if(0!=errCode) { PrintError(FnName, "pthread_join: errCode", "Thread returned an error", Exit, ThreadError); } } fprintf(stderr, "\n"); /* Get the total number of different */ numDifferent = 0; totalForward = 0; totalReverse = 0; for(i=0;i<numThreads;i++) { numDifferent += data[i].numDifferent; totalForward += data[i].totalForward; totalReverse += data[i].totalReverse; } /* Print counts from threads */ if(!(fp = fdopen(fileno(stdout), "w"))) { PrintError(FnName, "stdout", "Could not open stdout for writing", Exit, OpenFileError); } fprintf(fp, "# Number of unique reads was: %lld\n", (long long int)numDifferent); fprintf(fp, "# Found counts for %lld mismatches:\n", (long long int)i); /* Print the counts, sum over all threads */ numCountsLeft = numThreads; cur = 0; while(numCountsLeft > 0) { /* Get the result from all threads */ sum = 0; for(j=0;j<numThreads;j++) { if(cur <= data[j].c.maxCount[i]) { assert(data[j].c.counts[i][cur] >= 0); sum += data[j].c.counts[i][cur]; /* Update */ if(data[j].c.maxCount[i] == cur) { numCountsLeft--; } } } assert(sum >= 0); /* Print */ if(cur>0) { fprintf(fp, "%lld\t%lld\n", (long long int)cur, (long long int)sum); } cur++; } fclose(fp); /* Free memory */ for(i=0;i<numThreads;i++) { free(data[i].c.counts[0]); data[i].c.counts[0] = NULL; free(data[i].c.counts); data[i].c.counts=NULL; free(data[i].c.maxCount); data[i].c.maxCount = NULL; } free(threads); free(data); free(starts); starts=NULL; free(ends); ends=NULL; }
void *PrintHistogramThread(void *arg) { char *FnName = "PrintHistogramThread"; /* Get thread data */ ThreadData *data = (ThreadData*)arg; int64_t startIndex = data->startIndex; int64_t endIndex = data->endIndex; RGIndex *index = data->index; RGBinary *rg = data->rg; Counts *c = &data->c; int whichStrand = data->whichStrand; int threadID = data->threadID; int numMismatchesEnd = 0; int numMismatchesStart = 0; /* Local variables */ int skip; int64_t i=0; int64_t j=0; int64_t curIndex=0, nextIndex=0; int64_t counter=0; int64_t numDifferent = 0; int64_t numReadsNoMismatches = 0; int64_t numReadsNoMismatchesTotal = 0; int64_t numForward, numReverse; int64_t totalForward, totalReverse; int64_t numMatches; /* Allocate memory to hold histogram data */ c->counts = malloc(sizeof(int64_t*)*(numMismatchesEnd - numMismatchesStart + 1)); if(NULL == c->counts) { PrintError(FnName, "c->counts", "Could not allocate memory", Exit, MallocMemory); } c->maxCount = malloc(sizeof(int64_t)*(numMismatchesEnd - numMismatchesStart + 1)); if(NULL == c->maxCount) { PrintError(FnName, "c->maxCount", "Could not allocate memory", Exit, MallocMemory); } /* Initialize counts */ for(i=0;i<(numMismatchesEnd - numMismatchesStart + 1);i++) { c->counts[i] = malloc(sizeof(int64_t)); if(NULL == c->counts[i]) { PrintError(FnName, "c->counts[i]", "Could not allocate memory", Exit, MallocMemory); } c->counts[i][0] = 0; c->maxCount[i] = 0; } /* Go through every possible read in the genome using the index */ /* Go through the index */ totalForward = 0; totalReverse = 0; for(curIndex=startIndex, nextIndex=startIndex, counter=0, numDifferent=0; curIndex <= endIndex; curIndex = nextIndex) { if(counter >= BINDEXHIST_ROTATE_NUM) { fprintf(stderr, "\rthreadID:%2d\t%10lld", threadID, (long long int)(curIndex-startIndex)); counter -= BINDEXHIST_ROTATE_NUM; } /* Try each mismatch */ skip=0; i=0; /* Get the matches for the contig/pos */ if(0==GetMatchesFromContigPos(index, rg, (index->contigType == Contig_8)?(index->contigs_8[curIndex]):(index->contigs_32[curIndex]), index->positions[curIndex], &numForward, &numReverse) && 0 == i) { /* Skip over the rest */ skip =1 ; nextIndex++; } else { numMatches = numForward + numReverse; assert(numMatches > 0); /* Update the value of numReadsNoMismatches and numDifferent * if we have the results for no mismatches */ if(i==0) { assert(numForward > 0); totalForward += numForward; assert(numReverse >= 0); totalReverse += numReverse; /* If the reverse compliment does not match the + strand then it will only match the - strand. * Count it as unique as well as the + strand read. * */ if((BothStrands == whichStrand || ReverseStrand == whichStrand) && numReverse == 0) { numDifferent+=2; numReadsNoMismatches = 2; } else { /* Count only the + strand as a unique read. */ numReadsNoMismatches = 1; numDifferent++; } /* This will be the basis for update c->counts */ numReadsNoMismatchesTotal += numReadsNoMismatches; /* Add the range since we will be skipping over them */ if(numForward <= 0) { nextIndex++; counter++; } else { nextIndex += numForward; counter += numForward; } } /* Add to our list. We may have to reallocate this array */ if(numMatches > c->maxCount[i]) { j = c->maxCount[i]+1; /* This will determine where we begin initialization after reallocation */ /* Reallocate */ c->maxCount[i] = numMatches; assert(c->maxCount[i] > 0); c->counts[i] = realloc(c->counts[i], sizeof(int64_t)*(c->maxCount[i]+1)); if(NULL == c->counts[i]) { PrintError(FnName, "counts", "Could not allocate memory", Exit, MallocMemory); } /* Initialize from j to maxCount */ while(j<=c->maxCount[i]) { c->counts[i][j] = 0; j++; } } assert(numReadsNoMismatches > 0); assert(numMatches <= c->maxCount[i]); assert(c->counts[i][numMatches] >= 0); /* Add the number of reads that were found with no mismatches */ c->counts[i][numMatches] += numReadsNoMismatches; assert(c->counts[i][numMatches] > 0); } } fprintf(stderr, "\rthreadID:%2d\t%10lld", threadID, (long long int)(curIndex-startIndex)); /* Copy over numDifferent */ data->numDifferent = numDifferent; data->totalForward = totalForward; data->totalReverse = totalReverse; return NULL; }
// Main entry point int __cdecl wmain() { HRESULT hr = S_OK; WS_SERVICE_HOST* host = NULL; WS_SERVICE_ENDPOINT serviceEndpoint = {}; const WS_SERVICE_ENDPOINT* serviceEndpoints[1]; WS_ERROR* error = NULL; WS_SERVICE_ENDPOINT_PROPERTY serviceProperties[1]; const ULONG maxConcurrency = 100; serviceEndpoints[0] = &serviceEndpoint; serviceProperties[0].id = WS_SERVICE_ENDPOINT_PROPERTY_MAX_CONCURRENCY; serviceProperties[0].value = (void*)&maxConcurrency; serviceProperties[0].valueSize = sizeof(maxConcurrency); // Create Event object for closing the server closeServer = CreateEvent( NULL, TRUE, FALSE, NULL); if (closeServer == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Exit; } // Initialize service endpoint serviceEndpoint.address.url.chars = L"net.tcp://+/example"; // address given as uri serviceEndpoint.address.url.length = (ULONG)wcslen(serviceEndpoint.address.url.chars); serviceEndpoint.channelBinding = WS_TCP_CHANNEL_BINDING; // channel binding for the endpoint serviceEndpoint.channelType = WS_CHANNEL_TYPE_DUPLEX_SESSION; // the channel type serviceEndpoint.contract = &blockServiceContract; // the contract serviceEndpoint.properties = serviceProperties; serviceEndpoint.propertyCount = WsCountOf(serviceProperties); // Create an error object for storing rich error information hr = WsCreateError( NULL, 0, &error); if (FAILED(hr)) { goto Exit; } // Creating a service host hr = WsCreateServiceHost( serviceEndpoints, 1, NULL, 0, &host, error); if (FAILED(hr)) { goto Exit; } // WsOpenServiceHost to start the listeners in the service host hr = WsOpenServiceHost( host, NULL, error); if (FAILED(hr)) { goto Exit; } WaitForSingleObject(closeServer, INFINITE); // Aborts the service host so that the blocked method can complete. WsAbortServiceHost(host, NULL); // Close the service host hr = WsCloseServiceHost(host, NULL, error); if (FAILED(hr)) { goto Exit; } Exit: if (FAILED(hr)) { // Print out the error PrintError(hr, error); } if (host != NULL) { WsFreeServiceHost(host); } if (error != NULL) { WsFreeError(error); } if (closeServer != NULL) { CloseHandle(closeServer); } fflush(stdout); return SUCCEEDED(hr) ? 0 : -1; }
// Main entry point int __cdecl wmain() { HRESULT hr = S_OK; WS_SERVICE_HOST* host = NULL; WS_SERVICE_ENDPOINT serviceEndpoint = {}; const WS_SERVICE_ENDPOINT* serviceEndpoints[1]; serviceEndpoints[0] = &serviceEndpoint; WS_ERROR* error = NULL; // declare and initialize a username message security binding WS_USERNAME_MESSAGE_SECURITY_BINDING usernameBinding = {}; // zero out the struct usernameBinding.binding.bindingType = WS_USERNAME_MESSAGE_SECURITY_BINDING_TYPE; // set the binding type usernameBinding.bindingUsage = WS_SUPPORTING_MESSAGE_SECURITY_USAGE; // set the binding usage usernameBinding.passwordValidator = MyPasswordValidator; // declare and initialize an SSL transport security binding WS_SSL_TRANSPORT_SECURITY_BINDING sslBinding = {}; // zero out the struct sslBinding.binding.bindingType = WS_SSL_TRANSPORT_SECURITY_BINDING_TYPE; // set the binding type // NOTE: At the server, the SSL certificate for the listen URI must be // registered with http.sys using a tool such as httpcfg.exe. // declare and initialize the array of all security bindings WS_SECURITY_BINDING* securityBindings[2] = { &sslBinding.binding, &usernameBinding.binding }; // declare and initialize the security description WS_SECURITY_DESCRIPTION securityDescription = {}; // zero out the struct securityDescription.securityBindings = securityBindings; securityDescription.securityBindingCount = WsCountOf(securityBindings); WS_SERVICE_ENDPOINT_PROPERTY serviceEndpointProperties[1]; WS_SERVICE_PROPERTY_CLOSE_CALLBACK closeCallbackProperty = {CloseChannelCallback}; serviceEndpointProperties[0].id = WS_SERVICE_ENDPOINT_PROPERTY_CLOSE_CHANNEL_CALLBACK; serviceEndpointProperties[0].value = &closeCallbackProperty; serviceEndpointProperties[0].valueSize = sizeof(closeCallbackProperty); // Initialize service endpoint serviceEndpoint.address.url.chars = L"https://localhost:8443/example"; // address given as uri serviceEndpoint.address.url.length = (ULONG)wcslen(serviceEndpoint.address.url.chars); serviceEndpoint.channelBinding = WS_HTTP_CHANNEL_BINDING; // channel binding for the endpoint serviceEndpoint.channelType = WS_CHANNEL_TYPE_REPLY; // the channel type serviceEndpoint.securityDescription = &securityDescription; // security description serviceEndpoint.contract = &calculatorContract; // the contract serviceEndpoint.properties = serviceEndpointProperties; serviceEndpoint.propertyCount = WsCountOf(serviceEndpointProperties); serviceEndpoint.authorizationCallback = AuthorizationCallback; // Create an error object for storing rich error information hr = WsCreateError( NULL, 0, &error); if (FAILED(hr)) { goto Exit; } // Create Event object for closing the server closeServer = CreateEvent( NULL, TRUE, FALSE, NULL); if (closeServer == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Exit; } // Creating a service host hr = WsCreateServiceHost( serviceEndpoints, 1, NULL, 0, &host, error); if (FAILED(hr)) { goto Exit; } // WsOpenServiceHost to start the listeners in the service host hr = WsOpenServiceHost( host, NULL, error); if (FAILED(hr)) { goto Exit; } WaitForSingleObject(closeServer, INFINITE); // Close the service host hr = WsCloseServiceHost(host, NULL, error); if (FAILED(hr)) { goto Exit; } Exit: if (FAILED(hr)) { // Print out the error PrintError(hr, error); } if (host != NULL) { WsFreeServiceHost(host); } if (error != NULL) { WsFreeError(error); } if (closeServer != NULL) { CloseHandle(closeServer); } fflush(stdout); return SUCCEEDED(hr) ? 0 : -1; }
//----------------------------------------------------------------// void MOAIHttpTaskCurl::SetVerbose ( bool verbose ) { CURLcode result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_VERBOSE, verbose ? 1 : 0 ); PrintError ( result ); }
//----------------------------------------------------------------// void MOAIHttpTaskCurl::SetUserAgent ( cc8* useragent ) { CURLcode result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_USERAGENT, useragent ); PrintError ( result ); }
void MOAIHttpTaskCurl::SetFailOnError ( bool enable ) { CURLcode result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_FAILONERROR, ( u32 ) enable ); PrintError ( result ); }
int ActualFileSeek(ACTUALHANDLE handle, off64_t position) { // int retval; LARGE_INTEGER realpos; DWORD errcode; if(handle == NULL) return(-1); if(handle == INVALID_HANDLE_VALUE) return(-1); if(position < 0) return(-1); #ifdef VERBOSE_FUNCTION_ACTUALFILE PrintLog("CDVDiso file: ActualFileSeek(%llu)", position); #endif /* VERBOSE_FUNCTION_ACTUALFILE */ realpos.QuadPart = position; ////// WinXP code for seek // retval = SetFilePointerEx(handle, // realpos, // NULL, // FILE_BEGIN); // if(retval == 0) { ////// Win98 code for seek realpos.LowPart = SetFilePointer(handle, realpos.LowPart, &realpos.HighPart, FILE_BEGIN); errcode = GetLastError(); if((realpos.LowPart == 0xFFFFFFFF) && (errcode != NO_ERROR)) { #ifdef VERBOSE_WARNING_ACTUALFILE PrintLog("CDVDiso file: Error on seek (%llu)", position); PrintError("CDVDiso file", errcode); #endif /* VERBOSE_WARNING_ACTUALFILE */ return(-1); } // ENDIF- Error? Abort return(0); } // END ActualFileSeek()
int main(int argc, char *argv[]) { char *indexFileName=NULL; char *fastaFileName=NULL; int numThreads = 1; int whichStrand = 0; int space = NTSpace; int c; RGBinary rg; RGIndex index; while((c = getopt(argc, argv, "f:i:n:s:A:h")) >= 0) { switch(c) { case 'f': fastaFileName=strdup(optarg); break; case 'h': return PrintUsage(); case 'i': indexFileName=strdup(optarg); break; case 's': whichStrand=atoi(optarg); break; case 'n': numThreads=atoi(optarg); break; case 'A': space=atoi(optarg); break; default: fprintf(stderr, "Unrecognized option: -%c\n", c); return 1; } } if(1 == argc || argc != optind) { return PrintUsage(); } if(NULL == indexFileName) { PrintError(Name, "indexFileName", "Command line option", Exit, InputArguments); } if(NULL == fastaFileName) { PrintError(Name, "fastaFileName", "Command line option", Exit, InputArguments); } assert(whichStrand == BothStrands || whichStrand == ForwardStrand || whichStrand == ReverseStrand); /* Read in the rg binary file */ RGBinaryReadBinary(&rg, space, fastaFileName); /* Read the index */ RGIndexRead(&index, indexFileName); assert(index.space == rg.space); fprintf(stderr, "%s", BREAK_LINE); PrintHistogram(&index, &rg, whichStrand, numThreads); fprintf(stderr, "%s", BREAK_LINE); fprintf(stderr, "%s", BREAK_LINE); fprintf(stderr, "Cleaning up.\n"); /* Delete the index */ RGIndexDelete(&index); /* Delete the rg */ RGBinaryDelete(&rg); fprintf(stderr, "%s", BREAK_LINE); fprintf(stderr, "Terminating successfully!\n"); fprintf(stderr, "%s", BREAK_LINE); return 0; }
int ActualFileRead(ACTUALHANDLE handle, int bytes, char *buffer) { int retval; DWORD bytesread; #ifdef VERBOSE_WARNING_ACTUALFILE DWORD errcode; #endif /* VERBOSE_WARNING_ACTUALFILE */ if(handle == NULL) return(-1); if(handle == INVALID_HANDLE_VALUE) return(-1); if(bytes < 1) return(-1); if(buffer == NULL) return(-1); #ifdef VERBOSE_FUNCTION_ACTUALFILE PrintLog("CDVDiso file: ActualFileRead(%i)", bytes); #endif /* VERBOSE_FUNCTION_ACTUALFILE */ retval = ReadFile(handle, buffer, bytes, &bytesread, NULL); if(retval == 0) { #ifdef VERBOSE_WARNING_ACTUALFILE errcode = GetLastError(); PrintLog("CDVDiso file: Error reading from file"); PrintError("CDVDiso file", errcode); #endif /* VERBOSE_WARNING_ACTUALFILE */ return(-1); } // ENDIF- Error? Abort if(bytesread < bytes) { #ifdef VERBOSE_WARNING_ACTUALFILE PrintLog("CDVDiso file: Short Block! Only read %i out of %i bytes", bytesread, bytes); #endif /* VERBOSE_WARNING_ACTUALFILE */ } // ENDIF- Error? Abort return(bytesread); // Send back how many bytes read } // END ActualFileRead()
/* Get the matches for the contig/pos */ int GetMatchesFromContigPos(RGIndex *index, RGBinary *rg, uint32_t curContig, uint32_t curPos, int64_t *numForward, int64_t *numReverse) { char *FnName = "GetMatchesFromContigPos"; int returnLength, returnPosition; char *read=NULL; RGRanges ranges; RGMatch match; int readLength = index->width; int8_t readInt[SEQUENCE_LENGTH]; int32_t i; /* Initialize */ RGRangesInitialize(&ranges); RGMatchInitialize(&match); /* Get the read */ RGBinaryGetReference(rg, curContig, curPos, FORWARD, 0, &read, readLength, &returnLength, &returnPosition); assert(returnLength == readLength); assert(returnPosition == curPos); ConvertSequenceToIntegers(read, readInt, readLength); RGIndexGetRangesBothStrands(index, rg, readInt, readLength, 0, INT_MAX, INT_MAX, rg->space, BothStrands, &ranges); /* Transfer ranges to matches */ RGRangesCopyToRGMatch(&ranges, index, &match, rg->space, 0); /* Remove duplicates */ RGMatchRemoveDuplicates(&match, INT_MAX); assert(0 < match.numEntries); (*numForward) = (*numReverse) = 0; for(i=0;i<match.numEntries;i++) { switch(match.strands[i]) { case FORWARD: (*numForward)++; break; case REVERSE: (*numReverse)++; break; default: PrintError(FnName, NULL, "Could not understand strand", Exit, OutOfRange); break; } } assert((*numForward) > 0); /* It should at least match itself ! */ assert((*numReverse) >= 0); RGRangesFree(&ranges); RGMatchFree(&match); free(read); read=NULL; return 1; }
// Main entry point int __cdecl wmain() { HRESULT hr = S_OK; WS_ERROR* error = NULL; WS_CHANNEL* channel = NULL; WS_MESSAGE* requestMessage = NULL; WS_MESSAGE* replyMessage = NULL; WS_HEAP* heap = NULL; static const WS_STRING serviceUrl = WS_STRING_VALUE(L"http://localhost/example"); WS_ENDPOINT_ADDRESS address = {}; // Create an error object for storing rich error information hr = WsCreateError( NULL, 0, &error); if (FAILED(hr)) { goto Exit; } // Set up a property indicating streamined input and output WS_TRANSFER_MODE transferMode = WS_STREAMED_TRANSFER_MODE; WS_CHANNEL_PROPERTY transferModeProperty; transferModeProperty.id = WS_CHANNEL_PROPERTY_TRANSFER_MODE; transferModeProperty.value = &transferMode; transferModeProperty.valueSize = sizeof(transferMode); // Create a HTTP request channel hr = WsCreateChannel( WS_CHANNEL_TYPE_REQUEST, WS_HTTP_CHANNEL_BINDING, &transferModeProperty, 1, NULL, &channel, error); if (FAILED(hr)) { goto Exit; } // Initialize address of service address.url = serviceUrl; // Open channel to address hr = WsOpenChannel( channel, &address, NULL, error); if (FAILED(hr)) { goto Exit; } hr = WsCreateMessageForChannel( channel, NULL, 0, &requestMessage, error); if (FAILED(hr)) { goto Exit; } hr = WsCreateMessageForChannel( channel, NULL, 0, &replyMessage, error); if (FAILED(hr)) { goto Exit; } // Create a heap to store deserialized data hr = WsCreateHeap( /*maxSize*/ 2048, /*trimSize*/ 512, NULL, 0, &heap, error); if (FAILED(hr)) { goto Exit; } // Send request messages and receive reply messages for (int i = 0; i < 10; i++) { // Initialize message headers of the request message hr = WsInitializeMessage( requestMessage, WS_BLANK_MESSAGE, NULL, error); if (FAILED(hr)) { goto Exit; } // Add the action header to the request message hr = WsSetHeader( requestMessage, WS_ACTION_HEADER, WS_XML_STRING_TYPE, WS_WRITE_REQUIRED_VALUE, PurchaseOrder_wsdl.messages.PurchaseOrder.action, sizeof(*PurchaseOrder_wsdl.messages.PurchaseOrder.action), error); if (FAILED(hr)) { goto Exit; } // Generate a unique message ID that will be used for the request message WS_UNIQUE_ID messageID; ZeroMemory( &messageID, sizeof(messageID)); DWORD status = UuidCreate( &messageID.guid); if (status != RPC_S_OK) { hr = E_FAIL; goto Exit; } // Add the message ID to the request message hr = WsSetHeader( requestMessage, WS_MESSAGE_ID_HEADER, WS_UNIQUE_ID_TYPE, WS_WRITE_REQUIRED_VALUE, &messageID, sizeof(messageID), error); if (FAILED(hr)) { goto Exit; } // Send the message headers of the request message hr = WsWriteMessageStart( channel, requestMessage, NULL, error); if (FAILED(hr)) { goto Exit; } // Stream out some purchase orders for (int j = 0; j < 10; j++) { // Initialize body data _PurchaseOrderType purchaseOrder; purchaseOrder.quantity = 1; purchaseOrder.productName = L"Pencil"; // Serialize body data into message hr = WsWriteBody( requestMessage, &PurchaseOrder_wsdl.globalElements.PurchaseOrderType, WS_WRITE_REQUIRED_VALUE, &purchaseOrder, sizeof(purchaseOrder), error); if (FAILED(hr)) { goto Exit; } // Send accumulated message data once at least 4096 bytes have been accumulated hr = WsFlushBody( requestMessage, 4096, NULL, error); if (FAILED(hr)) { goto Exit; } } // Send the end of the request message hr = WsWriteMessageEnd( channel, requestMessage, NULL, error); if (FAILED(hr)) { goto Exit; } // Receive the headers of the reply message hr = WsReadMessageStart( channel, replyMessage, NULL, error); if (FAILED(hr)) { goto Exit; } // Stream in all the confirmations for (;;) { // Make sure we have at least once confirmation buffered. Each confirmation // may be up to 1024 bytes in size. hr = WsFillBody( replyMessage, 1024, NULL, error); if (FAILED(hr)) { goto Exit; } // Try to deserialize a confirmation into the heap _OrderConfirmationType* orderConfirmation; hr = WsReadBody( replyMessage, &PurchaseOrder_wsdl.globalElements.OrderConfirmationType, WS_READ_OPTIONAL_POINTER, heap, &orderConfirmation, sizeof(orderConfirmation), error); if (FAILED(hr)) { goto Exit; } // If there are no more confirmations, break out of the loop if (orderConfirmation == NULL) { break; } // Print out confirmation contents wprintf(L"%s\n", orderConfirmation->expectedShipDate); // Reset the heap which frees the confirmation data that was deserialized hr = WsResetHeap( heap, error); if (FAILED(hr)) { goto Exit; } } // Receive the end of the reply message hr = WsReadMessageEnd( channel, replyMessage, NULL, error); if (FAILED(hr)) { goto Exit; } // Reset message so it can be used again hr = WsResetMessage( replyMessage, error); if (FAILED(hr)) { goto Exit; } // Reset message so it can be used again hr = WsResetMessage( requestMessage, error); if (FAILED(hr)) { goto Exit; } } Exit: if (FAILED(hr)) { // Print out the error PrintError(hr, error); } if (channel != NULL) { // Close the channel WsCloseChannel(channel, NULL, error); } if (requestMessage != NULL) { WsFreeMessage(requestMessage); } if (replyMessage != NULL) { WsFreeMessage(replyMessage); } if (channel != NULL) { WsFreeChannel(channel); } if (error != NULL) { WsFreeError(error); } if (heap != NULL) { WsFreeHeap(heap); } fflush(stdout); return SUCCEEDED(hr) ? 0 : -1; }
void perspective(TrformStr *TrPtr, pPrefs *prefs) { double v[3]; // auxilliary vector double points_per_degree; double mt[3][3]; double alpha, beta, gammar; // Angles in rad double x_off, y_off, d; double a; uint32_t destwidth, destheight; fDesc fD; void *params[4]; // Parameters for perspective control functions params[0] = (void*)mt; params[1] = (void*)&d; params[2] = (void*)&x_off; params[3] = (void*)&y_off; // Set destination image parameters destwidth = prefs->width; destheight = prefs->height; if( destwidth <= 0 || destheight <= 0 ) { TrPtr->success = 0; PrintError( "Zero Destination Image Size" ); return; } if( SetDestImage(TrPtr, destwidth, destheight) != 0 ) { TrPtr->success = 0; PrintError( "Not enough Memory."); return; } // Set parameters for perspective transformation a = DEG_TO_RAD( prefs->hfov ); alpha = DEG_TO_RAD( prefs->y_beta ); beta = DEG_TO_RAD( prefs->x_alpha ); gammar = DEG_TO_RAD( prefs->gamma ); fD.func =(trfn)NULL; switch(prefs->format) { case _rectilinear: if( a >= PI ) { TrPtr->success = 0; PrintError("HFOV must be smaller than 180 degrees"); return; } d = TrPtr->src->width / ( 2.0 * tan( a/2.0 ) ); if( prefs->unit_is_cart ) { alpha = atan( (prefs->y_beta - TrPtr->src->height/2.0 ) / d ); beta = - atan( (prefs->x_alpha - TrPtr->src->width/2.0 ) / d ); } fD.func = persp_rect; break; case _spherical_tp: d = TrPtr->src->width / a; if( prefs->unit_is_cart ) { points_per_degree = ((double) TrPtr->src->width) / (a * 360 / (2 * PI)) ; alpha = ((TrPtr->src->height/2.0 - prefs->y_beta)/ points_per_degree) * 2 * PI / 360; beta = -((TrPtr->src->width/2.0 - prefs->x_alpha)/ points_per_degree) * 2 * PI / 360; } fD.func = persp_sphere; break; } SetMatrix( alpha, beta, gammar , mt, 1 ); // Offset v[0] = 0.0; v[1] = 0.0; v[2] = d; matrix_mult( mt, v ); x_off = v[0]*d/v[2]; y_off = v[1]*d/v[2]; // Do transformation if( fD.func != NULL) { fD.param = params; //transFormEx( TrPtr, &fD, &fD, 0, 1 ); transForm( TrPtr, &fD, 0 ); } else TrPtr->success = 0; if( TrPtr->success == 0 && ! (TrPtr->mode & _destSupplied)) // Moved here myfree( (void**)TrPtr->dest->data ); }
int MY_CDECL main(int numargs, char *args[]) { CFileInStream archiveStream; CLookToRead lookStream; CSzArEx db; SRes res; ISzAlloc allocImp; ISzAlloc allocTempImp; UInt16 *temp = NULL; size_t tempSize = 0; // UInt32 parents[NUM_PARENTS_MAX]; printf("\n7z ANSI-C Decoder " MY_VERSION_COPYRIGHT_DATE "\n\n"); if (numargs == 1) { printf( "Usage: 7zDec <command> <archive_name>\n\n" "<Commands>\n" " e: Extract files from archive (without using directory names)\n" " l: List contents of archive\n" " t: Test integrity of archive\n" " x: eXtract files with full paths\n"); return 0; } if (numargs < 3) { PrintError("incorrect command"); return 1; } #if defined(_WIN32) && !defined(USE_WINDOWS_FILE) && !defined(UNDER_CE) g_FileCodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; #endif allocImp.Alloc = SzAlloc; allocImp.Free = SzFree; allocTempImp.Alloc = SzAllocTemp; allocTempImp.Free = SzFreeTemp; #ifdef UNDER_CE if (InFile_OpenW(&archiveStream.file, L"\test.7z")) #else if (InFile_Open(&archiveStream.file, args[2])) #endif { PrintError("can not open input file"); return 1; } FileInStream_CreateVTable(&archiveStream); LookToRead_CreateVTable(&lookStream, False); lookStream.realStream = &archiveStream.s; LookToRead_Init(&lookStream); CrcGenerateTable(); SzArEx_Init(&db); res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp); if (res == SZ_OK) { char *command = args[1]; int listCommand = 0, testCommand = 0, fullPaths = 0; if (strcmp(command, "l") == 0) listCommand = 1; else if (strcmp(command, "t") == 0) testCommand = 1; else if (strcmp(command, "e") == 0) { } else if (strcmp(command, "x") == 0) { fullPaths = 1; } else { PrintError("incorrect command"); res = SZ_ERROR_FAIL; } if (res == SZ_OK) { UInt32 i; /* if you need cache, use these 3 variables. if you use external function, you can make these variable as static. */ UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */ Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */ size_t outBufferSize = 0; /* it can have any value before first call (if outBuffer = 0) */ for (i = 0; i < db.NumFiles; i++) { size_t offset = 0; size_t outSizeProcessed = 0; // const CSzFileItem *f = db.Files + i; size_t len; unsigned isDir = SzArEx_IsDir(&db, i); if (listCommand == 0 && isDir && !fullPaths) continue; len = SzArEx_GetFileNameUtf16(&db, i, NULL); // len = SzArEx_GetFullNameLen(&db, i); if (len > tempSize) { SzFree(NULL, temp); tempSize = len; temp = (UInt16 *)SzAlloc(NULL, tempSize * sizeof(temp[0])); if (!temp) { res = SZ_ERROR_MEM; break; } } SzArEx_GetFileNameUtf16(&db, i, temp); /* if (SzArEx_GetFullNameUtf16_Back(&db, i, temp + len) != temp) { res = SZ_ERROR_FAIL; break; } */ if (listCommand) { char attr[8], s[32], t[32]; UInt64 fileSize; GetAttribString(SzBitWithVals_Check(&db.Attribs, i) ? db.Attribs.Vals[i] : 0, isDir, attr); fileSize = SzArEx_GetFileSize(&db, i); UInt64ToStr(fileSize, s); if (SzBitWithVals_Check(&db.MTime, i)) ConvertFileTimeToString(&db.MTime.Vals[i], t); else { size_t j; for (j = 0; j < 19; j++) t[j] = ' '; t[j] = '\0'; } printf("%s %s %10s ", t, attr, s); res = PrintString(temp); if (res != SZ_OK) break; if (isDir) printf("/"); printf("\n"); continue; } fputs(testCommand ? "Testing ": "Extracting ", stdout); res = PrintString(temp); if (res != SZ_OK) break; if (isDir) printf("/"); else { res = SzArEx_Extract(&db, &lookStream.s, i, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &allocImp, &allocTempImp); if (res != SZ_OK) break; } if (!testCommand) { CSzFile outFile; size_t processedSize; size_t j; UInt16 *name = (UInt16 *)temp; const UInt16 *destPath = (const UInt16 *)name; for (j = 0; name[j] != 0; j++) if (name[j] == '/') { if (fullPaths) { name[j] = 0; MyCreateDir(name); name[j] = CHAR_PATH_SEPARATOR; } else destPath = name + j + 1; } if (isDir) { MyCreateDir(destPath); printf("\n"); continue; } else if (OutFile_OpenUtf16(&outFile, destPath)) { PrintError("can not open output file"); res = SZ_ERROR_FAIL; break; } processedSize = outSizeProcessed; if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed) { PrintError("can not write output file"); res = SZ_ERROR_FAIL; break; } if (File_Close(&outFile)) { PrintError("can not close output file"); res = SZ_ERROR_FAIL; break; } #ifdef USE_WINDOWS_FILE if (SzBitWithVals_Check(&db.Attribs, i)) SetFileAttributesW(destPath, db.Attribs.Vals[i]); #endif } printf("\n"); } IAlloc_Free(&allocImp, outBuffer); } } SzArEx_Free(&db, &allocImp); SzFree(NULL, temp); File_Close(&archiveStream.file); if (res == SZ_OK) { printf("\nEverything is Ok\n"); return 0; } if (res == SZ_ERROR_UNSUPPORTED) PrintError("decoder doesn't support this archive"); else if (res == SZ_ERROR_MEM) PrintError("can not allocate memory"); else if (res == SZ_ERROR_CRC) PrintError("CRC error"); else printf("\nERROR #%d\n", res); return 1; }
void GuardError(ErrorType error) { Printf(Exception,"CCore::Sys::Guard() : #;",PrintError(error)); }
// Main entry point int __cdecl wmain() { HRESULT hr = S_OK; WS_ERROR* error = NULL; WS_HEAP* heap = NULL; WS_SERVICE_PROXY* serviceProxy = NULL; int result = 0; WS_ENDPOINT_ADDRESS address = {}; static const WS_STRING url = WS_STRING_VALUE(L"https://localhost:8443/example"); address.url = url; // Create an error object for storing rich error information hr = WsCreateError( NULL, 0, &error); if (FAILED(hr)) { goto Exit; } // Create a heap to store deserialized data hr = WsCreateHeap( /*maxSize*/ 2048, /*trimSize*/ 512, NULL, 0, &heap, error); if (FAILED(hr)) { goto Exit; } // Create the proxy hr = DefaultBinding_ICalculator_CreateServiceProxy( NULL, NULL, 0, &serviceProxy, error); if (FAILED(hr)) { goto Exit; } hr = WsOpenServiceProxy(serviceProxy, &address, NULL, error); if (FAILED(hr)) { goto Exit; } hr = DefaultBinding_ICalculator_Add(serviceProxy, 1, 2, &result, heap, NULL, 0, NULL, error); if (FAILED(hr)) { goto Exit; } wprintf(L"%d + %d = %d\n", 1, 2, result); Exit: if (FAILED(hr)) { // Print out the error PrintError(hr, error); } if (serviceProxy != NULL) { WsCloseServiceProxy(serviceProxy, NULL, NULL); WsFreeServiceProxy(serviceProxy); } if (heap != NULL) { WsFreeHeap(heap); } if (error != NULL) { WsFreeError(error); } fflush(stdout); return SUCCEEDED(hr) ? 0 : -1; }
/****************************************************************************** * * Call the python object with all arguments * */ static void _CallPythonObject(void *mem, ffi_type *restype, SETFUNC setfunc, PyObject *callable, PyObject *converters, int flags, void **pArgs) { Py_ssize_t i; PyObject *result; PyObject *arglist = NULL; Py_ssize_t nArgs; PyObject *error_object = NULL; int *space; #ifdef WITH_THREAD PyGILState_STATE state = PyGILState_Ensure(); #endif nArgs = PySequence_Length(converters); /* Hm. What to return in case of error? For COM, 0xFFFFFFFF seems better than 0. */ if (nArgs < 0) { PrintError("BUG: PySequence_Length"); goto Done; } arglist = PyTuple_New(nArgs); if (!arglist) { PrintError("PyTuple_New()"); goto Done; } for (i = 0; i < nArgs; ++i) { /* Note: new reference! */ PyObject *cnv = PySequence_GetItem(converters, i); StgDictObject *dict; if (cnv) dict = PyType_stgdict(cnv); else { PrintError("Getting argument converter %d\n", i); goto Done; } if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { PyObject *v = dict->getfunc(*pArgs, dict->size); if (!v) { PrintError("create argument %d:\n", i); Py_DECREF(cnv); goto Done; } PyTuple_SET_ITEM(arglist, i, v); /* XXX XXX XX We have the problem that c_byte or c_short have dict->size of 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. BTW, the same problem occurs when they are pushed as parameters */ } else if (dict) { /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); if (!obj) { PrintError("create argument %d:\n", i); Py_DECREF(cnv); goto Done; } if (!CDataObject_Check(obj)) { Py_DECREF(obj); Py_DECREF(cnv); PrintError("unexpected result of create argument %d:\n", i); goto Done; } memcpy(obj->b_ptr, *pArgs, dict->size); PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); #ifdef MS_WIN32 TryAddRef(dict, obj); #endif } else { PyErr_SetString(PyExc_TypeError, "cannot build parameter"); PrintError("Parsing argument %d\n", i); Py_DECREF(cnv); goto Done; } Py_DECREF(cnv); /* XXX error handling! */ pArgs++; } #define CHECK(what, x) \ if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print() if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { error_object = _ctypes_get_errobj(&space); if (error_object == NULL) goto Done; if (flags & FUNCFLAG_USE_ERRNO) { int temp = space[0]; space[0] = errno; errno = temp; } #ifdef MS_WIN32 if (flags & FUNCFLAG_USE_LASTERROR) { int temp = space[1]; space[1] = GetLastError(); SetLastError(temp); } #endif } result = PyObject_CallObject(callable, arglist); CHECK("'calling callback function'", result); #ifdef MS_WIN32 if (flags & FUNCFLAG_USE_LASTERROR) { int temp = space[1]; space[1] = GetLastError(); SetLastError(temp); } #endif if (flags & FUNCFLAG_USE_ERRNO) { int temp = space[0]; space[0] = errno; errno = temp; } Py_XDECREF(error_object); if ((restype != &ffi_type_void) && result) { PyObject *keep; assert(setfunc); #ifdef WORDS_BIGENDIAN /* See the corresponding code in callproc.c, around line 961 */ if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) mem = (char *)mem + sizeof(ffi_arg) - restype->size; #endif keep = setfunc(mem, result, 0); CHECK("'converting callback result'", keep); /* keep is an object we have to keep alive so that the result stays valid. If there is no such object, the setfunc will have returned Py_None. If there is such an object, we have no choice than to keep it alive forever - but a refcount and/or memory leak will be the result. EXCEPT when restype is py_object - Python itself knows how to manage the refcount of these objects. */ if (keep == NULL) /* Could not convert callback result. */ PyErr_WriteUnraisable(callable); else if (keep == Py_None) /* Nothing to keep */ Py_DECREF(keep); else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { if (-1 == PyErr_Warn(PyExc_RuntimeWarning, "memory leak in callback function.")) PyErr_WriteUnraisable(callable); } } Py_XDECREF(result); Done: Py_XDECREF(arglist); #ifdef WITH_THREAD PyGILState_Release(state); #endif }
s32 DeviceTrayClose() { BOOL boolresult; DWORD byteswritten; DWORD errcode; if(devicehandle == NULL) return(-1); if(devicehandle == INVALID_HANDLE_VALUE) return(-1); if(traystatus == CDVD_TRAY_CLOSE) return(0); #ifdef VERBOSE_FUNCTION_DEVICE PrintLog("CDVDiso device: DeviceCloseTray()"); #endif /* VERBOSE_FUNCTION_DEVICE */ boolresult = DeviceIoControl(devicehandle, IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, &byteswritten, NULL); errcode = FinishCommand(boolresult); if(errcode != 0) { #ifdef VERBOSE_WARNING_DEVICE PrintLog("CDVDiso device: Couldn't signal media to load! (STORAGE)"); PrintError("CDVDiso device", errcode); #endif /* VERBOSE_WARNING_DEVICE */ // boolresult = DeviceIoControl(devicehandle, // IOCTL_CDROM_LOAD_MEDIA, // NULL, // 0, // NULL, // 0, // &byteswritten, // NULL); // } // ENDIF- Storage call failed. CDRom call? // if(boolresult == FALSE) { // errcode = GetLastError(); // #ifdef VERBOSE_WARNING_DEVICE // PrintLog("CDVDiso device: Couldn't signal media to load! (CDROM)"); // PrintError("CDVDiso device", errcode); // #endif /* VERBOSE_WARNING_DEVICE */ // boolresult = DeviceIoControl(devicehandle, // IOCTL_DISK_LOAD_MEDIA, // NULL, // 0, // NULL, // 0, // &byteswritten, // NULL); // } // ENDIF- CDRom call failed. Disk call? // if(boolresult == FALSE) { // #ifdef VERBOSE_WARNING_DEVICE // PrintLog("CDVDiso device: Couldn't signal media to load! (DISK)"); // PrintError("CDVDiso device", errcode); // #endif /* VERBOSE_WARNING_DEVICE */ return(-1); } // ENDIF- Media not available? return(0); } // END DeviceTrayClose()
/** * Install EFI driver - Will be the entrypoint for our driver executable * http://wiki.phoenix.com/wiki/index.php/EFI_IMAGE_ENTRY_POINT * * @v ImageHandle Handle identifying the loaded image * @v SystemTable Pointers to EFI system calls * @ret Status EFI status code to return on exit */ EFI_STATUS EFIAPI FSDriverInstall(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE* SystemTable) { EFI_STATUS Status; EFI_LOADED_IMAGE *LoadedImage = NULL; VOID *Interface; UINTN i; InitializeLib(ImageHandle, SystemTable); SetLogging(); EfiImageHandle = ImageHandle; /* Prevent the driver from being loaded twice by detecting and trying to * instantiate a custom protocol, which we use as a global mutex. */ MutexGUID = GetFSGuid(); Status = BS->LocateProtocol(MutexGUID, NULL, &Interface); if (Status == EFI_SUCCESS) { PrintError(L"This driver has already been installed\n"); return EFI_LOAD_ERROR; } /* The only valid status we expect is NOT FOUND here */ if (Status != EFI_NOT_FOUND) { PrintStatusError(Status, L"Could not locate global mutex"); return Status; } Status = LibInstallProtocolInterfaces(&MutexHandle, MutexGUID, &MutexProtocol, NULL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not install global mutex"); return Status; } /* Grab a handle to this image, so that we can add an unload to our driver */ Status = BS->OpenProtocol(ImageHandle, &LoadedImageProtocol, (VOID **) &LoadedImage, ImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not open loaded image protocol"); return Status; } /* Configure driver binding protocol */ FSDriverBinding.ImageHandle = ImageHandle; FSDriverBinding.DriverBindingHandle = ImageHandle; /* Install driver */ Status = LibInstallProtocolInterfaces(&FSDriverBinding.DriverBindingHandle, &DriverBindingProtocol, &FSDriverBinding, &ComponentNameProtocol, &FSComponentName, &ComponentName2Protocol, &FSComponentName2, NULL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not bind driver"); return Status; } /* Register the uninstall callback */ LoadedImage->Unload = FSDriverUninstall; /* Initialize the relevant GRUB fs module(s) */ // TODO: Eventually, we could try to turn each GRUB module into their // own EFI driver, have them register their interface and consume that. for (i = 0; GrubModuleInit[i] != NULL; i++) GrubModuleInit[i](); InitializeListHead(&FsListHead); PrintDebug(L"FS driver installed.\n"); return EFI_SUCCESS; }
s32 DeviceTrayOpen() { BOOL boolresult; DWORD byteswritten; DWORD errcode; if(devicehandle == NULL) return(-1); if(devicehandle == INVALID_HANDLE_VALUE) return(-1); if(traystatus == CDVD_TRAY_OPEN) return(0); #ifdef VERBOSE_FUNCTION_DEVICE PrintLog("CDVDiso device: DeviceOpenTray()"); #endif /* VERBOSE_FUNCTION_DEVICE */ boolresult = DeviceIoControl(devicehandle, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &byteswritten, &waitevent); errcode = FinishCommand(boolresult); if(errcode != 0) { #ifdef VERBOSE_WARNING_DEVICE PrintLog("CDVDiso device: Couldn't signal media to eject! (STORAGE)"); PrintError("CDVDiso device", errcode); #endif /* VERBOSE_WARNING_DEVICE */ // boolresult = DeviceIoControl(devicehandle, // IOCTL_DISK_EJECT_MEDIA, // NULL, // 0, // NULL, // 0, // &byteswritten, // NULL); // } // ENDIF- Storage Call failed? Try Disk call. // if(boolresult == FALSE) { // #ifdef VERBOSE_WARNING_DEVICE // PrintLog("CDVDiso device: Couldn't signal media to eject! (DISK)"); // PrintError("CDVDiso device", errcode); // #endif /* VERBOSE_WARNING_DEVICE */ return(-1); } // ENDIF- Disk Call failed as well? Give it up. return(0); } // END DeviceTrayOpen()
int PrintUserError(char *buffer) { return PrintError(buffer, "Incorrect command"); }
//HTTP CONNECT request exchange process bool __fastcall HTTP_CONNECTRequest( SOCKET_DATA *HTTPSocketData, fd_set *ReadFDS, fd_set *WriteFDS, timeval *Timeout, char *OriginalRecv, const size_t RecvSize) { //Initialization memset(OriginalRecv, 0, RecvSize); std::string HTTPString; HTTPString.append("CONNECT "); HTTPString.append(*Parameter.HTTP_TargetDomain); HTTPString.append(" HTTP/"); HTTPString.append(*Parameter.HTTP_Version); HTTPString.append("\r\nHost: "); HTTPString.append(*Parameter.HTTP_TargetDomain); HTTPString.append("\r\n"); if (Parameter.HTTP_HeaderField != nullptr && !Parameter.HTTP_HeaderField->empty()) HTTPString.append(*Parameter.HTTP_HeaderField); if (Parameter.HTTP_ProxyAuthorization != nullptr && !Parameter.HTTP_ProxyAuthorization->empty()) HTTPString.append(*Parameter.HTTP_ProxyAuthorization); HTTPString.append("\r\n"); //Socket timeout setting #if defined(PLATFORM_WIN) Timeout->tv_sec = Parameter.HTTP_SocketTimeout / SECOND_TO_MILLISECOND; Timeout->tv_usec = Parameter.HTTP_SocketTimeout % SECOND_TO_MILLISECOND * MICROSECOND_TO_MILLISECOND; #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) Timeout->tv_sec = Parameter.HTTP_SocketTimeout.tv_sec; Timeout->tv_usec = Parameter.HTTP_SocketTimeout.tv_usec; #endif //TCP connecting SSIZE_T RecvLen = SocketConnecting(IPPROTO_TCP, HTTPSocketData->Socket, (PSOCKADDR)&HTTPSocketData->SockAddr, HTTPSocketData->AddrLen, HTTPString.c_str(), HTTPString.length()); if (RecvLen == EXIT_FAILURE) { PrintError(LOG_ERROR_NETWORK, L"HTTP connecting error", 0, nullptr, 0); return false; } //HTTP CONNECT request exchange else if (RecvLen >= (SSIZE_T)DNS_PACKET_MINSIZE) { RecvLen = ProxySocketSelecting(HTTPSocketData->Socket, ReadFDS, WriteFDS, Timeout, nullptr, 0, OriginalRecv, RecvSize, HTTP_RESPONSE_MINSIZE, nullptr); } else { RecvLen = ProxySocketSelecting(HTTPSocketData->Socket, ReadFDS, WriteFDS, Timeout, HTTPString.c_str(), HTTPString.length(), OriginalRecv, RecvSize, HTTP_RESPONSE_MINSIZE, nullptr); } if (RecvLen < (SSIZE_T)HTTP_RESPONSE_MINSIZE) { PrintError(LOG_ERROR_NETWORK, L"HTTP request error", 0, nullptr, 0); return false; } else { OriginalRecv[RecvSize - 1U] = 0; HTTPString.clear(); HTTPString = OriginalRecv; } //HTTP CONNECT response check if (HTTPString.find("\r\n") == std::string::npos || HTTPString.find("HTTP/") == std::string::npos) { PrintError(LOG_ERROR_HTTP, L"HTTP server response error", 0, nullptr, 0); return false; } else if (HTTPString.find(" 200 ") == std::string::npos || HTTPString.find(" 200 ") >= HTTPString.find("\r\n")) //Not HTTP status code 200: OK { std::wstring wErrBuffer; HTTPString.erase(HTTPString.find("\r\n"), HTTPString.length() - HTTPString.find("\r\n")); MBSToWCSString(HTTPString.c_str(), HTTPString.length(), wErrBuffer); PrintError(LOG_ERROR_HTTP, wErrBuffer.c_str(), 0, nullptr, 0); return false; } return true; }
//----------------------------------------------------------------// void MOAIHttpTaskCurl::AffirmHandle () { if ( this->mEasyHandle ) return; CURLcode result; this->mEasyHandle = curl_easy_init (); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_HEADERFUNCTION, _writeHeader ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_HEADERDATA, this ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_WRITEFUNCTION, _writeData ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_WRITEDATA, this ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_FAILONERROR, 1 ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_NOPROGRESS, 0 ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_PROGRESSDATA, this ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_PROGRESSFUNCTION, _progressFunction ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_SSL_VERIFYPEER, 0 ); PrintError ( result ); result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_SSL_VERIFYHOST, 0 ); PrintError ( result ); #ifdef USE_ARES result = curl_easy_setopt ( this->mEasyHandle, CURLOPT_NOSIGNAL, 1 ); PrintError ( result ); #endif }