int csync_init(CSYNC *ctx) { int rc; time_t timediff = -1; char *exclude = NULL; char *lock = NULL; char *config = NULL; char errbuf[256] = {0}; if (ctx == NULL) { errno = EBADF; return -1; } ctx->status_code = CSYNC_STATUS_OK; /* Do not initialize twice */ if (ctx->status & CSYNC_STATUS_INIT) { return 1; } /* create dir if it doesn't exist */ if (! c_isdir(ctx->options.config_dir)) { c_mkdirs(ctx->options.config_dir, 0700); } /* create lock file */ if (asprintf(&lock, "%s/%s", ctx->options.config_dir, CSYNC_LOCK_FILE) < 0) { rc = -1; ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; goto out; } #ifndef _WIN32 if (csync_lock(lock) < 0) { rc = -1; ctx->status_code = CSYNC_STATUS_NO_LOCK; goto out; } #endif /* load config file */ if (asprintf(&config, "%s/%s", ctx->options.config_dir, CSYNC_CONF_FILE) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } rc = csync_config_parse_file(ctx, config); if (rc < 0) { CSYNC_LOG(CSYNC_LOG_PRIORITY_WARN, "Could not load config file %s, using defaults.", config); } #ifndef _WIN32 /* load global exclude list */ if (asprintf(&exclude, "%s/csync/%s", SYSCONFDIR, CSYNC_EXCLUDE_FILE) < 0) { rc = -1; ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; goto out; } if (csync_exclude_load(ctx, exclude) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_WARN, "Could not load %s - %s", exclude, errbuf); } SAFE_FREE(exclude); #endif /* load exclude list */ if (asprintf(&exclude, "%s/%s", ctx->options.config_dir, CSYNC_EXCLUDE_FILE) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } if (csync_exclude_load(ctx, exclude) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_INFO, "Could not load %s - %s", exclude, errbuf); } /* create/load statedb */ if (! csync_is_statedb_disabled(ctx)) { rc = asprintf(&ctx->statedb.file, "%s/.csync_journal.db", ctx->local.uri); if (rc < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; goto out; } CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "Journal: %s", ctx->statedb.file); rc = csync_statedb_load(ctx, ctx->statedb.file, &ctx->statedb.db); if (rc < 0) { ctx->status_code = CSYNC_STATUS_STATEDB_LOAD_ERROR; goto out; } } ctx->local.type = LOCAL_REPLICA; /* check for uri */ if ( !ctx->options.local_only_mode && csync_fnmatch("*://*", ctx->remote.uri, 0) == 0) { size_t len; len = strstr(ctx->remote.uri, "://") - ctx->remote.uri; /* get protocol */ if (len > 0) { char *module = NULL; /* module name */ module = c_strndup(ctx->remote.uri, len); if (module == NULL) { rc = -1; ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; goto out; } /* load module */ retry_vio_init: rc = csync_vio_init(ctx, module, NULL); if (rc < 0) { len = strlen(module); if (module[len-1] == 's') { module[len-1] = '\0'; goto retry_vio_init; } SAFE_FREE(module); ctx->status_code = CSYNC_STATUS_NO_MODULE; goto out; } SAFE_FREE(module); ctx->remote.type = REMOTE_REPLICA; } } else { ctx->remote.type = LOCAL_REPLICA; } if( !ctx->options.local_only_mode ) { timediff = csync_timediff(ctx); if (timediff > ctx->options.max_time_difference) { CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Clock skew detected. The time difference is greater than %d seconds!", ctx->options.max_time_difference); ctx->status_code = CSYNC_STATUS_TIMESKEW; rc = -1; goto out; } else if (timediff < 0) { CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Synchronisation is not possible!"); ctx->status_code = CSYNC_STATUS_TIMESKEW; rc = -1; goto out; } if (csync_unix_extensions(ctx) < 0) { CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Could not detect filesystem type."); ctx->status_code = CSYNC_STATUS_FILESYSTEM_UNKNOWN; rc = -1; goto out; } } /* Install progress callbacks in the module. */ if (ctx->callbacks.file_progress_cb != NULL) { int prc; prc = csync_vio_set_property(ctx, "file_progress_callback", &ctx->callbacks.file_progress_cb); if (prc == -1) { /* The module does not support the callbacks */ CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "Could not install file progress callback!"); ctx->callbacks.file_progress_cb = NULL; } } if (ctx->callbacks.overall_progress_cb != NULL) { int prc; prc = csync_vio_set_property(ctx, "overall_progress_callback", &ctx->callbacks.overall_progress_cb); if (prc == -1) { /* The module does not support the callbacks */ CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "Could not install overall progress callback!"); ctx->callbacks.overall_progress_cb = NULL; } } if (c_rbtree_create(&ctx->local.tree, _key_cmp, _data_cmp) < 0) { ctx->status_code = CSYNC_STATUS_TREE_ERROR; rc = -1; goto out; } if (c_rbtree_create(&ctx->remote.tree, _key_cmp, _data_cmp) < 0) { ctx->status_code = CSYNC_STATUS_TREE_ERROR; rc = -1; goto out; } ctx->status = CSYNC_STATUS_INIT; /* initialize random generator */ srand(time(NULL)); rc = 0; out: SAFE_FREE(lock); SAFE_FREE(exclude); SAFE_FREE(config); return rc; }
const char* strerror_tl(int savedErrno) { return strerror_r(savedErrno, t_errnobuf, sizeof t_errnobuf); }
/*! * \brief This function ... */ static int create_ssdp_sock_v6_ula_gua( /*! [] SSDP IPv6 socket to be created. */ SOCKET * ssdpSock) { char errorBuffer[ERROR_BUFFER_LEN]; struct ipv6_mreq ssdpMcastAddr; struct sockaddr_storage __ss; struct sockaddr_in6 *ssdpAddr6 = (struct sockaddr_in6 *)&__ss; int onOff; int ret = 0; *ssdpSock = socket_no_sigpipe(AF_INET6, SOCK_DGRAM, 0); if (*ssdpSock == INVALID_SOCKET) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in socket(): %s\n", errorBuffer); return UPNP_E_OUTOF_SOCKET; } onOff = 1; ret = setsockopt(*ssdpSock, SOL_SOCKET, SO_REUSEADDR, (char *)&onOff, sizeof(onOff)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() SO_REUSEADDR: %s\n", errorBuffer); ret = UPNP_E_SOCKET_ERROR; goto error_handler; } #if defined(BSD) || defined(__OSX__) || defined(__APPLE__) onOff = 1; ret = setsockopt(*ssdpSock, SOL_SOCKET, SO_REUSEPORT, (char *)&onOff, sizeof(onOff)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() SO_REUSEPORT: %s\n", errorBuffer); ret = UPNP_E_SOCKET_ERROR; goto error_handler; } #endif /* BSD, __OSX__, __APPLE__ */ onOff = 1; ret = setsockopt(*ssdpSock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&onOff, sizeof(onOff)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() IPV6_V6ONLY: %s\n", errorBuffer); ret = UPNP_E_SOCKET_ERROR; goto error_handler; } memset(&__ss, 0, sizeof(__ss)); ssdpAddr6->sin6_family = (sa_family_t)AF_INET6; ssdpAddr6->sin6_addr = in6addr_any; ssdpAddr6->sin6_scope_id = gIF_INDEX; ssdpAddr6->sin6_port = htons(SSDP_PORT); ret = bind(*ssdpSock, (struct sockaddr *)ssdpAddr6, sizeof(*ssdpAddr6)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in bind(), addr=0x%032lX, port=%d: %s\n", 0lu, SSDP_PORT, errorBuffer); ret = UPNP_E_SOCKET_BIND; goto error_handler; } memset((void *)&ssdpMcastAddr, 0, sizeof(ssdpMcastAddr)); ssdpMcastAddr.ipv6mr_interface = gIF_INDEX; /* SITE LOCAL */ inet_pton(AF_INET6, SSDP_IPV6_SITELOCAL, &ssdpMcastAddr.ipv6mr_multiaddr); ret = setsockopt(*ssdpSock, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char *)&ssdpMcastAddr, sizeof(ssdpMcastAddr)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() IPV6_JOIN_GROUP (join multicast group): %s\n", errorBuffer); ret = UPNP_E_SOCKET_ERROR; goto error_handler; } onOff = 1; ret = setsockopt(*ssdpSock, SOL_SOCKET, SO_BROADCAST, (char *)&onOff, sizeof(onOff)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() SO_BROADCAST (set broadcast): %s\n", errorBuffer); ret = UPNP_E_NETWORK_ERROR; goto error_handler; } ret = UPNP_E_SUCCESS; error_handler: if (ret != UPNP_E_SUCCESS) { if (shutdown(*ssdpSock, SD_BOTH) == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__, "Error in shutdown: %s\n", errorBuffer); } UpnpCloseSocket(*ssdpSock); } return ret; }
int test__syscall_openat_tp_fields(int subtest __maybe_unused) { struct record_opts opts = { .target = { .uid = UINT_MAX, .uses_mmap = true, }, .no_buffering = true, .freq = 1, .mmap_pages = 256, .raw_samples = true, }; const char *filename = "/etc/passwd"; int flags = O_RDONLY | O_DIRECTORY; struct perf_evlist *evlist = perf_evlist__new(); struct perf_evsel *evsel; int err = -1, i, nr_events = 0, nr_polls = 0; char sbuf[STRERR_BUFSIZE]; if (evlist == NULL) { pr_debug("%s: perf_evlist__new\n", __func__); goto out; } evsel = perf_evsel__newtp("syscalls", "sys_enter_openat"); if (IS_ERR(evsel)) { pr_debug("%s: perf_evsel__newtp\n", __func__); goto out_delete_evlist; } perf_evlist__add(evlist, evsel); err = perf_evlist__create_maps(evlist, &opts.target); if (err < 0) { pr_debug("%s: perf_evlist__create_maps\n", __func__); goto out_delete_evlist; } perf_evsel__config(evsel, &opts, NULL); thread_map__set_pid(evlist->threads, 0, getpid()); err = perf_evlist__open(evlist); if (err < 0) { pr_debug("perf_evlist__open: %s\n", strerror_r(errno, sbuf, sizeof(sbuf))); goto out_delete_evlist; } err = perf_evlist__mmap(evlist, UINT_MAX, false); if (err < 0) { pr_debug("perf_evlist__mmap: %s\n", strerror_r(errno, sbuf, sizeof(sbuf))); goto out_delete_evlist; } perf_evlist__enable(evlist); /* * Generate the event: */ openat(AT_FDCWD, filename, flags); while (1) { int before = nr_events; for (i = 0; i < evlist->nr_mmaps; i++) { union perf_event *event; while ((event = perf_evlist__mmap_read(evlist, i)) != NULL) { const u32 type = event->header.type; int tp_flags; struct perf_sample sample; ++nr_events; if (type != PERF_RECORD_SAMPLE) { perf_evlist__mmap_consume(evlist, i); continue; } err = perf_evsel__parse_sample(evsel, event, &sample); if (err) { pr_debug("Can't parse sample, err = %d\n", err); goto out_delete_evlist; } tp_flags = perf_evsel__intval(evsel, &sample, "flags"); if (flags != tp_flags) { pr_debug("%s: Expected flags=%#x, got %#x\n", __func__, flags, tp_flags); goto out_delete_evlist; } goto out_ok; } } if (nr_events == before) perf_evlist__poll(evlist, 10); if (++nr_polls > 5) { pr_debug("%s: no events!\n", __func__); goto out_delete_evlist; } } out_ok: err = 0; out_delete_evlist: perf_evlist__delete(evlist); out: return err; }
void posix_error(int code, char *msg) { char code_msg[MAXLINE]; fprintf(stderr, "%s: %s\n", msg, strerror_r(code, code_msg, MAXLINE)); exit(0); }
/** * Add a message to a queue * * This function provides basic functionnalities to other msg_* functions. * It adds a message to a queue (after having printed all stored messages if it * is full). If the message can't be converted to string in memory, it issues * a warning. */ static void QueueMsg( vlc_object_t *p_this, int i_type, const char *psz_module, const char *psz_format, va_list _args ) { assert (p_this); libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc); int i_header_size; /* Size of the additionnal header */ vlc_object_t *p_obj; char * psz_str = NULL; /* formatted message string */ char * psz_header = NULL; va_list args; msg_item_t * p_item = NULL; /* pointer to message */ msg_item_t item; /* message in case of a full queue */ msg_queue_t *p_queue; #if !defined(HAVE_VASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS) int i_size = strlen(psz_format) + INTF_MAX_MSG_SIZE; #endif if( p_this->i_flags & OBJECT_FLAGS_QUIET || (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) ) return; #ifndef __GLIBC__ /* Expand %m to strerror(errno) - only once */ char buf[strlen( psz_format ) + 2001], *ptr; strcpy( buf, psz_format ); ptr = (char*)buf; psz_format = (const char*) buf; for( ;; ) { ptr = strchr( ptr, '%' ); if( ptr == NULL ) break; if( ptr[1] == 'm' ) { char errbuf[2001]; size_t errlen; #ifndef WIN32 strerror_r( errno, errbuf, 1001 ); #else int sockerr = WSAGetLastError( ); if( sockerr ) { strncpy( errbuf, net_strerror( sockerr ), 1001 ); WSASetLastError( sockerr ); } if ((sockerr == 0) || (strcmp ("Unknown network stack error", errbuf) == 0)) strncpy( errbuf, strerror( errno ), 1001 ); #endif errbuf[1000] = 0; /* Escape '%' from the error string */ for( char *percent = strchr( errbuf, '%' ); percent != NULL; percent = strchr( percent + 2, '%' ) ) { memmove( percent + 1, percent, strlen( percent ) + 1 ); } errlen = strlen( errbuf ); memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 ); memcpy( ptr, errbuf, errlen ); break; /* Only once, so we don't overflow */ } /* Looks for conversion specifier... */ do ptr++; while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) ); if( *ptr ) ptr++; /* ...and skip it */ } #endif /* Convert message to string */ #if defined(HAVE_VASPRINTF) && !defined(__APPLE__) && !defined( SYS_BEOS ) vlc_va_copy( args, _args ); if( vasprintf( &psz_str, psz_format, args ) == -1 ) psz_str = NULL; va_end( args ); #else psz_str = (char*) malloc( i_size ); #endif if( psz_str == NULL ) { #ifdef __GLIBC__ fprintf( stderr, "main warning: can't store message (%m): " ); #else char psz_err[1001]; #ifndef WIN32 /* we're not using GLIBC, so we are sure that the error description * will be stored in the buffer we provide to strerror_r() */ strerror_r( errno, psz_err, 1001 ); #else strncpy( psz_err, strerror( errno ), 1001 ); #endif psz_err[1000] = '\0'; fprintf( stderr, "main warning: can't store message (%s): ", psz_err ); #endif vlc_va_copy( args, _args ); /* We should use utf8_vfprintf - but it calls malloc()... */ vfprintf( stderr, psz_format, args ); va_end( args ); fputs( "\n", stderr ); return; } i_header_size = 0; p_obj = p_this; while( p_obj != NULL ) { char *psz_old = NULL; if( p_obj->psz_header ) { i_header_size += strlen( p_obj->psz_header ) + 4; if( psz_header ) { psz_old = strdup( psz_header ); psz_header = (char*)realloc( psz_header, i_header_size ); snprintf( psz_header, i_header_size , "[%s] %s", p_obj->psz_header, psz_old ); } else { psz_header = (char *)malloc( i_header_size ); snprintf( psz_header, i_header_size, "[%s]", p_obj->psz_header ); } } free( psz_old ); p_obj = p_obj->p_parent; } #if !defined(HAVE_VASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS) vlc_va_copy( args, _args ); vsnprintf( psz_str, i_size, psz_format, args ); va_end( args ); psz_str[ i_size - 1 ] = 0; /* Just in case */ #endif LOCK_BANK; p_queue = &QUEUE; vlc_mutex_lock( &p_queue->lock ); /* Check there is room in the queue for our message */ if( p_queue->b_overflow ) { FlushMsg( p_queue ); if( ((p_queue->i_stop - p_queue->i_start + 1) % VLC_MSG_QSIZE) == 0 ) { /* Still in overflow mode, print from a dummy item */ p_item = &item; } else { /* Pheeew, at last, there is room in the queue! */ p_queue->b_overflow = false; } } else if( ((p_queue->i_stop - p_queue->i_start + 2) % VLC_MSG_QSIZE) == 0 ) { FlushMsg( p_queue ); if( ((p_queue->i_stop - p_queue->i_start + 2) % VLC_MSG_QSIZE) == 0 ) { p_queue->b_overflow = true; /* Put the overflow message in the queue */ p_item = p_queue->msg + p_queue->i_stop; p_queue->i_stop = (p_queue->i_stop + 1) % VLC_MSG_QSIZE; p_item->i_type = VLC_MSG_WARN; p_item->i_object_id = p_this->i_object_id; p_item->psz_object_type = p_this->psz_object_type; p_item->psz_module = strdup( "message" ); p_item->psz_msg = strdup( "message queue overflowed" ); p_item->psz_header = NULL; PrintMsg( p_this, p_item ); /* We print from a dummy item */ p_item = &item; } } if( !p_queue->b_overflow ) { /* Put the message in the queue */ p_item = p_queue->msg + p_queue->i_stop; p_queue->i_stop = (p_queue->i_stop + 1) % VLC_MSG_QSIZE; } /* Fill message information fields */ p_item->i_type = i_type; p_item->i_object_id = p_this->i_object_id; p_item->psz_object_type = p_this->psz_object_type; p_item->psz_module = strdup( psz_module ); p_item->psz_msg = psz_str; p_item->psz_header = psz_header; PrintMsg( p_this, p_item ); if( p_queue->b_overflow ) { free( p_item->psz_module ); free( p_item->psz_msg ); free( p_item->psz_header ); } vlc_mutex_unlock ( &p_queue->lock ); UNLOCK_BANK; }
char * sg_strperror(char **buf, const sg_error_details * const err_details) { #ifdef HAVE_STRERROR_R char errno_buf[128] = { '\0' }; #endif char *errno_msg = NULL; sg_error_details err_det; if((NULL == buf) || (NULL != *buf)) { sg_set_error_int(SG_ERROR_INVALID_ARGUMENT, 0, "strperror", empty_ap); return NULL; } if(NULL == err_details) { sg_get_error_details(&err_det); } else { err_det = *err_details; } if( NULL != (*buf = malloc(SG_STRPERROR_BUF_SIZE)) ) { if(err_det.errno_value) { #ifdef HAVE_STRERROR_R # ifdef STRERROR_R_RETURN_INT int rc; # else char *rc; # endif rc = strerror_r(err_det.errno_value, errno_buf, sizeof(errno_buf)); # ifdef STRERROR_R_RETURN_INT if(0 != rc) # else if(NULL == rc) # endif { sg_set_error_int(SG_ERROR_MALLOC, errno, "strerror_r", empty_ap); free(*buf); *buf = NULL; return NULL; } else { # ifdef STRERROR_R_RETURN_INT errno_msg = errno_buf; # else errno_msg = rc; # endif } #else errno_msg = strerror(errno); #endif } snprintf( *buf, SG_STRPERROR_BUF_SIZE, "%s (%s%s%s)", sg_str_error(err_det.error), err_det.errno_value ? errno_msg : "", err_det.errno_value ? ": " : "", err_det.error_arg ? err_det.error_arg : "" ); } else { sg_set_error_int(SG_ERROR_MALLOC, 0, "sg_strperror", empty_ap); } return *buf; }
/* File tree walker */ int csync_ftw(CSYNC *ctx, const char *uri, csync_walker_fn fn, unsigned int depth) { char errbuf[256] = {0}; char *filename = NULL; char *d_name = NULL; csync_vio_handle_t *dh = NULL; csync_vio_file_stat_t *dirent = NULL; csync_vio_file_stat_t *fs = NULL; int rc = 0; if (uri[0] == '\0') { errno = ENOENT; goto error; } if ((dh = csync_vio_opendir(ctx, uri)) == NULL) { /* permission denied */ if (errno == EACCES) { return 0; } else { strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "opendir failed for %s - %s", uri, errbuf); goto error; } } while ((dirent = csync_vio_readdir(ctx, dh))) { const char *path = NULL; int flag; d_name = dirent->name; if (d_name == NULL) { goto error; } /* skip "." and ".." */ if (d_name[0] == '.' && (d_name[1] == '\0' || (d_name[1] == '.' && d_name[2] == '\0'))) { csync_vio_file_stat_destroy(dirent); dirent = NULL; continue; } if (asprintf(&filename, "%s/%s", uri, d_name) < 0) { csync_vio_file_stat_destroy(dirent); dirent = NULL; goto error; } /* Create relative path for checking the exclude list */ switch (ctx->current) { case LOCAL_REPLICA: path = filename + strlen(ctx->local.uri) + 1; break; case REMOTE_REPLCIA: path = filename + strlen(ctx->remote.uri) + 1; break; default: break; } /* Check if file is excluded */ if (csync_excluded(ctx, path)) { CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE, "%s excluded", path); csync_vio_file_stat_destroy(dirent); dirent = NULL; continue; } fs = csync_vio_file_stat_new(); if (csync_vio_stat(ctx, filename, fs) == 0) { switch (fs->type) { case CSYNC_VIO_FILE_TYPE_SYMBOLIC_LINK: flag = CSYNC_FTW_FLAG_SLINK; break; case CSYNC_VIO_FILE_TYPE_DIRECTORY: flag = CSYNC_FTW_FLAG_DIR; break; case CSYNC_VIO_FILE_TYPE_BLOCK_DEVICE: case CSYNC_VIO_FILE_TYPE_CHARACTER_DEVICE: case CSYNC_VIO_FILE_TYPE_SOCKET: flag = CSYNC_FTW_FLAG_SPEC; break; case CSYNC_VIO_FILE_TYPE_FIFO: flag = CSYNC_FTW_FLAG_SPEC; break; default: flag = CSYNC_FTW_FLAG_FILE; break; }; } else { flag = CSYNC_FTW_FLAG_NSTAT; } CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE, "walk: %s", filename); /* Call walker function for each file */ rc = fn(ctx, filename, fs, flag); csync_vio_file_stat_destroy(fs); if (rc < 0) { csync_vio_closedir(ctx, dh); goto done; } if (flag == CSYNC_FTW_FLAG_DIR && depth) { rc = csync_ftw(ctx, filename, fn, depth - 1); if (rc < 0) { csync_vio_closedir(ctx, dh); goto done; } } SAFE_FREE(filename); csync_vio_file_stat_destroy(dirent); dirent = NULL; } csync_vio_closedir(ctx, dh); done: csync_vio_file_stat_destroy(dirent); SAFE_FREE(filename); return rc; error: SAFE_FREE(filename); return -1; }
JNIEXPORT jint JNICALL Java_com_beegfs_JBeeGFS_open(JNIEnv* env, jobject obj, jstring jFileName) { const char* fileName = env->GetStringUTFChars(jFileName, 0); int fd = open(fileName, O_RDONLY); if (fd == -1) { const unsigned errbufsize = 128; switch (errno) { case ELOOP: { jclass exceptionClass = env->FindClass("java/io/IOException"); env->ThrowNew(exceptionClass, fileName); } break; // interrupted case EINTR: { jclass exceptionClass = env->FindClass("java/io/InterruptedIOException"); env->ThrowNew(exceptionClass, "open() interrupted."); } break; // Problem with special files/ defice files case ENODEV: case ENXIO: // out of (any kind of) memory, name too long etc. case EMFILE: case ENAMETOOLONG: case ENFILE: case ENOMEM: case EFBIG: case EOVERFLOW: { char errbuf[errbufsize]; const char* errstr = strerror_r(errno, &errbuf[0], errbufsize); jstring jErrorString = env->NewStringUTF(errstr); jclass jError_class = env->FindClass("java/io/IOException"); jmethodID jError_constructor = env->GetMethodID(jError_class, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); jthrowable jError = static_cast<jthrowable>( env->NewObject(jError_class, jError_constructor, jFileName, NULL, jErrorString) ); env->Throw(jError); break; } // File not found case ENOTDIR: case EFAULT: case ENOENT: { jclass exceptionClass = env->FindClass("java/io/FileNotFoundException"); env->ThrowNew(exceptionClass, "open(): File not found."); break; } // Permission denied. case EACCES: case EPERM: { char errbuf[errbufsize]; const char* errstr = strerror_r(errno, &errbuf[0], errbufsize); jstring jErrorString = env->NewStringUTF(errstr); jclass jError_class = env->FindClass("java/io/IOException"); jmethodID jError_constructor = env->GetMethodID(jError_class, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); jthrowable jError = static_cast<jthrowable>( env->NewObject(jError_class, jError_constructor, jFileName, NULL, jErrorString) ); env->Throw(jError); break; } // Those are 'impossible' in our case, e.g. can only occur when writing or making new files case EEXIST: case EISDIR: case ENOSPC: case EROFS: case ETXTBSY: case EWOULDBLOCK: // fallthrough default: { char errbuf[errbufsize]; const char* errstr = strerror_r(errno, &errbuf[0], errbufsize); jclass exceptionClass = env->FindClass("java/lang/Error"); env->ThrowNew(exceptionClass, errstr); break; } } } return static_cast<jint>(fd); }
void exvsprintf(char **out_p, const char *msg_p, va_list vargs) { int len = strlen(msg_p); int max = len + 1024; char *tmp = (char *) malloc(max); strcpy(tmp, msg_p); // support for the "%y" format flag int s; char *pm = tmp; char *pa = (char *) (void *) vargs; char *py = 0; char *pmy = 0; DWORD dy = 0; while (*pm) { if (*pm == '%') { ++pm; if (!py && (*pm == 'y')) { pmy = pm-1; py = pa; dy = *((DWORD *) py); pa += sizeof(DWORD); } else { while (*pm && !isalpha(*pm) && (*pm != 'L') && (*pm != 'h') && (*pm != 'I')) ++ pm; s = 0; switch (*pm) { case 'c': s = sizeof(char); break; case 'C': s = sizeof(wint_t); break; case 'd':case 'i':case 'o':case 'u':case 'x':case 'X': s = sizeof(int); break; case 'e':case 'E':case 'f':case 'g':case 'G': s = sizeof(double); break; case 'n':case 'p':case 'S':case 's': s = sizeof(void *); break; } if (py) { memcpy(py, pa, s); py += s; } pa += s; } } pm++; } (*out_p) = (char *) realloc((*out_p), max); if (pmy) { int add = 0, off = pmy - tmp; memcpy((*out_p), tmp, off); #ifdef WIN32 add = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, 0, dy, 0, &((*out_p)[off]), 1024, 0); #else char *obuf = &((*out_p)[off]); #ifdef STRERROR_R_CHAR_P char * ret = strerror_r((int) dy, obuf, 1024); if (ret) { if (ret != obuf) { strcpy(obuf, ret); } add = strlen(obuf); } #else int ret = strerror_r((int) dy, obuf, 1024); if (ret) { add = strlen(obuf); } #endif #endif memcpy(&((*out_p)[add+off]), pmy+2, len-off-2); len = add + len - 2; if (len > 0 && (*out_p)[len-1] == '\n') --len; if (len > 0 && (*out_p)[len-1] == '\r') --len; (*out_p)[len] = '\0'; strcpy(tmp, (*out_p)); } // end support for the "%y" format flag #ifdef WIN32 _vsnprintf((*out_p), max, tmp, vargs); #else vsnprintf((*out_p), max, tmp, vargs); #endif free(tmp); }
static int system_strerror_r (int no, char *buf, size_t buflen) { return strerror_r (no, buf, buflen); }
void vsyslog(int pri, const char *fmt, va_list ap) { int cnt; char ch, *p; time_t now; int fd, saved_errno; char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64]; FILE *fp, *fmt_fp; struct bufcookie tbuf_cookie; struct bufcookie fmt_cookie; #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID /* Check for invalid bits. */ if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) { syslog(INTERNALLOG, "syslog: unknown facility/priority: %x", pri); pri &= LOG_PRIMASK|LOG_FACMASK; } saved_errno = errno; THREAD_LOCK(); /* Check priority against setlogmask values. */ if (!(LOG_MASK(LOG_PRI(pri)) & LogMask)) { THREAD_UNLOCK(); return; } /* Set default facility if none specified. */ if ((pri & LOG_FACMASK) == 0) pri |= LogFacility; /* Create the primary stdio hook */ tbuf_cookie.base = tbuf; tbuf_cookie.left = sizeof(tbuf); fp = fwopen(&tbuf_cookie, writehook); if (fp == NULL) { THREAD_UNLOCK(); return; } /* Build the message. */ (void)time(&now); (void)fprintf(fp, "<%d>", pri); (void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4); if (LogStat & LOG_PERROR) { /* Transfer to string buffer */ (void)fflush(fp); stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left); } if (LogTag == NULL) LogTag = _getprogname(); if (LogTag != NULL) (void)fprintf(fp, "%s", LogTag); if (LogStat & LOG_PID) (void)fprintf(fp, "[%d]", getpid()); if (LogTag != NULL) { (void)fprintf(fp, ": "); } /* Check to see if we can skip expanding the %m */ if (strstr(fmt, "%m")) { /* Create the second stdio hook */ fmt_cookie.base = fmt_cpy; fmt_cookie.left = sizeof(fmt_cpy) - 1; fmt_fp = fwopen(&fmt_cookie, writehook); if (fmt_fp == NULL) { fclose(fp); THREAD_UNLOCK(); return; } /* * Substitute error message for %m. Be careful not to * molest an escaped percent "%%m". We want to pass it * on untouched as the format is later parsed by vfprintf. */ for ( ; (ch = *fmt); ++fmt) { if (ch == '%' && fmt[1] == 'm') { ++fmt; strerror_r(saved_errno, errstr, sizeof(errstr)); fputs(errstr, fmt_fp); } else if (ch == '%' && fmt[1] == '%') { ++fmt; fputc(ch, fmt_fp); fputc(ch, fmt_fp); } else { fputc(ch, fmt_fp); } } /* Null terminate if room */ fputc(0, fmt_fp); fclose(fmt_fp); /* Guarantee null termination */ fmt_cpy[sizeof(fmt_cpy) - 1] = '\0'; fmt = fmt_cpy; } (void)vfprintf(fp, fmt, ap); (void)fclose(fp); cnt = sizeof(tbuf) - tbuf_cookie.left; /* Remove a trailing newline */ if (tbuf[cnt - 1] == '\n') cnt--; /* Output to stderr if requested. */ if (LogStat & LOG_PERROR) { struct iovec iov[2]; struct iovec *v = iov; v->iov_base = stdp; v->iov_len = cnt - (stdp - tbuf); ++v; v->iov_base = "\n"; v->iov_len = 1; (void)_writev(STDERR_FILENO, iov, 2); } /* Get connected, output the message to the local logger. */ if (!opened) openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0); connectlog(); /* * If the send() failed, there are two likely scenarios: * 1) syslogd was restarted * 2) /var/run/log is out of socket buffer space, which * in most cases means local DoS. * We attempt to reconnect to /var/run/log[priv] to take care of * case #1 and keep send()ing data to cover case #2 * to give syslogd a chance to empty its socket buffer. * * If we are working with a priveleged socket, then take * only one attempt, because we don't want to freeze a * critical application like su(1) or sshd(8). * */ if (send(LogFile, tbuf, cnt, 0) < 0) { if (errno != ENOBUFS) { disconnectlog(); connectlog(); } do { if (status == CONNPRIV) break; _usleep(1); if (send(LogFile, tbuf, cnt, 0) >= 0) { THREAD_UNLOCK(); return; } } while (errno == ENOBUFS); } else { THREAD_UNLOCK(); return; } /* * Output the message to the console; try not to block * as a blocking console should not stop other processes. * Make sure the error reported is the one from the syslogd failure. */ if (LogStat & LOG_CONS && (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >= 0) { struct iovec iov[2]; struct iovec *v = iov; p = strchr(tbuf, '>') + 1; v->iov_base = p; v->iov_len = cnt - (p - tbuf); ++v; v->iov_base = "\r\n"; v->iov_len = 2; (void)_writev(fd, iov, 2); (void)_close(fd); } THREAD_UNLOCK(); }
static void pn_i_strerror(int errnum, char *buf, size_t buflen) { if (strerror_r(errnum, buf, buflen) != 0) pni_fatal("strerror_r() failed\n"); }
static void handle_warning_en(const int en, const char *s) { char errs[256]; NaClLog(LOG_WARNING, "%s: %s\n", s, strerror_r(en, errs, sizeof(errs))); }
static int _csync_remove_dir(CSYNC *ctx, csync_file_stat_t *st) { c_list_t *list = NULL; char errbuf[256] = {0}; char *uri = NULL; int rc = -1; switch (ctx->current) { case LOCAL_REPLICA: if (asprintf(&uri, "%s/%s", ctx->local.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; return -1; } break; case REMOTE_REPLICA: if (asprintf(&uri, "%s/%s", ctx->remote.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; return -1; } break; default: break; } if (csync_vio_rmdir(ctx, uri) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { case ENOMEM: strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "dir: %s, command: rmdir, error: %s", uri, errbuf); rc = -1; break; case ENOTEMPTY: switch (ctx->current) { case LOCAL_REPLICA: list = c_list_prepend(ctx->local.list, (void *) st); if (list == NULL) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; return -1; } ctx->local.list = list; break; case REMOTE_REPLICA: list = c_list_prepend(ctx->remote.list, (void *) st); if (list == NULL) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; return -1; } ctx->remote.list = list; break; default: break; } rc = 0; break; default: strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "dir: %s, command: rmdir, error: %s", uri, errbuf); rc = 1; break; } goto out; } /* set instruction for the statedb merger */ st->instruction = CSYNC_INSTRUCTION_DELETED; CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "REMOVED dir: %s", uri); rc = 0; out: SAFE_FREE(uri); /* set instruction for the statedb merger */ if (rc != 0) { st->instruction = CSYNC_INSTRUCTION_NONE; } return rc; }
bool czsrv::send_file(void) { // std::clog << "[Sending file]" << std::endl; bool lastchunk = false; int chunks = 0; std::string::size_type pos = URI_str.find_last_of('.'); std::string filetype = URI_str.substr(pos+1); std::map<std::string, std::string>::const_iterator itr = mimetypes.find(filetype); if(mimetypes.end() != itr) { filetype.assign(itr->second); }else{ filetype.assign("text/html"); } // std::clog << "[mimetype] " << itr->second << std::endl; const int buffsize = 1024; char buffer[buffsize]; std::stringstream response; response << "HTTP/1.1 200 OK\r\nServer: " << APPNAME_str << "\r\nContent-Type: " << filetype << std::setbase(16) << "\r\nTransfer-Encoding: chunked\r\n\r\n" << std::flush; unsigned int ret; while(0 <= (ret = archive.read(buffer, buffsize))) { if(buffsize > ret) { //last chunk response << ret << "\r\n"; response.write(buffer, ret); response << "\r\n0\r\n\r\n" << std::flush; lastchunk = true; }else{ response << ret << "\r\n"; response.write(buffer, ret); response << "\r\n" << std::flush; } // std::clog<< response.str() << std::flush; if(-1 != (ret = send(client_socket, response.str().data(), response.str().length(), 0))) { chunks++; if(lastchunk) break; }else{ std::cerr << "send(): " << strerror_r(errno, error_msg_buffer, error_msg_buffer_size) << std::endl; //perror("[send] "); lastchunk = false; break; } response.str(std::string()); //empty response stream }//while else std::clog << "[unzRead failed: " << ret << " ]" << std::endl; // std::clog << "[" << chunks << " chunks sent]" << std::endl; if(lastchunk) std::clog << "File sent: \"" << URI_str << "\"" << std::endl; if(0 > ret){ send_NOT_FOUND(URI_str); return false; } return lastchunk; }
/** * Add a message to a queue * * This function provides basic functionnalities to other msg_* functions. * It adds a message to a queue (after having printed all stored messages if it * is full). If the message can't be converted to string in memory, it issues * a warning. */ void msg_GenericVa (vlc_object_t *p_this, int i_type, const char *psz_module, const char *psz_format, va_list _args) { size_t i_header_size; /* Size of the additionnal header */ vlc_object_t *p_obj; char * psz_str = NULL; /* formatted message string */ char * psz_header = NULL; va_list args; assert (p_this); if( p_this->i_flags & OBJECT_FLAGS_QUIET || (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) ) return; msg_bank_t *bank = libvlc_bank (p_this->p_libvlc); locale_t locale = uselocale (bank->locale); #ifndef __GLIBC__ /* Expand %m to strerror(errno) - only once */ char buf[strlen( psz_format ) + 2001], *ptr; strcpy( buf, psz_format ); ptr = (char*)buf; psz_format = (const char*) buf; for( ;; ) { ptr = strchr( ptr, '%' ); if( ptr == NULL ) break; if( ptr[1] == 'm' ) { char errbuf[2001]; size_t errlen; #ifndef WIN32 strerror_r( errno, errbuf, 1001 ); #else int sockerr = WSAGetLastError( ); if( sockerr ) { strncpy( errbuf, net_strerror( sockerr ), 1001 ); WSASetLastError( sockerr ); } if ((sockerr == 0) || (strcmp ("Unknown network stack error", errbuf) == 0)) strncpy( errbuf, strerror( errno ), 1001 ); #endif errbuf[1000] = 0; /* Escape '%' from the error string */ for( char *percent = strchr( errbuf, '%' ); percent != NULL; percent = strchr( percent + 2, '%' ) ) { memmove( percent + 1, percent, strlen( percent ) + 1 ); } errlen = strlen( errbuf ); memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 ); memcpy( ptr, errbuf, errlen ); break; /* Only once, so we don't overflow */ } /* Looks for conversion specifier... */ do ptr++; while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) ); if( *ptr ) ptr++; /* ...and skip it */ } #endif /* Convert message to string */ vlc_va_copy( args, _args ); if( vasprintf( &psz_str, psz_format, args ) == -1 ) psz_str = NULL; va_end( args ); if( psz_str == NULL ) { int canc = vlc_savecancel (); /* Do not print half of a message... */ #ifdef __GLIBC__ fprintf( stderr, "main warning: can't store message (%m): " ); #else char psz_err[1001]; #ifndef WIN32 /* we're not using GLIBC, so we are sure that the error description * will be stored in the buffer we provide to strerror_r() */ strerror_r( errno, psz_err, 1001 ); #else strncpy( psz_err, strerror( errno ), 1001 ); #endif psz_err[1000] = '\0'; fprintf( stderr, "main warning: can't store message (%s): ", psz_err ); #endif vlc_va_copy( args, _args ); /* We should use utf8_vfprintf - but it calls malloc()... */ vfprintf( stderr, psz_format, args ); va_end( args ); fputs( "\n", stderr ); vlc_restorecancel (canc); uselocale (locale); return; } uselocale (locale); msg_item_t * p_item = malloc (sizeof (*p_item)); if (p_item == NULL) return; /* Uho! */ vlc_gc_init (p_item, msg_Free); p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL; i_header_size = 0; p_obj = p_this; while( p_obj != NULL ) { char *psz_old = NULL; if( p_obj->psz_header ) { i_header_size += strlen( p_obj->psz_header ) + 4; if( psz_header ) { psz_old = strdup( psz_header ); psz_header = xrealloc( psz_header, i_header_size ); snprintf( psz_header, i_header_size , "[%s] %s", p_obj->psz_header, psz_old ); } else { psz_header = xmalloc( i_header_size ); snprintf( psz_header, i_header_size, "[%s]", p_obj->psz_header ); } } free( psz_old ); p_obj = p_obj->p_parent; } /* Fill message information fields */ p_item->i_type = i_type; p_item->i_object_id = (uintptr_t)p_this; p_item->psz_object_type = p_this->psz_object_type; p_item->psz_module = strdup( psz_module ); p_item->psz_msg = psz_str; p_item->psz_header = psz_header; PrintMsg( p_this, p_item ); vlc_rwlock_rdlock (&bank->lock); for (int i = 0; i < bank->i_sub; i++) { msg_subscription_t *sub = bank->pp_sub[i]; sub->func (sub->opaque, p_item, 0); } vlc_rwlock_unlock (&bank->lock); msg_Release (p_item); }
_public_ int sd_journal_sendv(const struct iovec *iov, int n) { PROTECT_ERRNO; int fd, r; _cleanup_close_ int buffer_fd = -1; struct iovec *w; uint64_t *l; int i, j = 0; static const union sockaddr_union sa = { .un.sun_family = AF_UNIX, .un.sun_path = "/run/systemd/journal/socket", }; struct msghdr mh = { .msg_name = (struct sockaddr*) &sa.sa, .msg_namelen = SOCKADDR_UN_LEN(sa.un), }; ssize_t k; bool have_syslog_identifier = false; bool seal = true; assert_return(iov, -EINVAL); assert_return(n > 0, -EINVAL); w = newa(struct iovec, n * 5 + 3); l = newa(uint64_t, n); for (i = 0; i < n; i++) { char *c, *nl; if (_unlikely_(!iov[i].iov_base || iov[i].iov_len <= 1)) return -EINVAL; c = memchr(iov[i].iov_base, '=', iov[i].iov_len); if (_unlikely_(!c || c == iov[i].iov_base)) return -EINVAL; have_syslog_identifier = have_syslog_identifier || (c == (char *) iov[i].iov_base + 17 && startswith(iov[i].iov_base, "SYSLOG_IDENTIFIER")); nl = memchr(iov[i].iov_base, '\n', iov[i].iov_len); if (nl) { if (_unlikely_(nl < c)) return -EINVAL; /* Already includes a newline? Bummer, then * let's write the variable name, then a * newline, then the size (64bit LE), followed * by the data and a final newline */ w[j++] = IOVEC_MAKE(iov[i].iov_base, c - (char*) iov[i].iov_base); w[j++] = IOVEC_MAKE_STRING("\n"); l[i] = htole64(iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1); w[j++] = IOVEC_MAKE(&l[i], sizeof(uint64_t)); w[j++] = IOVEC_MAKE(c + 1, iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1); } else /* Nothing special? Then just add the line and * append a newline */ w[j++] = iov[i]; w[j++] = IOVEC_MAKE_STRING("\n"); } if (!have_syslog_identifier && string_is_safe(program_invocation_short_name)) { /* Implicitly add program_invocation_short_name, if it * is not set explicitly. We only do this for * program_invocation_short_name, and nothing else * since everything else is much nicer to retrieve * from the outside. */ w[j++] = IOVEC_MAKE_STRING("SYSLOG_IDENTIFIER="); w[j++] = IOVEC_MAKE_STRING(program_invocation_short_name); w[j++] = IOVEC_MAKE_STRING("\n"); } fd = journal_fd(); if (_unlikely_(fd < 0)) return fd; mh.msg_iov = w; mh.msg_iovlen = j; k = sendmsg(fd, &mh, MSG_NOSIGNAL); if (k >= 0) return 0; /* Fail silently if the journal is not available */ if (errno == ENOENT) return 0; if (!IN_SET(errno, EMSGSIZE, ENOBUFS)) return -errno; /* Message doesn't fit... Let's dump the data in a memfd or * temporary file and just pass a file descriptor of it to the * other side. * * For the temporary files we use /dev/shm instead of /tmp * here, since we want this to be a tmpfs, and one that is * available from early boot on and where unprivileged users * can create files. */ buffer_fd = memfd_new(NULL); if (buffer_fd < 0) { if (buffer_fd == -ENOSYS) { buffer_fd = open_tmpfile_unlinkable("/dev/shm", O_RDWR | O_CLOEXEC); if (buffer_fd < 0) return buffer_fd; seal = false; } else return buffer_fd; } n = writev(buffer_fd, w, j); if (n < 0) return -errno; if (seal) { r = memfd_set_sealed(buffer_fd); if (r < 0) return r; } r = send_one_fd_sa(fd, buffer_fd, mh.msg_name, mh.msg_namelen, 0); if (r == -ENOENT) /* Fail silently if the journal is not available */ return 0; return r; } static int fill_iovec_perror_and_send(const char *message, int skip, struct iovec iov[]) { PROTECT_ERRNO; size_t n, k; k = isempty(message) ? 0 : strlen(message) + 2; n = 8 + k + 256 + 1; for (;;) { char buffer[n]; char* j; errno = 0; j = strerror_r(_saved_errno_, buffer + 8 + k, n - 8 - k); if (errno == 0) { char error[STRLEN("ERRNO=") + DECIMAL_STR_MAX(int) + 1]; if (j != buffer + 8 + k) memmove(buffer + 8 + k, j, strlen(j)+1); memcpy(buffer, "MESSAGE=", 8); if (k > 0) { memcpy(buffer + 8, message, k - 2); memcpy(buffer + 8 + k - 2, ": ", 2); } xsprintf(error, "ERRNO=%i", _saved_errno_); assert_cc(3 == LOG_ERR); iov[skip+0] = IOVEC_MAKE_STRING("PRIORITY=3"); iov[skip+1] = IOVEC_MAKE_STRING(buffer); iov[skip+2] = IOVEC_MAKE_STRING(error); return sd_journal_sendv(iov, skip + 3); } if (errno != ERANGE) return -errno; n *= 2; } } _public_ int sd_journal_perror(const char *message) { struct iovec iovec[3]; return fill_iovec_perror_and_send(message, 0, iovec); } _public_ int sd_journal_stream_fd(const char *identifier, int priority, int level_prefix) { static const union sockaddr_union sa = { .un.sun_family = AF_UNIX, .un.sun_path = "/run/systemd/journal/stdout", }; _cleanup_close_ int fd = -1; char *header; size_t l; int r; assert_return(priority >= 0, -EINVAL); assert_return(priority <= 7, -EINVAL); fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); if (fd < 0) return -errno; r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)); if (r < 0) return -errno; if (shutdown(fd, SHUT_RD) < 0) return -errno; (void) fd_inc_sndbuf(fd, SNDBUF_SIZE); identifier = strempty(identifier); l = strlen(identifier); header = alloca(l + 1 + 1 + 2 + 2 + 2 + 2 + 2); memcpy(header, identifier, l); header[l++] = '\n'; header[l++] = '\n'; /* unit id */ header[l++] = '0' + priority; header[l++] = '\n'; header[l++] = '0' + !!level_prefix; header[l++] = '\n'; header[l++] = '0'; header[l++] = '\n'; header[l++] = '0'; header[l++] = '\n'; header[l++] = '0'; header[l++] = '\n'; r = loop_write(fd, header, l, false); if (r < 0) return r; r = fd; fd = -1; return r; } _public_ int sd_journal_print_with_location(int priority, const char *file, const char *line, const char *func, const char *format, ...) { int r; va_list ap; va_start(ap, format); r = sd_journal_printv_with_location(priority, file, line, func, format, ap); va_end(ap); return r; } _public_ int sd_journal_printv_with_location(int priority, const char *file, const char *line, const char *func, const char *format, va_list ap) { char buffer[8 + LINE_MAX], p[STRLEN("PRIORITY=") + DECIMAL_STR_MAX(int) + 1]; struct iovec iov[5]; char *f; assert_return(priority >= 0, -EINVAL); assert_return(priority <= 7, -EINVAL); assert_return(format, -EINVAL); xsprintf(p, "PRIORITY=%i", priority & LOG_PRIMASK); memcpy(buffer, "MESSAGE=", 8); vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap); /* Strip trailing whitespace, keep prefixing whitespace */ (void) strstrip(buffer); /* Suppress empty lines */ if (isempty(buffer+8)) return 0; /* func is initialized from __func__ which is not a macro, but * a static const char[], hence cannot easily be prefixed with * CODE_FUNC=, hence let's do it manually here. */ ALLOCA_CODE_FUNC(f, func); iov[0] = IOVEC_MAKE_STRING(buffer); iov[1] = IOVEC_MAKE_STRING(p); iov[2] = IOVEC_MAKE_STRING(file); iov[3] = IOVEC_MAKE_STRING(line); iov[4] = IOVEC_MAKE_STRING(f); return sd_journal_sendv(iov, ELEMENTSOF(iov)); }
static switch_status_t my_on_reporting(switch_core_session_t *session) { struct json_object *json_cdr = NULL; const char *json_text = NULL; char *path = NULL; char *curl_json_text = NULL; const char *logdir = NULL; char *json_text_escaped = NULL; int fd = -1, err_dir_index; uint32_t cur_try; long httpRes; CURL *curl_handle = NULL; struct curl_slist *headers = NULL; struct curl_slist *slist = NULL; switch_channel_t *channel = switch_core_session_get_channel(session); switch_status_t status = SWITCH_STATUS_FALSE; int is_b; const char *a_prefix = ""; if (globals.shutdown) { return SWITCH_STATUS_SUCCESS; } is_b = channel && switch_channel_get_originator_caller_profile(channel); if (!globals.log_b && is_b) { const char *force_cdr = switch_channel_get_variable(channel, SWITCH_FORCE_PROCESS_CDR_VARIABLE); if (!switch_true(force_cdr)) { return SWITCH_STATUS_SUCCESS; } } if (!is_b && globals.prefix_a) a_prefix = "a_"; if (generate_json_cdr(session, &json_cdr) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Generating Data!\n"); return SWITCH_STATUS_FALSE; } json_text = json_object_to_json_string(json_cdr); if (!json_text) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n"); goto error; } switch_thread_rwlock_rdlock(globals.log_path_lock); if (!(logdir = switch_channel_get_variable(channel, "json_cdr_base"))) { logdir = globals.log_dir; } if (!zstr(logdir) && (globals.log_http_and_disk || !globals.url_count)) { path = switch_mprintf("%s%s%s%s.cdr.json", logdir, SWITCH_PATH_SEPARATOR, a_prefix, switch_core_session_get_uuid(session)); switch_thread_rwlock_unlock(globals.log_path_lock); if (path) { #ifdef _MSC_VER if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) > -1) { #else if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) > -1) { #endif int wrote; wrote = write(fd, json_text, (unsigned) strlen(json_text)); close(fd); fd = -1; } else { char ebuf[512] = { 0 }; #ifdef WIN32 strerror_s(ebuf, sizeof(ebuf), errno); #else strerror_r(errno, ebuf, sizeof(ebuf)); #endif switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error writing [%s][%s]\n", path, ebuf); } switch_safe_free(path); } } else { switch_thread_rwlock_unlock(globals.log_path_lock); } /* try to post it to the web server */ if (globals.url_count) { char *destUrl = NULL; curl_handle = curl_easy_init(); if (globals.encode) { switch_size_t need_bytes = strlen(json_text) * 3; json_text_escaped = malloc(need_bytes); switch_assert(json_text_escaped); memset(json_text_escaped, 0, need_bytes); if (globals.encode == ENCODING_DEFAULT) { headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded"); switch_url_encode(json_text, json_text_escaped, need_bytes); } else { headers = curl_slist_append(headers, "Content-Type: application/x-www-form-base64-encoded"); switch_b64_encode((unsigned char *) json_text, need_bytes / 3, (unsigned char *) json_text_escaped, need_bytes); } json_text = json_text_escaped; if (!(curl_json_text = switch_mprintf("cdr=%s", json_text))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n"); goto error; } } else { headers = curl_slist_append(headers, "Content-Type: application/x-www-form-plaintext"); curl_json_text = (char *)json_text; } if (!zstr(globals.cred)) { curl_easy_setopt(curl_handle, CURLOPT_HTTPAUTH, globals.auth_scheme); curl_easy_setopt(curl_handle, CURLOPT_USERPWD, globals.cred); } curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl_handle, CURLOPT_POST, 1); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, curl_json_text); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "freeswitch-json/1.0"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, httpCallBack); if (globals.disable100continue) { slist = curl_slist_append(slist, "Expect:"); curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, slist); } if (globals.ssl_cert_file) { curl_easy_setopt(curl_handle, CURLOPT_SSLCERT, globals.ssl_cert_file); } if (globals.ssl_key_file) { curl_easy_setopt(curl_handle, CURLOPT_SSLKEY, globals.ssl_key_file); } if (globals.ssl_key_password) { curl_easy_setopt(curl_handle, CURLOPT_SSLKEYPASSWD, globals.ssl_key_password); } if (globals.ssl_version) { if (!strcasecmp(globals.ssl_version, "SSLv3")) { curl_easy_setopt(curl_handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3); } else if (!strcasecmp(globals.ssl_version, "TLSv1")) { curl_easy_setopt(curl_handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); } } if (globals.ssl_cacert_file) { curl_easy_setopt(curl_handle, CURLOPT_CAINFO, globals.ssl_cacert_file); } /* these were used for testing, optionally they may be enabled if someone desires curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 120); // tcp timeout curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1); // 302 recursion level */ for (cur_try = 0; cur_try < globals.retries; cur_try++) { if (cur_try > 0) { switch_yield(globals.delay * 1000000); } destUrl = switch_mprintf("%s?uuid=%s", globals.urls[globals.url_index], switch_core_session_get_uuid(session)); curl_easy_setopt(curl_handle, CURLOPT_URL, destUrl); if (!strncasecmp(destUrl, "https", 5)) { curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0); } if (globals.enable_cacert_check) { curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, TRUE); } if (globals.enable_ssl_verifyhost) { curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 2); } curl_easy_perform(curl_handle); curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &httpRes); switch_safe_free(destUrl); if (httpRes == 200) { goto success; } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Got error [%ld] posting to web server [%s]\n", httpRes, globals.urls[globals.url_index]); globals.url_index++; switch_assert(globals.url_count <= MAX_URLS); if (globals.url_index >= globals.url_count) { globals.url_index = 0; } switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Retry will be with url [%s]\n", globals.urls[globals.url_index]); } } curl_easy_cleanup(curl_handle); curl_slist_free_all(headers); curl_slist_free_all(slist); slist = NULL; headers = NULL; curl_handle = NULL; /* if we are here the web post failed for some reason */ switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to post to web server, writing to file\n"); for (err_dir_index = 0; err_dir_index < globals.err_dir_count; err_dir_index++) { switch_thread_rwlock_rdlock(globals.log_path_lock); path = switch_mprintf("%s%s%s%s.cdr.json", globals.err_log_dir[err_dir_index], SWITCH_PATH_SEPARATOR, a_prefix, switch_core_session_get_uuid(session)); switch_thread_rwlock_unlock(globals.log_path_lock); if (path) { #ifdef _MSC_VER if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) > -1) { #else if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) > -1) { #endif int wrote; wrote = write(fd, json_text, (unsigned) strlen(json_text)); close(fd); fd = -1; break; } else { char ebuf[512] = { 0 }; #ifdef WIN32 strerror_s(ebuf, sizeof(ebuf), errno); #else strerror_r(errno, ebuf, sizeof(ebuf)); #endif switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open %s! [%s]\n", path, ebuf); } switch_safe_free(path); } } } success: status = SWITCH_STATUS_SUCCESS; error: if (curl_handle) { curl_easy_cleanup(curl_handle); } if (headers) { curl_slist_free_all(headers); } if (slist) { curl_slist_free_all(slist); } if (curl_json_text != json_text) { switch_safe_free(curl_json_text); } json_object_put(json_cdr); switch_safe_free(json_text_escaped); return status; } static void event_handler(switch_event_t *event) { const char *sig = switch_event_get_header(event, "Trapped-Signal"); if (sig && !strcmp(sig, "HUP")) { if (globals.rotate) { set_json_cdr_log_dirs(); } } } static switch_state_handler_table_t state_handlers = { /*.on_init */ NULL, /*.on_routing */ NULL, /*.on_execute */ NULL, /*.on_hangup */ NULL, /*.on_exchange_media */ NULL, /*.on_soft_execute */ NULL, /*.on_consume_media */ NULL, /*.on_hibernate */ NULL, /*.on_reset */ NULL, /*.on_park */ NULL, /*.on_reporting */ my_on_reporting }; SWITCH_MODULE_LOAD_FUNCTION(mod_json_cdr_load) { char *cf = "json_cdr.conf"; switch_xml_t cfg, xml, settings, param; switch_status_t status = SWITCH_STATUS_SUCCESS; /* test global state handlers */ switch_core_add_state_handler(&state_handlers); *module_interface = switch_loadable_module_create_module_interface(pool, modname); memset(&globals, 0, sizeof(globals)); if (switch_event_bind_removable(modname, SWITCH_EVENT_TRAP, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL, &globals.node) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n"); return SWITCH_STATUS_GENERR; } globals.log_http_and_disk = 0; globals.log_b = 1; globals.disable100continue = 0; globals.pool = pool; globals.auth_scheme = CURLAUTH_BASIC; switch_thread_rwlock_create(&globals.log_path_lock, pool); /* parse the config */ if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of %s failed\n", cf); return SWITCH_STATUS_TERM; } if ((settings = switch_xml_child(cfg, "settings"))) { for (param = switch_xml_child(settings, "param"); param; param = param->next) { char *var = (char *) switch_xml_attr_soft(param, "name"); char *val = (char *) switch_xml_attr_soft(param, "value"); if (!strcasecmp(var, "cred") && !zstr(val)) { globals.cred = switch_core_strdup(globals.pool, val); } else if (!strcasecmp(var, "url") && !zstr(val)) { if (globals.url_count >= MAX_URLS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "maximum urls configured!\n"); } else { globals.urls[globals.url_count++] = switch_core_strdup(globals.pool, val); } } else if (!strcasecmp(var, "log-http-and-disk")) { globals.log_http_and_disk = switch_true(val); } else if (!strcasecmp(var, "delay") && !zstr(val)) { globals.delay = (uint32_t) atoi(val); } else if (!strcasecmp(var, "log-b-leg")) { globals.log_b = switch_true(val); } else if (!strcasecmp(var, "prefix-a-leg")) { globals.prefix_a = switch_true(val); } else if (!strcasecmp(var, "disable-100-continue") && switch_true(val)) { globals.disable100continue = 1; } else if (!strcasecmp(var, "encode") && !zstr(val)) { if (!strcasecmp(val, "base64")) { globals.encode = ENCODING_BASE64; } else { globals.encode = switch_true(val) ? ENCODING_DEFAULT : ENCODING_NONE; } } else if (!strcasecmp(var, "retries") && !zstr(val)) { globals.retries = (uint32_t) atoi(val); } else if (!strcasecmp(var, "rotate") && !zstr(val)) { globals.rotate = switch_true(val); } else if (!strcasecmp(var, "log-dir")) { if (zstr(val)) { globals.base_log_dir = switch_core_sprintf(globals.pool, "%s%sjson_cdr", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR); } else { if (switch_is_file_path(val)) { globals.base_log_dir = switch_core_strdup(globals.pool, val); } else { globals.base_log_dir = switch_core_sprintf(globals.pool, "%s%s%s", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, val); } } } else if (!strcasecmp(var, "err-log-dir")) { if (globals.err_dir_count >= MAX_ERR_DIRS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "maximum error directories configured!\n"); } else { if (zstr(val)) { globals.base_err_log_dir[globals.err_dir_count++] = switch_core_sprintf(globals.pool, "%s%sjson_cdr", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR); } else { if (switch_is_file_path(val)) { globals.base_err_log_dir[globals.err_dir_count++] = switch_core_strdup(globals.pool, val); } else { globals.base_err_log_dir[globals.err_dir_count++] = switch_core_sprintf(globals.pool, "%s%s%s", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, val); } } } } else if (!strcasecmp(var, "enable-cacert-check") && switch_true(val)) { globals.enable_cacert_check = 1; } else if (!strcasecmp(var, "ssl-cert-path")) { globals.ssl_cert_file = val; } else if (!strcasecmp(var, "ssl-key-path")) { globals.ssl_key_file = val; } else if (!strcasecmp(var, "ssl-key-password")) { globals.ssl_key_password = val; } else if (!strcasecmp(var, "ssl-version")) { globals.ssl_version = val; } else if (!strcasecmp(var, "ssl-cacert-file")) { globals.ssl_cacert_file = val; } else if (!strcasecmp(var, "enable-ssl-verifyhost") && switch_true(val)) { globals.enable_ssl_verifyhost = 1; } else if (!strcasecmp(var, "auth-scheme")) { if (*val == '=') { globals.auth_scheme = 0; val++; } if (!strcasecmp(val, "basic")) { globals.auth_scheme |= CURLAUTH_BASIC; } else if (!strcasecmp(val, "digest")) { globals.auth_scheme |= CURLAUTH_DIGEST; } else if (!strcasecmp(val, "NTLM")) { globals.auth_scheme |= CURLAUTH_NTLM; } else if (!strcasecmp(val, "GSS-NEGOTIATE")) { globals.auth_scheme |= CURLAUTH_GSSNEGOTIATE; } else if (!strcasecmp(val, "any")) { globals.auth_scheme = CURLAUTH_ANY; } } } if (!globals.err_dir_count) { if (!zstr(globals.base_log_dir)) { globals.base_err_log_dir[globals.err_dir_count++] = switch_core_strdup(globals.pool, globals.base_log_dir); } else { globals.base_err_log_dir[globals.err_dir_count++] = switch_core_sprintf(globals.pool, "%s%sjson_cdr", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR); } } } if (globals.retries < 0) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Retries is negative, setting to 0\n"); globals.retries = 0; } if (globals.retries && globals.delay <= 0) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Retries set but delay 0 setting to 5000ms\n"); globals.delay = 5000; } globals.retries++; set_json_cdr_log_dirs(); switch_xml_free(xml); return status; } SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_json_cdr_shutdown) { int err_dir_index = 0; globals.shutdown = 1; switch_safe_free(globals.log_dir); for (;err_dir_index < globals.err_dir_count; err_dir_index++) { switch_safe_free(globals.err_log_dir[err_dir_index]); } switch_event_unbind(&globals.node); switch_core_remove_state_handler(&state_handlers); switch_thread_rwlock_destroy(globals.log_path_lock); return SWITCH_STATUS_SUCCESS; }
void LVlinear_load_model(lvError *lvErr, const char *path_in, LVlinear_model *model_out){ try{ errno = 0; model *mdl = load_model(path_in); if (mdl == nullptr){ // Allocate room for output error message (truncated if buffer is too small) const size_t bufSz = 256; char buf[bufSz] = ""; std::string errstr; #if defined(_WIN32) || defined(_WIN64) if (strerror_s(buf, bufSz, errno) != 0) errstr = buf; else errstr = "Unknown error"; #elif (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE if (strerror_r(errno, buf, bufSz) != 0) errstr = buf; else errstr = "Unknown error"; #else char* gnuerr = strerror_r(errno, buf, bufSz); if (gnuerr != nullptr) errstr = gnuerr; else errstr = "Unknown error"; #endif errno = 0; throw LVException(__FILE__, __LINE__, "Model load operation failed (" + errstr + ")."); } else{ // liblinear returns uninitialized values for the parameters (except solver type) (mdl->param).C = 0; (mdl->param).eps = 0; (mdl->param).init_sol = nullptr; (mdl->param).nr_weight = 0; (mdl->param).p = 0; (mdl->param).weight = nullptr; (mdl->param).weight_label = nullptr; LVConvertModel(*mdl, *model_out); free_model_content(mdl); } } catch (LVException &ex) { (*(model_out->label))->dimSize = 0; (*(model_out->w))->dimSize = 0; (*(model_out->param).weight)->dimSize = 0; (*(model_out->param).weight_label)->dimSize = 0; ex.returnError(lvErr); } catch (std::exception &ex) { (*(model_out->label))->dimSize = 0; (*(model_out->w))->dimSize = 0; (*(model_out->param).weight)->dimSize = 0; (*(model_out->param).weight_label)->dimSize = 0; LVException::returnStdException(lvErr, __FILE__, __LINE__, ex); } catch (...) { (*(model_out->label))->dimSize = 0; (*(model_out->w))->dimSize = 0; (*(model_out->param).weight)->dimSize = 0; (*(model_out->param).weight_label)->dimSize = 0; LVException ex(__FILE__, __LINE__, "Unknown exception has occurred"); ex.returnError(lvErr); } }
int main (int argc, char *argv[]) { int var = 1; /* The fork system call is used by a process to request that the kernel create a new process. After fork has been called a new child process exists. Both the parent and the child then keep executing from the point right after the call to fork. Thus, both the parent and the child process both get a return value from fork. The child process gets a return value of 0, and the parent process gets a return value equal to the process ID of the newly created child. */ int c1 = 0; c1 = fork (); if (c1 == 0) { /* we enter this block only if fork returns 0, which indicates that we are the child process */ printf ("Value of var from child = %d\n", var); ++var; // var is only incremented in the child process } else { // the parent process does not increment var; it sleeps instead int status; int retvalue = 0; while (retvalue != c1) { status = 0; retvalue = waitpid (c1, &status, 0); if (retvalue < 0) { char buffer[256]; strerror_r (errno, buffer, 256); printf ("error occured %s\n", buffer); break; } else { printf ("state of process %d changed - ", retvalue); if (WIFEXITED (status)) { printf ("exited, status=%d\n", WEXITSTATUS (status)); } else if (WIFSIGNALED (status)) { printf ("killed by signal %d\n", WTERMSIG (status)); } else if (WIFSTOPPED (status)) { printf ("stopped by signal %d\n", WSTOPSIG (status)); } else if (WIFCONTINUED (status)) { printf ("continued\n"); } } } } /* The line below will be executed twice: once from the child and once from the parent. Recall that the parent process and child process have separate address spaces; thus, because only the child incremented the value of var, only the child will print that the value of var is 2. */ printf ("From process %d, value of var is %d.\n", getpid (), var); return 0; }
int client_to_svr( pbs_net_t hostaddr, /* I - internet addr of host */ unsigned int port, /* I - port to which to connect */ int local_port, /* I - BOOLEAN: not 0 to use local reserved port */ char *EMsg) /* O (optional,minsize=1024) */ { const char id[] = "client_to_svr"; struct sockaddr_in local; struct sockaddr_in remote; int sock; unsigned short tryport = 777; int rc; #ifndef NOPRIVPORTS int errorsock; int bind_retry; int flags; #endif int one = 1; int trycount = 0; struct timespec rem; #define STARTPORT 144 #define ENDPORT (IPPORT_RESERVED - 1) #define NPORTS (ENDPORT - STARTPORT + 1) #define SHUFFLE_COUNT 3 if (EMsg != NULL) EMsg[0] = '\0'; errno = 0; /* In case we can't connect go to sleep for 1 millisecond and try again */ rem.tv_sec = 0; rem.tv_nsec = 1000000; memset(&local, 0, sizeof(local)); memset(&remote, 0, sizeof(remote)); local.sin_family = AF_INET; local.sin_addr.s_addr = 0; local.sin_port = 0; retry: /* retry goto added (rentec) */ /* get socket */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { char err_buf[1024]; if (strerror_r(errno, err_buf, sizeof(err_buf))) err_buf[0] = '\0'; if (EMsg != NULL) sprintf(EMsg, "cannot create socket in %s - errno: %d %s", id, errno, err_buf); return(PBS_NET_RC_FATAL); } if (sock >= PBS_NET_MAX_CONNECTIONS) { if (EMsg != NULL) sprintf(EMsg, "PBS_NET_MAX_CONNECTIONS exceeded in %s", id); close(sock); /* too many connections */ return(PBS_NET_RC_RETRY); } #ifndef NOPRIVPORTS flags = fcntl(sock, F_GETFL); flags |= O_NONBLOCK; fcntl(sock, F_SETFL, flags); #endif /* !NOPRIVPORTS */ /* If local privilege port requested, bind to one */ /* must be root privileged to do this */ if (local_port != FALSE) { /* set REUSEADDR (rentec) */ setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one)); #ifndef NOPRIVPORTS if (trycount < SHUFFLE_COUNT) { errorsock = -1; #ifdef HAVE_BINDRESVPORT /* * bindresvport seems to cause connect() failures in some odd corner case when * talking to a local daemon. So we'll only try this once and fallback to * the slow loop around bind() if connect() fails with EADDRINUSE * or EADDRNOTAVAIL. * http://www.supercluster.org/pipermail/torqueusers/2006-June/003740.html */ for (bind_retry = 0; bind_retry < 3; bind_retry++) { errorsock = bindresvport(sock, &local); if (errorsock == 0) break; usleep(1000); } if (errorsock != 0) { char err_buf[1024]; if (strerror_r(errno, err_buf, sizeof(err_buf))) err_buf[0] = '\0'; /* bindresvport could not get a privileged port */ if (EMsg != NULL) sprintf(EMsg, "cannot bind to reserved port in %s - errno: %d %s", id, errno, err_buf); close(sock); return(PBS_NET_RC_FATAL); } tryport = ntohs(local.sin_port); goto jump_to_check; #else /* HAVE_BINDRESVPORT */ /* Pseudo-casual shuffling of tryport */ tryport = (rand() % NPORTS) + STARTPORT; #endif /* HAVE_BINDRESVPORT */ } else { /* A simple port search after SHUFFLE_COUNT shuffling */ if (tryport > ENDPORT) { tryport = STARTPORT; } } retry_bind: local.sin_port = htons(tryport); errorsock = bind(sock, (struct sockaddr *)&local, sizeof(local)); #ifdef HAVE_BINDRESVPORT jump_to_check: #endif /* HAVE_BINDRESVPORT */ if (errorsock < 0) { #ifdef NDEBUG2 char err_buf[1024]; if (strerror_r(errno, err_buf, sizeof(err_buf))) err_buf[0] = '\0'; fprintf(stderr, "INFO: cannot bind to port %d, errno: %d - %s\n", tryport, errno, err_buf); #endif /* NDEBUG2 */ /* Terminate on errors, except "address already in use" */ if ((errno == EADDRINUSE) || (errno == EINVAL) || (errno == EADDRNOTAVAIL)) { if (tryport++ < ENDPORT) goto retry_bind; } if (EMsg != NULL) { char err_buf[1024]; if (strerror_r(errno, err_buf, sizeof(err_buf))) err_buf[0] = '\0'; sprintf(EMsg, "cannot bind to reserved port in %s - errno: %d %s", id, errno, err_buf); } close(sock); return(PBS_NET_RC_RETRY); } #endif /* !NOPRIVPORTS */ } /* END if (local_port != FALSE) */ else { rc = bind(sock, (const struct sockaddr *)&local, sizeof(local)); if (rc != 0) { if (EMsg != NULL) sprintf(EMsg, "could not bind local socket: %s", strerror(errno)); close(sock); return(-1); } } /* bind successful!!! */ /* connect to specified server host and port */ remote.sin_addr.s_addr = htonl(hostaddr); remote.sin_port = htons((unsigned short)port); remote.sin_family = AF_INET; if (connect(sock, (struct sockaddr *)&remote, sizeof(remote)) >= 0) { /* SUCCESS */ return(sock); } /* process failure */ if (errno == EINPROGRESS) if (await_connect(MaxConnectTimeout, sock) == 0) { return(sock); } #ifdef NDEBUG2 char err_buf[1024]; if (strerror_r(errno, err_buf, sizeof(err_buf))) err_buf[0] = '\0'; fprintf(stderr, "INFO: cannot connect to port %d, errno=%d - %s\n", tryport, errno, err_buf); #endif /* NDEBUG2 */ switch (errno) { case ECONNREFUSED: /* Connection refused */ if (EMsg != NULL) sprintf(EMsg, "cannot connect to port %d in %s - connection refused.\n Check if trqauthd should be running\n", port, id); close(sock); return(PBS_NET_RC_RETRY); /*NOTREACHED*/ case EINPROGRESS: /* Operation now in progress */ case EALREADY: /* Operation already in progress */ case EISCONN: /* Transport endpoint is already connected */ case ETIMEDOUT: /* Connection timed out */ case EAGAIN: /* Operation would block */ case EINTR: /* Interrupted system call */ if (await_connect(MaxConnectTimeout, sock) == 0) { /* socket not ready for writing after MaxConnectTimeout microseconds timeout */ /* no network failures detected */ break; }/* Interrupted system call */ /* fall through to next case */ case EINVAL: /* Invalid argument */ case EADDRINUSE: /* Address already in use */ case EADDRNOTAVAIL: /* Cannot assign requested address */ /* TCP is not ready for us. Sleep for a millisecond and see if that will change anything before the next retry */ nanosleep(&rem,&rem); if (local_port != FALSE) { if (trycount++ > (NPORTS)) { close(sock); return(PBS_NET_RC_RETRY); } #if TCP_RETRY_LIMIT != 0 else if (trycount > TCP_RETRY_LIMIT) { if (EMsg != NULL) { char err_buf[1024]; if (strerror_r(errno, err_buf, sizeof(err_buf))) err_buf[0] = '\0'; sprintf(EMsg, "cannot connect to port %d in %s - errno:%d %s", port, id, errno, err_buf); } close(sock); return(PBS_NET_RC_FATAL); } #endif /* def TCP_RETRY_LIMIT */ /* continue port search (rentec) */ tryport++; close(sock); goto retry; } default: char err_buf[1024]; if (strerror_r(errno, err_buf, sizeof(err_buf))) err_buf[0] = '\0'; if (EMsg != NULL) sprintf(EMsg, "cannot connect to port %d in %s - errno:%d %s", tryport, id, errno, err_buf); close(sock); return(PBS_NET_RC_FATAL); } /* END switch (errno) */ return(sock); } /* END client_to_svr() */
void unix_error(char *msg) { char errno_msg[MAXLINE]; fprintf(stderr, "%s: %s\n", msg, strerror_r(errno, errno_msg, MAXLINE)); exit(0); }
static int _csync_backup_file(CSYNC *ctx, csync_file_stat_t *st, char **duri) { enum csync_replica_e drep = -1; enum csync_replica_e rep_bak = -1; char *suri = NULL; char errbuf[256] = {0}; int rc = -1; rep_bak = ctx->replica; if(st->instruction==CSYNC_INSTRUCTION_CONFLICT) { CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE,"CSYNC_INSTRUCTION_CONFLICT"); switch (ctx->current) { case LOCAL_REPLICA: drep = ctx->remote.type; if (asprintf(&suri, "%s/%s", ctx->remote.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } if (_backup_path(duri, ctx->remote.uri,st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } break; case REMOTE_REPLICA: drep = ctx->local.type; if (asprintf(&suri, "%s/%s", ctx->local.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } if ( _backup_path(duri, ctx->local.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } break; default: break; } } else { CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE,"instruction not allowed: %i %s", st->instruction, csync_instruction_str(st->instruction)); ctx->status_code = CSYNC_STATUS_UNSUCCESSFUL; rc = -1; goto out; } CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE,"suri: %s",suri); CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE,"duri: %s",*duri); /* rename the older file to conflict */ ctx->replica = drep; if (csync_vio_rename(ctx, suri, *duri) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { case ENOMEM: rc = -1; break; default: rc = 1; break; } strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: rename, error: %s", *duri, errbuf); goto out; } /* set instruction for the statedb merger */ st->instruction = CSYNC_INSTRUCTION_NONE; CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "BACKUP file: %s", *duri); rc = 0; out: /* set instruction for the statedb merger */ if (rc != 0) { st->instruction = CSYNC_INSTRUCTION_ERROR; } SAFE_FREE(suri); ctx->replica = rep_bak; return rc; }
/** * Emit a log message. This function is the variable argument list equivalent * to vlc_Log(). */ void vlc_vaLog (vlc_object_t *obj, int type, const char *module, const char *format, va_list args) { if (obj != NULL && obj->i_flags & OBJECT_FLAGS_QUIET) return; /* C locale to get error messages in English in the logs */ locale_t c = newlocale (LC_MESSAGES_MASK, "C", (locale_t)0); locale_t locale = uselocale (c); #ifndef __GLIBC__ /* Expand %m to strerror(errno) - only once */ char buf[strlen(format) + 2001], *ptr; strcpy (buf, format); ptr = (char*)buf; format = (const char*) buf; for( ;; ) { ptr = strchr( ptr, '%' ); if( ptr == NULL ) break; if( ptr[1] == 'm' ) { char errbuf[2001]; size_t errlen; #ifndef WIN32 strerror_r( errno, errbuf, 1001 ); #else int sockerr = WSAGetLastError( ); if( sockerr ) { strncpy( errbuf, net_strerror( sockerr ), 1001 ); WSASetLastError( sockerr ); } if ((sockerr == 0) || (strcmp ("Unknown network stack error", errbuf) == 0)) strncpy( errbuf, strerror( errno ), 1001 ); #endif errbuf[1000] = 0; /* Escape '%' from the error string */ for( char *percent = strchr( errbuf, '%' ); percent != NULL; percent = strchr( percent + 2, '%' ) ) { memmove( percent + 1, percent, strlen( percent ) + 1 ); } errlen = strlen( errbuf ); memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 ); memcpy( ptr, errbuf, errlen ); break; /* Only once, so we don't overflow */ } /* Looks for conversion specifier... */ do ptr++; while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) ); if( *ptr ) ptr++; /* ...and skip it */ } #endif /* Fill message information fields */ msg_item_t msg; msg.i_object_id = (uintptr_t)obj; msg.psz_object_type = (obj != NULL) ? obj->psz_object_type : "generic"; msg.psz_module = module; msg.psz_header = NULL; for (vlc_object_t *o = obj; o != NULL; o = o->p_parent) if (o->psz_header != NULL) { msg.psz_header = o->psz_header; break; } /* Pass message to subscribers */ libvlc_priv_t *priv = libvlc_priv (obj->p_libvlc); va_list ap; va_copy (ap, args); if (priv->b_color) PrintColorMsg (&priv->i_verbose, type, &msg, format, ap); else PrintMsg (&priv->i_verbose, type, &msg, format, ap); va_end (ap); vlc_rwlock_rdlock (&msg_lock); for (msg_subscription_t *sub = msg_head; sub != NULL; sub = sub->next) { va_copy (ap, args); sub->func (sub->opaque, type, &msg, format, ap); va_end (ap); } vlc_rwlock_unlock (&msg_lock); uselocale (locale); freelocale (c); }
static int _csync_push_file(CSYNC *ctx, csync_file_stat_t *st) { enum csync_replica_e srep = -1; enum csync_replica_e drep = -1; enum csync_replica_e rep_bak = -1; char *suri = NULL; char *duri = NULL; char *turi = NULL; char *tdir = NULL; csync_vio_handle_t *sfp = NULL; csync_vio_handle_t *dfp = NULL; csync_vio_file_stat_t *tstat = NULL; char errbuf[256] = {0}; char buf[MAX_XFER_BUF_SIZE] = {0}; ssize_t bread = 0; ssize_t bwritten = 0; struct timeval times[2]; int rc = -1; int count = 0; int flags = 0; rep_bak = ctx->replica; switch (ctx->current) { case LOCAL_REPLICA: srep = ctx->local.type; drep = ctx->remote.type; if (asprintf(&suri, "%s/%s", ctx->local.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } if (asprintf(&duri, "%s/%s", ctx->remote.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } break; case REMOTE_REPLICA: srep = ctx->remote.type; drep = ctx->local.type; if (asprintf(&suri, "%s/%s", ctx->remote.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } if (asprintf(&duri, "%s/%s", ctx->local.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } break; default: break; } /* Open the source file */ ctx->replica = srep; flags = O_RDONLY|O_NOFOLLOW; #ifdef O_NOATIME /* O_NOATIME can only be set by the owner of the file or the superuser */ if (st->uid == ctx->pwd.uid || ctx->pwd.euid == 0) { flags |= O_NOATIME; } #endif sfp = csync_vio_open(ctx, suri, flags, 0); if (sfp == NULL) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); if (errno == ENOMEM) { rc = -1; } else { rc = 1; } strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: open(O_RDONLY), error: %s", suri, errbuf ); goto out; } if (_push_to_tmp_first(ctx)) { /* create the temporary file name */ if (asprintf(&turi, "%s.XXXXXX", duri) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } /* We just want a random file name here, open checks if the file exists. */ if (c_tmpname(turi) < 0) { ctx->status_code = CSYNC_STATUS_PARAM_ERROR; rc = -1; goto out; } } else { /* write to the target file directly as the HTTP server does it atomically */ if (asprintf(&turi, "%s", duri) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE, "Remote repository atomar push enabled for %s.", turi ); } /* Create the destination file */ ctx->replica = drep; while ((dfp = csync_vio_open(ctx, turi, O_CREAT|O_EXCL|O_WRONLY|O_NOCTTY, C_FILE_MODE)) == NULL) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { case EEXIST: if (count++ > 10) { CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: open(O_CREAT), error: max count exceeded", duri); ctx->status_code = CSYNC_STATUS_OPEN_ERROR; rc = 1; goto out; } if(_push_to_tmp_first(ctx)) { if (c_tmpname(turi) < 0) { ctx->status_code = CSYNC_STATUS_PARAM_ERROR; rc = -1; goto out; } } break; case ENOENT: /* get the directory name */ tdir = c_dirname(turi); if (tdir == NULL) { rc = -1; goto out; } if (csync_vio_mkdirs(ctx, tdir, C_DIR_MODE) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_WARN, "dir: %s, command: mkdirs, error: %s", tdir, errbuf); } break; case ENOMEM: rc = -1; strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: open(O_CREAT), error: %s", turi, errbuf); goto out; break; default: strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: open(O_CREAT), error: %s", turi, errbuf); rc = 1; goto out; break; } } /* copy file */ for (;;) { ctx->replica = srep; bread = csync_vio_read(ctx, sfp, buf, MAX_XFER_BUF_SIZE); if (bread < 0) { /* read error */ ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: read, error: %s", suri, errbuf); rc = 1; goto out; } else if (bread == 0) { /* done */ break; } ctx->replica = drep; bwritten = csync_vio_write(ctx, dfp, buf, bread); if (bwritten < 0 || bread != bwritten) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: write, error: bread = %zu, bwritten = %zu - %s", duri, bread, bwritten, errbuf); rc = 1; goto out; } } ctx->replica = srep; if (csync_vio_close(ctx, sfp) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: close, error: %s", suri, errbuf); } sfp = NULL; ctx->replica = drep; if (csync_vio_close(ctx, dfp) < 0) { dfp = NULL; ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { /* stop if no space left or quota exceeded */ case ENOSPC: case EDQUOT: strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: close, error: %s", turi, errbuf); rc = -1; goto out; break; default: CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: close, error: %s", turi, strerror_r(errno, errbuf, sizeof(errbuf))); break; } } dfp = NULL; /* * Check filesize */ ctx->replica = drep; tstat = csync_vio_file_stat_new(); if (tstat == NULL) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; rc = -1; goto out; } if (csync_vio_stat(ctx, turi, tstat) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { case ENOMEM: rc = -1; break; default: rc = 1; break; } strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: stat, error: %s", turi, errbuf); goto out; } if (st->size != tstat->size) { CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, error: incorrect filesize (size: %jd should be %jd)", turi, tstat->size, st->size); ctx->status_code = CSYNC_STATUS_FILE_SIZE_ERROR; rc = 1; goto out; } if (_push_to_tmp_first(ctx)) { /* override original file */ ctx->replica = drep; if (csync_vio_rename(ctx, turi, duri) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { case ENOMEM: rc = -1; break; default: rc = 1; break; } strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: rename, error: %s", duri, errbuf); goto out; } } /* set mode only if it is not the default mode */ if ((st->mode & 07777) != C_FILE_MODE) { if (csync_vio_chmod(ctx, duri, st->mode) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { case ENOMEM: rc = -1; break; default: rc = 1; break; } strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "file: %s, command: chmod, error: %s", duri, errbuf); goto out; } } /* set owner and group if possible */ if (ctx->pwd.euid == 0) { csync_vio_chown(ctx, duri, st->uid, st->gid); } /* sync time */ times[0].tv_sec = times[1].tv_sec = st->modtime; times[0].tv_usec = times[1].tv_usec = 0; ctx->replica = drep; csync_vio_utimes(ctx, duri, times); /* set instruction for the statedb merger */ st->instruction = CSYNC_INSTRUCTION_UPDATED; CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "PUSHED file: %s", duri); rc = 0; out: ctx->replica = srep; csync_vio_close(ctx, sfp); ctx->replica = drep; csync_vio_close(ctx, dfp); csync_vio_file_stat_destroy(tstat); /* set instruction for the statedb merger */ if (rc != 0) { st->instruction = CSYNC_INSTRUCTION_ERROR; if (turi != NULL) { csync_vio_unlink(ctx, turi); } } SAFE_FREE(suri); SAFE_FREE(duri); SAFE_FREE(turi); SAFE_FREE(tdir); ctx->replica = rep_bak; return rc; }
void MQTT_setup() { printf("[MQTT] setup\n"); char *id = NULL; char *id_prefix = NULL; int i; char *host = "192.168.1.127"; int port = 1883; int keepalive = 60; bool clean_session = true; bool debug = false; int rc, rc2; char hostname[21]; char err[1024]; uint8_t *will_payload = NULL; long will_payloadlen = 0; int will_qos = 0; bool will_retain = false; char *will_topic = NULL; printf("[MQTT] Initialization MQTT at %s:%i\n", host, port); if(clean_session == false && (id_prefix || !id)){ fprintf(stderr, "[MQTT] Error: You must provide a client id if you are using the -c option.\n"); return 1; } if(id_prefix){ id = malloc(strlen(id_prefix)+10); if(!id){ fprintf(stderr, "[MQTT] Error: Out of memory.\n"); return 1; } snprintf(id, strlen(id_prefix)+10, "%s%d", id_prefix, getpid()); }else if(!id){ id = malloc(30); if(!id){ fprintf(stderr, "[MQTT] Error: Out of memory.\n"); return 1; } memset(hostname, 0, 21); gethostname(hostname, 20); snprintf(id, 23, "mosq_sub_%d_%s", getpid(), hostname); } if(will_payload && !will_topic){ fprintf(stderr, "[MQTT] Error: Will payload given, but no will topic given.\n"); return 1; } if(will_retain && !will_topic){ fprintf(stderr, "[MQTT] Error: Will retain given, but no will topic given.\n"); return 1; } if(MQTT_password && !MQTT_username){ fprintf(stderr, "[MQTT] Warning: Not using password since username not set.\n"); } mosquitto_lib_init(); MQTT_mosq = mosquitto_new(id, NULL); if(!MQTT_mosq){ fprintf(stderr, "[MQTT] Error: Out of memory.\n"); return 1; } if(will_topic && mosquitto_will_set(MQTT_mosq, true, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){ fprintf(stderr, "[MQTT] Error: Problem setting will.\n"); return 1; } if(MQTT_username && mosquitto_username_pw_set(MQTT_mosq, MQTT_username, MQTT_password)){ fprintf(stderr, "[MQTT] Error: Problem setting username and password.\n"); return 1; } mosquitto_connect_callback_set(MQTT_mosq, MQTT_connect_callback); mosquitto_message_callback_set(MQTT_mosq, MQTT_message_callback); mosquitto_subscribe_callback_set(MQTT_mosq, MQTT_subscribe_callback); rc = mosquitto_connect(MQTT_mosq, host, port, keepalive, clean_session); if(rc){ if(rc == MOSQ_ERR_ERRNO){ strerror_r(errno, err, 1024); fprintf(stderr, "[MQTT] Error: %s\n", err); }else{ fprintf(stderr, "[MQTT] Unable to connect (%d).\n", rc); } //return rc; } }
static int _csync_sync_dir(CSYNC *ctx, csync_file_stat_t *st) { enum csync_replica_e dest = -1; enum csync_replica_e replica_bak; char errbuf[256] = {0}; char *uri = NULL; struct timeval times[2]; int rc = -1; replica_bak = ctx->replica; switch (ctx->current) { case LOCAL_REPLICA: dest = ctx->remote.type; if (asprintf(&uri, "%s/%s", ctx->remote.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; return -1; } break; case REMOTE_REPLICA: dest = ctx->local.type; if (asprintf(&uri, "%s/%s", ctx->local.uri, st->path) < 0) { ctx->status_code = CSYNC_STATUS_MEMORY_ERROR; return -1; } break; default: break; } ctx->replica = dest; /* chmod is if it is not the default mode */ if ((st->mode & 07777) != C_DIR_MODE) { if (csync_vio_chmod(ctx, uri, st->mode) < 0) { ctx->status_code = csync_errno_to_status(errno, CSYNC_STATUS_PROPAGATE_ERROR); switch (errno) { case ENOMEM: rc = -1; break; default: rc = 1; break; } strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "dir: %s, command: chmod, error: %s", uri, errbuf); goto out; } } /* set owner and group if possible */ if (ctx->pwd.euid == 0) { csync_vio_chown(ctx, uri, st->uid, st->gid); } times[0].tv_sec = times[1].tv_sec = st->modtime; times[0].tv_usec = times[1].tv_usec = 0; csync_vio_utimes(ctx, uri, times); /* set instruction for the statedb merger */ st->instruction = CSYNC_INSTRUCTION_UPDATED; CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "SYNCED dir: %s", uri); ctx->replica = replica_bak; rc = 0; out: SAFE_FREE(uri); /* set instruction for the statedb merger */ if (rc != 0) { st->instruction = CSYNC_INSTRUCTION_ERROR; } return rc; }
/*! * \brief */ static int create_ssdp_sock_v4( /*! [] SSDP IPv4 socket to be created. */ SOCKET *ssdpSock) { char errorBuffer[ERROR_BUFFER_LEN]; int onOff; u_char ttl = (u_char)4; struct ip_mreq ssdpMcastAddr; struct sockaddr_storage __ss; struct sockaddr_in *ssdpAddr4 = (struct sockaddr_in *)&__ss; int ret = 0; struct in_addr addr; *ssdpSock = socket_no_sigpipe(AF_INET, SOCK_DGRAM, 0); if (*ssdpSock == INVALID_SOCKET) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in socket(): %s\n", errorBuffer); return UPNP_E_OUTOF_SOCKET; } onOff = 1; ret = setsockopt(*ssdpSock, SOL_SOCKET, SO_REUSEADDR, (char *)&onOff, sizeof(onOff)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() SO_REUSEADDR: %s\n", errorBuffer); ret = UPNP_E_SOCKET_ERROR; goto error_handler; } #if defined(BSD) || defined(__OSX__) || defined(__APPLE__) onOff = 1; ret = setsockopt(*ssdpSock, SOL_SOCKET, SO_REUSEPORT, (char *)&onOff, sizeof(onOff)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() SO_REUSEPORT: %s\n", errorBuffer); ret = UPNP_E_SOCKET_ERROR; goto error_handler; } #endif /* BSD, __OSX__, __APPLE__ */ memset(&__ss, 0, sizeof(__ss)); ssdpAddr4->sin_family = (sa_family_t)AF_INET; ssdpAddr4->sin_addr.s_addr = htonl(INADDR_ANY); ssdpAddr4->sin_port = htons(SSDP_PORT); ret = bind(*ssdpSock, (struct sockaddr *)ssdpAddr4, sizeof(*ssdpAddr4)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in bind(), addr=0x%08X, port=%d: %s\n", INADDR_ANY, SSDP_PORT, errorBuffer); ret = UPNP_E_SOCKET_BIND; goto error_handler; } memset((void *)&ssdpMcastAddr, 0, sizeof(struct ip_mreq)); ssdpMcastAddr.imr_interface.s_addr = inet_addr(gIF_IPV4); ssdpMcastAddr.imr_multiaddr.s_addr = inet_addr(SSDP_IP); ret = setsockopt(*ssdpSock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ssdpMcastAddr, sizeof(struct ip_mreq)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() IP_ADD_MEMBERSHIP (join multicast group): %s\n", errorBuffer); ret = UPNP_E_SOCKET_ERROR; goto error_handler; } /* Set multicast interface. */ memset((void *)&addr, 0, sizeof(struct in_addr)); addr.s_addr = inet_addr(gIF_IPV4); ret = setsockopt(*ssdpSock, IPPROTO_IP, IP_MULTICAST_IF, (char *)&addr, sizeof addr); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__, "Error in setsockopt() IP_MULTICAST_IF (set multicast interface): %s\n", errorBuffer); /* This is probably not a critical error, so let's continue. */ } /* result is not checked becuase it will fail in WinMe and Win9x. */ ret = setsockopt(*ssdpSock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); onOff = 1; ret = setsockopt(*ssdpSock, SOL_SOCKET, SO_BROADCAST, (char *)&onOff, sizeof(onOff)); if (ret == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_CRITICAL, SSDP, __FILE__, __LINE__, "Error in setsockopt() SO_BROADCAST (set broadcast): %s\n", errorBuffer); ret = UPNP_E_NETWORK_ERROR; goto error_handler; } ret = UPNP_E_SUCCESS; error_handler: if (ret != UPNP_E_SUCCESS) { if (shutdown(*ssdpSock, SD_BOTH) == -1) { strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN); UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__, "Error in shutdown: %s\n", errorBuffer); } UpnpCloseSocket(*ssdpSock); } return ret; }
//SUCCESS: return the length 0f the command result,the length may great than the bufferLen //TIME OUT: return RESULT_TIME_OUT //OTHER ERROR: return <0 int PhoneConnectionC::sendAtCommand_direct(const char *atCommand, char resultBuffer[], int bufferLen, int timeout) { QMutexLocker locker(&m_waitMutex); if(atCommand == NULL || resultBuffer == NULL || bufferLen <= 0) return PC_RESULT_PARAM_ERROR; #ifdef IBD_DEBUG static unsigned int csqCount=0; static unsigned int zpasCount=0; if(strncmp(atCommand,"AT+CSQ\r\n",strlen("AT+CSQ\r\n"))==0) { if((csqCount++)%(10*60)==0) IBD_PRINTF(DEBUG_INFOMATION,"Send AT(%s):%s\n",m_devName,atCommand); } else if(strncmp(atCommand,"AT+ZPAS?\r\n",strlen("AT+ZPAS?\r\n"))==0) { if((zpasCount++)%(10*60)==0) IBD_PRINTF(DEBUG_INFOMATION,"Send AT(%s):%s\n",m_devName,atCommand); } else { IBD_PRINTF(DEBUG_INFOMATION,"Send AT(%s):%s\n",m_devName,atCommand); } #endif int writeLen=0; while(writeLen<(int)strlen(atCommand)) { int len=write(m_comFd, atCommand+writeLen, strlen(atCommand)-writeLen); if(len<=0) { if(errno==EINTR) { continue; } else { char buffer[100]; IBD_PRINTF(DEBUG_EMERGENCY,"Send AT(%s):%s error=%s\n",m_devName,atCommand,strerror_r(errno,buffer,100)); return PC_RESULT_OP_ERROR; } } writeLen+=len; } m_command = atCommand; m_commandResult = resultBuffer; m_commandResultLen = bufferLen; bool waitResult = m_event.wait(&m_waitMutex, timeout); if((strstr(resultBuffer,"+CIPRXGET: 3") && strstr(resultBuffer,"+CIPRXGET: 1"))){ m_command = atCommand; m_commandResult = resultBuffer + strlen(resultBuffer); m_commandResultLen = bufferLen - strlen(resultBuffer) - 1; waitResult = m_event.wait(&m_waitMutex, timeout*3); //waitResult == 0 when mechine first start //printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@+CIPRXGET: 1 waitResult: %d == %s@@@@@@@@@@@@@@@@@@@@@@@@@@@\n", waitResult, resultBuffer); m_command = NULL; m_commandResult = NULL; return strlen(resultBuffer); } if((strncmp(atCommand,"AT+CIPSTATUS\r\n",strlen("AT+CIPSTATUS\r\n"))==0 || strstr(atCommand,"AT+CIPSTART=") != NULL)){ m_command = atCommand; m_commandResult = resultBuffer; m_commandResultLen = bufferLen; waitResult = m_event.wait(&m_waitMutex, timeout*3); //waitResult == 0 when mechine first start //printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@waitResult: %d == %s@@@@@@@@@@@@@@@@@@@@@@@@@@@\n", waitResult, resultBuffer); m_command = NULL; m_commandResult = NULL; return strlen(resultBuffer); } m_command = NULL; m_commandResult = NULL; if(waitResult == false) { IBD_PRINTF(DEBUG_WARNING,"Send AT(%s):%s timeout\n",m_devName,atCommand); return PC_RESULT_TIME_OUT; } return m_commandResultLen; }