static char *bpf_dump(const struct sock_filter bpf, int n) { int v; const char *fmt, *op; static char image[256]; char operand[64]; v = bpf.k; switch (bpf.code) { default: op = "unimp"; fmt = "0x%x"; v = bpf.code; break; case BPF_RET | BPF_K: op = "ret"; fmt = "#0x%x"; break; case BPF_RET | BPF_A: op = "ret"; fmt = ""; break; case BPF_LD | BPF_W | BPF_ABS: op = "ld"; fmt = "[%d]"; break; case BPF_LD | BPF_H | BPF_ABS: op = "ldh"; fmt = "[%d]"; break; case BPF_LD | BPF_B | BPF_ABS: op = "ldb"; fmt = "[%d]"; break; case BPF_LD | BPF_W | BPF_LEN: op = "ld"; fmt = "#pktlen"; break; case BPF_LD | BPF_W | BPF_IND: op = "ld"; fmt = "[x + %d]"; break; case BPF_LD | BPF_H | BPF_IND: op = "ldh"; fmt = "[x + %d]"; break; case BPF_LD | BPF_B | BPF_IND: op = "ldb"; fmt = "[x + %d]"; break; case BPF_LD | BPF_IMM: op = "ld"; fmt = "#0x%x"; break; case BPF_LDX | BPF_IMM: op = "ldx"; fmt = "#0x%x"; break; case BPF_LDX | BPF_MSH | BPF_B: op = "ldxb"; fmt = "4*([%d]&0xf)"; break; case BPF_LD | BPF_MEM: op = "ld"; fmt = "M[%d]"; break; case BPF_LDX | BPF_MEM: op = "ldx"; fmt = "M[%d]"; break; case BPF_ST: op = "st"; fmt = "M[%d]"; break; case BPF_STX: op = "stx"; fmt = "M[%d]"; break; case BPF_JMP | BPF_JA: op = "ja"; fmt = "%d"; v = n + 1 + bpf.k; break; case BPF_JMP | BPF_JGT | BPF_K: op = "jgt"; fmt = "#0x%x"; break; case BPF_JMP | BPF_JGE | BPF_K: op = "jge"; fmt = "#0x%x"; break; case BPF_JMP | BPF_JEQ | BPF_K: op = "jeq"; fmt = "#0x%x"; break; case BPF_JMP | BPF_JSET | BPF_K: op = "jset"; fmt = "#0x%x"; break; case BPF_JMP | BPF_JGT | BPF_X: op = "jgt"; fmt = "x"; break; case BPF_JMP | BPF_JGE | BPF_X: op = "jge"; fmt = "x"; break; case BPF_JMP | BPF_JEQ | BPF_X: op = "jeq"; fmt = "x"; break; case BPF_JMP | BPF_JSET | BPF_X: op = "jset"; fmt = "x"; break; case BPF_ALU | BPF_ADD | BPF_X: op = "add"; fmt = "x"; break; case BPF_ALU | BPF_SUB | BPF_X: op = "sub"; fmt = "x"; break; case BPF_ALU | BPF_MUL | BPF_X: op = "mul"; fmt = "x"; break; case BPF_ALU | BPF_DIV | BPF_X: op = "div"; fmt = "x"; break; case BPF_ALU | BPF_AND | BPF_X: op = "and"; fmt = "x"; break; case BPF_ALU | BPF_OR | BPF_X: op = "or"; fmt = "x"; break; case BPF_ALU | BPF_LSH | BPF_X: op = "lsh"; fmt = "x"; break; case BPF_ALU | BPF_RSH | BPF_X: op = "rsh"; fmt = "x"; break; case BPF_ALU | BPF_ADD | BPF_K: op = "add"; fmt = "#%d"; break; case BPF_ALU | BPF_SUB | BPF_K: op = "sub"; fmt = "#%d"; break; case BPF_ALU | BPF_MUL | BPF_K: op = "mul"; fmt = "#%d"; break; case BPF_ALU | BPF_DIV | BPF_K: op = "div"; fmt = "#%d"; break; case BPF_ALU | BPF_AND | BPF_K: op = "and"; fmt = "#0x%x"; break; case BPF_ALU | BPF_OR | BPF_K: op = "or"; fmt = "#0x%x"; break; case BPF_ALU | BPF_LSH | BPF_K: op = "lsh"; fmt = "#%d"; break; case BPF_ALU | BPF_RSH | BPF_K: op = "rsh"; fmt = "#%d"; break; case BPF_ALU | BPF_NEG: op = "neg"; fmt = ""; break; case BPF_MISC | BPF_TAX: op = "tax"; fmt = ""; break; case BPF_MISC | BPF_TXA: op = "txa"; fmt = ""; break; } slprintf(operand, sizeof(operand), fmt, v); slprintf(image, sizeof(image), (BPF_CLASS(bpf.code) == BPF_JMP && BPF_OP(bpf.code) != BPF_JA) ? "L%d: %s %s, L%d, L%d" : "L%d: %s %s", n, op, operand, n + 1 + bpf.jt, n + 1 + bpf.jf); return image; }
const char *cli_errstr(struct cli_state *cli) { fstring cli_error_message; uint32 flgs2 = SVAL(cli->inbuf,smb_flg2), errnum; uint8 errclass; int i; char *result; if (!cli->initialised) { fstrcpy(cli_error_message, "[Programmer's error] cli_errstr called on unitialized cli_stat struct!\n"); goto done; } /* Was it server socket error ? */ if (cli->fd == -1 && cli->smb_rw_error) { switch(cli->smb_rw_error) { case SMB_READ_TIMEOUT: slprintf(cli_error_message, sizeof(cli_error_message) - 1, "Call timed out: server did not respond after %d milliseconds", cli->timeout); break; case SMB_READ_EOF: slprintf(cli_error_message, sizeof(cli_error_message) - 1, "Call returned zero bytes (EOF)" ); break; case SMB_READ_ERROR: slprintf(cli_error_message, sizeof(cli_error_message) - 1, "Read error: %s", strerror(errno) ); break; case SMB_WRITE_ERROR: slprintf(cli_error_message, sizeof(cli_error_message) - 1, "Write error: %s", strerror(errno) ); break; case SMB_READ_BAD_SIG: slprintf(cli_error_message, sizeof(cli_error_message) - 1, "Server packet had invalid SMB signature!"); break; case SMB_NO_MEMORY: slprintf(cli_error_message, sizeof(cli_error_message) - 1, "Out of memory"); break; default: slprintf(cli_error_message, sizeof(cli_error_message) - 1, "Unknown error code %d\n", cli->smb_rw_error ); break; } goto done; } /* Case #1: RAP error */ if (cli->rap_error) { for (i = 0; rap_errmap[i].message != NULL; i++) { if (rap_errmap[i].err == cli->rap_error) { return rap_errmap[i].message; } } slprintf(cli_error_message, sizeof(cli_error_message) - 1, "RAP code %d", cli->rap_error); goto done; } /* Case #2: 32-bit NT errors */ if (flgs2 & FLAGS2_32_BIT_ERROR_CODES) { NTSTATUS status = NT_STATUS(IVAL(cli->inbuf,smb_rcls)); return nt_errstr(status); } cli_dos_error(cli, &errclass, &errnum); /* Case #3: SMB error */ return cli_smb_errstr(cli); done: result = talloc_strdup(talloc_tos(), cli_error_message); SMB_ASSERT(result); return result; }
static bool api_rpcTNP(struct pipes_struct *p, struct ncacn_packet *pkt, const struct api_struct *api_rpc_cmds, int n_cmds, const struct ndr_syntax_id *syntax) { int fn_num; uint32_t offset1; const struct ndr_interface_table *table; /* interpret the command */ DEBUG(4,("api_rpcTNP: %s op 0x%x - ", ndr_interface_name(&syntax->uuid, syntax->if_version), pkt->u.request.opnum)); table = ndr_table_by_uuid(&syntax->uuid); if (table == NULL) { DEBUG(0,("unknown interface\n")); return false; } if (DEBUGLEVEL >= 50) { fstring name; slprintf(name, sizeof(name)-1, "in_%s", dcerpc_default_transport_endpoint(pkt, NCACN_NP, table)); dump_pdu_region(name, pkt->u.request.opnum, &p->in_data.data, 0, p->in_data.data.length); } for (fn_num = 0; fn_num < n_cmds; fn_num++) { if (api_rpc_cmds[fn_num].opnum == pkt->u.request.opnum && api_rpc_cmds[fn_num].fn != NULL) { DEBUG(3, ("api_rpcTNP: rpc command: %s\n", api_rpc_cmds[fn_num].name)); break; } } if (fn_num == n_cmds) { /* * For an unknown RPC just return a fault PDU but * return True to allow RPC's on the pipe to continue * and not put the pipe into fault state. JRA. */ DEBUG(4, ("unknown\n")); setup_fault_pdu(p, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR)); return True; } offset1 = p->out_data.rdata.length; DEBUG(6, ("api_rpc_cmds[%d].fn == %p\n", fn_num, api_rpc_cmds[fn_num].fn)); /* do the actual command */ if(!api_rpc_cmds[fn_num].fn(p)) { DEBUG(0,("api_rpcTNP: %s: %s failed.\n", ndr_interface_name(&syntax->uuid, syntax->if_version), api_rpc_cmds[fn_num].name)); data_blob_free(&p->out_data.rdata); return False; } if (p->fault_state) { DEBUG(4,("api_rpcTNP: fault(%d) return.\n", p->fault_state)); setup_fault_pdu(p, NT_STATUS(p->fault_state)); p->fault_state = 0; return true; } if (DEBUGLEVEL >= 50) { fstring name; slprintf(name, sizeof(name)-1, "out_%s", dcerpc_default_transport_endpoint(pkt, NCACN_NP, table)); dump_pdu_region(name, pkt->u.request.opnum, &p->out_data.rdata, offset1, p->out_data.rdata.length); } DEBUG(5,("api_rpcTNP: called %s successfully\n", ndr_interface_name(&syntax->uuid, syntax->if_version))); /* Check for buffer underflow in rpc parsing */ if ((DEBUGLEVEL >= 10) && (pkt->frag_length < p->in_data.data.length)) { DEBUG(10, ("api_rpcTNP: rpc input buffer underflow (parse error?)\n")); dump_data(10, p->in_data.data.data + pkt->frag_length, p->in_data.data.length - pkt->frag_length); } return True; }
static int iprint_job_resume(int snum, struct printjob *pjob) { int ret = 1; /* Return value */ http_t *http = NULL; /* HTTP connection to server */ ipp_t *request = NULL, /* IPP Request */ *response = NULL; /* IPP Response */ cups_lang_t *language = NULL; /* Default language */ char uri[HTTP_MAX_URI]; /* printer-uri attribute */ char httpPath[HTTP_MAX_URI]; /* path portion of the printer-uri */ DEBUG(5,("iprint_job_resume(%d, %p (%d))\n", snum, pjob, pjob->sysjob)); /* * Make sure we don't ask for passwords... */ cupsSetPasswordCB(iprint_passwd_cb); /* * Try to connect to the server... */ if ((http = httpConnect(iprint_server(), ippPort())) == NULL) { DEBUG(0,("Unable to connect to iPrint server %s - %s\n", iprint_server(), strerror(errno))); goto out; } /* * Build an IPP_RELEASE_JOB request, which requires the following * attributes: * * attributes-charset * attributes-natural-language * printer-uri * job-id * requesting-user-name */ request = ippNew(); request->request.op.operation_id = IPP_RELEASE_JOB; request->request.op.request_id = 1; language = cupsLangDefault(); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, "utf-8"); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, language->language); slprintf(uri, sizeof(uri) - 1, "ipp://%s/ipp/%s", iprint_server(), PRINTERNAME(snum)); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", pjob->sysjob); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, pjob->user); /* * Do the request and get back a response... */ slprintf(httpPath, sizeof(httpPath) - 1, "/ipp/%s", PRINTERNAME(snum)); if ((response = cupsDoRequest(http, request, httpPath)) != NULL) { if (response->request.status.status_code >= IPP_OK_CONFLICT) { DEBUG(0,("Unable to release job %d - %s\n", pjob->sysjob, ippErrorString(cupsLastError()))); } else { ret = 0; } } else { DEBUG(0,("Unable to release job %d - %s\n", pjob->sysjob, ippErrorString(cupsLastError()))); } out: if (response) ippDelete(response); if (language) cupsLangFree(language); if (http) httpClose(http); return ret; }
static int iprint_queue_get(const char *sharename, enum printing_types printing_type, char *lpq_command, print_queue_struct **q, print_status_struct *status) { fstring printername; http_t *http = NULL; /* HTTP connection to server */ ipp_t *request = NULL, /* IPP Request */ *response = NULL; /* IPP Response */ ipp_attribute_t *attr = NULL; /* Current attribute */ cups_lang_t *language = NULL; /* Default language */ char uri[HTTP_MAX_URI]; /* printer-uri attribute */ char serviceUri[HTTP_MAX_URI]; /* service-uri attribute */ char httpPath[HTTP_MAX_URI]; /* path portion of the uri */ int jobUseUnixTime = 0; /* Whether job times should * be assumed to be Unix time */ int qcount = 0, /* Number of active queue entries */ qalloc = 0; /* Number of queue entries allocated */ print_queue_struct *queue = NULL, /* Queue entries */ *temp; /* Temporary pointer for queue */ const char *user_name, /* job-originating-user-name attribute */ *job_name; /* job-name attribute */ int job_id; /* job-id attribute */ int job_k_octets; /* job-k-octets attribute */ time_t job_time; /* time-at-creation attribute */ time_t printer_current_time = 0; /* printer's current time */ time_t printer_up_time = 0; /* printer's uptime */ ipp_jstate_t job_status; /* job-status attribute */ int job_priority; /* job-priority attribute */ static const char *jattrs[] = /* Requested job attributes */ { "job-id", "job-k-octets", "job-name", "job-originating-user-name", "job-priority", "job-state", "time-at-creation", }; static const char *pattrs[] = /* Requested printer attributes */ { "printer-state", "printer-state-message", "printer-current-time", "printer-up-time" }; *q = NULL; /* HACK ALERT!!! The porblem with support the 'printer name' option is that we key the tdb off the sharename. So we will overload the lpq_command string to pass in the printername (which is basically what we do for non-cups printers ... using the lpq_command to get the queue listing). */ fstrcpy( printername, lpq_command ); DEBUG(5,("iprint_queue_get(%s, %p, %p)\n", printername, q, status)); /* * Make sure we don't ask for passwords... */ cupsSetPasswordCB(iprint_passwd_cb); /* * Try to connect to the server... */ if ((http = httpConnect(iprint_server(), ippPort())) == NULL) { DEBUG(0,("Unable to connect to iPrint server %s - %s\n", iprint_server(), strerror(errno))); goto out; } /* * Generate the printer URI and the service URI that goes with it... */ slprintf(uri, sizeof(uri) - 1, "ipp://%s/ipp/%s", iprint_server(), printername); slprintf(serviceUri, sizeof(serviceUri) - 1, "ipp://%s/ipp/", iprint_server()); /* * For Linux iPrint servers from OES SP1 on, the iPrint server * uses Unix time for job start times unless it detects the iPrint * client in an http User-Agent header. (This was done to accomodate * CUPS broken behavior. According to RFC 2911, section 4.3.14, job * start times are supposed to be relative to how long the printer has * been up.) Since libcups doesn't allow us to set that header before * the request is sent, this ugly hack allows us to detect the server * version and decide how to interpret the job time. */ if (iprint_get_server_version(http, serviceUri) >= NOVELL_SERVER_VERSION_OES_SP1) jobUseUnixTime = 1; request = ippNew(); request->request.op.operation_id = IPP_GET_PRINTER_ATTRIBUTES; request->request.op.request_id = 2; language = cupsLangDefault(); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, "utf-8"); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, language->language); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", (sizeof(pattrs) / sizeof(pattrs[0])), NULL, pattrs); /* * Do the request and get back a response... */ slprintf(httpPath, sizeof(httpPath) - 1, "/ipp/%s", printername); if ((response = cupsDoRequest(http, request, httpPath)) == NULL) { DEBUG(0,("Unable to get printer status for %s - %s\n", printername, ippErrorString(cupsLastError()))); *q = queue; goto out; } if (response->request.status.status_code >= IPP_OK_CONFLICT) { DEBUG(0,("Unable to get printer status for %s - %s\n", printername, ippErrorString(response->request.status.status_code))); *q = queue; goto out; } /* * Get the current printer status and convert it to the SAMBA values. */ if ((attr = ippFindAttribute(response, "printer-state", IPP_TAG_ENUM)) != NULL) { if (attr->values[0].integer == IPP_PRINTER_STOPPED) status->status = LPSTAT_STOPPED; else status->status = LPSTAT_OK; } if ((attr = ippFindAttribute(response, "printer-state-message", IPP_TAG_TEXT)) != NULL) fstrcpy(status->message, attr->values[0].string.text); if ((attr = ippFindAttribute(response, "printer-current-time", IPP_TAG_DATE)) != NULL) printer_current_time = ippDateToTime(attr->values[0].date); if ((attr = ippFindAttribute(response, "printer-up-time", IPP_TAG_INTEGER)) != NULL) printer_up_time = attr->values[0].integer; ippDelete(response); response = NULL; /* * Build an IPP_GET_JOBS request, which requires the following * attributes: * * attributes-charset * attributes-natural-language * requested-attributes * printer-uri */ request = ippNew(); request->request.op.operation_id = IPP_GET_JOBS; request->request.op.request_id = 3; ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, "utf-8"); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, language->language); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", (sizeof(jattrs) / sizeof(jattrs[0])), NULL, jattrs); /* * Do the request and get back a response... */ slprintf(httpPath, sizeof(httpPath) - 1, "/ipp/%s", printername); if ((response = cupsDoRequest(http, request, httpPath)) == NULL) { DEBUG(0,("Unable to get jobs for %s - %s\n", uri, ippErrorString(cupsLastError()))); goto out; } if (response->request.status.status_code >= IPP_OK_CONFLICT) { DEBUG(0,("Unable to get jobs for %s - %s\n", uri, ippErrorString(response->request.status.status_code))); goto out; } /* * Process the jobs... */ qcount = 0; qalloc = 0; queue = NULL; for (attr = response->attrs; attr != NULL; attr = attr->next) { /* * Skip leading attributes until we hit a job... */ while (attr != NULL && attr->group_tag != IPP_TAG_JOB) attr = attr->next; if (attr == NULL) break; /* * Allocate memory as needed... */ if (qcount >= qalloc) { qalloc += 16; queue = SMB_REALLOC_ARRAY(queue, print_queue_struct, qalloc); if (queue == NULL) { DEBUG(0,("iprint_queue_get: Not enough memory!")); qcount = 0; goto out; } } temp = queue + qcount; memset(temp, 0, sizeof(print_queue_struct)); /* * Pull the needed attributes from this job... */ job_id = 0; job_priority = 50; job_status = IPP_JOB_PENDING; job_time = 0; job_k_octets = 0; user_name = NULL; job_name = NULL; while (attr != NULL && attr->group_tag == IPP_TAG_JOB) { if (attr->name == NULL) { attr = attr->next; break; } if (strcmp(attr->name, "job-id") == 0 && attr->value_tag == IPP_TAG_INTEGER) job_id = attr->values[0].integer; if (strcmp(attr->name, "job-k-octets") == 0 && attr->value_tag == IPP_TAG_INTEGER) job_k_octets = attr->values[0].integer; if (strcmp(attr->name, "job-priority") == 0 && attr->value_tag == IPP_TAG_INTEGER) job_priority = attr->values[0].integer; if (strcmp(attr->name, "job-state") == 0 && attr->value_tag == IPP_TAG_ENUM) job_status = (ipp_jstate_t)(attr->values[0].integer); if (strcmp(attr->name, "time-at-creation") == 0 && attr->value_tag == IPP_TAG_INTEGER) { /* * If jobs times are in Unix time, the accuracy of the job * start time depends upon the iPrint server's time being * set correctly. Otherwise, the accuracy depends upon * the Samba server's time being set correctly */ if (jobUseUnixTime) job_time = attr->values[0].integer; else job_time = time(NULL) - printer_up_time + attr->values[0].integer; } if (strcmp(attr->name, "job-name") == 0 && (attr->value_tag == IPP_TAG_NAMELANG || attr->value_tag == IPP_TAG_NAME)) job_name = attr->values[0].string.text; if (strcmp(attr->name, "job-originating-user-name") == 0 && (attr->value_tag == IPP_TAG_NAMELANG || attr->value_tag == IPP_TAG_NAME)) user_name = attr->values[0].string.text; attr = attr->next; } /* * See if we have everything needed... */ if (user_name == NULL || job_name == NULL || job_id == 0) { if (attr == NULL) break; else continue; } temp->job = job_id; temp->size = job_k_octets * 1024; temp->status = job_status == IPP_JOB_PENDING ? LPQ_QUEUED : job_status == IPP_JOB_STOPPED ? LPQ_PAUSED : job_status == IPP_JOB_HELD ? LPQ_PAUSED : LPQ_PRINTING; temp->priority = job_priority; temp->time = job_time; strncpy(temp->fs_user, user_name, sizeof(temp->fs_user) - 1); strncpy(temp->fs_file, job_name, sizeof(temp->fs_file) - 1); qcount ++; if (attr == NULL) break; } /* * Return the job queue... */ *q = queue; out: if (response) ippDelete(response); if (language) cupsLangFree(language); if (http) httpClose(http); return qcount; }
/***************************************************************************** * do the actual mangling to 8.3 format * the buffer must be able to hold 13 characters (including the null) ***************************************************************************** */ static void to_8_3(char *s, int default_case) { int csum; char *p; char extension[4]; char base[9]; int baselen = 0; int extlen = 0; extension[0] = 0; base[0] = 0; p = strrchr(s,'.'); if( p && (strlen(p+1) < (size_t)4) ) { BOOL all_normal = ( strisnormal(p+1, default_case) ); /* XXXXXXXXX */ if( all_normal && p[1] != 0 ) { *p = 0; csum = str_checksum( s ); *p = '.'; } else csum = str_checksum(s); } else csum = str_checksum(s); strupper_m( s ); if( p ) { if( p == s ) safe_strcpy( extension, "___", 3 ); else { *p++ = 0; while( *p && extlen < 3 ) { if ( *p != '.') { extension[extlen++] = p[0]; } p++; } extension[extlen] = 0; } } p = s; while( *p && baselen < 5 ) { if (isbasechar(*p)) { base[baselen++] = p[0]; } p++; } base[baselen] = 0; csum = csum % (MANGLE_BASE*MANGLE_BASE); (void)slprintf(s, 12, "%s%c%c%c", base, magic_char, mangle( csum/MANGLE_BASE ), mangle( csum ) ); if( *extension ) { (void)pstrcat( s, "." ); (void)pstrcat( s, extension ); } }
/********************************************************************** * Query user security object */ static NTSTATUS cmd_samr_query_sec_obj(struct cli_state *cli, TALLOC_CTX *mem_ctx, int argc, char **argv) { POLICY_HND connect_pol, domain_pol, user_pol, *pol; NTSTATUS result = NT_STATUS_UNSUCCESSFUL; uint32 info_level = 4; fstring server; uint32 user_rid = 0; TALLOC_CTX *ctx = NULL; SEC_DESC_BUF *sec_desc_buf=NULL; BOOL domain = False; ctx=talloc_init(); if (argc > 2) { printf("Usage: %s [rid|-d]\n", argv[0]); printf("\tSpecify rid for security on user, -d for security on domain\n"); return NT_STATUS_OK; } if (argc == 2) { if (strcmp(argv[1], "-d") == 0) domain = True; else sscanf(argv[1], "%i", &user_rid); } slprintf (server, sizeof(fstring)-1, "\\\\%s", cli->desthost); strupper (server); result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, &connect_pol); if (!NT_STATUS_IS_OK(result)) goto done; if (domain || user_rid) result = cli_samr_open_domain(cli, mem_ctx, &connect_pol, MAXIMUM_ALLOWED_ACCESS, &domain_sid, &domain_pol); if (!NT_STATUS_IS_OK(result)) goto done; if (user_rid) result = cli_samr_open_user(cli, mem_ctx, &domain_pol, MAXIMUM_ALLOWED_ACCESS, user_rid, &user_pol); if (!NT_STATUS_IS_OK(result)) goto done; /* Pick which query pol to use */ pol = &connect_pol; if (domain) pol = &domain_pol; if (user_rid) pol = &user_pol; /* Query SAM security object */ result = cli_samr_query_sec_obj(cli, mem_ctx, pol, info_level, ctx, &sec_desc_buf); if (!NT_STATUS_IS_OK(result)) goto done; display_sec_desc(sec_desc_buf->sec); done: talloc_destroy(ctx); return result; }
static BOOL tdb_update_sam(struct pdb_methods *my_methods, SAM_ACCOUNT* newpwd, int flag) { struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data; TDB_CONTEXT *pwd_tdb = NULL; TDB_DATA key, data; uint8 *buf = NULL; fstring keystr; fstring name; BOOL ret = True; uint32 user_rid; /* invalidate the existing TDB iterator if it is open */ if (tdb_state->passwd_tdb) { tdb_close(tdb_state->passwd_tdb); tdb_state->passwd_tdb = NULL; } /* open the account TDB passwd*/ pwd_tdb = tdbsam_tdbopen(tdb_state->tdbsam_location, O_RDWR | O_CREAT); if (!pwd_tdb) { DEBUG(0, ("tdb_update_sam: Unable to open TDB passwd (%s)!\n", tdb_state->tdbsam_location)); return False; } if (!pdb_get_group_rid(newpwd)) { DEBUG (0,("tdb_update_sam: Failing to store a SAM_ACCOUNT for [%s] without a primary group RID\n", pdb_get_username(newpwd))); ret = False; goto done; } if ( !(user_rid = pdb_get_user_rid(newpwd)) ) { DEBUG(0,("tdb_update_sam: SAM_ACCOUNT (%s) with no RID!\n", pdb_get_username(newpwd))); ret = False; goto done; } /* copy the SAM_ACCOUNT struct into a BYTE buffer for storage */ if ((data.dsize=init_buffer_from_sam (&buf, newpwd, False)) == -1) { DEBUG(0,("tdb_update_sam: ERROR - Unable to copy SAM_ACCOUNT info BYTE buffer!\n")); ret = False; goto done; } data.dptr = (char *)buf; fstrcpy(name, pdb_get_username(newpwd)); strlower_m(name); DEBUG(5, ("Storing %saccount %s with RID %d\n", flag == TDB_INSERT ? "(new) " : "", name, user_rid)); /* setup the USER index key */ slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name); key.dptr = keystr; key.dsize = strlen(keystr) + 1; /* add the account */ if (tdb_store(pwd_tdb, key, data, flag) != TDB_SUCCESS) { DEBUG(0, ("Unable to modify passwd TDB!")); DEBUGADD(0, (" Error: %s", tdb_errorstr(pwd_tdb))); DEBUGADD(0, (" occured while storing the main record (%s)\n", keystr)); ret = False; goto done; } /* setup RID data */ data.dsize = strlen(name) + 1; data.dptr = name; /* setup the RID index key */ slprintf(keystr, sizeof(keystr)-1, "%s%.8x", RIDPREFIX, user_rid); key.dptr = keystr; key.dsize = strlen (keystr) + 1; /* add the reference */ if (tdb_store(pwd_tdb, key, data, flag) != TDB_SUCCESS) { DEBUG(0, ("Unable to modify TDB passwd !")); DEBUGADD(0, (" Error: %s\n", tdb_errorstr(pwd_tdb))); DEBUGADD(0, (" occured while storing the RID index (%s)\n", keystr)); ret = False; goto done; } done: /* cleanup */ tdb_close (pwd_tdb); SAFE_FREE(buf); return (ret); }
int psec_getsec(char *printer) { SEC_DESC_BUF *secdesc_ctr = NULL; TALLOC_CTX *mem_ctx = NULL; fstring keystr, sidstr, tdb_path; prs_struct ps; int result = 0, i; ZERO_STRUCT(ps); /* Open tdb for reading */ slprintf(tdb_path, sizeof(tdb_path) - 1, "%s/ntdrivers.tdb", lp_lockdir()); tdb = tdb_open(tdb_path, 0, 0, O_RDONLY, 0600); if (!tdb) { printf("psec: failed to open nt drivers database: %s\n", sys_errlist[errno]); return 1; } /* Get security blob from tdb */ slprintf(keystr, sizeof(keystr) - 1, "SECDESC/%s", printer); mem_ctx = talloc_init(); if (!mem_ctx) { printf("memory allocation error\n"); result = 1; goto done; } if (tdb_prs_fetch(tdb, keystr, &ps, mem_ctx) != 0) { printf("error fetching descriptor for printer %s\n", printer); /* cannot do a prs_mem_free() when tdb_prs_fetch fails */ /* as the prs structure has not been initialized */ tdb_close(tdb); talloc_destroy(mem_ctx); return 1; } /* Unpack into security descriptor buffer */ if (!sec_io_desc_buf("nt_printing_getsec", &secdesc_ctr, &ps, 1)) { printf("error unpacking sec_desc_buf\n"); result = 1; goto done; } /* Print owner and group sid */ if (secdesc_ctr->sec->owner_sid) { sid_to_string(sidstr, secdesc_ctr->sec->owner_sid); } else { fstrcpy(sidstr, ""); } printf("%s\n", sidstr); if (secdesc_ctr->sec->grp_sid) { sid_to_string(sidstr, secdesc_ctr->sec->grp_sid); } else { fstrcpy(sidstr, ""); } printf("%s\n", sidstr); /* Print aces */ if (!secdesc_ctr->sec->dacl) { result = 0; goto done; } for (i = 0; i < secdesc_ctr->sec->dacl->num_aces; i++) { SEC_ACE *ace = &secdesc_ctr->sec->dacl->ace[i]; sid_to_string(sidstr, &ace->sid); printf("%d %d 0x%08x %s\n", ace->type, ace->flags, ace->info.mask, sidstr); } done: if (tdb) tdb_close(tdb); if (mem_ctx) talloc_destroy(mem_ctx); if (secdesc_ctr) free_sec_desc_buf(&secdesc_ctr); prs_mem_free(&ps); return result; }
static void enter_mode_read_pcap(struct mode *mode) { int ret, fd, fdo = 0; struct pcap_pkthdr phdr; struct sock_fprog bpf_ops; struct tx_stats stats; struct frame_map fm; uint8_t *out; size_t out_len; unsigned long trunced = 0; struct timeval start, end, diff; if (!pcap_ops[mode->pcap]) panic("pcap group not supported!\n"); fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME); ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type); if (ret) panic("error reading pcap header!\n"); if (pcap_ops[mode->pcap]->prepare_reading_pcap) { ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd); if (ret) panic("error prepare reading pcap!\n"); } fmemset(&fm, 0, sizeof(fm)); fmemset(&bpf_ops, 0, sizeof(bpf_ops)); fmemset(&stats, 0, sizeof(stats)); bpf_parse_rules(mode->filter, &bpf_ops); dissector_init_all(mode->print_mode); out_len = 64 * 1024; out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE); printf("BPF:\n"); bpf_dump_all(&bpf_ops); printf("MD: RD %s ", pcap_ops[mode->pcap]->name); #ifdef _LARGEFILE64_SOURCE printf("lf64 "); #endif ioprio_print(); printf("\n"); if (mode->device_out) { fdo = open_or_die_m(mode->device_out, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE, DEFFILEMODE); } gettimeofday(&start, NULL); while (likely(sigint == 0)) { do { memset(&phdr, 0, sizeof(phdr)); ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr, out, out_len); if (unlikely(ret < 0)) goto out; if (unlikely(phdr.len == 0)) { trunced++; continue; } if (unlikely(phdr.len > out_len)) { phdr.len = out_len; trunced++; } } while (mode->filter && !bpf_run_filter(&bpf_ops, out, phdr.len)); pcap_pkthdr_to_tpacket_hdr(&phdr, &fm.tp_h); stats.tx_bytes += fm.tp_h.tp_len; stats.tx_packets++; show_frame_hdr(&fm, mode->print_mode, RING_MODE_EGRESS); dissector_entry_point(out, fm.tp_h.tp_snaplen, mode->link_type, mode->print_mode); if (mode->device_out) { int i = 0; char bout[80]; slprintf(bout, sizeof(bout), "{\n "); write_or_die(fdo, bout, strlen(bout)); while (i < fm.tp_h.tp_snaplen) { slprintf(bout, sizeof(bout), "0x%02x, ", out[i]); write_or_die(fdo, bout, strlen(bout)); i++; if (i % 10 == 0) { slprintf(bout, sizeof(bout), "\n", out[i]); write_or_die(fdo, bout, strlen(bout)); if (i < fm.tp_h.tp_snaplen) { slprintf(bout, sizeof(bout), " ", out[i]); write_or_die(fdo, bout, strlen(bout)); } } } if (i % 10 != 0) { slprintf(bout, sizeof(bout), "\n"); write_or_die(fdo, bout, strlen(bout)); } slprintf(bout, sizeof(bout), "}\n\n"); write_or_die(fdo, bout, strlen(bout)); } if (frame_cnt_max != 0 && stats.tx_packets >= frame_cnt_max) { sigint = 1; break; } } out: gettimeofday(&end, NULL); diff = tv_subtract(end, start); fflush(stdout); printf("\n"); printf("\r%12lu frames outgoing\n", stats.tx_packets); printf("\r%12lu frames truncated (larger than mtu)\n", trunced); printf("\r%12lu bytes outgoing\n", stats.tx_bytes); printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec); xfree(out); bpf_release(&bpf_ops); dissector_cleanup_all(); if (pcap_ops[mode->pcap]->prepare_close_pcap) pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ); close(fd); if (mode->device_out) close(fdo); }
static NTSTATUS tdbsam_getsampwnam (struct pdb_methods *my_methods, SAM_ACCOUNT *user, const char *sname) { NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data; TDB_CONTEXT *pwd_tdb; TDB_DATA data, key; fstring keystr; fstring name; if ( !user ) { DEBUG(0,("pdb_getsampwnam: SAM_ACCOUNT is NULL.\n")); return nt_status; } /* Data is stored in all lower-case */ fstrcpy(name, sname); strlower_m(name); /* set search key */ slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name); key.dptr = keystr; key.dsize = strlen(keystr) + 1; /* open the accounts TDB */ if (!(pwd_tdb = tdbsam_tdbopen(tdb_state->tdbsam_location, O_RDONLY))) { if (errno == ENOENT) { /* * TDB file doesn't exist, so try to create new one. This is useful to avoid * confusing error msg when adding user account first time */ if (!(pwd_tdb = tdbsam_tdbopen(tdb_state->tdbsam_location, O_CREAT ))) { DEBUG(0, ("pdb_getsampwnam: TDB passwd (%s) did not exist. File successfully created.\n", tdb_state->tdbsam_location)); } else { DEBUG(0, ("pdb_getsampwnam: TDB passwd (%s) does not exist. Couldn't create new one. Error was: %s\n", tdb_state->tdbsam_location, strerror(errno))); } /* requested user isn't there anyway */ nt_status = NT_STATUS_NO_SUCH_USER; return nt_status; } DEBUG(0, ("pdb_getsampwnam: Unable to open TDB passwd (%s)!\n", tdb_state->tdbsam_location)); return nt_status; } /* get the record */ data = tdb_fetch(pwd_tdb, key); if (!data.dptr) { DEBUG(5,("pdb_getsampwnam (TDB): error fetching database.\n")); DEBUGADD(5, (" Error: %s\n", tdb_errorstr(pwd_tdb))); DEBUGADD(5, (" Key: %s\n", keystr)); tdb_close(pwd_tdb); return nt_status; } /* unpack the buffer */ if (!init_sam_from_buffer(user, (unsigned char *)data.dptr, data.dsize)) { DEBUG(0,("pdb_getsampwent: Bad SAM_ACCOUNT entry returned from TDB!\n")); SAFE_FREE(data.dptr); tdb_close(pwd_tdb); return nt_status; } SAFE_FREE(data.dptr); /* no further use for database, close it now */ tdb_close(pwd_tdb); return NT_STATUS_OK; }
int psec_setsec(char *printer) { DOM_SID user_sid, group_sid; SEC_ACE *ace_list = NULL; SEC_ACL *dacl = NULL; SEC_DESC *sd; SEC_DESC_BUF *sdb = NULL; int result = 0, num_aces = 0; fstring line, keystr, tdb_path; size_t size; prs_struct ps; TALLOC_CTX *mem_ctx = NULL; BOOL has_user_sid = False, has_group_sid = False; ZERO_STRUCT(ps); /* Open tdb for reading */ slprintf(tdb_path, sizeof(tdb_path) - 1, "%s/ntdrivers.tdb", lp_lockdir()); tdb = tdb_open(tdb_path, 0, 0, O_RDWR, 0600); if (!tdb) { printf("psec: failed to open nt drivers database: %s\n", sys_errlist[errno]); result = 1; goto done; } /* Read owner and group sid */ fgets(line, sizeof(fstring), stdin); if (line[0] != '\n') { string_to_sid(&user_sid, line); has_user_sid = True; } fgets(line, sizeof(fstring), stdin); if (line[0] != '\n') { string_to_sid(&group_sid, line); has_group_sid = True; } /* Read ACEs from standard input for discretionary ACL */ while(fgets(line, sizeof(fstring), stdin)) { int ace_type, ace_flags; uint32 ace_mask; fstring sidstr; DOM_SID sid; SEC_ACCESS sa; if (sscanf(line, "%d %d 0x%x %s", &ace_type, &ace_flags, &ace_mask, sidstr) != 4) { continue; } string_to_sid(&sid, sidstr); ace_list = Realloc(ace_list, sizeof(SEC_ACE) * (num_aces + 1)); init_sec_access(&sa, ace_mask); init_sec_ace(&ace_list[num_aces], &sid, ace_type, sa, ace_flags); num_aces++; } dacl = make_sec_acl(ACL_REVISION, num_aces, ace_list); free(ace_list); /* Create security descriptor */ sd = make_sec_desc(SEC_DESC_REVISION, has_user_sid ? &user_sid : NULL, has_group_sid ? &group_sid : NULL, NULL, /* System ACL */ dacl, /* Discretionary ACL */ &size); free_sec_acl(&dacl); sdb = make_sec_desc_buf(size, sd); free_sec_desc(&sd); /* Write security descriptor to tdb */ mem_ctx = talloc_init(); if (!mem_ctx) { printf("memory allocation error\n"); result = 1; goto done; } prs_init(&ps, (uint32)sec_desc_size(sdb->sec) + sizeof(SEC_DESC_BUF), 4, mem_ctx, MARSHALL); if (!sec_io_desc_buf("nt_printing_setsec", &sdb, &ps, 1)) { printf("sec_io_desc_buf failed\n"); goto done; } slprintf(keystr, sizeof(keystr) - 1, "SECDESC/%s", printer); if (!tdb_prs_store(tdb, keystr, &ps)==0) { printf("Failed to store secdesc for %s\n", printer); goto done; } done: if (tdb) tdb_close(tdb); if (sdb) free_sec_desc_buf(&sdb); if (mem_ctx) talloc_destroy(mem_ctx); prs_mem_free(&ps); return result; }
/* * Make a new bundle or join us to an existing bundle * if we are doing multilink. */ int mp_join_bundle() { lcp_options *go = &lcp_gotoptions[0]; lcp_options *ho = &lcp_hisoptions[0]; lcp_options *ao = &lcp_allowoptions[0]; int unit, pppd_pid; int l, mtu; char *p; TDB_DATA key, pid, rec; if (doing_multilink) { /* have previously joined a bundle */ if (!go->neg_mrru || !ho->neg_mrru) { notice("oops, didn't get multilink on renegotiation"); lcp_close(0, "multilink required"); return 0; } /* XXX should check the peer_authname and ho->endpoint are the same as previously */ return 0; } if (!go->neg_mrru || !ho->neg_mrru) { /* not doing multilink */ if (go->neg_mrru) notice("oops, multilink negotiated only for receive"); mtu = ho->neg_mru? ho->mru: PPP_MRU; if (mtu > ao->mru) mtu = ao->mru; if (demand) { /* already have a bundle */ cfg_bundle(0, 0, 0, 0); netif_set_mtu(0, mtu); return 0; } make_new_bundle(0, 0, 0, 0); set_ifunit(1); netif_set_mtu(0, mtu); return 0; } doing_multilink = 1; /* * Find the appropriate bundle or join a new one. * First we make up a name for the bundle. * The length estimate is worst-case assuming every * character has to be quoted. */ l = 4 * strlen(peer_authname) + 10; if (ho->neg_endpoint) l += 3 * ho->endpoint.length + 8; if (bundle_name) l += 3 * strlen(bundle_name) + 2; bundle_id = malloc(l); if (bundle_id == 0) novm("bundle identifier"); p = bundle_id; p += slprintf(p, l-1, "BUNDLE=\"%q\"", peer_authname); if (ho->neg_endpoint || bundle_name) *p++ = '/'; if (ho->neg_endpoint) p += slprintf(p, bundle_id+l-p, "%s", epdisc_to_str(&ho->endpoint)); if (bundle_name) p += slprintf(p, bundle_id+l-p, "/%v", bundle_name); /* Make the key for the list of links belonging to the bundle */ l = p - bundle_id; blinks_id = malloc(l + 7); if (blinks_id == NULL) novm("bundle links key"); slprintf(blinks_id, l + 7, "BUNDLE_LINKS=%s", bundle_id + 7); /* * For demand mode, we only need to configure the bundle * and attach the link. */ mtu = MIN(ho->mrru, ao->mru); if (demand) { cfg_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf); netif_set_mtu(0, mtu); script_setenv("BUNDLE", bundle_id + 7, 1); return 0; } /* * Check if the bundle ID is already in the database. */ unit = -1; lock_db(); key.dptr = bundle_id; key.dsize = p - bundle_id; pid = tdb_fetch(pppdb, key); if (pid.dptr != NULL) { /* bundle ID exists, see if the pppd record exists */ rec = tdb_fetch(pppdb, pid); if (rec.dptr != NULL && rec.dsize > 0) { /* make sure the string is null-terminated */ rec.dptr[rec.dsize-1] = 0; /* parse the interface number */ parse_num(rec.dptr, "IFNAME=ppp", &unit); /* check the pid value */ if (!parse_num(rec.dptr, "PPPD_PID=", &pppd_pid) || !process_exists(pppd_pid) || !owns_unit(pid, unit)) unit = -1; free(rec.dptr); } free(pid.dptr); } if (unit >= 0) { /* attach to existing unit */ if (bundle_attach(unit)) { set_ifunit(0); script_setenv("BUNDLE", bundle_id + 7, 0); make_bundle_links(1); unlock_db(); info("Link attached to %s", ifname); return 1; } /* attach failed because bundle doesn't exist */ } /* we have to make a new bundle */ make_new_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf); set_ifunit(1); netif_set_mtu(0, mtu); script_setenv("BUNDLE", bundle_id + 7, 1); make_bundle_links(0); unlock_db(); info("New bundle %s created", ifname); multilink_master = 1; return 0; }
BOOL disk_quotas(const char *path, SMB_BIG_UINT *bsize, SMB_BIG_UINT *dfree, SMB_BIG_UINT *dsize) { uid_t euser_id; int ret; struct dqblk D; #if defined(SUNOS5) struct quotctl command; int file; static struct mnttab mnt; static pstring name; pstring devopt; #else /* SunOS4 */ struct mntent *mnt; static pstring name; #endif FILE *fd; SMB_STRUCT_STAT sbuf; SMB_DEV_T devno ; static SMB_DEV_T devno_cached = 0 ; static int found ; euser_id = geteuid(); if ( sys_stat(path,&sbuf) == -1 ) return(False) ; devno = sbuf.st_dev ; DEBUG(5,("disk_quotas: looking for path \"%s\" devno=%x\n", path,(unsigned int)devno)); if ( devno != devno_cached ) { devno_cached = devno ; #if defined(SUNOS5) if ((fd = sys_fopen(MNTTAB, "r")) == NULL) return(False) ; found = False ; slprintf(devopt, sizeof(devopt) - 1, "dev=%x", (unsigned int)devno); while (getmntent(fd, &mnt) == 0) { if( !hasmntopt(&mnt, devopt) ) continue; DEBUG(5,("disk_quotas: testing \"%s\" %s\n", mnt.mnt_mountp,devopt)); /* quotas are only on vxfs, UFS or NFS */ if ( strcmp( mnt.mnt_fstype, MNTTYPE_UFS ) == 0 || strcmp( mnt.mnt_fstype, "nfs" ) == 0 || strcmp( mnt.mnt_fstype, "vxfs" ) == 0 ) { found = True ; break; } } pstrcpy(name,mnt.mnt_mountp) ; pstrcat(name,"/quotas") ; fclose(fd) ; #else /* SunOS4 */ if ((fd = setmntent(MOUNTED, "r")) == NULL) return(False) ; found = False ; while ((mnt = getmntent(fd)) != NULL) { if ( sys_stat(mnt->mnt_dir,&sbuf) == -1 ) continue ; DEBUG(5,("disk_quotas: testing \"%s\" devno=%x\n", mnt->mnt_dir,(unsigned int)sbuf.st_dev)); if (sbuf.st_dev == devno) { found = True ; break; } } pstrcpy(name,mnt->mnt_fsname) ; endmntent(fd) ; #endif } if ( ! found ) return(False) ; save_re_uid(); set_effective_uid(0); #if defined(SUNOS5) if ( strcmp( mnt.mnt_fstype, "nfs" ) == 0) { BOOL retval; DEBUG(5,("disk_quotas: looking for mountpath (NFS) \"%s\"\n", mnt.mnt_special)); retval = nfs_quotas(mnt.mnt_special, euser_id, bsize, dfree, dsize); restore_re_uid(); return retval; } DEBUG(5,("disk_quotas: looking for quotas file \"%s\"\n", name)); if((file=sys_open(name, O_RDONLY,0))<0) { restore_re_uid(); return(False); } command.op = Q_GETQUOTA; command.uid = euser_id; command.addr = (caddr_t) &D; ret = ioctl(file, Q_QUOTACTL, &command); close(file); #else DEBUG(5,("disk_quotas: trying quotactl on device \"%s\"\n", name)); ret = quotactl(Q_GETQUOTA, name, euser_id, &D); #endif restore_re_uid(); if (ret < 0) { DEBUG(5,("disk_quotas ioctl (Solaris) failed. Error = %s\n", strerror(errno) )); #if defined(SUNOS5) && defined(VXFS_QUOTA) /* If normal quotactl() fails, try vxfs private calls */ set_effective_uid(euser_id); DEBUG(5,("disk_quotas: mount type \"%s\"\n", mnt.mnt_fstype)); if ( 0 == strcmp ( mnt.mnt_fstype, "vxfs" )) { BOOL retval; retval = disk_quotas_vxfs(name, path, bsize, dfree, dsize); return(retval); } #else return(False); #endif } /* If softlimit is zero, set it equal to hardlimit. */ if (D.dqb_bsoftlimit==0) D.dqb_bsoftlimit = D.dqb_bhardlimit; /* Use softlimit to determine disk space. A user exceeding the quota is told * that there's no space left. Writes might actually work for a bit if the * hardlimit is set higher than softlimit. Effectively the disk becomes * made of rubber latex and begins to expand to accommodate the user :-) */ if (D.dqb_bsoftlimit==0) return(False); *bsize = DEV_BSIZE; *dsize = D.dqb_bsoftlimit; if (D.dqb_curblocks > D.dqb_bsoftlimit) { *dfree = 0; *dsize = D.dqb_curblocks; } else *dfree = D.dqb_bsoftlimit - D.dqb_curblocks; DEBUG(5,("disk_quotas for path \"%s\" returning bsize %.0f, dfree %.0f, dsize %.0f\n", path,(double)*bsize,(double)*dfree,(double)*dsize)); return(True); }
/* create a pid file in the pid directory. open it and leave it locked */ void pidfile_create(const char *program_name) { int fd; char buf[20]; const char *short_configfile; char *name; pid_t pid; /* Add a suffix to the program name if this is a process with a * none default configuration file name. */ if (strcmp( CONFIGFILE, get_dyn_CONFIGFILE()) == 0) { name = SMB_STRDUP(program_name); } else { short_configfile = strrchr( get_dyn_CONFIGFILE(), '/'); if (short_configfile == NULL) { /* conf file in current directory */ short_configfile = get_dyn_CONFIGFILE(); } else { /* full/relative path provided */ short_configfile++; } if (asprintf(&name, "%s-%s", program_name, short_configfile) == -1) { smb_panic("asprintf failed"); } } if (asprintf(&pidFile_name, "%s/%s.pid", lp_piddir(), name) == -1) { smb_panic("asprintf failed"); } pid = pidfile_pid(name); if (pid != 0) { DEBUG(0,("ERROR: %s is already running. File %s exists and process id %d is running.\n", name, pidFile_name, (int)pid)); exit(1); } fd = sys_open(pidFile_name, O_NONBLOCK | O_CREAT | O_WRONLY | O_EXCL, 0644); if (fd == -1) { DEBUG(0,("ERROR: can't open %s: Error was %s\n", pidFile_name, strerror(errno))); exit(1); } if (fcntl_lock(fd,SMB_F_SETLK,0,1,F_WRLCK)==False) { DEBUG(0,("ERROR: %s : fcntl lock of file %s failed. Error was %s\n", name, pidFile_name, strerror(errno))); exit(1); } memset(buf, 0, sizeof(buf)); slprintf(buf, sizeof(buf) - 1, "%u\n", (unsigned int) sys_getpid()); if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf)) { DEBUG(0,("ERROR: can't write to file %s: %s\n", pidFile_name, strerror(errno))); exit(1); } /* Leave pid file open & locked for the duration... */ SAFE_FREE(name); }
int psec_setsec(char *printer) { struct dom_sid user_sid, group_sid; SEC_ACE *ace_list = NULL; SEC_ACL *dacl = NULL; SEC_DESC *sd; SEC_DESC_BUF *sdb = NULL; int result = 0, num_aces = 0; fstring line, keystr, tdb_path; size_t size; prs_struct ps; TALLOC_CTX *mem_ctx = NULL; BOOL has_user_sid = False, has_group_sid = False; ZERO_STRUCT(ps); /* Open tdb for reading */ slprintf(tdb_path, sizeof(tdb_path) - 1, "%s/ntdrivers.tdb", lp_lockdir()); tdb = tdb_open(tdb_path, 0, 0, O_RDWR, 0600); if (!tdb) { printf("psec: failed to open nt drivers database: %s\n", sys_errlist[errno]); result = 1; goto done; } /* Read owner and group sid */ fgets(line, sizeof(fstring), stdin); if (line[0] != '\n') { string_to_sid(&user_sid, line); has_user_sid = True; } fgets(line, sizeof(fstring), stdin); if (line[0] != '\n') { string_to_sid(&group_sid, line); has_group_sid = True; } /* Read ACEs from standard input for discretionary ACL */ while(fgets(line, sizeof(fstring), stdin)) { int ace_type, ace_flags; uint32 ace_mask; fstring sidstr; struct dom_sid sid; SEC_ACCESS sa; if (sscanf(line, "%d %d 0x%x %s", &ace_type, &ace_flags, &ace_mask, sidstr) != 4) { continue; } string_to_sid(&sid, sidstr); ace_list = Realloc(ace_list, sizeof(SEC_ACE) * (num_aces + 1)); init_sec_access(&sa, ace_mask); init_sec_ace(&ace_list[num_aces], &sid, ace_type, sa, ace_flags); num_aces++; } dacl = make_sec_acl(ACL_REVISION, num_aces, ace_list); free(ace_list); /* Create security descriptor */ sd = make_sec_desc(SEC_DESC_REVISION, has_user_sid ? &user_sid : NULL, has_group_sid ? &group_sid : NULL
static int process_root(int local_flags) { struct passwd *pwd; int result = 0; char *old_passwd = NULL; if (local_flags & LOCAL_SET_LDAP_ADMIN_PW) { char *ldap_admin_dn = lp_ldap_admin_dn(); if ( ! *ldap_admin_dn ) { DEBUG(0,("ERROR: 'ldap admin dn' not defined! Please check your smb.conf\n")); goto done; } printf("Setting stored password for \"%s\" in secrets.tdb\n", ldap_admin_dn); if ( ! *ldap_secret ) { new_passwd = prompt_for_new_password(stdin_passwd_get); fstrcpy(ldap_secret, new_passwd); } if (!store_ldap_admin_pw(ldap_secret)) { DEBUG(0,("ERROR: Failed to store the ldap admin password!\n")); } goto done; } /* Ensure passdb startup(). */ if(!initialize_password_db(False, NULL)) { DEBUG(0, ("Failed to open passdb!\n")); exit(1); } /* Ensure we have a SAM sid. */ get_global_sam_sid(); /* * Ensure both add/delete user are not set * Ensure add/delete user and either remote machine or join domain are * not both set. */ if(((local_flags & (LOCAL_ADD_USER|LOCAL_DELETE_USER)) == (LOCAL_ADD_USER|LOCAL_DELETE_USER)) || ((local_flags & (LOCAL_ADD_USER|LOCAL_DELETE_USER)) && (remote_machine != NULL))) { usage(); } /* Only load interfaces if we are doing network operations. */ if (remote_machine) { load_interfaces(); } if (!user_name[0] && (pwd = getpwuid_alloc(talloc_autofree_context(), geteuid()))) { fstrcpy(user_name, pwd->pw_name); TALLOC_FREE(pwd); } if (!user_name[0]) { fprintf(stderr,"You must specify a username\n"); exit(1); } if (local_flags & LOCAL_TRUST_ACCOUNT) { /* add the $ automatically */ static fstring buf; /* * Remove any trailing '$' before we * generate the initial machine password. */ if (user_name[strlen(user_name)-1] == '$') { user_name[strlen(user_name)-1] = 0; } if (local_flags & LOCAL_ADD_USER) { SAFE_FREE(new_passwd); new_passwd = smb_xstrdup(user_name); strlower_m(new_passwd); } /* * Now ensure the username ends in '$' for * the machine add. */ slprintf(buf, sizeof(buf)-1, "%s$", user_name); fstrcpy(user_name, buf); } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) { static fstring buf; if ((local_flags & LOCAL_ADD_USER) && (new_passwd == NULL)) { /* * Prompt for trusting domain's account password */ new_passwd = prompt_for_new_password(stdin_passwd_get); if(!new_passwd) { fprintf(stderr, "Unable to get newpassword.\n"); exit(1); } } /* prepare uppercased and '$' terminated username */ slprintf(buf, sizeof(buf) - 1, "%s$", user_name); fstrcpy(user_name, buf); } else { if (remote_machine != NULL) { old_passwd = get_pass("Old SMB password:"******"Unable to get old password.\n"); exit(1); } } if (!(local_flags & LOCAL_SET_PASSWORD)) { /* * If we are trying to enable a user, first we need to find out * if they are using a modern version of the smbpasswd file that * disables a user by just writing a flag into the file. If so * then we can re-enable a user without prompting for a new * password. If not (ie. they have a no stored password in the * smbpasswd file) then we need to prompt for a new password. */ if(local_flags & LOCAL_ENABLE_USER) { struct samu *sampass = NULL; sampass = samu_new( NULL ); if (!sampass) { fprintf(stderr, "talloc fail for struct samu.\n"); exit(1); } if (!pdb_getsampwnam(sampass, user_name)) { fprintf(stderr, "Failed to find user %s in passdb backend.\n", user_name ); exit(1); } if(pdb_get_nt_passwd(sampass) == NULL) { local_flags |= LOCAL_SET_PASSWORD; } TALLOC_FREE(sampass); } } if((local_flags & LOCAL_SET_PASSWORD) && (new_passwd == NULL)) { new_passwd = prompt_for_new_password(stdin_passwd_get); if(!new_passwd) { fprintf(stderr, "Unable to get new password.\n"); exit(1); } } } if (!NT_STATUS_IS_OK(password_change(remote_machine, user_name, old_passwd, new_passwd, local_flags))) { result = 1; goto done; } if(remote_machine) { printf("Password changed for user %s on %s.\n", user_name, remote_machine ); } else if(!(local_flags & (LOCAL_ADD_USER|LOCAL_DISABLE_USER|LOCAL_ENABLE_USER|LOCAL_DELETE_USER|LOCAL_SET_NO_PASSWORD|LOCAL_SET_PASSWORD))) { struct samu *sampass = NULL; sampass = samu_new( NULL ); if (!sampass) { fprintf(stderr, "talloc fail for struct samu.\n"); exit(1); } if (!pdb_getsampwnam(sampass, user_name)) { fprintf(stderr, "Failed to find user %s in passdb backend.\n", user_name ); exit(1); } printf("Password changed for user %s.", user_name ); if(pdb_get_acct_ctrl(sampass)&ACB_DISABLED) { printf(" User has disabled flag set."); } if(pdb_get_acct_ctrl(sampass) & ACB_PWNOTREQ) { printf(" User has no password flag set."); } printf("\n"); TALLOC_FREE(sampass); } done: SAFE_FREE(old_passwd); SAFE_FREE(new_passwd); return result; }
/***************************************************** return a connection to a server *******************************************************/ static struct cli_state *connect_one(char *share, int snum) { struct cli_state *c; char *server_n; fstring server; fstring myname; static int count; NTSTATUS status; int flags = 0; fstrcpy(server,share+2); share = strchr_m(server,'\\'); if (!share) return NULL; *share = 0; share++; server_n = server; slprintf(myname,sizeof(myname), "lock-%lu-%u", (unsigned long)getpid(), count++); /* have to open a new connection */ if (use_kerberos) { flags |= CLI_FULL_CONNECTION_USE_KERBEROS; } if (use_oplocks) { flags |= CLI_FULL_CONNECTION_OPLOCKS; } status = cli_connect_nb(server_n, NULL, 0, 0x20, myname, SMB_SIGNING_DEFAULT, flags, &c); if (!NT_STATUS_IS_OK(status)) { DEBUG(0, ("Connection to %s failed. Error %s\n", server_n, nt_errstr(status))); return NULL; } status = cli_negprot(c, PROTOCOL_NT1); if (!NT_STATUS_IS_OK(status)) { DEBUG(0, ("protocol negotiation failed: %s\n", nt_errstr(status))); cli_shutdown(c); return NULL; } if (!got_pass) { char *pass = getpass("Password: "******"session setup failed: %s\n", nt_errstr(status))); return NULL; } /* * These next two lines are needed to emulate * old client behaviour for people who have * scripts based on client output. * QUESTION ? Do we want to have a 'client compatibility * mode to turn these on/off ? JRA. */ if (*c->server_domain || *c->server_os || *c->server_type) DEBUG(1,("Domain=[%s] OS=[%s] Server=[%s]\n", c->server_domain,c->server_os,c->server_type)); DEBUG(4,(" session setup ok\n")); status = cli_tcon_andx(c, share, "?????", password[snum], strlen(password[snum])+1); if (!NT_STATUS_IS_OK(status)) { DEBUG(0,("tree connect failed: %s\n", nt_errstr(status))); cli_shutdown(c); return NULL; } DEBUG(4,(" tconx ok\n")); return c; }
static NTSTATUS script_check_user_credentials(const struct auth_context *auth_context, void *my_private_data, TALLOC_CTX *mem_ctx, const auth_usersupplied_info *user_info, auth_serversupplied_info **server_info) { const char *script = lp_parm_const_string( GLOBAL_SECTION_SNUM, "auth_script", "script", NULL); char *secret_str; size_t secret_str_len; char hex_str[49]; int ret, i; if (!script) { return NT_STATUS_INVALID_PARAMETER; } if (!user_info) { return NT_STATUS_INVALID_PARAMETER; } if (!auth_context) { DEBUG(3,("script_check_user_credentials: no auth_info !\n")); return NT_STATUS_INVALID_PARAMETER; } secret_str_len = strlen(user_info->domain) + 1 + strlen(user_info->smb_name) + 1 + 16 + 1 + /* 8 bytes of challenge going to 16 */ 48 + 1 + /* 24 bytes of challenge going to 48 */ 48 + 1; secret_str = (char *)malloc(secret_str_len); if (!secret_str) { return NT_STATUS_NO_MEMORY; } safe_strcpy( secret_str, user_info->domain, secret_str_len - 1); safe_strcat( secret_str, "\n", secret_str_len - 1); safe_strcat( secret_str, user_info->smb_name, secret_str_len - 1); safe_strcat( secret_str, "\n", secret_str_len - 1); for (i = 0; i < 8; i++) { slprintf(&hex_str[i*2], 3, "%02X", auth_context->challenge.data[i]); } safe_strcat( secret_str, hex_str, secret_str_len - 1); safe_strcat( secret_str, "\n", secret_str_len - 1); if (user_info->lm_resp.data) { for (i = 0; i < 24; i++) { slprintf(&hex_str[i*2], 3, "%02X", user_info->lm_resp.data[i]); } safe_strcat( secret_str, hex_str, secret_str_len - 1); } safe_strcat( secret_str, "\n", secret_str_len - 1); if (user_info->nt_resp.data) { for (i = 0; i < 24; i++) { slprintf(&hex_str[i*2], 3, "%02X", user_info->nt_resp.data[i]); } safe_strcat( secret_str, hex_str, secret_str_len - 1); } safe_strcat( secret_str, "\n", secret_str_len - 1); DEBUG(10,("script_check_user_credentials: running %s with parameters:\n%s\n", script, secret_str )); ret = smbrunsecret( script, secret_str); SAFE_FREE(secret_str); if (ret) { DEBUG(1,("script_check_user_credentials: failed to authenticate %s\\%s\n", user_info->domain, user_info->smb_name )); /* auth failed. */ return NT_STATUS_NO_SUCH_USER; } /* Cause the auth system to keep going.... */ return NT_STATUS_NOT_IMPLEMENTED; }
/**************************************************************************** deliver the message ****************************************************************************/ static void msg_deliver(void) { pstring name; int i; int fd; char *msg; int len; if (! (*lp_msg_command())) { DEBUG(1,("no messaging command specified\n")); msgpos = 0; return; } /* put it in a temporary file */ slprintf(name,sizeof(name)-1, "%s/msg.XXXXXX",tmpdir()); fd = smb_mkstemp(name); if (fd == -1) { DEBUG(1,("can't open message file %s\n",name)); return; } /* * Incoming message is in DOS codepage format. Convert to UNIX. */ if ((len = convert_string_allocate(NULL,CH_DOS, CH_UNIX, msgbuf, msgpos, (void **) &msg)) < 0 || !msg) { DEBUG(3,("Conversion failed, delivering message in DOS codepage format\n")); for (i = 0; i < msgpos;) { if (msgbuf[i] == '\r' && i < (msgpos-1) && msgbuf[i+1] == '\n') { i++; continue; } write(fd, &msgbuf[i++], 1); } } else { for (i = 0; i < len;) { if (msg[i] == '\r' && i < (len-1) && msg[i+1] == '\n') { i++; continue; } write(fd, &msg[i++],1); } SAFE_FREE(msg); } close(fd); /* run the command */ if (*lp_msg_command()) { fstring alpha_msgfrom; fstring alpha_msgto; pstring s; pstrcpy(s,lp_msg_command()); pstring_sub(s,"%f",alpha_strcpy(alpha_msgfrom,msgfrom,NULL,sizeof(alpha_msgfrom))); pstring_sub(s,"%t",alpha_strcpy(alpha_msgto,msgto,NULL,sizeof(alpha_msgto))); standard_sub_basic(current_user_info.smb_name, s, sizeof(s)); pstring_sub(s,"%s",name); smbrun(s,NULL); } msgpos = 0; }
static NTSTATUS cmd_samr_query_useraliases(struct cli_state *cli, TALLOC_CTX *mem_ctx, int argc, char **argv) { POLICY_HND connect_pol, domain_pol; NTSTATUS result = NT_STATUS_UNSUCCESSFUL; uint32 user_rid, num_aliases, *alias_rids; int i; fstring server; DOM_SID tmp_sid; DOM_SID2 sid; DOM_SID global_sid_Builtin; string_to_sid(&global_sid_Builtin, "S-1-5-32"); if (argc != 3) { printf("Usage: %s builtin|domain rid\n", argv[0]); return NT_STATUS_OK; } sscanf(argv[2], "%i", &user_rid); slprintf (server, sizeof(fstring)-1, "\\\\%s", cli->desthost); strupper (server); result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, &connect_pol); if (!NT_STATUS_IS_OK(result)) { goto done; } if (StrCaseCmp(argv[1], "domain")==0) result = cli_samr_open_domain(cli, mem_ctx, &connect_pol, MAXIMUM_ALLOWED_ACCESS, &domain_sid, &domain_pol); else if (StrCaseCmp(argv[1], "builtin")==0) result = cli_samr_open_domain(cli, mem_ctx, &connect_pol, MAXIMUM_ALLOWED_ACCESS, &global_sid_Builtin, &domain_pol); else return NT_STATUS_OK; if (!NT_STATUS_IS_OK(result)) { goto done; } sid_copy(&tmp_sid, &domain_sid); sid_append_rid(&tmp_sid, user_rid); init_dom_sid2(&sid, &tmp_sid); result = cli_samr_query_useraliases(cli, mem_ctx, &domain_pol, 1, &sid, &num_aliases, &alias_rids); if (!NT_STATUS_IS_OK(result)) { goto done; } for (i = 0; i < num_aliases; i++) { printf("\tgroup rid:[0x%x]\n", alias_rids[i]); } done: return result; }
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; php_url *resource = NULL; int use_ssl; int use_proxy = 0; char *scratch = NULL; char *tmp = NULL; char *ua_str = NULL; zval **ua_zval = NULL, **tmpzval = NULL; int scratch_len = 0; int body = 0; char location[HTTP_HEADER_BLOCK_SIZE]; zval *response_header = NULL; int reqok = 0; char *http_header_line = NULL; char tmp_line[128]; size_t chunk_size = 0, file_size = 0; int eol_detect = 0; char *transport_string, *errstr = NULL; int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0; char *protocol_version = NULL; int protocol_version_len = 3; /* Default: "1.0" */ struct timeval timeout; char *user_headers = NULL; int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0); int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0); php_stream_filter *transfer_encoding = NULL; tmp_line[0] = '\0'; if (redirect_max < 1) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting"); return NULL; } resource = php_url_parse(path); if (resource == NULL) { return NULL; } if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) { if (!context || php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE || Z_TYPE_PP(tmpzval) != IS_STRING || Z_STRLEN_PP(tmpzval) <= 0) { php_url_free(resource); return php_stream_open_wrapper_ex(path, mode, ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context); } /* Called from a non-http wrapper with http proxying requested (i.e. ftp) */ request_fulluri = 1; use_ssl = 0; use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { /* Normal http request (possibly with proxy) */ if (strpbrk(mode, "awx+")) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections"); php_url_free(resource); return NULL; } use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's'; /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; else if (resource->port == 0) resource->port = 80; if (context && php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port); } } if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval); timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000); } else { timeout.tv_sec = FG(default_socket_timeout); timeout.tv_usec = 0; } stream = php_stream_xport_create(transport_string, transport_len, options, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, NULL, &timeout, context, &errstr, NULL); if (stream) { php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout); } if (errstr) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr); efree(errstr); errstr = NULL; } efree(transport_string); if (stream && use_proxy && use_ssl) { smart_str header = {0}; smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1); smart_str_appends(&header, resource->host); smart_str_appendc(&header, ':'); smart_str_append_unsigned(&header, resource->port); smart_str_appendl(&header, " HTTP/1.0\r\n\r\n", sizeof(" HTTP/1.0\r\n\r\n")-1); if (php_stream_write(stream, header.c, header.len) != header.len) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } smart_str_free(&header); if (stream) { char header_line[HTTP_HEADER_BLOCK_SIZE]; /* get response header */ while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) { if (header_line[0] == '\n' || header_line[0] == '\r' || header_line[0] == '\0') { break; } } } /* enable SSL transport layer */ if (stream) { if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } } } if (stream == NULL) goto out; /* avoid buffering issues while reading header */ if (options & STREAM_WILL_CAST) chunk_size = php_stream_set_chunk_size(stream, 1); /* avoid problems with auto-detecting when reading the headers -> the headers * are always in canonical \r\n format */ eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); php_stream_context_set(stream, context); php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0); if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); redirect_max = Z_LVAL_PP(tmpzval); } if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { /* As per the RFC, automatically redirected requests MUST NOT use other methods than * GET and HEAD unless it can be confirmed by the user */ if (!redirected || (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0) || (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0) ) { scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval); scratch = emalloc(scratch_len); strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1); strcat(scratch, " "); } } } if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval)); } if (!scratch) { scratch_len = strlen(path) + 29 + protocol_version_len; scratch = emalloc(scratch_len); strcpy(scratch, "GET "); } /* Should we send the entire path in the request line, default to no. */ if (!request_fulluri && context && php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) { zval tmp = **tmpzval; zval_copy_ctor(&tmp); convert_to_boolean(&tmp); request_fulluri = Z_BVAL(tmp) ? 1 : 0; zval_dtor(&tmp); } if (request_fulluri) { /* Ask for everything */ strcat(scratch, path); } else { /* Send the traditional /path/to/file?query_string */ /* file */ if (resource->path && *resource->path) { strlcat(scratch, resource->path, scratch_len); } else { strlcat(scratch, "/", scratch_len); } /* query string */ if (resource->query) { strlcat(scratch, "?", scratch_len); strlcat(scratch, resource->query, scratch_len); } } /* protocol version we are speaking */ if (protocol_version) { strlcat(scratch, " HTTP/", scratch_len); strlcat(scratch, protocol_version, scratch_len); strlcat(scratch, "\r\n", scratch_len); efree(protocol_version); protocol_version = NULL; } else { strlcat(scratch, " HTTP/1.0\r\n", scratch_len); } /* send it */ php_stream_write(stream, scratch, strlen(scratch)); if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { tmp = NULL; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; smart_str tmpstr = {0}; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos) ) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader)); smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1); } } smart_str_0(&tmpstr); /* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */ if (tmpstr.c) { tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC); smart_str_free(&tmpstr); } } if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { /* Remove newlines and spaces from start and end php_trim will estrndup() */ tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC); } if (tmp && strlen(tmp) > 0) { if (!header_init) { /* Remove post headers for redirects */ int l = strlen(tmp); char *s, *s2, *tmp_c = estrdup(tmp); php_strtolower(tmp_c, l); if ((s = strstr(tmp_c, "content-length:"))) { if ((s2 = memchr(s, '\n', tmp_c + l - s))) { int b = tmp_c + l - 1 - s2; memmove(tmp, tmp + (s2 + 1 - tmp_c), b); memmove(tmp_c, s2 + 1, b); } else { tmp[s - tmp_c] = *s = '\0'; } l = strlen(tmp_c); } if ((s = strstr(tmp_c, "content-type:"))) { if ((s2 = memchr(s, '\n', tmp_c + l - s))) { memmove(tmp, tmp + (s2 + 1 - tmp_c), tmp_c + l - 1 - s2); } else { tmp[s - tmp_c] = '\0'; } } efree(tmp_c); tmp_c = php_trim(tmp, strlen(tmp), NULL, 0, NULL, 3 TSRMLS_CC); efree(tmp); tmp = tmp_c; } user_headers = estrdup(tmp); /* Make lowercase for easy comparison against 'standard' headers */ php_strtolower(tmp, strlen(tmp)); if (strstr(tmp, "user-agent:")) { have_header |= HTTP_HEADER_USER_AGENT; } if (strstr(tmp, "host:")) { have_header |= HTTP_HEADER_HOST; } if (strstr(tmp, "from:")) { have_header |= HTTP_HEADER_FROM; } if (strstr(tmp, "authorization:")) { have_header |= HTTP_HEADER_AUTH; } if (strstr(tmp, "content-length:")) { have_header |= HTTP_HEADER_CONTENT_LENGTH; } if (strstr(tmp, "content-type:")) { have_header |= HTTP_HEADER_TYPE; } } if (tmp) { efree(tmp); } } /* auth header if it was specified */ if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) { /* decode the strings first */ php_url_decode(resource->user, strlen(resource->user)); /* scratch is large enough, since it was made large enough for the whole URL */ strcpy(scratch, resource->user); strcat(scratch, ":"); /* Note: password is optional! */ if (resource->pass) { php_url_decode(resource->pass, strlen(resource->pass)); strcat(scratch, resource->pass); } tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL); if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) { php_stream_write(stream, scratch, strlen(scratch)); php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0); } efree(tmp); tmp = NULL; } /* if the user has configured who they are, send a From: line */ if (((have_header & HTTP_HEADER_FROM) == 0) && cfg_get_string("from", &tmp) == SUCCESS) { if (snprintf(scratch, scratch_len, "From: %s\r\n", tmp) > 0) php_stream_write(stream, scratch, strlen(scratch)); } /* Send Host: header so name-based virtual hosts work */ if ((have_header & HTTP_HEADER_HOST) == 0) { if ((use_ssl && resource->port != 443 && resource->port != 0) || (!use_ssl && resource->port != 80 && resource->port != 0)) { if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) php_stream_write(stream, scratch, strlen(scratch)); } else { if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) { php_stream_write(stream, scratch, strlen(scratch)); } } } if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { ua_str = Z_STRVAL_PP(ua_zval); } else if (FG(user_agent)) { ua_str = FG(user_agent); } if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) { #define _UA_HEADER "User-Agent: %s\r\n" char *ua; size_t ua_len; ua_len = sizeof(_UA_HEADER) + strlen(ua_str); /* ensure the header is only sent if user_agent is not blank */ if (ua_len > sizeof(_UA_HEADER)) { ua = emalloc(ua_len + 1); if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) { ua[ua_len] = 0; php_stream_write(stream, ua, ua_len); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header"); } if (ua) { efree(ua); } } } if (user_headers) { /* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. */ if ( header_init && context && !(have_header & HTTP_HEADER_CONTENT_LENGTH) && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0 ) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); have_header |= HTTP_HEADER_CONTENT_LENGTH; } php_stream_write(stream, user_headers, strlen(user_headers)); php_stream_write(stream, "\r\n", sizeof("\r\n")-1); efree(user_headers); } /* Request content, such as for POST requests */ if (header_init && context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); } if (!(have_header & HTTP_HEADER_TYPE)) { php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n", sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded"); } php_stream_write(stream, "\r\n", sizeof("\r\n")-1); php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); php_stream_write(stream, "\r\n\r\n", sizeof("\r\n\r\n")-1); } else { php_stream_write(stream, "\r\n", sizeof("\r\n")-1); } location[0] = '\0'; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (header_init) { zval *tmp; MAKE_STD_ZVAL(tmp); array_init(tmp); ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", tmp); } { zval **rh; zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh); response_header = *rh; } if (!php_stream_eof(stream)) { size_t tmp_line_len; /* get response header */ if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) { zval *http_response; int response_code; if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) { ignore_errors = zend_is_true(*tmpzval); } /* when we request only the header, don't fail even on error codes */ if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) { reqok = 1; } /* all status codes in the 2xx range are defined by the specification as successful; * all status codes in the 3xx range are for redirection, and so also should never * fail */ if (response_code >= 200 && response_code < 400) { reqok = 1; } else { switch(response_code) { case 403: php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT, tmp_line, response_code); break; default: /* safety net in the event tmp_line == NULL */ if (!tmp_line_len) { tmp_line[0] = '\0'; } php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE, tmp_line, response_code); } } if (tmp_line[tmp_line_len - 1] == '\n') { --tmp_line_len; if (tmp_line[tmp_line_len - 1] == '\r') { --tmp_line_len; } } MAKE_STD_ZVAL(http_response); ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL); } } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!"); goto out; } /* read past HTTP headers */ http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE); while (!body && !php_stream_eof(stream)) { size_t http_header_line_length; if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') { char *e = http_header_line + http_header_line_length - 1; if (*e != '\n') { do { /* partial header */ php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length); e = http_header_line + http_header_line_length - 1; } while (*e != '\n'); continue; } while (*e == '\n' || *e == '\r') { e--; } http_header_line_length = e - http_header_line + 1; http_header_line[http_header_line_length] = '\0'; if (!strncasecmp(http_header_line, "Location: ", 10)) { strlcpy(location, http_header_line + 10, sizeof(location)); } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) { php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0); } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) { file_size = atoi(http_header_line + 16); php_stream_notify_file_size(context, file_size, http_header_line, 0); } else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) { /* create filter to decode response body */ if (!(options & STREAM_ONLY_GET_HEADERS)) { long decode = 1; if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_boolean(*tmpzval); decode = Z_LVAL_PP(tmpzval); } if (decode) { transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC); if (transfer_encoding) { /* don't store transfer-encodeing header */ continue; } } } } if (http_header_line[0] == '\0') { body = 1; } else { zval *http_header; MAKE_STD_ZVAL(http_header); ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL); } } else { break; } } if (!reqok || location[0] != '\0') { if (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1) { goto out; } if (location[0] != '\0') php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); if (context) { /* keep the context for the next try */ zend_list_addref(context->rsrc_id); } php_stream_close(stream); stream = NULL; if (location[0] != '\0') { char new_path[HTTP_HEADER_BLOCK_SIZE]; char loc_path[HTTP_HEADER_BLOCK_SIZE]; *new_path='\0'; if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && strncasecmp(location, "https://", sizeof("https://")-1) && strncasecmp(location, "ftp://", sizeof("ftp://")-1) && strncasecmp(location, "ftps://", sizeof("ftps://")-1))) { if (*location != '/') { if (*(location+1) != '\0' && resource->path) { char *s = strrchr(resource->path, '/'); if (!s) { s = resource->path; if (!s[0]) { efree(s); s = resource->path = estrdup("/"); } else { *s = '/'; } } s[1] = '\0'; if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') { snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location); } else { snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location); } } else { snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); } } else { strlcpy(loc_path, location, sizeof(loc_path)); } if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path); } else { snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path); } } else { strlcpy(new_path, location, sizeof(new_path)); } php_url_free(resource); /* check for invalid redirection URLs */ if ((resource = php_url_parse(new_path)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); goto out; } #define CHECK_FOR_CNTRL_CHARS(val) { \ if (val) { \ unsigned char *s, *e; \ int l; \ l = php_url_decode(val, strlen(val)); \ s = (unsigned char*)val; e = s + l; \ while (s < e) { \ if (iscntrl(*s)) { \ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \ goto out; \ } \ s++; \ } \ } \ } /* check for control characters in login, password & path */ if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) { CHECK_FOR_CNTRL_CHARS(resource->user) CHECK_FOR_CNTRL_CHARS(resource->pass) CHECK_FOR_CNTRL_CHARS(resource->path) } stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC); } else {
static int iprint_job_submit(int snum, struct printjob *pjob) { int ret = 1; /* Return value */ http_t *http = NULL; /* HTTP connection to server */ ipp_t *request = NULL, /* IPP Request */ *response = NULL; /* IPP Response */ ipp_attribute_t *attr; /* Current attribute */ cups_lang_t *language = NULL; /* Default language */ char uri[HTTP_MAX_URI]; /* printer-uri attribute */ char *clientname = NULL; /* hostname of client for job-originating-host attribute */ DEBUG(5,("iprint_job_submit(%d, %p (%d))\n", snum, pjob, pjob->sysjob)); /* * Make sure we don't ask for passwords... */ cupsSetPasswordCB(iprint_passwd_cb); /* * Try to connect to the server... */ if ((http = httpConnect(iprint_server(), ippPort())) == NULL) { DEBUG(0,("Unable to connect to iPrint server %s - %s\n", iprint_server(), strerror(errno))); goto out; } /* * Build an IPP_PRINT_JOB request, which requires the following * attributes: * * attributes-charset * attributes-natural-language * printer-uri * requesting-user-name * [document-data] */ request = ippNew(); request->request.op.operation_id = IPP_PRINT_JOB; request->request.op.request_id = 1; language = cupsLangDefault(); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, "utf-8"); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, language->language); slprintf(uri, sizeof(uri) - 1, "ipp://%s/ipp/%s", iprint_server(), PRINTERNAME(snum)); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, pjob->user); clientname = client_name(); if (strcmp(clientname, "UNKNOWN") == 0) { clientname = client_addr(); } ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-originating-host-name", NULL, clientname); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL, pjob->jobname); /* * Do the request and get back a response... */ slprintf(uri, sizeof(uri) - 1, "/ipp/%s", PRINTERNAME(snum)); if ((response = cupsDoFileRequest(http, request, uri, pjob->filename)) != NULL) { if (response->request.status.status_code >= IPP_OK_CONFLICT) { DEBUG(0,("Unable to print file to %s - %s\n", PRINTERNAME(snum), ippErrorString(cupsLastError()))); } else { ret = 0; } } else { DEBUG(0,("Unable to print file to `%s' - %s\n", PRINTERNAME(snum), ippErrorString(cupsLastError()))); } if ( ret == 0 ) unlink(pjob->filename); /* else print_job_end will do it for us */ if ( ret == 0 ) { attr = ippFindAttribute(response, "job-id", IPP_TAG_INTEGER); if (attr != NULL && attr->group_tag == IPP_TAG_JOB) { pjob->sysjob = attr->values[0].integer; } } out: if (response) ippDelete(response); if (language) cupsLangFree(language); if (http) httpClose(http); return ret; }
void standard_sub_basic(const char *smb_name, char *str,size_t len) { char *p, *s; fstring pidstr; struct passwd *pass; const char *local_machine_name = get_local_machine_name(); for (s=str; (p=strchr_m(s, '%'));s=p) { fstring tmp_str; int l = (int)len - (int)(p-str); if (l < 0) l = 0; switch (*(p+1)) { case 'U' : fstrcpy(tmp_str, smb_name); strlower_m(tmp_str); string_sub(p,"%U",tmp_str,l); break; case 'G' : fstrcpy(tmp_str, smb_name); if ((pass = Get_Pwnam(tmp_str))!=NULL) { string_sub(p,"%G",gidtoname(pass->pw_gid),l); } else { p += 2; } break; case 'D' : fstrcpy(tmp_str, current_user_info.domain); strupper_m(tmp_str); string_sub(p,"%D", tmp_str,l); break; case 'I' : string_sub(p,"%I", client_addr(),l); break; case 'i' : string_sub(p,"%i", client_socket_addr(),l); break; case 'L' : if (local_machine_name && *local_machine_name) string_sub(p,"%L", local_machine_name,l); else { pstring temp_name; pstrcpy(temp_name, global_myname()); strlower_m(temp_name); string_sub(p,"%L", temp_name,l); } break; case 'M' : string_sub(p,"%M", client_name(),l); break; case 'R' : string_sub(p,"%R", remote_proto,l); break; case 'T' : string_sub(p,"%T", timestring(False),l); break; case 'a' : string_sub(p,"%a", remote_arch,l); break; case 'd' : slprintf(pidstr,sizeof(pidstr)-1, "%d",(int)sys_getpid()); string_sub(p,"%d", pidstr,l); break; case 'h' : string_sub(p,"%h", myhostname(),l); break; case 'm' : string_sub(p,"%m", get_remote_machine_name(),l); break; case 'v' : string_sub(p,"%v", SAMBA_VERSION_STRING,l); break; case '$' : p += expand_env_var(p,l); break; /* Expand environment variables */ case '\0': p++; break; /* don't run off the end of the string */ default: p+=2; break; } } }
static int chapms2_verify_response(int id, char *name, unsigned char *secret, int secret_len, unsigned char *challenge, unsigned char *response, char *message, int message_space) { unsigned char md[MS_CHAP2_RESPONSE_LEN]; char saresponse[MS_AUTH_RESPONSE_LENGTH+1]; int challenge_len, response_len; challenge_len = *challenge++; /* skip length, is 16 */ response_len = *response++; if (response_len != MS_CHAP2_RESPONSE_LEN) goto bad; /* not even the right length */ /* Generate the expected response and our mutual auth. */ ChapMS2(challenge, &response[MS_CHAP2_PEER_CHALLENGE], name, (char *)secret, secret_len, md, (unsigned char *)saresponse, MS_CHAP2_AUTHENTICATOR); /* compare MDs and send the appropriate status */ /* * Per RFC 2759, success message must be formatted as * "S=<auth_string> M=<message>" * where * <auth_string> is the Authenticator Response (mutual auth) * <message> is a text message * * However, some versions of Windows (win98 tested) do not know * about the M=<message> part (required per RFC 2759) and flag * it as an error (reported incorrectly as an encryption error * to the user). Since the RFC requires it, and it can be * useful information, we supply it if the peer is a conforming * system. Luckily (?), win98 sets the Flags field to 0x04 * (contrary to RFC requirements) so we can use that to * distinguish between conforming and non-conforming systems. * * Special thanks to Alex Swiridov <*****@*****.**> for * help debugging this. */ if (memcmp(&md[MS_CHAP2_NTRESP], &response[MS_CHAP2_NTRESP], MS_CHAP2_NTRESP_LEN) == 0) { if (response[MS_CHAP2_FLAGS]) slprintf(message, message_space, "S=%s", saresponse); else slprintf(message, message_space, "S=%s M=%s", saresponse, "Access granted"); return 1; } bad: /* * Failure message must be formatted as * "E=e R=r C=c V=v M=m" * where * e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE) * r = retry (we use 1, ok to retry) * c = challenge to use for next response, we reuse previous * v = Change Password version supported, we use 0 * m = text message * * The M=m part is only for MS-CHAPv2. Neither win2k nor * win98 (others untested) display the message to the user anyway. * They also both ignore the E=e code. * * Note that it's safe to reuse the same challenge as we don't * actually accept another response based on the error message * (and no clients try to resend a response anyway). * * Basically, this whole bit is useless code, even the small * implementation here is only because of overspecification. */ slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0 M=%s", challenge_len, challenge, "Access denied"); return 0; }
char *alloc_sub_basic(const char *smb_name, const char *str) { char *b, *p, *s, *t, *r, *a_string; fstring pidstr; struct passwd *pass; const char *local_machine_name = get_local_machine_name(); /* workaround to prevent a crash while lookinf at bug #687 */ if ( !str ) { DEBUG(0,("alloc_sub_basic: NULL source string! This should not happen\n")); return NULL; } a_string = strdup(str); if (a_string == NULL) { DEBUG(0, ("alloc_sub_specified: Out of memory!\n")); return NULL; } for (b = s = a_string; (p = strchr_m(s, '%')); s = a_string + (p - b)) { r = NULL; b = t = a_string; switch (*(p+1)) { case 'U' : r = strdup_lower(smb_name); if (r == NULL) goto error; t = realloc_string_sub(t, "%U", r); break; case 'G' : r = strdup(smb_name); if (r == NULL) goto error; if ((pass = Get_Pwnam(r))!=NULL) { t = realloc_string_sub(t, "%G", gidtoname(pass->pw_gid)); } break; case 'D' : r = strdup_upper(current_user_info.domain); if (r == NULL) goto error; t = realloc_string_sub(t, "%D", r); break; case 'I' : t = realloc_string_sub(t, "%I", client_addr()); break; case 'L' : if (local_machine_name && *local_machine_name) t = realloc_string_sub(t, "%L", local_machine_name); else t = realloc_string_sub(t, "%L", global_myname()); break; case 'N': t = realloc_string_sub(t, "%N", automount_server(smb_name)); break; case 'M' : t = realloc_string_sub(t, "%M", client_name()); break; case 'R' : t = realloc_string_sub(t, "%R", remote_proto); break; case 'T' : t = realloc_string_sub(t, "%T", timestring(False)); break; case 'a' : t = realloc_string_sub(t, "%a", remote_arch); break; case 'd' : slprintf(pidstr,sizeof(pidstr)-1, "%d",(int)sys_getpid()); t = realloc_string_sub(t, "%d", pidstr); break; case 'h' : t = realloc_string_sub(t, "%h", myhostname()); break; case 'm' : t = realloc_string_sub(t, "%m", remote_machine); break; case 'v' : t = realloc_string_sub(t, "%v", SAMBA_VERSION_STRING); break; case '$' : t = realloc_expand_env_var(t, p); /* Expand environment variables */ break; default: break; } p++; SAFE_FREE(r); if (t == NULL) goto error; a_string = t; } return a_string; error: SAFE_FREE(a_string); return NULL; }
int main(int argc, char *argv[]) { char *p, *u; const char *libd = dyn_LIBDIR; pstring line, wd; int opt; extern char *optarg; extern int optind; dbf = x_stdout; smbw_setup_shared(); while ((opt = getopt(argc, argv, "W:U:R:d:P:l:hL:")) != EOF) { switch (opt) { case 'L': libd = optarg; break; case 'W': smbw_setshared("WORKGROUP", optarg); break; case 'l': smbw_setshared("LOGFILE", optarg); break; case 'P': smbw_setshared("PREFIX", optarg); break; case 'd': smbw_setshared("DEBUG", optarg); break; case 'U': p = strchr_m(optarg,'%'); if (p) { *p=0; smbw_setshared("PASSWORD",p+1); } smbw_setshared("USER", optarg); break; case 'R': smbw_setshared("RESOLVE_ORDER",optarg); break; case 'h': default: smbsh_usage(); } } if (!smbw_getshared("USER")) { printf("Username: "******"USER", u); } if (!smbw_getshared("PASSWORD")) { p = getpass("Password: "******"PASSWORD", p); } setenv("PS1", "smbsh$ ", 1); sys_getwd(wd); slprintf(line,sizeof(line)-1,"PWD_%d", (int)getpid()); smbw_setshared(line, wd); slprintf(line,sizeof(line)-1,"%s/smbwrapper.so", libd); setenv("LD_PRELOAD", line, 1); slprintf(line,sizeof(line)-1,"%s/smbwrapper.32.so", libd); if (file_exist(line, NULL)) { slprintf(line,sizeof(line)-1,"%s/smbwrapper.32.so:DEFAULT", libd); setenv("_RLD_LIST", line, 1); slprintf(line,sizeof(line)-1,"%s/smbwrapper.so:DEFAULT", libd); setenv("_RLDN32_LIST", line, 1); } else { slprintf(line,sizeof(line)-1,"%s/smbwrapper.so:DEFAULT", libd); setenv("_RLD_LIST", line, 1); } { char *shellpath = getenv("SHELL"); if(shellpath) execl(shellpath,"smbsh",NULL); else execl("/bin/sh","smbsh",NULL); } printf("launch failed!\n"); return 1; }
int main(int argc, char *argv[]) { static char *cmdstr = NULL; struct cmd_set **cmd_set; static struct vfs_state vfs; int i; static char *filename = NULL; /* make sure the vars that get altered (4th field) are in a fixed location or certain compilers complain */ poptContext pc; struct poptOption long_options[] = { POPT_AUTOHELP {"file", 'f', POPT_ARG_STRING, &filename, 0, }, {"command", 'c', POPT_ARG_STRING, &cmdstr, 0, "Execute specified list of commands" }, POPT_COMMON_SAMBA POPT_TABLEEND }; setlinebuf(stdout); pc = poptGetContext("vfstest", argc, (const char **) argv, long_options, 0); while(poptGetNextOpt(pc) != -1); poptFreeContext(pc); /* TODO: check output */ reload_services(False); /* the following functions are part of the Samba debugging facilities. See lib/debug.c */ setup_logging("vfstest", True); /* Load command lists */ cmd_set = vfstest_command_list; while(*cmd_set) { add_command_set(*cmd_set); add_command_set(separator_command); cmd_set++; } /* some basic initialization stuff */ sec_init(); conn_init(); vfs.conn = conn_new(); string_set(&vfs.conn->user,"vfstest"); for (i=0; i < 1024; i++) vfs.files[i] = NULL; /* some advanced initiliazation stuff */ smbd_vfs_init(vfs.conn); /* Do we have a file input? */ if (filename && filename[0]) { process_file(&vfs, filename); return 0; } /* Do anything specified with -c */ if (cmdstr && cmdstr[0]) { char *cmd; char *p = cmdstr; while((cmd=next_command(&p)) != NULL) { process_cmd(&vfs, cmd); } return 0; } /* Loop around accepting commands */ while(1) { pstring prompt; char *line; slprintf(prompt, sizeof(prompt) - 1, "vfstest $> "); line = smb_readline(prompt, NULL, completion_fn); if (line == NULL) break; if (line[0] != '\n') process_cmd(&vfs, line); } free(vfs.conn); return 0; }
/* called when a session is created */ BOOL session_claim(user_struct *vuser) { int i = 0; TDB_DATA data; struct sockaddr sa; struct in_addr *client_ip; struct sessionid sessionid; uint32 pid = (uint32)sys_getpid(); TDB_DATA key; fstring keystr; char * hostname; int tdb_store_flag; /* If using utmp, we do an inital 'lock hold' store, but we don't need this if we are just using the (unique) pid/vuid combination */ vuser->session_keystr = NULL; /* don't register sessions for the guest user - its just too expensive to go through pam session code for browsing etc */ if (vuser->guest) { return True; } if (!tdb) { tdb = tdb_open_log(lock_path("sessionid.tdb"), 0, TDB_CLEAR_IF_FIRST|TDB_DEFAULT, O_RDWR | O_CREAT, 0644); if (!tdb) { DEBUG(1,("session_claim: failed to open sessionid tdb\n")); return False; } } ZERO_STRUCT(sessionid); data.dptr = NULL; data.dsize = 0; if (lp_utmp()) { for (i=1;i<MAX_SESSION_ID;i++) { slprintf(keystr, sizeof(keystr)-1, "ID/%d", i); key.dptr = keystr; key.dsize = strlen(keystr)+1; if (tdb_store(tdb, key, data, TDB_INSERT) == 0) break; } if (i == MAX_SESSION_ID) { DEBUG(1,("session_claim: out of session IDs (max is %d)\n", MAX_SESSION_ID)); return False; } slprintf(sessionid.id_str, sizeof(sessionid.id_str)-1, SESSION_UTMP_TEMPLATE, i); tdb_store_flag = TDB_MODIFY; } else { slprintf(keystr, sizeof(keystr)-1, "ID/%lu/%u", (long unsigned int)sys_getpid(), vuser->vuid); slprintf(sessionid.id_str, sizeof(sessionid.id_str)-1, SESSION_TEMPLATE, (long unsigned int)sys_getpid(), vuser->vuid); key.dptr = keystr; key.dsize = strlen(keystr)+1; tdb_store_flag = TDB_REPLACE; } /* If 'hostname lookup' == yes, then do the DNS lookup. This is needed because utmp and PAM both expect DNS names client_name() handles this case internally. */ hostname = client_name(); if (strcmp(hostname, "UNKNOWN") == 0) { hostname = client_addr(); } fstrcpy(sessionid.username, vuser->user.unix_name); fstrcpy(sessionid.hostname, hostname); sessionid.id_num = i; /* Only valid for utmp sessions */ sessionid.pid = pid; sessionid.uid = vuser->uid; sessionid.gid = vuser->gid; fstrcpy(sessionid.remote_machine, get_remote_machine_name()); fstrcpy(sessionid.ip_addr, client_addr()); client_ip = client_inaddr(&sa); if (!smb_pam_claim_session(sessionid.username, sessionid.id_str, sessionid.hostname)) { DEBUG(1,("pam_session rejected the session for %s [%s]\n", sessionid.username, sessionid.id_str)); if (tdb_store_flag == TDB_MODIFY) { tdb_delete(tdb, key); } return False; } data.dptr = (char *)&sessionid; data.dsize = sizeof(sessionid); if (tdb_store(tdb, key, data, tdb_store_flag) != 0) { DEBUG(1,("session_claim: unable to create session id record\n")); return False; } if (lp_utmp()) { sys_utmp_claim(sessionid.username, sessionid.hostname, client_ip, sessionid.id_str, sessionid.id_num); } vuser->session_keystr = strdup(keystr); if (!vuser->session_keystr) { DEBUG(0, ("session_claim: strdup() failed for session_keystr\n")); return False; } return True; }
static NTSTATUS cmd_samr_query_usergroups(struct cli_state *cli, TALLOC_CTX *mem_ctx, int argc, const char **argv) { POLICY_HND connect_pol, domain_pol, user_pol; NTSTATUS result = NT_STATUS_UNSUCCESSFUL; uint32 num_groups, user_rid; uint32 access_mask = MAXIMUM_ALLOWED_ACCESS; DOM_GID *user_gids; int i; fstring server; if ((argc < 2) || (argc > 3)) { printf("Usage: %s rid [access mask]\n", argv[0]); return NT_STATUS_OK; } sscanf(argv[1], "%i", &user_rid); if (argc > 2) sscanf(argv[2], "%x", &access_mask); slprintf(server, sizeof(fstring)-1, "\\\\%s", cli->desthost); strupper_m(server); result = try_samr_connects(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, &connect_pol); if (!NT_STATUS_IS_OK(result)) goto done; result = cli_samr_open_domain(cli, mem_ctx, &connect_pol, MAXIMUM_ALLOWED_ACCESS, &domain_sid, &domain_pol); if (!NT_STATUS_IS_OK(result)) goto done; result = cli_samr_open_user(cli, mem_ctx, &domain_pol, access_mask, user_rid, &user_pol); if (!NT_STATUS_IS_OK(result)) goto done; result = cli_samr_query_usergroups(cli, mem_ctx, &user_pol, &num_groups, &user_gids); if (!NT_STATUS_IS_OK(result)) goto done; for (i = 0; i < num_groups; i++) { printf("\tgroup rid:[0x%x] attr:[0x%x]\n", user_gids[i].g_rid, user_gids[i].attr); } done: return result; }