void* sendPackets(void* data) { // Send Header Header* h = initHeader(filename, "dave"); char* h_s = serializeHeader(h); sendto(sock, h_s, strlen(h_s), 0, (struct sockaddr *) &servAddr, sizeof(servAddr)); // Send the packets for (;;) { if (!isEmpty(ph)) { char *s; Packet* p = malloc(sizeof(Packet)); getLock(ph); p = removePacket(ph, p); // Get packet unlock(ph); s = serializePacket(p); // Convert into sendable char array sendto(sock, s, strlen(s), 0, (struct sockaddr *) &servAddr, sizeof(servAddr)); if (p->fragment == DUMMY_FRAG_NUM) { printf("Done Sending!!\n"); pthread_exit(0); } } } }
bool CipherFileIO::writeOneBlock(const IORequest &req) { if (haveHeader && fsConfig->reverseEncryption) { VLOG(1) << "writing to a reverse mount with per-file IVs is not implemented"; return false; } int bs = blockSize(); off_t blockNum = req.offset / bs; if (haveHeader && fileIV == 0) initHeader(); bool ok; if (req.dataLen != bs) { ok = streamWrite(req.data, (int)req.dataLen, blockNum ^ fileIV); } else { ok = blockWrite(req.data, (int)req.dataLen, blockNum ^ fileIV); } if (ok) { if (haveHeader) { IORequest tmpReq = req; tmpReq.offset += HEADER_SIZE; ok = base->write(tmpReq); } else ok = base->write(req); } else { VLOG(1) << "encodeBlock failed for block " << blockNum << ", size " << req.dataLen; ok = false; } return ok; }
void init(){ LOGGER = log_create(LOG_PATH, "MaRTA", true, LOG_LEVEL_DEBUG); CONF = config_create(CONF_PATH); //HACK estaba mal el nombre de la funcion o no la encontraba o no se if(LOGGER == NULL){ perror("ERROR! no pudo levantar ni el log!"); exit(EXIT_FAILURE); } if(CONF == NULL){ log_error(LOGGER, "\nERROR AL LEVANTAR ARCHIVO DE CONFIGURACION\n( Don't PANIC! Si estas por consola ejecuta: ln -s ../%s %s )\n\n" , CONF_PATH , CONF_PATH); exit(EXIT_FAILURE); } // if(!validarConfig()){ //HACK no lo necesitaba, no entendi el codigo del map y no me servia, anda :P // log_error(LOGGER, "No pudo obtenerse alguno de los parametros de configuracion"); // exit(EXIT_FAILURE); // } mapa_nodos = dictionary_create(); lista_jobs = list_create(); pthread_mutex_init(&mutex_mapa_nodos, NULL); pthread_mutex_init(&mutex_lista_jobs, NULL); log_info(LOGGER, "intenta conectarse a la ip %s con puerto %d", config_get_string_value(CONF, "IP_FS"), config_get_int_value(CONF, "PUERTO_FS")); socketFS = conectarAServidor(config_get_string_value(CONF, "IP_FS"), config_get_int_value(CONF, "PUERTO_FS")); while (socketFS == -1) { log_info(LOGGER, "Filesystem no levantado. Se reintenta conexion en unos segundos"); sleep(5); socketFS = conectarAServidor(config_get_string_value(CONF, "IP_FS"), config_get_int_value(CONF, "PUERTO_FS")); } header_t header; initHeader(&header); header.tipo = MARTA_TO_FS_HANDSHAKE; header.largo_mensaje = 0; header.cantidad_paquetes = 1; log_info(LOGGER, "Conectado a FS! envio header %s", getDescription(header.tipo)); enviar_header(socketFS, &header); t_mensaje mensaje; memset(&mensaje, 0, sizeof(t_mensaje)); recibir_t_mensaje(socketFS, &mensaje); log_info(LOGGER, "recibo respuesta %s de FS", getDescription(mensaje.tipo)); while(mensaje.tipo != ACK){ log_info(LOGGER, "Todavia el FS no esta disponible. Header recibido: %s. Reintento en 5 segundos", getDescription(header.tipo)); sleep(5); enviar_header(socketFS, &header); recibir_t_mensaje(socketFS, &mensaje); } recibirNodosFS(); log_info(LOGGER, "%s: FS está operativo. Continúo", getDescription(header.tipo)); }
void QtChatHistoryWidget::init(const QString & contactId, const QString & senderName, const QString & accountId, const QTime & time, const QDate & date){ initHeader(contactId,senderName,accountId,time,date); _theme->initTemplate(); setHtml(_theme->getTemplate(), QUrl(_theme->getThemePath())); }
LRESULT DownloadPage::onInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { PropPage::translate(texts); initHeader(IDC_DOWNLOADPAGE_TITLE); PropPage::read(items); updateDirectoryControlsLayout(); CUpDownCtrl(GetDlgItem(IDC_FILESPIN)).SetRange32(0, 100); CUpDownCtrl(GetDlgItem(IDC_SLOTSSPIN)).SetRange32(0, 100); CUpDownCtrl(GetDlgItem(IDC_SPEEDSPIN)).SetRange32(0, 10000); return TRUE; }
Monitor::Monitor() { monitor_model = new QStandardItemModel(); monitor_model->setObjectName("monitor_model"); initHeader(); monitor_model_proxy = new MonitorFilter(); monitor_model_proxy->setSourceModel(monitor_model); initMas(); }
bool CipherFileIO::setIV(uint64_t iv) { rDebug("in setIV, current IV = %" PRIu64 ", new IV = %" PRIu64 ", fileIV = %" PRIu64, externalIV, iv, fileIV); if (externalIV == 0) { // we're just being told about which IV to use. since we haven't // initialized the fileIV, there is no need to just yet.. externalIV = iv; if (fileIV != 0) rWarning("fileIV initialized before externalIV! (%" PRIu64 ", %" PRIu64 ")", fileIV, externalIV); } else if (haveHeader) { // we have an old IV, and now a new IV, so we need to update the fileIV // on disk. if (fileIV == 0) { // ensure the file is open for read/write.. int newFlags = lastFlags | O_RDWR; int res = base->open(newFlags); if (res < 0) { if (res == -EISDIR) { // duh -- there are no file headers for directories! externalIV = iv; return base->setIV(iv); } else { rDebug("writeHeader failed to re-open for write"); return false; } } initHeader(); } uint64_t oldIV = externalIV; externalIV = iv; if (!writeHeader()) { externalIV = oldIV; return false; } } return base->setIV(iv); }
omr_error_t initialiseComponentList(UtComponentList **componentListPtr) { OMRPORT_ACCESS_FROM_OMRPORT(OMR_TRACEGLOBAL(portLibrary)); UtComponentList *componentList = (UtComponentList *)omrmem_allocate_memory(sizeof(UtComponentList), OMRMEM_CATEGORY_TRACE); UT_DBGOUT(2, ("<UT> initialiseComponentList: %p\n", componentListPtr)); if (componentList == NULL) { UT_DBGOUT(1, ("<UT> Unable to allocate component list\n")); return OMR_ERROR_OUT_OF_NATIVE_MEMORY; } initHeader(&componentList->header, UT_TRACE_COMPONENT_LIST, sizeof(UtComponentList)); componentList->head = NULL; componentList->deferredConfigInfoHead = NULL; *componentListPtr = componentList; UT_DBGOUT(2, ("<UT> initialiseComponentList: %p completed\n", componentListPtr)); return OMR_ERROR_NONE; }
/* * Helper for empty array -> packed transitions. Creates an array * with one element. The element is transferred into the array (should * already be incref'd). */ ALWAYS_INLINE ArrayLval EmptyArray::MakePackedInl(TypedValue tv) { auto const cap = kPackedSmallSize; auto const ad = static_cast<ArrayData*>( MM().objMalloc(sizeof(ArrayData) + cap * sizeof(TypedValue)) ); assert(cap == CapCode::ceil(cap).code); ad->m_sizeAndPos = 1; // size=1, pos=0 ad->initHeader(CapCode::exact(cap), HeaderKind::Packed, 1); auto const lval = reinterpret_cast<TypedValue*>(ad + 1); lval->m_data = tv.m_data; lval->m_type = tv.m_type; assert(ad->kind() == ArrayData::kPackedKind); assert(ad->m_size == 1); assert(ad->m_pos == 0); assert(ad->hasExactlyOneRef()); assert(PackedArray::checkInvariants(ad)); return { ad, &tvAsVariant(lval) }; }
int CipherFileIO::truncate(off_t size) { int res = 0; if (!haveHeader) { res = BlockFileIO::truncateBase(size, base.get()); } else { if (0 == fileIV) { // empty file.. create the header.. if (!base->isWritable()) { // open for write.. int newFlags = lastFlags | O_RDWR; if (base->open(newFlags) < 0) VLOG(1) << "writeHeader failed to re-open for write"; } initHeader(); } // can't let BlockFileIO call base->truncate(), since it would be using // the wrong size.. res = BlockFileIO::truncateBase(size, 0); if (res == 0) base->truncate(size + HEADER_SIZE); } return res; }
omr_error_t initialiseComponentData(UtComponentData **componentDataPtr, UtModuleInfo *moduleInfo, const char *componentName) { OMRPORT_ACCESS_FROM_OMRPORT(OMR_TRACEGLOBAL(portLibrary)); UtComponentData *componentData = (UtComponentData *)omrmem_allocate_memory(sizeof(UtComponentData), OMRMEM_CATEGORY_TRACE); UT_DBGOUT(2, ("<UT> initialiseComponentData: %s\n", componentName)); if (componentData == NULL) { UT_DBGOUT(1, ("<UT> Unable to allocate componentData for %s\n", componentName)); return OMR_ERROR_OUT_OF_NATIVE_MEMORY; } initHeader(&componentData->header, UT_TRACE_COMPONENT_DATA, sizeof(UtComponentData)); componentData->componentName = (char *)omrmem_allocate_memory(strlen(componentName) + 1, OMRMEM_CATEGORY_TRACE); if (componentData->componentName == NULL) { UT_DBGOUT(1, ("<UT> Unable to allocate componentData's name field for %s\n", componentName)); return OMR_ERROR_OUT_OF_NATIVE_MEMORY; } strcpy(componentData->componentName, componentName); /* Setup the fully qualified name here as when we come to print out trace counters the modules may have been * freed already. */ if (moduleInfo->traceVersionInfo->traceVersion >= 7 && moduleInfo->containerModule != NULL) { char qualifiedName[MAX_QUALIFIED_NAME_LENGTH]; omrstr_printf(qualifiedName, MAX_QUALIFIED_NAME_LENGTH, "%s(%s)", moduleInfo->name, moduleInfo->containerModule->name); componentData->qualifiedComponentName = (char *)omrmem_allocate_memory(strlen(qualifiedName) + 1, OMRMEM_CATEGORY_TRACE); if (componentData->qualifiedComponentName == NULL) { UT_DBGOUT(1, ("<UT> Unable to allocate componentData's name field for %s\n", componentName)); return OMR_ERROR_OUT_OF_NATIVE_MEMORY; } strcpy(componentData->qualifiedComponentName, qualifiedName); } else { componentData->qualifiedComponentName = componentData->componentName; } if (moduleInfo->formatStringsFileName != NULL) { componentData->formatStringsFileName = (char *)omrmem_allocate_memory(strlen(moduleInfo->formatStringsFileName) + 1, OMRMEM_CATEGORY_TRACE); if (componentData->formatStringsFileName == NULL) { UT_DBGOUT(1, ("<UT> Unable to allocate componentData's format strings file name field for %s\n", componentName)); return OMR_ERROR_OUT_OF_NATIVE_MEMORY; } strcpy(componentData->formatStringsFileName, moduleInfo->formatStringsFileName); } else { componentData->formatStringsFileName = NULL; } componentData->moduleInfo = moduleInfo; componentData->tracepointCount = moduleInfo->count; componentData->numFormats = 0; componentData->tracepointFormattingStrings = NULL; componentData->tracepointcounters = NULL; componentData->alreadyfailedtoloaddetails = 0; componentData->next = NULL; componentData->prev = NULL; *componentDataPtr = componentData; UT_DBGOUT(2, ("<UT> initialiseComponentData complete: %s\n", componentName)); return OMR_ERROR_NONE; }
Initializer() { auto const ad = reinterpret_cast<ArrayData*>(&s_theEmptyArray); ad->m_sizeAndPos = 0; ad->initHeader(HeaderKind::Empty, StaticValue); }
LRESULT MagnetPage::onInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { PropPage::translate(texts); initHeader(IDC_MAGNETPAGE_TITLE); PropPage::read(items); return TRUE; }
void escucha(int puerto) { int myPID = process_get_thread_id(); log_info(LOGGER, "************** Comienza a escuchar MaRTA a los Jobs (PID: %d) ***************",myPID); //Logica principal para administrar conexiones fd_set master; //file descriptor list fd_set read_fds; //file descriptor list temporal para el select() int fdmax; //maximo numero de file descriptor para hacer las busquedas en comunicaciones int listener;//socket escucha int newfd;//file descriptor del cliente aceptado struct sockaddr_storage remoteaddr; //dirección del cliente socklen_t addrlen; char remoteIP[INET6_ADDRSTRLEN]; int i; // socket entrante struct addrinfo hints; FD_ZERO(&master); //clear the master FD_ZERO(&read_fds); //clear the temp set //Lleno la estructura de tipo addrinfo memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; t_socket_info socketInfo; socketInfo.sin_addr.s_addr = INADDR_ANY; socketInfo.sin_family = AF_INET; socketInfo.sin_port = htons(puerto); memset(&(socketInfo.sin_zero), '\0', 8); listener = crearSocket(); bindearSocket(listener, socketInfo); // listen turns on server mode for a socket. if (listen(listener, 10) == -1) { perror("listen"); exit(3); } // add the listener to the master set FD_SET(listener, &master); // keep track of the biggest file descriptor fdmax = listener; // so far, it's this one for(;;){ read_fds = master; // copy it if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(4); } // run through the existing connections looking for data to read for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) { // we got one!! if (i == listener) { // handle new connections addrlen = sizeof remoteaddr; newfd = accept(listener, (struct sockaddr *) &remoteaddr, &addrlen); if (newfd == -1) { log_error(LOGGER, string_from_format( "Hubo un error en el accept para el fd: %i", i)); } else { FD_SET(newfd, &master); // add to master set if (newfd > fdmax) { // keep track of the max fdmax = newfd; } //Shows the new connection administrated log_info(LOGGER, string_from_format( "selectserver: new connection from %s on socket %d\n", inet_ntop(remoteaddr.ss_family, get_in_addr( (struct sockaddr*) &remoteaddr), remoteIP, INET6_ADDRSTRLEN), newfd)); } } else { header_t header; initHeader(&header); log_info(LOGGER, "Esperamos recibir mensajes de los Jobs"); if(recibir_header_simple(i, &header) != EXITO){ log_error(LOGGER, "Error al recibir header. Considero que viene de un cliente que se cayó"); header.tipo = ERR_CONEXION_CERRADA; } log_info(LOGGER, "Mensaje recibido! Header: %s", getDescription(header.tipo)); switch(header.tipo){ case ERR_CONEXION_CERRADA: close(i); FD_CLR(i, &master); job_eliminar(i, header); break; case JOB_TO_MARTA_FILES: // agrego el job a la lista sincronizada, gestiono las estructuras y blah job_agregar(i, header); // le pido al fs los bloques de los archivos del job y actualizo el job de la lista procesarArchivos(i, header); break; case JOB_TO_MARTA_MAP_OK: notificarMapOk(i, header); break; case JOB_TO_MARTA_MAP_ERROR: notificarMapError(i, header); break; case JOB_TO_MARTA_REDUCE_OK: notificarReduceOk(i, header); break; case JOB_TO_MARTA_REDUCE_ERROR: notificarReduceError(i, header); break; default: log_error(LOGGER, "ERROR mensaje NO RECONOCIDO (%d) !!\n", header); } } } } } }
void principal () { int id_proceso, i, se_desconecto; int fin = false; int sockPlataforma = -1; header_t header; fd_set master; fd_set read_fds; FD_ZERO(&master); FD_ZERO(&read_fds); int max_desc = 0; char buffer[BUF_LEN]; id_proceso = getpid(); log_info(LOGGER,"************** Iniciando Nivel '%s' (PID: %d) ***************\n", NOMBRENIVEL, id_proceso); // Conectar con proceso Plataforma conectar(configNivelPlataformaIp(), configNivelPlataformaPuerto(), &sockPlataforma); if (enviarMSJNuevoNivel(sockPlataforma) != EXITO) { log_error(LOGGER, "ERROR en conexion con Plataforma"); finalizarNivel(); exit(EXIT_FAILURE); } // Agrego descriptor del socket de conexion con plataforma agregar_descriptor(sockPlataforma, &master, &max_desc); // Agrego descriptor del inotify agregar_descriptor(notifyFD, &master, &max_desc); // Agrego descriptor de comunicacion con hilo de interbloqueo por pipe agregar_descriptor(hiloInterbloqueo.fdPipeI2N[0], &master, &max_desc); // Agrego fd del pipe con hilos enemigos agregarFDPipeEscuchaEnemigo(&master, &max_desc); // Lanzo Hilo de Interbloqueo pthread_create (&hiloInterbloqueo.tid, NULL, (void*) interbloqueo, NULL); while(!fin) { FD_ZERO (&read_fds); read_fds = master; if((select(max_desc+1, &read_fds, NULL, NULL, NULL)) == -1) { log_error(LOGGER, "NIVEL_MAIN ERROR en el select"); } else { for(i = 0; i <= max_desc; i++) { if (FD_ISSET(i, &read_fds)) { if (i == sockPlataforma) { log_debug(LOGGER, "1) recibo mensaje socket %d", i); initHeader(&header); recibir_header(i, &header, &master, &se_desconecto); if(se_desconecto) { log_info(LOGGER, "Se desconecto el socket %d ", i); quitar_descriptor(i, &master, &max_desc); } else { log_debug(LOGGER, "Llego mensaje %d (fd:%d)", header.tipo, i); switch(header.tipo) { case NIVEL_CONECTADO: log_info(LOGGER, "Llego mensaje '%d' NIVEL_CONECTADO (fd:%d)", header.tipo, i); break; case NUEVO_PERSONAJE: log_info(LOGGER, "Llego mensaje '%d' NUEVO_PERSONAJE (fd:%d)", header.tipo, i); tratarNuevoPersonaje(i, header, &master); break; case SOLICITUD_UBICACION: log_info(LOGGER, "Llego mensaje '%d' SOLICITUD_UBICACION (fd:%d)", header.tipo, i); tratarSolicitudUbicacion(i, header, &master); break; case SOLICITUD_RECURSO: log_info(LOGGER, "Llego mensaje '%d' SOLICITUD_RECURSO (fd:%d)", header.tipo, i); tratarSolicitudRecurso(i, header, &master); break; case MOVIMIENTO_REALIZADO: log_info(LOGGER, "Llego mensaje '%d' MOVIMIENTO_REALIZADO (fd:%d)", header.tipo, i); tratarMovimientoRealizado(i, header, &master); break; case PLAN_NIVEL_FINALIZADO: log_info(LOGGER, "Llego mensaje '%d' PLAN_NIVEL_FINALIZADO (fd:%d)", header.tipo, i); tratarPlanNivelFinalizado (i, header, &master); break; case MUERTE_PERSONAJE: log_info(LOGGER, "Llego mensaje '%d' MUERTE_PERSONAJE (fd:%d)", header.tipo, i); tratarMuertePersonaje (i, header, &master); break; case PERSONAJE_DESBLOQUEADO: log_info(LOGGER, "Llego mensaje '%d' PERSONAJE_DESBLOQUEADO (fd:%d)", header.tipo, i); desbloquearPersonaje(i, header, &master); break; default: log_error(LOGGER, "Llego mensaje '%d' NO RECONOCIDO (fd:%d)", header.tipo, i); break; } } } else if (i == notifyFD) { log_info(LOGGER, "Hubo un cambio en el archivo de configuracion (fd:%d)", i); read(notifyFD, buffer, BUF_LEN); levantarCambiosArchivoConfiguracionNivel(); log_info(LOGGER, "Nuevos Valores: algoritmo=%s - quantum=%d - retardo=%d", configNivelAlgoritmo(), configNivelQuantum(), configNivelRetardo()); enviarMsjCambiosConfiguracion(sockPlataforma); } else if ( i == hiloInterbloqueo.fdPipeI2N[0]) { // Llega mensaje desde hilo interbloqueo por Pipe log_info(LOGGER, "NivelMain: Recibo mensaje desde Interbloqueo por Pipe: %d", i); initHeader(&header); read (i, &header, sizeof(header_t)); log_debug(LOGGER, "NivelMain: mensaje recibido '%d'", header.tipo); switch (header.tipo) { case MUERTE_PERSONAJE_XRECOVERY: log_debug(LOGGER, "'%d' ES MUERTE_PERSONAJE_XRECOVERY", header.tipo); // TODO Mover personaje a una lista de fiambres?? // informar al planificador enviarMsjMuertexRecovery(sockPlataforma); break; } } else { // NO ES NI notifyFD NI mi Planificador Ni el hilo de Interbloqueo // Entonces debe ser un hilo Enemigo log_debug(LOGGER, "NivelMain: actividad en el socket %d", i); log_info(LOGGER, "NivelMain: Recibo mensaje desde Enemigo por Pipe: %d", i); initHeader(&header); read (i, &header, sizeof(header_t)); log_debug(LOGGER, "NivelMain: mensaje recibido '%d'", header.tipo); switch (header.tipo) { case MUERTE_PERSONAJE_XENEMIGO: log_debug(LOGGER, "'%d' ES MUERTE_PERSONAJE_XENEMIGO", header.tipo); // TODO mover personaje a lista de fiambres ?? // informar al planificador enviarMsjMuertexEnemigo(sockPlataforma); break; } // if(se_desconecto) // { // log_info(LOGGER, "Se desconecto el socket %d", i); // quitar_descriptor(i, &master, &max_desc); // // } else { // log_debug(LOGGER, "2) Llego mensaje del socket %d: %d NO RECONOCIDO", i, header.tipo); // } } } } } } // Cierro while pthread_join (hiloInterbloqueo.tid, NULL); //espera que finalice el hilo de interbloqueo para continuar close (sockPlataforma); return; }
/** * Очищает модель монитора. */ void Monitor::clear() { monitor_model->clear(); initHeader(); }